-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdatabase.py
2854 lines (2188 loc) · 84.1 KB
/
database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import config
import MySQLdb
import MySQLdb.cursors
import time
import traceback
import re
from php2python import *
__version__ = "0.3"
class Database:
"""a python mysql query builder in codeIgniter activerecord style"""
def __init__(self, config_class=None):
""" Read Config"""
autoinit = False
if config_class:
""" From object"""
self.set_config(config_class)
autoinit = config_class.autoinit
else:
"""From configuration class"""
self.init_config()
autoinit = config.database.autoinit
# from DB_active_rec.php
self.ar_select = []
self.ar_distinct = False
self.ar_from = []
self.ar_join = []
self.ar_where = []
self.ar_like = []
self.ar_groupby = []
self.ar_having = []
self.ar_keys = []
self.ar_limit = False
self.ar_offset = False
self.ar_order = False
self.ar_orderby = []
self.ar_set = {} #changed from [] to {}
self.ar_wherein = []
self.ar_aliased_tables = []
self.ar_store_array = []
#Active Record Caching variables
self.ar_caching = False
self.ar_cache_exists = []
self.ar_cache_select = []
self.ar_cache_from = []
self.ar_cache_join = []
self.ar_cache_where = []
self.ar_cache_like = []
self.ar_cache_groupby = []
self.ar_cache_having = []
self.ar_cache_orderby = []
self.ar_cache_set = {} #changed from [] to {}
self.ar_no_escape = []
self.ar_cache_no_escape = []
# from DB_driver.php
self.swap_pre = ''
self.benchmark = 0
self.query_count = 0
self.bind_marker = '?'
self.save_queries = True
self.queries = []
self.query_times = []
self.data_cache = []
self.trans_enabled = True
self.trans_strict = True
self._trans_depth = 0
self._trans_status = True # Used with transactions to determine if a rollback should occur
self.cache_on = False
self.cachedir = ''
self.cache_autodel = False
self.CACHE = None # The cache class object
# Private variables
self.__protect_identifiers = True
self._reserved_identifiers = ['*'] # Identifiers that should NOT be escaped
# The character used for escaping
self._escape_char = '`'
# clause and character used for LIKE escape sequences - not used in MySQL
self._like_escape_str = ''
self._like_escape_chr = ''
# Whether to use the MySQL "delete hack" which allows the number
# of affected rows to be shown. Uses a preg_replace when enabled,
# adding a bit more processing to all queries.
self.delete_hack = True
# The syntax to count rows is slightly different across different
# database engines, so this string appears in each driver and is
# used for the count_all() and count_all_results() functions.
self._count_string = 'SELECT COUNT(*) AS '
self._random_keyword = ' RAND()' # database specific random keyword
self._cursor = None
if autoinit:
self.connect()
def init_config(self):
self._dbhost = config.database.hostname
self._dbport = int(config.database.port)
self._dbuser = config.database.username
self._dbpass = config.database.password
self._dbname = config.database.database
self._charset = config.database.charset
self.db_debug = config.database.dbdebug
# from mysql_driver.php
self.dbdriver = config.database.dbdriver
# from DB_driver.php
self.dbprefix = config.database.dbprefix
def set_config(self, config_class):
self._dbhost = config_class.hostname
self._dbport = int(config_class.port)
self._dbuser = config_class.username
self._dbpass = config_class.password
self._dbname = config_class.database
self._charset = config_class.charset
self.db_debug = config_class.dbdebug
# from mysql_driver.php
self.dbdriver = config_class.dbdriver
# from DB_driver.php
self.dbprefix = config_class.dbprefix
def connect(self):
try:
self._conn = MySQLdb.connect(host=self._dbhost, user=self._dbuser, passwd=self._dbpass, db=self._dbname, port=self._dbport, charset = self._charset, cursorclass = MySQLdb.cursors.DictCursor)
if self.db_debug:
print("#db connected.")
return True
except MySQLdb.OperationalError as error:
self._conn = None
if self.db_debug:
print("#OperationalError:%s" % error)
return False
except:
self._conn = None
if self.db_debug:
print(traceback.format_exc())
return False
# --------------------------------------------------------------------
def close(self):
self._conn.close()
self._alive = False
# --------------------------------------------------------------------
def ping(self):
try:
if self._conn:
self._conn.ping()
self._cursor = self._conn.cursor()
return True
else:
if self.db_debug:
print("#_conn Type Error, reconnect")
self.connect()
return False
except MySQLdb.OperationalError as error:
if self.db_debug:
print("#OperationalError:%s, reconnect." % error)
self.connect()
return False
except:
if self.db_debug:
print(traceback.format_exc())
self.connect()
return False
# --------------------------------------------------------------------
def mysql_real_escape_string(self, string):
if self._conn:
string = self._conn.escape_string(string)
else:
string = ''.join({'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}.get(c, c) for c in string)
return string
# --------------------------------------------------------------------
def _has_operator(self, str):
"""
* Tests whether the string has an SQL operator
*
* @access private
* @param string
* @return bool
"""
str = str.strip()
match = re.search("(\s|<|>|!|=|is null|is not null)", str, re.IGNORECASE)
if not match:
return False
else:
return True
# --------------------------------------------------------------------
def _track_aliases(self, table):
"""
* Track Aliases
*
* Used to track SQL statements written with aliased tables.
*
* @param string The table to inspect
* @return string
"""
if isinstance(table, list):
for t in table:
self._track_aliases(t)
return
# Does the string contain a comma? If so, we need to separate
# the string into discreet statements
if ',' in table:
return self._track_aliases(table.split(','))
# if a table alias is used we can recognize it by a space
if ' ' in table:
# if the alias is written with the AS keyword, remove it
table = re.sub('\s+AS\s+', ' ', table, flags = re.IGNORECASE)
# Grab the alias
table = table[table.rfind(' '):].strip()
# Store the alias, if it doesn't already exist
if table not in self.ar_aliased_tables:
self.ar_aliased_tables.append(table)
# --------------------------------------------------------------------
def _merge_cache(self):
"""
* Merge Cache
*
* When called, this function merges any cached AR arrays with
* locally called ones.
*
* @return void
"""
if len(self.ar_cache_exists) == 0:
return
for val in self.ar_cache_exists:
ar_variable = 'ar_' + val
ar_cache_var = 'ar_cache_' + val
if len(getattr(self, ar_cache_var)) == 0:
continue
if isinstance(getattr(self, ar_variable), list):
setattr(self, ar_variable, list(set(getattr(self, ar_cache_var) + getattr(self, ar_variable))))
elif isinstance(self.ar_variable, dict):
setattr(self, ar_variable, list(set(dict(getattr(self, ar_cache_var), **getattr(self, ar_variable)))))
# If we are "protecting identifiers" we need to examine the "from"
# portion of the query to determine if there are any aliases
if self.__protect_identifiers == True and len(self.ar_cache_from) > 0:
self._track_aliases(self.ar_from)
self.ar_no_escape = self.ar_cache_no_escape
# --------------------------------------------------------------------
def _compile_select(self, select_override = False):
"""
* Compile the SELECT statement
*
* Generates a query string based on which functions were used.
* Should not be called directly. The get() function calls it.
*
* @return string
"""
# Combine any cached components with the current statements
#self._merge_cache()
# ----------------------------------------------------------------
# Write the "select" portion of the query
if select_override != False:
sql = select_override
else:
sql = 'SELECT ' if not self.ar_distinct else 'SELECT DISTINCT '
if len(self.ar_select) == 0:
sql += '*'
else:
# Cycle through the "select" portion of the query and prep each column name.
# The reason we protect identifiers here rather then in the select() function
# is because until the user calls the from() function we don't know if there are aliases
for i in range(len(self.ar_select)):
try:
no_escape = self.ar_no_escape[i]
except IndexError:
no_escape = None
self.ar_select[i] = self._protect_identifiers(self.ar_select[i], False, no_escape)
sql += ', '.join(self.ar_select)
# ----------------------------------------------------------------
# Write the "FROM" portion of the query
if len(self.ar_from) > 0:
sql += "\n FROM "
sql += self._from_tables(self.ar_from)
# ----------------------------------------------------------------
# Write the "JOIN" portion of the query
if len(self.ar_join) > 0:
sql += "\n"
sql += "\n".join(self.ar_join)
# ----------------------------------------------------------------
# Write the "WHERE" portion of the query
if len(self.ar_where) > 0 or len(self.ar_like) > 0:
sql += "\nWHERE "
sql += "\n".join(self.ar_where)
# ----------------------------------------------------------------
# Write the "LIKE" portion of the query
if len(self.ar_like) > 0:
if len(self.ar_where) > 0:
sql += "\nAND "
sql += "\n".join(self.ar_like)
# ----------------------------------------------------------------
# Write the "GROUP BY" portion of the query
if len(self.ar_groupby) > 0:
sql += "\nGROUP BY "
sql += ', '.join(self.ar_groupby)
# ----------------------------------------------------------------
# Write the "HAVING" portion of the query
if len(self.ar_having) > 0:
sql += "\nHAVING "
sql += "\n".join(self.ar_having)
# ----------------------------------------------------------------
# Write the "ORDER BY" portion of the query
if len(self.ar_orderby) > 0:
sql += "\nORDER BY "
sql += ', '.join(self.ar_orderby)
if self.ar_order != False:
sql += ' DESC' if self.ar_order.lower() == 'desc' else ' ASC' # add .lower, haven't check
# ----------------------------------------------------------------
# Write the "LIMIT" portion of the query
if (isinstance(self.ar_limit, int) and self.ar_limit > 0) or (isinstance(self.ar_limit, str) and self.ar_limit.isdigit()):
sql += "\n"
sql = self._limit(sql, int(self.ar_limit), int(self.ar_offset))
return sql
# --------------------------------------------------------------------
def compile_binds(self, sql, binds):
"""
* Compile Bindings
*
* @access public
* @param string the sql statement
* @param array an array of bind data
* @return string
"""
if self.bind_marker not in sql:
return sql
if not isinstance(binds, list):
binds = list(binds)
# Get the sql segments around the bind markers
segments = sql.split(self.bind_marker)
# The count of bind should be 1 less then the count of segments
# If there are more bind arguments trim it down
if len(binds) >= len(segments):
binds = binds[0:len(segments)-1]
# Construct the binded query
result = segments[0]
i = 0
for bind in binds:
result += self.escape(bind)
i+=1
result += segments[i]
return result
# --------------------------------------------------------------------
def is_write_type(self, sql):
"""
* Determines if a query is a "write" type.
*
* @access public
* @param string An SQL query string
* @return boolean
"""
if not re.search('^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+', sql, re.IGNORECASE):
return False
else:
return True
# --------------------------------------------------------------------
def elapsed_time(self, decimals = 6):
"""
* Calculate the aggregate query elapsed time
*
* @access public
* @param integer The number of decimal places
* @return integer
"""
return number_format(self.benchmark, decimals)
# --------------------------------------------------------------------
def total_queries(self):
"""
* Returns the total number of queries
*
* @access public
* @return integer
"""
return self.query_count
# --------------------------------------------------------------------
def last_query(self):
"""
* Returns the last query that was executed
*
* @access public
* @return void
"""
return self.queries[-1]
# --------------------------------------------------------------------
def escape(self, string):
"""
* "Smart" Escape String
*
* Escapes data based on type
* Sets boolean and null types
*
* @access public
* @param string
* @return mixed
"""
if isinstance(string, str):
string = "'" + self.escape_str(string) + "'"
elif isinstance(string, bool):
string = 0 if string == False else 1
elif string is None:
string = 'NULL'
return string
# --------------------------------------------------------------------
def escape_like_str(self, str):
"""
* Escape LIKE String
*
* Calls the individual driver for platform
* specific escaping for LIKE conditions
*
* @access public
* @param string
* @return mixed
"""
return self.escape_str(str, True)
# --------------------------------------------------------------------
def escape_str(self, string, like = False):
"""
* Escape String
*
* @access public
* @param string
* @param bool whether or not the string will be used in a LIKE condition
* @return string
"""
if isinstance(string, dict):
for key,val in string.items():
string[key] = self.escape_str(val, like)
return string
if self._conn:
string = self.mysql_real_escape_string(string)
else:
string = ''.join({'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}.get(c, c) for c in string)
# escape LIKE condition wildcards
if like == True:
string = string.replace('%', '\\%')
string = string.replace('_', '\\_')
return string.decode('utf-8')
# --------------------------------------------------------------------
def _escape_identifiers(self, item):
"""
* Escape the SQL Identifiers
*
* This function escapes column and table names
*
* @access private
* @param string
* @return string
"""
if self._escape_char == '':
return item
for id in self._reserved_identifiers:
if '.'+id in item:
str = self._escape_char + item.replace('.', self._escape_char+'.')
# remove duplicates if the user already included the escape
return re.sub('['+self._escape_char+']+', self._escape_char, item)
if '.' in item:
str = self._escape_char + item.replace('.', self._escape_char+'.'+self._escape_char) + self._escape_char
else:
str = self._escape_char + item + self._escape_char
# remove duplicates if the user already included the escape
return re.sub('['+self._escape_char+']+', self._escape_char, str)
# --------------------------------------------------------------------
def _from_tables(self, tables):
"""
* From Tables
*
* This function implicitly groups FROM tables so there is no confusion
* about operator precedence in harmony with SQL standards
*
* @access public
* @param type
* @return type
"""
# if not isinstance(tables, list)
# tables = list(tables)
# return '(' + ', '.join(tables) + ')'
if isinstance(tables, list):
return '(' + ', '.join(tables) + ')'
elif isinstance(tables, str):
return tables
else:
raise TypeError #unknow tables name type
# --------------------------------------------------------------------
def _protect_identifiers(self, item, prefix_single = False, protect_identifiers = None, field_exists = True):
"""
* Protect Identifiers
*
* This function is used extensively by the Active Record class, and by
* a couple functions in this class.
* It takes a column or table name (optionally with an alias) and inserts
* the table prefix onto it. Some logic is necessary in order to deal with
* column names that include the path. Consider a query like this:
*
* SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table
*
* Or a query with aliasing:
*
* SELECT m.member_id, m.member_name FROM members AS m
*
* Since the column name can include up to four segments (host, DB, table, column)
* or also have an alias prefix, we need to do a bit of work to figure this out and
* insert the table prefix (if it exists) in the proper position, and escape only
* the correct identifiers.
*
* @access private
* @param string
* @param bool
* @param mixed
* @param bool
* @return string
"""
if not isinstance(protect_identifiers, bool):
protect_identifiers = self._protect_identifiers
if isinstance(item, list):
escaped_array = []
for k,v in item.items():
escaped_array[self._protect_identifiers(k)] = self._protect_identifiers(v)
return escaped_array
# Convert tabs or multiple spaces into single spaces
item = re.sub('[\t ]+', ' ', item)
# If the item has an alias declaration we remove it and set it aside.
# Basically we remove everything to the right of the first space
pos = item.find(' ')
if pos >= 0:
alias = item[pos:]
item = item[0:- len(alias)]
else:
alias = ''
# This is basically a bug fix for queries that use MAX, MIN, etc.
# If a parenthesis is found we know that we do not need to
# escape the data or add a prefix. There's probably a more graceful
# way to deal with this, but I'm not thinking of it -- Rick
if '(' in item:
return item + alias
# Break the string apart if it contains periods, then insert the table prefix
# in the correct location, assuming the period doesn't indicate that we're dealing
# with an alias. While we're at it, we will escape the components
if '.' in item:
parts = item.split('.')
# Does the first segment of the exploded item match
# one of the aliases previously identified? If so,
# we have nothing more to do other than escape the item
if parts[0] in self.ar_aliased_tables:
if protect_identifiers == True:
for key,val in parts.items():
if val not in self._reserved_identifiers:
parts[key] = self._escape_identifiers(val) #TODO: not convert yet
item = '.'.join(parts)
return item + alias
# Is there a table prefix defined in the config file? If not, no need to do anything
if self.dbprefix != '':
# We now add the table prefix based on some logic.
# Do we have 4 segments (hostname.database.table.column)?
# If so, we add the table prefix to the column name in the 3rd segment.
try:
parts[3]
i = 2
except NameError:
# we have 3 segments (database.table.column)?
# so, we add the table prefix to the column name in 2nd position
try:
parts[2]
i = 1
except NameError:
# we have 2 segments (table.column)?
# so, we add the table prefix to the column name in 1st segment
i = 0
# flag is set when the supplied item does not contain a field name.
# can happen when this function is being called from a JOIN.
if field_exists == False:
i += 1
# table prefix and replace if necessary
if self.swap_pre != '' and cmp(parts[i][:len(self.swap_pre)], self.swap_pre[:len(self.swap_pre)]) == 0:
parts[i] = re.sub("^"+self.swap_pre+"(\S+?)", self.dbprefix+"\1", parts[i]) #TOTO: unsure \\1 or \1
# only add the table prefix if it does not already exist
if parts[i][0:len(self.dbprefix)] != self.dbprefix:
parts[i] = self.dbprefix + parts[i]
# the parts back together
item = '.'.join(parts)
if protect_identifiers == True:
item = self._escape_identifiers(item)
return item + alias
# there a table prefix? If not, no need to insert it
if self.dbprefix != '':
# table prefix and replace if necessary
if self.swap_pre != '' and cmp(item[:len(self.swap_pre)], self.swap_pre[:len(self.swap_pre)]) == 0:
item = re.sub("^"+self.swap_pre+"(\S+?)", self.dbprefix+"\1", item) #TOTO: unsure \\1 or \1
# we prefix an item with no segments?
if prefix_single == True and item[0:len(self.dbprefix)] != self.dbprefix:
item = self.dbprefix + item
if protect_identifiers == True and item not in self._reserved_identifiers:
item = self._escape_identifiers(item)
return item + alias
# --------------------------------------------------------------------
def select(self, select = '*', escape = None):
"""
* Select
*
* Generates the SELECT portion of the query
*
* @param string
* @return object
"""
if isinstance(select, str):
select = select.split(',')
for val in select:
val = val.strip()
if val != '':
self.ar_select.append(val)
self.ar_no_escape.append(escape)
if self.ar_caching == True:
self.ar_cache_select.append(val)
self.ar_cache_exists.append('select')
self.ar_cache_no_escape.append(escape)
return self
# --------------------------------------------------------------------
def select_max(self, select = '', alias = ''):
"""
* Select Max
*
* Generates a SELECT MAX(field) portion of a query
*
* @param string the field
* @param string an alias
* @return object
"""
return self._max_min_avg_sum(select, alias, 'MAX')
# --------------------------------------------------------------------
def select_min(self, select = '', alias = ''):
"""
* Select Min
*
* Generates a SELECT MIN(field) portion of a query
*
* @param string the field
* @param string an alias
* @return object
"""
return self._max_min_avg_sum(select, alias, 'MIN')
# --------------------------------------------------------------------
def select_avg(self, select = '', alias = ''):
"""
* Select Average
*
* Generates a SELECT AVG(field) portion of a query
*
* @param string the field
* @param string an alias
* @return object
"""
return self._max_min_avg_sum(select, alias, 'AVG')
# --------------------------------------------------------------------
def select_sum(self, select = '', alias = ''):
"""
* Select Sum
*
* Generates a SELECT SUM(field) portion of a query
*
* @param string the field
* @param string an alias
* @return object
"""
return self._max_min_avg_sum(select, alias, 'SUM')
# --------------------------------------------------------------------
def _max_min_avg_sum(self, select = '', alias = '', type = 'MAX'):
"""
* Processing Function for the four functions above:
*
* select_max()
* select_min()
* select_avg()
* select_sum()
*
* @param string the field
* @param string an alias
* @return object
"""
if not isinstance(select, str) or select == '':
self.display_error('db_invalid_query')
type = type.upper()
if type not in ['MAX', 'MIN', 'AVG', 'SUM']:
show_error('Invalid function type: %s' % type)
if alias == '':
alias = self._create_alias_from_table(select.strip())
sql = type + '(' + self._protect_identifiers(select.strip()) + ') AS ' + alias
self.ar_select.append(sql)
if self.ar_caching == True:
self.ar_cache_select.append(sql)
self.ar_cache_exists.append('select')
return self
# --------------------------------------------------------------------
def _create_alias_from_table(self, item):
"""
* Determines the alias name based on the table
*
* @param string
* @return string
"""
if '.' in item:
return item.split('.')[:-1]
return item
# --------------------------------------------------------------------
def distinct(self, val = True):
"""
* DISTINCT
*
* Sets a flag which tells the query string compiler to add DISTINCT
*
* @param bool
* @return object
"""
self.ar_distinct = val if isinstance(val, bool) else True
return self
# --------------------------------------------------------------------
def table(self, table):
"""
* Table
*
* Generates the FROM portion of the query
*
* @param mixed can be a string or array
* @return object
"""
# TODO: mutipule tables 'FROM' is not supported yet
# for val in table:
# if ',' in val:
# for v in val.split(','):
# v = v.strip()
# self._track_aliases(v)
# self.ar_from.append(self._protect_identifiers(v, True, None, False))
# if self.ar_caching == True:
# self.ar_cache_from.append(self._protect_identifiers(v, True, None, False))
# self.ar_cache_exists.append('from')
# else:
# val = val.strip()
# # any aliases that might exist. We use this information
# # the _protect_identifiers to know whether to add a table prefix
# self._track_aliases(val)
# self.ar_from.append(self._protect_identifiers(val, True, None, False))
# if self.ar_caching == True:
# self.ar_cache_from.append(self._protect_identifiers(val, True, None, False))
# self.ar_cache_exists.append('from')
table = table.strip()
# any aliases that might exist. We use this information
# the _protect_identifiers to know whether to add a table prefix
self._track_aliases(table)
self.ar_from.append(self._protect_identifiers(table, True, None, False))
if self.ar_caching == True:
self.ar_cache_from.append(self._protect_identifiers(table, True, None, False))
self.ar_cache_exists.append('from')
return self
# --------------------------------------------------------------------
def join(self, table, cond, type = ''):
"""
* Join
*
* Generates the JOIN portion of the query
*
* @param string
* @param string the join condition
* @param string the type of join
* @return object
"""
if type != '':
type = type.strip().upper()
if type not in ['LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER']:
type = ''
else:
type += ' '
# Extract any aliases that might exist. We use this information
# in the _protect_identifiers to know whether to add a table prefix
self._track_aliases(table)
# Strip apart the condition and protect the identifiers
match = re.search('/([\w\.]+)([\W\s]+)(.+)/', cond)