/
Builder.py
461 lines (412 loc) · 9.38 KB
/
Builder.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
from Grammar import Grammar
from Connection import Connection
"""
@class: Builder
@version: 1.0
@author: sidfate
@desc: builder query and execute
"""
class Builder:
wheres = []
orders = []
tables = []
fields = []
groups = []
havings = []
limits = {}
distinct = False
def __init__(self, config):
self.connection = Connection(config)
self.grammar = Grammar()
"""
Select the table.
@param string table
@return self
"""
def table(self, table):
if self.connection.config.has_key('prefix'):
table = self.connection.config['prefix']+table
if not table in self.tables:
self.tables.append(table)
return self
"""
Add an "order by".
@param dict|string sort
@param string way
@return self
"""
def order(self, sort, way="asc"):
if isinstance(sort, dict):
for k, v in sort.items():
self.orders.append({'sort': k, 'way': v})
else:
self.orders.append({'sort': sort, 'way': way.lower()})
return self
"""
Select the fields.
@param tuple args
@return self
"""
def select(self, *args):
args = list(args)
if len(args) == 0:
self.fields = ["*"]
else:
for item in args:
self.fields += item if isinstance(item, list) else [item]
self.fields = list(set(self.fields))
return self
"""
Add a "distinct".
@return self
"""
def distinct(self):
self.distinct = True
return self
"""
Limit the number of results.
@param int offset
@param int num
@return self
"""
def limit(self, offset, num=0):
self.limits = {'num': offset, 'offset': 0} if num==0 else {'offset': offset, 'num': num}
return self
"""
Add a basic "where".
@param string field
@param string operator
@param string value
@param string boolean
@return self
"""
def where(self, field, operator=None, value=None, boolean='and'):
if not value:
value = operator
operator = '='
whereType = 'basic'
self.wheres.append({'field': field, 'value': value, 'operator': operator, 'boolean': boolean, 'type': whereType})
return self
"""
Add a "or where".
@param string field
@param string operator
@param string value
@return self
"""
def orWhere(self, field, operator=None, value=None):
return self.where(field, operator, value, 'or')
"""
Add a where between.
@param string field
@param string value
@param string boolean
@param boolean isNot
@return self
"""
def whereBetween(self, field, value, boolean='and', isNot=False):
if not isinstance(value, list):
value = list(value)
whereType = 'between'
self.wheres.append({'field': field, 'value': value, 'boolean': boolean, 'not': isNot, 'type': whereType})
return self
"""
Add a or where between.
@param string field
@param string value
@return self
"""
def orwhereBetween(self, field, value):
return self.whereBetween(field, value, 'or')
"""
Add a where not between.
@param string field
@param string value
@return self
"""
def whereNotBetween(self, field, value):
return self.whereBetween(field, value, 'and', True)
"""
Add a or where not between.
@param string field
@param string value
@return self
"""
def orWhereNotBetween(self, field, value):
return self.whereBetween(field, value, 'or', True)
"""
Add a where in.
@param string field
@param string value
@param string boolean
@param boolean isNot
@return self
"""
def whereIn(self, field, value, boolean='and', isNot=False):
if not isinstance(value, list):
value = list(value)
whereType = 'in'
self.wheres.append({'field': field, 'value': value, 'boolean': boolean, 'not': isNot, 'type': whereType})
return self
"""
Add a or where in.
@param string field
@param string value
@return self
"""
def orWhereIn(self, field, value):
return self.whereIn(field, value, 'or')
"""
Add a where not in.
@param string field
@param string value
@return self
"""
def whereNotIn(self, field, value):
return self.whereIn(field, value, 'and', True)
"""
Add a or where not in.
@param string field
@param string value
@return self
"""
def orWhereNotIn(self, field, value):
return self.whereIn(field, value, 'or', True)
"""
Add a where is null.
@param string field
@param string boolean
@param boolean isNot
@return self
"""
def whereNull(self, field, boolean='and', isNot=False):
whereType = 'null'
self.wheres.append({'field': field, 'boolean': boolean, 'not': isNot, 'type': whereType})
return self
"""
Add a or where is null.
@param string field
@return self
"""
def orWhereNull(self, field):
return self.whereNull(field, 'or')
"""
Add a where is not null.
@param string field
@return self
"""
def whereNotNull(self, field):
return self.whereNull(field, 'and', True)
"""
Add a or where is not null.
@param string field
@return self
"""
def orWhereNotNull(self, field):
return self.whereNull(field, 'or', True)
"""
Add a raw where.
@param string sql
#param string boolean
@return self
"""
def whereRaw(self, sql, boolean='and'):
whereType = 'raw'
self.wheres.append({'sql': sql, 'boolean': boolean, 'type': whereType})
return self
"""
Add a or raw where.
@param string sql
@return self
"""
def orWhereRaw(self, sql):
return self.whereRaw(sql, 'or')
"""
Add a group by.
@param tuple args
@return self
"""
def groupBy(self, *args):
args = list(args)
for item in args:
self.groups += item if isinstance(item, list) else [item]
self.groups = list(set(self.groups))
return self
"""
Add a having.
@param string field
@param string operator
@param string value
@param string boolean
@return self
"""
def having(self, field, operator=None, value=None, boolean='and'):
whereType = 'basic'
self.havings.append({'field': field, 'value': value, 'operator': operator, 'boolean': boolean, 'type': whereType})
return self
"""
Add a or having.
@param string field
@param string operator
@param string value
@return self
"""
def orHaving(self, field, operator=None, value=None):
return self.having(field, operator, value, 'or')
"""
Add a raw having.
@param string sql
@param string boolean
@return self
"""
def havingRaw(self, sql, boolean='and'):
whereType = 'raw'
self.havings.append({'sql': sql, 'boolean': boolean, 'type': whereType})
return self
"""
Add a raw or having.
@param string sql
@return self
"""
def orHavingRaw(self, sql):
return self.havingRaw(sql, 'or')
"""
def join(self):
return self.whereNull(field, 'or')
def leftJoin(self):
pass
"""
"""
get all of results
@return tuple
"""
def get(self):
results = self.connection.select(self.__toSql())
self.__optEnd()
return results
"""
get the first column of results
@return dict
"""
def first(self):
results = self.connection.select(self.__toSql())
self.__optEnd()
return results[0] if len(results) != 0 else results
"""
get the field from the first column of results
@param string field
@return mixed
"""
def pluck(self, field):
self.fields = [field]
results = self.connection.select(self.__toSql())
self.__optEnd()
return results[0][field] if len(results) != 0 else None
"""
get list of the field from results
"""
def lists(self, field):
self.fields = [field]
results = self.connection.select(self.__toSql())
self.__optEnd()
if len(results) == 0:
return None
else:
lists = []
for item in results:
lists.append(item[field])
return lists
"""
Return the sum of results of a given field.
@return numeric
"""
def count(self):
return self.aggregate(self.count.__name__, '*')
"""
Return the max of results of a given field.
@param string field
@return numeric
"""
def max(self, field):
return self.aggregate(self.max.__name__, field)
"""
Return the min of results of a given field.
@param string field
@return numeric
"""
def min(self, field):
return self.aggregate(self.min.__name__, field)
"""
Return the avg of results of a given field.
@param string field
@return numeric
"""
def avg(self, field):
return self.aggregate(self.avg.__name__, field)
"""
Return the sum of results of a given field.
@param string field
@return numeric
"""
def sum(self, field):
return self.aggregate(self.sum.__name__, field)
"""
Deal aggregate query.
@param string func
@param string field
@return numeric
"""
def aggregate(self, func, field):
self.fields = [func+"("+field+") as "+func]
results = self.connection.select(self.__toSql())
self.__optEnd()
return results[0][func] if len(results) != 0 else 0
"""
Insert a recode.
@return boolean
"""
def insert(self, values):
sql = self.grammar.compileInsert(self, values)
self.__optEnd()
return self.connection.insert(sql)
"""
Get the insert id
@return int
"""
def getInsertId(self):
return self.connection.getInsertId()
"""
Update a record.
@param dict values
@return boolean
"""
def update(self, values):
sql = self.grammar.compileUpdate(self, values)
self.__optEnd()
return self.connection.update(sql)
"""
Delete a record.
@return boolean
"""
def delete(self):
sql = self.grammar.compileDelete(self)
self.__optEnd()
return self.connection.delete(sql)
"""
Create the select sql
@return string
"""
def __toSql(self):
return self.grammar.compileSelect(self)
"""
clean up record
"""
def __optEnd(self):
self.wheres = []
self.orders = []
self.tables = []
self.fields = []
self.groups = []
self.havings = []
self.limits = {}
self.distinct = False