Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlrocks.lua
More file actions
Latest commit
1379 lines (1179 loc) · 38 KB
/
Copy pathsqlrocks.lua
File metadata and controls
1379 lines (1179 loc) · 38 KB
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
--
-- Sqlrocks, is a transparent, schemaless library for building and composing SQL statements.
--
-- @author leite (xico@simbio.se)
-- @license MIT
-- @copyright Simbiose 2015
localstring, math, table=require'string', require'math', require'table'
localfind, match, gmatch, gsub, sub, lower, upper, format, max, floor, concat, insert,
type, pairs, ipairs, tostring, select, next, error, rawset, setmetatable, getmetatable=
string.find, string.match, string.gmatch, string.gsub, string.sub, string.lower,
string.upper, string.format, math.max, math.floor, table.concat, table.insert, type,
pairs, ipairs, tostring, select, next, error, rawset, setmetatable, getmetatable
string, math, table=nil, nil, nil
localreserved= {
abort=true, action=true, add=true, after=true, all=true, alter=true, analyse=true,
analyze=true, ['and']=true, any=true, array=true, as=true, asc=true,
asymmetric=true, attach=true, authorization=true, autoincrement=true, before=true,
begin=true, between=true, both=true, by=true, cascade=true, case=true, cast=true,
check=true, collate=true, collation=true, column=true, commit=true, conflict=true,
constraint=true, create=true, cross=true, current_catalog=true, current_date=true,
current_role=true, current_time=true, current_timestamp=true, current_user=true,
database=true, default=true, deferrable=true, deferred=true, delete=true,
desc=true, detach=true, distinct=true, ['do']=true, drop=true, each=true,
['else']=true, ['end']=true, escape=true, except=true, exclusive=true, exists=true,
explain=true, fail=true, ['false']=true, fetch=true, ['for']=true, foreign=true,
freeze=true, from=true, full=true, glob=true, grant=true, group=true, having=true,
['if']=true, ignore=true, ilike=true, immediate=true, ['in']=true, index=true,
indexed=true, initially=true, inner=true, insert=true, instead=true,
intersect=true, into=true, is=true, isnull=true, join=true, key=true, lateral=true,
leading=true, left=true, like=true, limit=true, localtime=true,
localtimestamp=true, match=true, natural=true, no=true, ['not']=true, notnull=true,
null=true, of=true, offset=true, on=true, only=true, ['or']=true, order=true,
outer=true, over=true, overlaps=true, placing=true, plan=true, pragma=true,
primary=true, query=true, raise=true, references=true, regexp=true, reindex=true,
release=true, rename=true, replace=true, restrict=true, returning=true, right=true,
rollback=true, row=true, savepoint=true, ['select']=true, session_user=true,
set=true, similar=true, some=true, symmetric=true, table=true, temp=true,
temporary=true, ['then']=true, trailing=true, transaction=true, trigger=true,
['true']=true, union=true, unique=true, update=true, to=true, user=true, using=true,
vacuum=true, values=true, variadic=true, verbose=true, view=true, virtual=true,
when=true, where=true, window=true, with=true}
localcompounds= {
union='UNION', unionAll='UNION ALL', intersect='INTERSECT',
intersectAll='INTERSECT ALL', minus='MINUS', minusAll='MINUS ALL',
except='EXCEPT', exceptAll='EXCEPT ALL'}
localEMPTY, SPACE, DOT, COMA, COMA_SPC, Q_MARK, STAR, PAR_SPC, LT, LE, NOT_EQ,
EQ, GT, GE, DOLLAR, QUOTE, QQ, ESP_AND, ESP_AS, _INDEX, _HAVING, I, _RETURNING,
USING, WHERE, ALLSPACE, AND, ANYSPACE, COLS, CROSS, DELSPACEFROMSPACE, DEL,
FOR_UPDATE, FOR_UPDATE_TBLS, FULL, FUNCTION, GROUPBY, GROUP_BY, HASH, INDEX,
INNER, INSERT, IS_NOT_NULL, IS_NULL, LEFT, NO_WAIT, NUMBER, OR_ABORT, OR_FAIL,
OR_IGNORE, OR_REPLACE, OR_ROLLBACK, OR, ORDERBY, ORDER_BY, RETURNING, RIGHT,
SELECT, _SELECT, STRING, TABLE, TBLS, TEMP, UPDATE, _UPDATE, VALS_P=
'', '', '.', ',', ', ', '?', '*', ') ', '<', '<=', '<>', '=', '>', '>=', '$',
"'", "''", ' AND ', ' AS ', '__index', '_having', '_i', '_returning', '_using',
'_where', 'ALL ', 'AND', 'ANY ', 'cols', 'CROSS', 'DELETE FROM ', 'delete',
'FOR UPDATE ', 'for_update_tbls', 'FULL', 'function', 'GROUP BY ', 'group_by',
'Hash', 'index', 'INNER', 'INSERT ', 'IS NOT NULL', 'IS NULL', 'LEFT', 'NO WAIT ',
'number', 'OR ABORT ', 'OR FAIL ', 'OR IGNORE ', 'OR REPLACE ', 'OR ROLLBACK ',
'OR', 'ORDER BY ', 'order_by', 'RETURNING ', 'RIGHT', 'SELECT ', 'select', 'string',
'table', 'tbls', 'TEMP ', 'UPDATE ', 'update', 'VALUES ('
localpatterns= {
DQS='"%s"', CAP1='([^%.]+)', DPS='(%s)', SSPACE='%s ', SSPACESSSPACE='%s %s ',
SSPACESSSPACESS='%s %s %s%s', SSPACESSUNDERS='%s %s_%s', SSPACES='%s %s',
SEQS='%s = %s', SEQSS='%s = %s%s', S_BTW_S_AND_S='%s BETWEEN %s AND %s',
S_IN_S='%s IN (%s)', S_JOIN_S_ON_S='%s JOIN %s ON %s', S_LIKE_SS='%s LIKE %s%s',
S_SET='%s SET ', S_S='%s_%s', CAP2='%s*([^%s,$]+)%s*,?$?', SS='%s%s',
S7='%s%s%s%s%s%s%s', EXISTS_S='EXISTS (%s)', FROM_S='FROM %s ', HVG_S='HAVING %s',
CAP3='^([%w%_%-%d]*)%.?([%w%_%-%d]*)%.?([%w%_%-%d]*)%s?[aA]?[sS]?%s?([[%w%_%-%d]*]?)$',
EXPECT_VAL_GOT='expecting %d values, got %d', INTO_S_P='INTO %s (', NOT_S='NOT %s',
INTO_SS='INTO %s%s ', LIMIT_S='LIMIT %s ', OFFSET_S='OFFSET %s ',
USING_S='USING %s ', WHERE_S='WHERE %s', ESCAPE_Q_S=" ESCAPE '%s'", Q_S_Q="'%s'",
EXPECT_HASH="expecting hash, got a '%s'", UNSP_N_D=
'Unsupported number of tables in pseudo-view: %d'
}
--
--
--
--
--
localclass
do
localclasses=setmetatable({}, {__mode='k'})
localfunctiondeep_copy(t, dest)
localt, r=tor {}, destor {}
fork,vinpairs(t) do
iftype(v) ==TABLEandk~=_INDEXthen
r[k] =deep_copy(v)
else
r[k] =v
end
end
returnr
end
localfunctionis(self, klass)
localm=getmetatable(self)
whilemdo
ifm==klassthenreturntrueend
m=m.super
end
returnfalse
end
localfunctioninclude(self, ...)
ifnot...thenreturnend
fork,vinpairs(...) do
ifself[k] thenself[k] =nilend
self[k] =v
end
end
localfunctionextends(self, ...)
localmeta= {}
if...thendeep_copy(..., deep_copy(self, meta)) elsedeep_copy(self, meta) end
setmetatable(meta, getmetatable(self))
returnmeta
end
localfunctionnew_index(self, key, value)
rawset(self, key, value)
fori=1, #classes[self] do
classes[self][i][key] =value
end
end
class=function (base)
localc, mt= {}, {}
iftype(base) ==TABLEthen
fori,vinpairs(base) doc[i] =vend
c.super=base
end
c.__index=c
c.is=is
c.extends=extends
c.include=include
mt.__newindex=new_index
classes[c] = {}
mt.__call=function(self, ...)
localobj= {}
setmetatable(obj, c)
ifc.__initthenc.__init(obj, ...) end
returnobj
end
ifc.superthen
insert(classes[c.super], c)
end
setmetatable(c, mt)
returnc
end
end
--
--
--
--
--
localHash=class()
Hash.__name='Hash'
functionHash:__init(bootstrap)
rawset(self, I, 0)
rawset(self, 'index', {})
ifTABLE~=type(bootstrap) thenreturnend
fork,vinpairs(bootstrap) doself.index[k] =vend
end
functionHash:__newindex(key, val)
ifnotself.index[key] then
insert(self.index, key)
end
ifnil==valthen
fori=1, #self.indexdo
ifself.index[i] ==keythen
remove(self.index, i)
self._i=self._i>0and (self._i-1) orself._i
end
end
end
self.index[key] =val
end
functionHash:__index(key)
returnrawget(getmetatable(self), key) orself.index[key]
end
functionHash:__pairs()
self._i=0
localfunctioniter(self)
self._i=self._i+1
localk=self.index[self._i]
ifkthenreturnk, self.index[k] end
end
returniter, self
end
functionHash:add(index, val)
ifNUMBER==type(index) then
insert(self.index[self.index[index]], val)
else
insert(self.index[index], val)
end
end
functionHash:set(index, val)
ifself.index[index] then
self.index[self.index[index]] =valreturntrue
end
returnfalse
end
functionHash:get(index)
ifself.index[index] thenreturnself.index[self.index[index]] end
returnnil
end
functionHash:__len()
return#self.index
end
functionHash:__sub(hash)
ifnot(TABLE==type(hash) andhash.__name=='Hash') then
error(format(patterns.EXPECT_HASH, type(hash)))
end
localnew_index= {}
fori=1, #self.indexdo
ifhash.index[self.index[i]] then
insert(new_index, self.index[i])
new_index[self.index[i]] =self.index[self.index[i]]
end
end
returngetmetatable(self)(new_index)
end
functionHash:__add(hash)
ifnot(TABLE==type(hash) andhash.__name=='Hash') then
error(format(patterns.EXPECT_HASH, type(hash)))
end
localnew_hash=getmetatable(self)(self.index)
fori=1, #hash.indexdo
ifnotnew_hash.index[hash.index[i]] then
new_hash[hash.index[i]] =hash.index[hash.index[i]]
end
end
returnnew_hash
end
--
--
--
--
--
localfunctionclone(orig)
localorig_type, copy=type(orig), {}
--local copy
ifTABLE==orig_typeandorig.isthen
copy=orig:extends()
elseifTABLE==orig_typethen
--copy = {}
fororig_key, orig_valueinnext, orig, nildo
copy[clone(orig_key)] =clone(orig_value)
end
else
copy=orig
end
returncopy
end
localfunctionis_array(t)
ifnottortype(t) ~=TABLEthenreturnfalseend
locali=0
for_inpairs(t) do
i=i+1
ift[i] ==nilthenreturnfalseend
end
returntrue
end
localfunctionargs2array(args)
ifnotargsthenreturn {} end
if#args==1andis_array(args[1]) then
returnargs[1]
elseifSTRING==type(args[1]) andfind(args[1], COMA, 1, true) ~=nilthen
localresults= {}
gsub(args[1], patterns.CAP2, function(st) insert(results, st) end)
returnresults
elseifTABLE==type(args[1]) and#args==1then
returnargs[1]
else
returnargs
end
end
localfunctionargs2object(args)
ifTABLE==type(args[1]) thenreturnargs[1] end
localobj= {}
ifnil~=args[1] thenobj[args[1]] =args[2] end
returnobj
end
localfunctioncheck_same_len(length, expected)
assert(length==expected, format(patterns.EXPECT_VAL_GOT, length, expected))
end
localfunctionconvert(col, new_aliases)
localcol_parts= {}
forkeyingmatch(col, "([^%.]+)") doinsert(col_parts, key) end
if#col_parts==1thenreturncolend
localtbl_ix=#col_parts-1
localtbl_alias=col_parts[tbl_ix]
ifnew_aliases[tbl_alias] then
col_parts[tbl_ix] =new_aliases[tbl_alias]
returnconcat(col_parts, DOT)
end
returncol
end
localfunctionconvert_expr(expr, new_aliases)
ifexpr.colthenexpr.col=convert(expr.col, new_aliases) end
ifexpr.expressionsthen
fori=1, #expr.expressionsdo
convert_expr(expr.expressions[i], new_aliases)
end
end
end
localfunctionnamespaced_on(on, new_aliases)
localnamespace= {}
forkey, valueinpairs(on) do
namespace[convert(key, new_aliases)] =convert(value, new_aliases)
end
returnnamespace
end
-- define basic class-like metatables
localSelect, Insert, Update, Delete
localSql, Val, Statement, Join, Group, Not, Binary, Like, Between, Unary,
In, Exists=class(), class(), class(), class(), class(), class(), class(),
class(), class(), class(), class(), class()
Sql.__name, Val.__name, Statement.__name, Join.__name, Group.__name, Not.__name,
Binary.__name, Like.__name, Between.__name, Unary.__name,
In.__name, Exists.__name='Sql', 'Val', 'Statement', 'Join', 'Group', 'Not',
'Binary', 'Like', 'Between', 'Unary', 'In', 'Exists'
functionget_alias(tbl)
localsep=ESP_AS
localsep_ix=find(tbl, sep, 1, true)
ifnotsep_ixthen
sep=SPACE
sep_ix=find(tbl, sep, 1, true)
end
ifsep_ixthenreturnsub(tbl, sep_ix+#sep, -1) end
returntbl
end
functionget_table(tbl)
localsep_ix=find(tbl, SPACE, 1, true)
ifsep_ixthenreturnsub(tbl, 1, sep_ix-1) end
returntbl
end
localfunctionis_expr(e)
returne.isand (e:is(Group) ore:is(Not) ore:is(Binary) ore:is(Unary) or
e:is(In) ore:is(Like) ore:is(Between) ore:is(Exists))
end
localfunctionhandle_value(val, opts)
local_type=type(val)
ifTABLE==_typeandval.isthen
ifval:is(Statement) thenreturnformat(patterns.DPS, val:_toString(opts)) end
ifval:is(Sql) thenreturntostring(val) end
end
ifoptsandopts.parameterizedthen
insert(opts.values, val)
localprefix=EMPTY
ifopts.placeholderandopts.placeholder=='%' then
prefix='%s'
opts.value_ix=opts.value_ix+1
returnprefix
else
prefix=format(patterns.SS, (opts.placeholderorDOLLAR), tostring(opts.value_ix))
opts.value_ix=opts.value_ix+1
returnprefix
end
end
ifSTRING==_typeorTABLE==_typethen
returnformat(
patterns.Q_S_Q,
gsub(tostring(TABLE==_typeandconcat(val, COMA) orval), QUOTE, QQ)
)
end
returnval
end
localfunctionhandle_column(expr, opts)
ifexpr.isthen
ifexpr:is(Statement) thenreturnformat(patterns.DPS, expr:_toString(opts)) end
ifexpr:is(Val) thenreturnhandle_value(expr.val, opts) end
end
localdb, tb, fd, al=match(expr, patterns.CAP3)
ifdbthen
localtb_dot, db_dot=DOT, DOT
iffd==EMPTYandtb==EMPTYthen
fd= (reserved[lower(db)] andformat(patterns.DQS, db) ordb)
db=EMPTYdb_dot=EMPTYtb_dot=EMPTY
elseiffd==EMPTYandtb~=EMPTYthen
fd, tb= (reserved[lower(tb)] andformat(patterns.DQS, tb) ortb),
(reserved[lower(db)] andformat(patterns.DQS, db) ordb) db=EMPTYdb_dot=EMPTY
else
fd, tb, db= (reserved[lower(fd)] andformat(patterns.DQS, fd) orfd),
(reserved[lower(tb)] andformat(patterns.DQS, tb) ortb),
(reserved[lower(db)] andformat(patterns.DQS, db) ordb)
end
returnformat(
patterns.S7, db, db_dot, tb, tb_dot, fd, (al==EMPTYandEMPTYorESP_AS), al)
end
returnexpr
end
--
--
--
--
--
localfunctionhandles(res, data, opts, ...)
localboth, value, appends, addendum=...
both, value, appends, addendum=
(bothorfalse), (valueorfalse), (appendsorCOMA_SPC), (addendumorSPACE)
ifboththen
fork,vinpairs(data) do
insert(res, format(
patterns.SEQSS, handle_column(k, opts), handle_value(v, opts), appends))
end
res[#res] =format(patterns.SS, sub(res[#res], 1, ((#appends+1) *-1)), addendum)
returnres
end
ifvaluethen
ifdata.isanddata.is(data, Hash) andTABLE==type(data.get(data, 1)) then
fori=1, #data.get(data, 1) do
fork,vinpairs(data) do
insert(res, format(patterns.SS, handle_value(v[i], opts), appends))
end
res[#res] =format('%s), (', sub(res[#res], 1, -3))
end
res[#res] =sub(res[#res], 1, -5)
returnres
end
fork, vinpairs(data) do
insert(res, format(patterns.SS, handle_value(v, opts), appends))
end
else
forkeyinpairs(data) do
ifNUMBER==type(key) then
fork,vinpairs(data) do
insert(res, format(patterns.SS, handle_column(v, opts), appends))
end
else
forkinpairs(data) do
insert(res, format(patterns.SS, handle_column(k, opts), appends))
end
end
break
end
end
res[#res] =format(patterns.SS, sub(res[#res], 1, ((#appends+1) *-1)), addendum)
returnres
end
--
--
--
--
--
localfunction_and(...) returnGroup('AND', args2array({...})) end
localfunction_or(...) returnGroup(OR, args2array({...})) end
localfunctionisNull(col) returnUnary('IS NULL', col) end
localfunctionisNotNull(col) returnUnary('IS NOT NULL', col) end
localfunctioninnerJoin(self, ...) returnself:_addJoins({...}, 'INNER') end
localfunctionleftJoin(self, ...) returnself:_addJoins({...}, 'LEFT') end
localfunctionrightJoin(self, ...) returnself:_addJoins({...}, RIGHT) end
localfunctionfullJoin(self, ...) returnself:_addJoins({...}, FULL) end
localfunctionwhere(self, ...) returnself:_addExpression({...}, '_where') end
localfunctiongroup(self, ...) returnself:_addListArgs({...}, GROUP_BY) end
localfunctionorder(self, ...) returnself:_addListArgs({...}, ORDER_BY) end
localfunctionorReplace(self) self._or=OR_REPLACEreturnselfend
localfunctionorRollback(self) self._or=OR_ROLLBACKreturnselfend
localfunctionorAbort(self) self._or=OR_ABORTreturnselfend
localfunctionorFail(self) self._or=OR_FAILreturnselfend
localfunctionorIgnore(self) self._or=OR_IGNOREreturnselfend
localfunctioneq(col, val) returnBinary(EQ, col, val) end
localfunctioneqAll(col, val) returnBinary(EQ, col, val, 'ALL ') end
localfunctioneqAny(col, val) returnBinary(EQ, col, val, 'ANY ') end
localfunctionnotEq(col, val) returnBinary(NOT_EQ, col, val) end
localfunctionnotEqAll(col, val) returnBinary(NOT_EQ, col, val, 'ALL ') end
localfunctionnotEqAny(col, val) returnBinary(NOT_EQ, col, val, 'ANY ') end
localfunctionlt(col, val) returnBinary(LT, col, val) end
localfunctionltAll(col, val) returnBinary(LT, col, val, 'ALL ') end
localfunctionltAny(col, val) returnBinary(LT, col, val, 'ANY ') end
localfunctionle(col, val) returnBinary(LE, col, val) end
localfunctionleAll(col, val) returnBinary(LE, col, val, 'ALL ') end
localfunctionleAny(col, val) returnBinary(LE, col, val, 'ANY ') end
localfunctiongt(col, val) returnBinary(GT, col, val) end
localfunctiongtAll(col, val) returnBinary(GT, col, val, 'ALL ') end
localfunctiongtAny(col, val) returnBinary(GT, col, val, 'ANY ') end
localfunctionge(col, val) returnBinary(GE, col, val) end
localfunctiongeAll(col, val) returnBinary(GE, col, val, 'ALL ') end
localfunctiongeAny(col, val) returnBinary(GE, col, val, 'ANY ') end
localfunctioninto(self, tbl) self._into=tblreturnselfend
localfunctionintoTemp(self, tbl) self._into_tmp=truereturnself:into(tbl) end
localfunctionforUpdate(self, ...)
self.for_update=true
returnself:_addListArgs({...}, FOR_UPDATE_TBLS)
end
localfunctionobj2equals(obj, expressions)
forkeyinpairs(obj) doinsert(expressions, eq(key, obj[key])) end
returnexpressions
end
--
--
--
--
--
functionStatement:__init(type)
self.type=type
end
functionStatement:clone()
localctor
ifself:is(Select) thenctor=Select
elseifself:is(Insert) thenctor=Insert
elseifself:is(Update) thenctor=Update
elseifself:is(Delete) thenctor=Deleteend
localstmt=ctor:extends(self)
ifstmt._wherethenstmt._where=clone(stmt._where) end
ifstmt.joinsthenstmt.joins=clone(stmt.joins) end
ifstmt._valuesthenstmt._values=Hash(stmt._values.index) end
returnstmt
end
functionStatement:toParams(opts)
ifself.prev_stmtthen
returnself.prev_stmt:toParams(opts)
end
opts=optsor {}
opts.parameterized, opts.values, opts.value_ix=
(opts.parameterizedortrue), (opts.valuesor {}), (opts.value_ixor1)
localsql, result= (self..opts), {}
localvv, vk=next(opts.values)
ifTABLE==type(vk) then
for_, keyinpairs(opts.values) do
insert(result, (key.isandtostring(key) orconcat(key, COMA)))
end
else
fori=1, #opts.valuesdo
insert(result, opts.values[i])
end
end
return {text=sql, values=result}
end
functionStatement:__tostring()
returnself:__concat({})
end
functionStatement:__concat(opts)
ifself.prev_stmtthenreturntostring(self.prev_stmt)
elsereturnself:_toString(opts) end
end
functionStatement:_exprToString(opts, expr)
expr= (exprorself._where)
expr.parens=false
ifexpr.expressionsand#expr.expressions==1then
expr.expressions[1].parens=false
end
returnformat(patterns.SSPACE, (expr..opts))
end
functionStatement:_add(arr, name)
ifnotself[name] thenself[name] = {} end
ifTABLE==type(arr) andnotarr.isthen
fori=1, #arrdoinsert(self[name], arr[i]) end
else
insert(self[name], arr)
end
returnself
end
functionStatement:_addListArgs(args, name)
returnself:_add(args2array(args), name)
end
functionStatement:_addExpression(args, name)
ifnotself[name] thenself[name] =_and() end
if#args==2andTABLE~=type(args[1]) andTABLE~=type(args[2]) or
(#args==2andargs[1].isand (args[1]:is(Sql) orargs[1]:is(Val)) or
args[2] andargs[2].isand (args[2]:is(Sql) orargs[2]:is(Val))) then
insert(self[name].expressions, eq(args[1], args[2]))
else
forkinpairs(args) do
ifis_expr(args[k]) then
insert(self[name].expressions, args[k])
else
obj2equals(args[k], self[name].expressions)
end
end
end
returnself
end
functionStatement:_addJoins(args, _type)
ifnotself.joinsthenself.joins= {} end
localtbls, on
ifTABLE==type(args[2]) then
tbls, on= {args[1]}, args[2]
else
tbls=args2array(args)
end
for_, tblinpairs(tbls) do
tbl=self:expandAlias(tbl)
localleft_tbl=self.last_joinor (self.tblsandself.tbls[#self.tbls])
insert(self.joins, Join(tbl, left_tbl, on, _type))
self.joins[#self.joins]._joinCriteria=self._joinCriteria
end
self.last_join=tbls[#tbls]
returnself
end
functionStatement:expandAlias(tbl)
returnself._aliases[tbl] andformat(patterns.SSPACES, self._aliases[tbl], tbl) ortbl
end
--
--
--
--
--
Select=class(Statement)
Select.__name='Select'
functionSelect:__init(...)
self.super.__init(self, _SELECT)
returnself:select(...)
end
functionSelect:select(...)
returnself:_addListArgs({...}, 'cols')
end
functionSelect:distinct(...)
self._distinct=true
returnself:_addListArgs({...}, 'cols')
end
functionSelect:crossJoin(...)
returnself:_addJoins({...}, 'CROSS')
end
functionSelect:on(...)
localon=...
locallast_join, arr=self.joins[#self.joins]
ifis_expr(on) then
last_join.on=on
else
last_join.on=last_join.onor {}
localargs=args2object({...})
fork,vinpairs(args) do
last_join.on[k] =v
end
end
returnself
end
functionSelect:having(...)
returnself:_addExpression({...}, _HAVING)
end
functionSelect:limit(count)
self._limit=count
returnself
end
functionSelect:offset(count)
self._offset=count
returnself
end
functionSelect:noWait()
self.no_wait=true
returnself
end
functionSelect:from(...)
localarr=args2array({...})
fori=1, #arrdo
arr[i] =self:expandAlias(arr[i])
end
returnself:_add(arr, TBLS)
end
Select.into=into
Select.intoTable=into
Select.intoTemp=intoTemp
Select.intoTempTable=intoTemp
Select.forUpdate=forUpdate
Select.forUpdateOf=forUpdate
Select.join=innerJoin
Select.innerJoin=innerJoin
Select.leftJoin=leftJoin
Select.leftOuterJoin=leftJoin
Select.rightJoin=rightJoin
Select.rightOuterJoin=rightJoin
Select.fullJoin=fullJoin
Select.fullOuterJoin=fullJoin
Select.where=where
Select._and=where
Select.group=group
Select.groupBy=group
Select.order=order
Select.orderBy=order
forkey, valueinpairs(compounds) do
Select[key] =function(self, ...)
localstmts, stmt=args2array({...})
ifTABLE==type(stmts) and#stmts==0andnotstmts.isthen
stmt=Select()
stmt.prev_stmt, stmt._aliases, stmt._views, stmt._joinCriteria=
self, self._aliases, self._views, self._joinCriteria
stmts= {stmt}
end
self:_add(stmts, '_' ..key)
ifstmtthen
returnstmt
end
returnself
end
end
functionSelect:joinView(view, on, _type)
localalias, view_name=get_alias(view), get_table(view)
localview=self._views[view_name]
localtbl=format(patterns.SSPACES, get_table(view.tbls[1]), alias)
localnew_aliases= {[get_alias(view.tbls[1])] =alias}
self:_addJoins({tbl, (onor {})}, (_typeandupper(_type) or'INNER'))
ifview.joinsthen
localj_alias, j_tbl, _tbl=EMPTY, EMPTY, EMPTY
fori=1, #view.joinsdo
j_alias, j_tbl=get_alias(view.joins[i].tbl), get_table(view.joins[i].tbl)
new_aliases[j_alias] =format(patterns.S_S, alias, j_alias)
_tbl=format(patterns.SSPACESSUNDERS, j_tbl, alias, j_alias)
localjoin=
Join(_tbl, view.joins[i].left_tbl, view.joins[i].on, view.joins[i].type)
join._joinCriteria=self._joinCriteria
ifnotjoin.onthenjoin.on=join:autoGenerateOn(_tbl, join.left_tbl) end
insert(self.joins, join)
join.on=namespaced_on(join.on, new_aliases)
end
end
ifview._wherethen
fori=1, #view._where.expressionsdo
localexpr=view._where.expressions[i]:extends()
convert_expr(expr, new_aliases)
self:where(expr)
end
end
returnself
end
functionSelect:_toString(opts)
localcols, res= (#self.cols>0andself.colsor {STAR}), {SELECT}
ifself._distincttheninsert(res, 'DISTINCT ') end
handles(res, cols, opts)
ifself._intothen
insert(res, format(patterns.INTO_SS, (self._into_tmpandTEMPorEMPTY), self._into))
end
ifself.tblsthen
insert(res, format(patterns.FROM_S, concat(self.tbls, COMA_SPC)))
end
ifself.joinsthen
fori=1, #self.joinsdo
insert(res, format(patterns.SSPACE, (self.joins[i] ..opts)))
end
end
ifself._wherethen
insert(res, format(patterns.WHERE_S, self:_exprToString(opts)))
end
ifself.group_bythen
insert(res, GROUPBY)
handles(res, self.group_by, opts)
end
ifself._havingthen
insert(res, format(patterns.HVG_S, self:_exprToString(opts, self._having)))
end
ifself.order_bythen
insert(res, ORDERBY)
handles(res, self.order_by, opts)
end
ifself._limitthen
insert(res, format(patterns.LIMIT_S, tostring(self._limit)))
end
ifself._offsetthen
insert(res, format(patterns.OFFSET_S, tostring(self._offset)))
end
forkey, valueinpairs(compounds) do
localstmt=self['_' ..key]
ifstmtand#stmt>0then
insert(res, value)
insert(res, SPACE)
fori=1, (#stmt-1) do
insert(res, format(patterns.SSPACESSSPACE, stmt[i]:_toString(opts), value))
end
insert(res, stmt[#stmt]:_toString(opts))
insert(res, SPACE)
end
end
ifself.for_updatethen
insert(res, FOR_UPDATE)
ifself.for_update_tblsthen
insert(res, concat(self.for_update_tbls, COMA_SPC))
insert(res, SPACE)
end
ifself.no_waittheninsert(res, 'NO WAIT ') end
end
returnsub(concat(res), 1, -2)
end
--
--
--
--
--
Insert=class(Statement)
Insert.__name='Insert'
functionInsert:__init(expansions, tbl, ...)
self._aliases=expansions
self.super.__init(self, 'insert')
returnself:into(tbl, ...)
end
Insert.orReplace=orReplace
Insert.orRollback=orRollback
Insert.orAbort=orAbort
Insert.orFail=orFail
Insert.orIgnore=orIgnore
functionInsert:into(tbl, ...)
iftblthenself.tbls= {self:expandAlias(tbl)} end
localvalues= {...}
if#values>0then
ifSTRING==type(values[1]) or
(is_array(values[1]) andSTRING==type(values[1][1]))
then
self._split_keys_vals_mode, self._values=true, Hash(args2array({...}))
else
self:values(...)
end
end
returnself
end
functionInsert:values(...)
localvalues, check=args2array({...}), 0
ifself._split_keys_vals_modeand#values>0then
ifTABLE==type(values[1]) then
check_same_len(#self._values, #values[1])
fori=1, #values[1] doself._values.set(self._values, i, {values[1][i]}) end
fori=2, #valuesdo
check_same_len(#self._values, #values[i])
fork=1, #values[i] doself._values.add(self._values, k, values[i][k]) end
end
else
check_same_len(#self._values, #values)
fork=1, #valuesdoself._values.set(self._values, k, values[k]) end
end
gotoreturning
end
self._values=self._valuesorHash()
ifTABLE==type(values[1]) andTABLE==type(values[1][1]) then
fork,vinpairs(values[1][1]) doself._values[k] = {v} end
fori=2, #values[1] do
check_same_len(#self._values, #values[1][i])
fork,vinpairs(values[1][i]) doself._values.add(self._values, k, v) end
end
else
fork,vinpairs((values[1] orvalues)) doself._values[k] =vend
end
::returning::
returnself
end
functionInsert:select(...)
self._select=Select(...)
self._select._aliases, self._select._views, self._select._joinCriteria=
self._aliases, self._views, self._joinCriteria
self._select.prev_stmt=self
returnself._select
end
functionInsert:returning(...)
returnself._addListArgs({...}, _RETURNING)
end
functionInsert:_toString(opts)
localres= {'INSERT '}
ifself._ortheninsert(res, self._or) end
insert(res, format(patterns.INTO_S_P, concat(self.tbls, COMA_SPC)))
handles(res, self._values, opts, false, false, nil, EMPTY)
insert(res, PAR_SPC)
ifself._selectthen
insert(res, self._select:_toString(opts))
insert(res, SPACE)
else
insert(res, VALS_P)
handles(res, self._values, opts, false, true, nil, EMPTY)
insert(res, PAR_SPC)
end
ifself._returningthen
insert(res, RETURNING)
handles(res, self._returning, opts)
end
returnsub(concat(res), 1, -2)
end
--
--
--
--
--
Update=class(Statement)
Update.__name='Update'
functionUpdate:__init(expansions, tbl, ...)
self._aliases=expansions
self.super.__init(self, _UPDATE)
self.tbls= {self:expandAlias(tbl)}
if...thenself:set(...) end
returnself
end
Update.orReplace=orReplace