-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsqlpp.lua
1825 lines (1582 loc) · 52.1 KB
/
sqlpp.lua
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
--[=[
SQL preprocessor, postprocessor and generator API.
Written by Cosmin Apreutesei. Public Domain.
Written as a generic wrapper over your favorite SQL connector library,
its purpose is to give SQL more power, unlike ORMs which take away even
the one it has. So definitely not for OOP-heads. If you like SQL though,
sqlpp will help you make dynamic queries, generate update queries for you
from structured data, extract database schema into a structured format
and even generate DDL SQL from schema diffs so you can automate your
migrations.
Preprocessor features
* `#if #elif #else #endif` conditionals
* `$foo` text substitutions
* `$foo(args...)` macro substitutions
* `?` and `:foo` quoted-value substitutions
* `??` and `::foo` quoted-name substitutions
* `{foo}` unquoted substitutions
* symbol (object) substitutions (for encoding `null` and `default`)
* removing double-dash comments (for [mysql])
Backends & writing your own
SQLpp currently supports MySQL and Tarantool clients.
Writing a backend for your favorite RDBMS is easy. At the minimum you have
to show sqlpp how to connect to your engine and how to quote strings,
and if you want schema diffs you have to write the queries to extract metadata
from information tables. Use `sqlpp_mysql.lua` or `sqlpp_tarantoo.lua`
as a reference for how to do all that.
INSTANCING
sqlpp(engine) -> spp create a preprocessor instance
spp.connect(options) -> cmd connect to a database
spp.use(rawconn) -> cmd use an existing connection
cmd:use(db, [schema], [opt]) switch current database
cmd:close() close connection
SQL FORMATTING
cmd:sqlname(s) -> s format name: `'foo.bar'` -> `'`foo`.`bar`'`
cmd:esc(s) -> s escape a string to be used inside SQL string literals
cmd:sqlval(v[, field]) -> s format a Lua value as an SQL literal
cmd:sqlrows(rows[, indent]) -> s format `{{a,b},{c,d}}` as `'(a, b), (c, d)'`
spp.tsv_rows(opt, s) -> rows parse a tab-separated list into a list of rows
cmd:sqltsv(opt, s) -> s parse a tab-separated list and format with `sqlrows()`
cmd:sqldiff(diff) -> {sql1,...} format a [schema] diff object
SQL PREPROCESSING
cmd:sqlquery(sql, ...) -> sql, names preprocess a query
cmd:sqlprepare(sql, ...) -> sql, names preprocess a query but leave `?` placeholders
cmd:sqlparams(sql, [t]) -> sql, names substitute named params
cmd:sqlargs(sql, ...) -> sql substitute positional args
QUERY EXECUTION
cmd:query([opt], sql, ...) -> rows, cols query with preprocessing
opt.parse `false` to skip preprocessing
opt.MYSQL_OPTION option to pass to mysql query()
cmd:first_row([opt], sql, ...) -> rows, cols query and return the first row
cmd:first_row_vals([opt], sql, ...) -> v1,... query and return the first row unpacked
cmd:each_row([opt], sql, ...) -> iter query and iterate rows
cmd:each_row_vals([opt], sql, ...)-> iter query and iterate rows unpacked
cmd:each_group(col, [opt], sql, ...) -> iter query, group by col and iterate groups
cmd:prepare([opt], sql, ...) -> stmt prepare query
opt.parse `false` to skip preprocessing
opt.MYSQL_OPTION option to pass to mysql prepare
stmt:exec(...) -> rows, cols execute prepared query
stmt:first_row(...) -> rows, cols query and return the first row
stmt:each_row(...) -> iter query and iterate rows
stmt:each_row_vals(...)-> iter query and iterate rows unpacked
stmt:each_group(col, ...) -> iter query, group by col and iterate groups
cmd:atomic(fn, ...) -> ... call a function inside a transaction
cmd:has_ddl(sql) -> true|false check if an expanded query has DDL commands in it
cmd:on_table_changed(f) call f(sch, tbl) on update queries
GROUPING
spp.groups(col, rows|groups) -> groups group rows
spp.each_group(col, rows|groups) -> iter group rows and iterate groups
SCHEMA REFLECTION
cmd:dbs() -> {db1,...} list databases
cmd:tables([db]) -> {tbl1,...} list tables in (current) db
cmd:table_def(['[DB.]TABLE']) -> t get table definition from `cmd.schemas.DB`
cmd:extract_schema([db], [opt]) -> sc extract db [schema]
opt.all extract all
opt.indexes extract indexes (mysql)
opt.checks extract check constriants (mysql)
opt.views extract views (mysql)
opt.triggers extract triggers (mysql)
opt.functions extract functions (mysql)
opt.procs extract stored procs (mysql)
spp.empty_schema() -> sc create an empty [schema]
cmd.schemas.DB = sc set schema manually for a database
DDL COMMANDS
cmd:create_db(name, [charset], [collation]) create database
cmd:drop_db(name, [opt]) drop database
cmd:rename_db(old_db, new_db, [opt]) rename database
cmd:rename_user(old_user, new_user, [opt] rename user
cmd:drop_user(user, [opt]) drop user
cmd:grant_user(user, db, [opt]) grant user access to a db
cmd:sync_schema(source_schema) sync schema with a source schema
MDL COMMANDS
cmd:insert_row(tbl, vals, [col_map]) insert a row
cmd:insert_or_update_row(tbl, vals, [col_map], [compact], [opt]) insert or update row
cmd:insert_rows(tbl, rows, [col_map], [opt]) insert rows with one query
cmd:update_row(tbl, vals, col_map, [scurity_filter], [opt]) update row
cmd:delete_row(tbl, vals, col_map, [scurity_filter], [opt]) delete row
MODULE SYSTEM
function sqlpp_package.NAME(spp) end extend the preprocessor with a module
spp.import(module) import sqlpp module
MODULES
require'sqlpp_mysql' make the MySQL module available
spp.import'mysql' load the MySQL module into spp
EXTENDING THE PREPROCESSOR
spp.keyword.KEYWORD -> symbol get a symbol for a keyword
spp.keywords[SYMBOL] = keyword set a keyword for a symbol
spp.subst'NAME text...' create a substitution for `$NAME`
function spp.macro.NAME(self, ...) end create a macro to be used as `$NAME(...)`
## Preprocessor
### sqlpp() -> spp
Create a preprocessor instance. Modules can be loaded into the instance
with `spp.import()`.
The preprocessor doesn't work all by itself, it needs a database-specific
module to implement the particulars of your database engine. Currently only
the MySQL engine is implemented in the module `sqlpp_mysql`.
### spp.connect(options) -> cmd` <br> `spp.use(rawconn) -> cmd
Make a command API based on a low-level query execution API.
Options are passed-through to the connector. Additional option:
* `schema`: set a [schema] for the chosen database.
### cmd:sqlquery(sql, ...) -> sql, names
Preprocess a SQL query, including hashtag conditionals, macro substitutions,
quoted and unquoted param substitutions, symbol substitutions and removing
comments.
Named args (called params, i.e. `:foo` and `::foo`) are looked up in vararg#1
if it's a table but positional args (called args, i.e. `?` and `??`) are
looked up in `...`. Because of this, you're not allowed to mix named args
and positional args in the same query otherwise vararg#1 would be used both
as the table to look-up named args from, and as the first positional arg.
Notes on value expansion:
* no expansion is done inside string literals so it's safe to do multiple
preproceessor passes (i.e. preprocess partially-preprocessed queries).
* list values of form `{foo, bar}` expand to `foo, bar`, which is mostly
useful for `in (?)` expressions (also because an empty list `{}` expands
to `null` instead of empty string which would result in `in ()` which is
invalid syntax in MySQL).
* never use dots in database names, table names or column names,
or `sqlname()` won't work (other SQL tools won't work either).
* avoid using multi-line comments except for optimizer hints because
the preprocessor does not currently know to avoid parsing inside them
as it does with string literals (OTOH this allows you to parametrize
optimizer hints).
### spp.define_symbol(sql, [sym]) -> sym
### spp.symbol_for.SQL -> sym
Define a symbol object for an SQL keyword. Symbols are used to encode
special SQL values in queries, for instance using `spp.symbol_for.default`
as a parameter value will be substituted by the keyword `default`.
Set a keyword to be substituted for a symbol object. Since symbols can be
any Lua objects, you can add a symbol from an external library to be used
directly in SQL parameters. For instance:
spp.define_symbol('null', require'cjson'.null)
This enables using JSON null values as SQL parameters.
### spp.subst'NAME text...'
Create an unquoted text substitution for `$NAME`.
### function spp.macro.NAME(self, ...) end
Create a macro to be used as `$NAME(...)`. Param args are expanded before
macros.
## Query execution
### Field metadata
Select queries return `cols` as a second return value which contains the
metadata for the fields of the result set. For fields that can be traced
back to their origin tables, the metadata will be augmented with information
from the schema at `cmd.schemas.DB` which you have to assign yourself.
The schema can be defined manually or it can be taken from the server.
#### Example
```lua
cmd.schemas[cmd.db] = cmd:extract_schema()
```
]=]
if not ... then require'sqlpp_mysql_test'; return end
require'glue'
local
assert, type =
assert, type
local sqlpp_package = {}
function issqlpp(v)
local mt = getmetatable(v)
return mt and rawget(mt, 'issqlpp') or false
end
function _G.sqlpp(init)
assert(init, 'engine module name or engine init function expected')
if type(init) == 'string' then
init = require('sqlpp_'..init).init_spp
end
local spp = {issqlpp = true}
setmetatable(spp, spp)
local cmd = {spp = spp, type = 'sqlpp', debug_prefix = 'Q'}
spp.command = cmd
local avoid_code = string.byte'?' --because we're gonna match '?' alone later
local function mark(n)
assert(n <= 254, 'too many substitutions')
local n = n ~= avoid_code and n or 255
return '\0'..char(n)
end
--parsing string literals -------------------------------------------------
local function collect_strings(s, repl)
local i = 1
local t = {}
::next_string::
local i1 = s:find("'", i, true)
if i1 then --string literal start
local j = i1 + 1
::again::
local i2 = s:find("'", j, true) --potential string literal end
if i2 then
if i2 > j and s:sub(i2-1, i2-1) == '\\' then --skip over \'
j = i2 + 1
goto again
elseif s:sub(i2+1, i2+1) == "'" then --skip over ''
j = i2 + 2
goto again
else
add(t, s:sub(i, i1 - 1))
add(repl, s:sub(i1, i2))
add(t, mark(#repl))
i = i2 + 1
goto next_string
end
else
error('string literal not closed:\n\n'..s)
end
else
add(t, s:sub(i))
end
return cat(t)
end
--conditional compilation -------------------------------------------------
--Process #if #elif #else #endif conditionals.
--Also normalize newlines and remove single-line comments which the mysql
--client protocol cannot parse. Multiline comments are not removed since
--they can be used for optimizer hints.
local globals_mt = {__index = _G}
local function parse_expr(s, params)
local f = assert(loadstring('return '..s))
params = update({}, params) --copy it so we alter it
setmetatable(params, globals_mt)
setfenv(f, params)
return f()
end
local function spp_ifs(sql, params)
local t = {}
local state = {active = true}
local states = {state}
local level = 1
for line in sql:lines() do
local s, expr = line:match'^%s*#([%w_]+)(.*)'
if s == 'if' then
level = level + 1
if state.active then
local active = parse_expr(expr, params) and true or false
state = {active = active, activated = active}
else
state = {active = false, activated = true}
end
states[level] = state
elseif s == 'else' then
assert(level > 1, '#else without #if')
assert(not state.done, '#else after #else')
if not state.activated then
state.active = true
state.activated = true
else
state.active = false
end
state.done = true
elseif s == 'elif' then
assert(level > 1, '#elif without #if')
assert(not state.done, '#elif after #else')
if not state.activated and parse_expr(expr, params) then
state.active = true
state.activated = true
else
state.active = false
end
elseif s == 'endif' then
assert(level > 1, '#endif without #if')
states[level] = nil
level = level - 1
state = states[level]
elseif state.active then
line = line:gsub('%-%-.*', '') --remove `-- ...` comments
line = line:gsub('#.*', '') -- remove `# ...` comments
if trim(line) ~= '' then
add(t, line)
end
end
end
assert(level == 1, '#endif missing')
return cat(t, '\n')
end
--quoting -----------------------------------------------------------------
local symbols = {} --{sym -> sql}
spp.symbol_for = {} --{keyword -> sym}
function spp.define_symbol(sql, sym)
assertf(not spp.symbol_for[sql], 'symbol already defined for `%s`', sql)
sym = sym or {sql}
symbols[sym] = sql
spp.symbol_for[sql] = sym
return sym
end
function cmd:sqlstring(s)
return "'"..self:esc(s).."'"
end
function cmd:sqlnumber(x) --stub
return fmt('%0.17g', x) --max precision, min length.
end
function cmd:sqlboolean(v) --stub
return tostring(v)
end
cmd.allow_quoting = false
function cmd:check_allow_quoting(s)
assertf(self.allow_quoting, 'use of reserved word: "%s"', s)
return true
end
--NOTE: don't use dots in db names, table names and column names!
cmd.sqlname_quote = '"'
function cmd:sqlname(s)
s = s and trim(s) or ''
assert(s ~= '', 'sql name missing')
local q = self.sqlname_quote
if s:sub(1, 1) == q then --already quoted
return s
end
if not s:find('.', 1, true) then
return self:needs_quoting(s) and self:check_allow_quoting(s) and q..s..q or s
end
self:needs_quoting'x' --avoid yield accross C-call boundary :rolleyes:
return s:gsub('[^%.]+', function(s)
return self:needs_quoting(s) and self:check_allow_quoting(s) and q..trim(s)..q or s
end)
end
function cmd:sqlval(v, field)
local to_sql = field and field[spp.TO_SQL]
if v == nil then
return 'null'
elseif to_sql then
return to_sql(v, field, self)
elseif type(v) == 'number' then
return self:sqlnumber(v)
elseif type(v) == 'string' then
return self:sqlstring(v)
elseif type(v) == 'boolean' then
return self:sqlboolean(v)
elseif symbols[v] then
return symbols[v]
elseif type(v) == 'table' then
if #v > 0 then --list: for use in `in (?)`
local t = {}
for i,v in ipairs(v) do
t[i] = self:sqlval(v, field)
end
return cat(t, ', ')
else --empty list: good for 'in (?)' but NOT GOOD for `not in (?)` !!!
return 'null'
end
else
error('invalid value ' .. v)
end
end
function cmd:binval(v, field)
local to_bin = field and field.TO_BIN
if to_bin then
return to_bin(v)
else
return v
end
end
--macros ------------------------------------------------------------------
local defines = {}
function spp.subst(def) --'name type'
local name, val = def:match'([%w_]+)%s+(.*)'
assertf(not defines[name], 'macro already defined: $%s', name)
defines[name] = val
end
spp.macro = {}
local function macro_arg(self, arg, t)
local k = arg:match'^:([%w_][%w_%:]*)'
if k then --unparsed param expansion.
return t[k]
else
local s = arg:match'^"([^"]+)"$'
if s then --verbatim arg, see $filter()
return s
else --parsed param expansion.
return self:sqlparams(arg, t)
end
end
end
local function macro_subst(self, name, args, t)
local macro = assertf(spp.macro[name], 'undefined macro: $%s()', name)
args = args:sub(2,-2)..','
local dt = {}
for arg in args:gmatch'([^,]+)' do
arg = trim(arg)
dt[#dt+1] = macro_arg(self, arg, t) --expand params in macro args *unquoted*!
end
return macro(self, unpack(dt))
end
--named params & positional args substitution -----------------------------
function cmd:sqlparams(sql, vals)
self:needs_quoting'x' --avoid yield accross C-call boundary :rolleyes:
local names = {}
return sql:gsub('::([%w_]+)', function(k) -- ::col, ::table, etc.
add(names, k)
return self:sqlname(vals[k])
end):gsub(':([%w_][%w_%:]*)', function(k) -- :foo, :foo:old, etc.
add(names, k)
return self:sqlval(vals[k])
end), names
end
function cmd:sqlargs(sql, vals) --not used
self:needs_quoting'x' --avoid yield accross C-call boundary :rolleyes:
local i = 0
return (sql:gsub('%?%?', function() -- ??
i = i + 1
return self:sqlname(vals[i])
end):gsub('%?', function() -- ?
i = i + 1
return self:sqlval(vals[i])
end))
end
--preprocessor ------------------------------------------------------------
local function args_params(...)
local args = select('#', ...) > 0 and pack(...) or empty
local params = type((...)) == 'table' and (...) or empty
return args, params
end
local function sqlquery(self, prepare, sql, ...)
self:needs_quoting'x' --avoid yield accross C-call boundary :rolleyes:
local args, params = args_params(...)
if not sql:find'[#$:?{]' and not sql:find'%-%-' then --nothing to see here
return sql, empty
end
local sql = spp_ifs(sql, params) --#if ... #endif
--We can't just expand values on-the-fly in multiple passes of gsub()
--because each pass would result in a partially-expanded query with
--string literals inside so the next pass would parse inside those
--literals. To avoid that, we replace expansion points inside the query
--with special markers and on a second step we replace the markers
--with the expanded values.
--step 1: find all expansion points and replace them with a marker
--that string literals can't contain.
local repl = {}
--collect string literals
sql = collect_strings(sql, repl)
--collect macros
local macros = {}
sql = sql:gsub('$([%w_]+)(%b())', function(name, args)
add(macros, name)
add(macros, args)
return mark(#repl + #macros / 2)
end) --$foo(arg1,...)
for i = 1, #macros, 2 do
local m_name, m_args = macros[i], macros[i+1]
add(repl, macro_subst(self, m_name, m_args, params) or '')
end
--collect defines
sql = sql:gsub('$([%w_]+)', function(name)
add(repl, assertf(defines[name], '$%s is undefined', name))
return mark(#repl)
end) --$foo
local param_names = {}
--collect verbatims
sql = subst(sql, function(name)
add(param_names, name)
add(repl, assertf(params[name], '{%s} is missing', name))
return mark(#repl)
end) --{foo}
local param_map = prepare and {}
--collect named params
sql = sql:gsub('::([%w_]+)', function(k) -- ::col, ::table, etc.
add(param_names, k)
add(repl, self:sqlname(params[k]))
return mark(#repl)
end):gsub(':([%w_][%w_%:]*)', function(k) -- :foo, :foo:old, etc.
add(param_names, k)
if prepare then
add(param_map, k)
add(repl, '?')
else
add(repl, opt and opt.prepare and '?' or self:sqlval(params[k]))
end
return mark(#repl)
end)
--collect indexed params
local i = 0
sql = sql:gsub('%?%?', function() -- ??
i = i + 1
add(repl, self:sqlname(args[i]))
return mark(#repl)
end):gsub('%?', function() -- ?
i = i + 1
if prepare then
add(param_map, i)
add(repl, '?')
else
add(repl, self:sqlval(args[i]))
end
return mark(#repl)
end)
assert(not (#param_names > 0 and i > 0),
'both named params and positional args found')
--step 3: expand markers.
sql = sql:gsub('%z(.)', function(ci)
local i = string.byte(ci)
if i == 255 then i = avoid_code end
return repl[i]
end)
return sql, param_names, param_map
end
function cmd:sqlquery(sql, ...)
return sqlquery(self, nil, sql, ...)
end
function cmd:sqlprepare(sql, ...)
return sqlquery(self, true, sql, ...)
end
local function map_params(stmt, cmd, param_map, ...)
local args, params = args_params(...)
local t = {}
for i,k in ipairs(param_map) do
local v
if type(k) == 'number' then --arg
v = args[k]
else --param
v = params[k]
end
t[i] = cmd:binval(v, stmt.params[i])
t.n = i
end
return t
end
--schema diff formatting --------------------------------------------------
local function ix_cols(self, t)
local dt = {}
for i,s in ipairs(t) do
dt[i] = self:sqlname(s) .. (t.desc and t.desc[i] and ' desc' or '')
end
return cat(dt, ', ')
end
function cmd:sqlcol(fld, cf)
return _('%-26s %-14s %-16s %s', self:sqlname(fld.col), self:sqltype(fld),
self:sqlcol_flags(fld) or '',
cf ~= nil and (cf == false and 'first' or 'after '..self:sqlname(cf)) or ''
)
end
function cmd:sqlpk(pk, tbl_name)
return _('primary key (%s)', ix_cols(self, pk))
end
function cmd:sqluk(name, uk)
return _('constraint %-20s unique (%s)', self:sqlname(name), ix_cols(self, uk))
end
function cmd:sqlix(name, ix, tbl_name)
return _('index %-20s on %s (%s)',
self:sqlname(name), self:sqlname(tbl_name), ix_cols(self, ix))
end
function cmd:sqlfk(name, fk)
assertf(fk.ref_cols, 'fk not resolved: %s', name)
local ondelete = fk.ondelete or 'no action'
local onupdate = fk.onupdate or 'no action'
local a1 = ondelete ~= 'no action' and ' on delete '..ondelete or ''
local a2 = onupdate ~= 'no action' and ' on update '..onupdate or ''
return _('constraint %-20s foreign key (%s) references %s (%s)%s%s',
self:sqlname(name), ix_cols(self, fk.cols), self:sqlname(fk.ref_table),
ix_cols(self, fk.ref_cols), a1, a2)
end
function cmd:sqltrigger(tbl_name, name, tg)
local BODY = spp.engine..'_body'
return tg[BODY] and _('trigger %s %s %s on %s for each row\n%s',
self:sqlname(name), tg.when, tg.op, self:sqlname(tbl_name), tg[BODY])
end
function cmd:sqlproc(name, proc)
local BODY = spp.engine..'_body'
if not proc[BODY] then return end
local args = {}; for i,arg in ipairs(proc.args) do
args[i] = _('%s %s', arg.mode or 'in', self:sqlcol(arg))
end
return _('procedure %s (\n\t%s\n)\n%s', name, cat(args, ',\n\t'), proc[BODY])
end
function cmd:sqlcheck(name, ck)
local BODY = spp.engine..'_body'
local s = ck[BODY] or ck.body
return s and _('constraint %-20s check (%s)', self:sqlname(name), s)
end
function cmd:sqltable(t)
local dt = {}
for i,fld in ipairs(t.fields) do
dt[i] = self:sqlcol(fld)
end
if t.pk then
add(dt, self:sqlpk(t.pk, t.name))
end
if t.uks then
for name, uk in sortedpairs(t.uks) do
add(dt, self:sqluk(name, uk))
end
end
if t.checks then
for name, ck in sortedpairs(t.checks) do
add(dt, self:sqlcheck(name, ck))
end
end
return _('(\n\t%s\n)', cat(dt, ',\n\t'))
end
function cmd:sqldiff(diff)
assertf(diff.engine == spp.engine,
'diff engine is `%s`, expected `%s`', diff.engine, spp.engine)
local dt = {}
local function P(...) add(dt, _(...)) end
local function N(s) return self:sqlname(s) end
local BODY = spp.engine..'_body'
local fk_bin = {} --{fk->true}
--gather fks pointing to tables that need to be removed.
if diff.tables and diff.tables.remove then
for _, tbl in pairs(diff.tables.remove) do
if tbl.fks then
for _, fk in pairs(tbl.fks) do
if diff.tables.remove[fk.ref_table] then
fk_bin[fk] = true
end
end
end
end
end
if diff.tables and diff.tables.update then
for _, d in pairs(diff.tables.update) do
--gather fks pointing to fields that need to be removed.
if d.fields and d.fields.remove then
for col in pairs(d.fields.remove) do
for _, tbl in pairs(diff.old_schema.tables) do
if tbl.fks then
for fk_name, fk in pairs(tbl.fks) do
for _, ref_col in ipairs(fk.ref_cols) do
if ref_col == col then
fk_bin[fk] = true
end
end
end
end
end
end
end
--gather fks that need to be explicitly removed.
if d.fks and d.fks.remove then
for _,fk in pairs(d.fks.remove) do
fk_bin[fk] = true
end
end
end
end
--drop gathered fks.
for fk in sortedpairs(fk_bin, function(fk1, fk2) return fk1.name < fk2.name end) do
P('alter table %-16s drop %-16s %s', N(fk.table), 'foreign key', N(fk.name))
end
--drop procs.
if diff.procs and diff.procs.remove then
for proc_name, proc in sortedpairs(diff.procs.remove) do
if proc[BODY] then
P('drop %-16s %s', 'procedure', N(proc_name))
end
end
end
--drop tables.
if diff.tables and diff.tables.remove then
for tbl_name in sortedpairs(diff.tables.remove) do
P('drop table %s', N(tbl_name))
end
end
local function add_or_update_rows(tbl)
if not tbl.rows then return end
local t = {}
for _, field in ipairs(tbl.fields) do
add(t, N(field.col)..' = new.'..N(field.col))
end
local set_sql = cat(t, ',\n\t')
P('insert into %s values\n%s\nas new on duplicate key update\n%s',
N(tbl.name),
self:sqlrows(tbl.rows, {n = #tbl.fields, indent = '\t'}),
set_sql)
end
--add new tables.
if diff.tables and diff.tables.add then
for tbl_name, tbl in sortedpairs(diff.tables.add) do
P('create table %-16s %s', N(tbl_name), self:sqltable(tbl))
local tgs = tbl.triggers
if tgs then
local function cmp_tg(tg1, tg2)
local a = tgs[tg1]
local b = tgs[tg2]
if a.op ~= b.op then return a.op < b.op end
if a.when ~= b.when then return a.when < b.when end
return a.pos < b.pos
end
for tg_name, tg in sortedpairs(tgs, cmp_tg) do
local s = self:sqltrigger(tbl_name, tg_name, tg)
if s then P('create %s', s) end
end
end
if tbl.ixs then
for ix_name, ix in sortedpairs(tbl.ixs) do
P('create %s', self:sqlix(ix_name, ix, tbl_name))
end
end
add_or_update_rows(tbl)
end
end
--update tables.
if diff.tables and diff.tables.update then
for old_tbl_name, d in sortedpairs(diff.tables.update) do
--remove constraints, indexes and triggers.
if d.uks and d.uks.remove then
for uk_name in sortedpairs(d.uks.remove) do
P('alter table %-16s drop %-16s %s',
N(old_tbl_name), 'key', N(uk_name))
end
end
if d.ixs and d.ixs.remove then
for ix_name in sortedpairs(d.ixs.remove) do
P('drop index %-16s on %-16s', N(ix_name), N(old_tbl_name))
end
end
if d.checks and d.checks.remove then
for ck_name in sortedpairs(d.checks.remove) do
P('alter table %-16s drop %-16s %s',
N(old_tbl_name), 'check', N(ck_name))
end
end
if d.triggers and d.triggers.remove then
for tg_name, tg in sortedpairs(d.triggers.remove) do
if tg[BODY] then P('drop trigger %-16s', N(tg_name)) end
end
end
--doing table changes in a single statement allows both column
--name changes and column position changes without conflicts,
--and also changing the pk on autoinc fields without mysql whining.
local changes = {}
if d.remove_pk then
add(changes, 'drop primary key')
end
if d.fields then
--remove columns.
if d.fields.remove then
local function cmp_by_col_pos(col1, col2)
local f1 = d.fields.remove[col1]
local f2 = d.fields.remove[col2]
return f1.col_pos < f2.col_pos
end
for col, fld in sortedpairs(d.fields.remove, cmp_by_col_pos) do
add(changes, _('drop %s', N(col)))
end
end
--add columns.
if d.fields.add then
local function cmp_by_col_pos(col1, col2)
local f1 = d.fields.add[col1]
local f2 = d.fields.add[col2]
return f1.col_pos < f2.col_pos
end
for col, fld in sortedpairs(d.fields.add, cmp_by_col_pos) do
add(changes, _('add %s', self:sqlcol(fld, fld.col_in_front)))
end
end
--modify columns (incl. changing column order).
if d.fields.update then
local function cmp_by_col_pos(col1, col2)
local d1 = d.fields.update[col1]
local d2 = d.fields.update[col2]
return d1.new.col_pos < d2.new.col_pos
end
for old_col, fd in sortedpairs(d.fields.update, cmp_by_col_pos) do
add(changes, _('change %-26s %s',
N(old_col), self:sqlcol(fd.new, fd.new.col_in_front)))
end
end
end --d.fields
if d.add_pk then
add(changes, _('add %s', self:sqlpk(d.add_pk, old_tbl_name)))
end
if #changes > 0 then
P('alter table %-16s\n\t%s',
N(old_tbl_name), concat(changes, ',\n\t'))
end
--rename table before adding constraints back.
local new_tbl_name = d.new.name
if old_tbl_name ~= new_tbl_name then
P('rename table %-16s to %-16s', N(old_tbl_name), N(new_tbl_name))
end
--add constraints, indexes and triggers.
if d.uks and d.uks.add then
for uk_name, uk in sortedpairs(d.uks.add) do
P('alter table %-16s add %s',
N(new_tbl_name), self:sqluk(uk_name, uk))
end
end
if d.ixs and d.ixs.add then
for ix_name, ix in sortedpairs(d.ixs.add) do
P('create %s', self:sqlix(ix_name, ix, new_tbl_name))
end
end
if d.checks and d.checks.add then
for ck_name, ck in sortedpairs(d.checks.add) do
P('alter table %-16s add %s',
N(new_tbl_name), self:sqlcheck(ck_name, ck))
end
end
if d.triggers and d.triggers.add then
for tg_name, tg in sortedpairs(d.triggers.add) do
local s = self:sqltrigger(new_tbl_name, tg_name, tg)
if s then P('create '..s) end
end
end
--pr(d)
--add_or_update_rows(tbl)
end
end
--add new fks for current tables.
if diff.tables and diff.tables.update then
for _, d in sortedpairs(diff.tables.update) do
local new_tbl_name = d.new.name
if d.fks and d.fks.add then
for fk_name, fk in sortedpairs(d.fks.add) do
P('alter table %-16s add %s',
N(new_tbl_name), self:sqlfk(fk_name, fk))
end
end
end
end
--add new fks for added tables.
if diff.tables and diff.tables.add then
for tbl_name, tbl in sortedpairs(diff.tables.add) do
if tbl.fks and diff.old_schema.supports_fks then
for fk_name, fk in sortedpairs(tbl.fks) do
P('alter table %-16s add %s',
N(tbl_name), self:sqlfk(fk_name, fk))
end
end
end
end
--add new procs.
if diff.procs and diff.procs.add then
for proc_name, proc in sortedpairs(diff.procs.add) do
local s = self:sqlproc(proc_name, proc)
if s then P('create %s', s) end
end
end