-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
init.lua
1449 lines (1190 loc) · 40.6 KB
/
init.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
local arrays = require "pgmoon.arrays"
local json = require "pgmoon.json"
local cjson = require "cjson"
local cjson_safe = require "cjson.safe"
local utils = require "kong.tools.utils"
local new_tab = require "table.new"
local clear_tab = require "table.clear"
local kong = kong
local ngx = ngx
local encode_base64 = ngx.encode_base64
local decode_base64 = ngx.decode_base64
local encode_array = arrays.encode_array
local encode_json = json.encode_json
local setmetatable = setmetatable
local update_time = ngx.update_time
local get_phase = ngx.get_phase
local tonumber = tonumber
local concat = table.concat
local insert = table.insert
local assert = assert
local ipairs = ipairs
local pairs = pairs
local error = error
local upper = string.upper
local pack = table.pack -- luacheck: ignore
local null = ngx.null
local type = type
local load = load
local find = string.find
local now = ngx.now
local fmt = string.format
local rep = string.rep
local sub = string.sub
local log = ngx.log
local NOTICE = ngx.NOTICE
local LIMIT = {}
local UNIQUE = {}
local function noop(...)
return ...
end
local function now_updated()
update_time()
return now()
end
-- @param name Query name, for debugging purposes
-- @param query A string describing an array of single-quoted strings which
-- contain parts of an SQL query including numeric placeholders like $0, $1, etc.
-- All parts of that array were processed via using string.format("%q"),
-- so that all newlines and quotes are preserved.
-- @return Produces a function which, given an array of arguments,
-- interpolates them in the right places and outputs a ready-to-use SQL query.
local function compile(name, query)
local c = [=====[
local v = ... or {}
return concat { ]=====]
.. query:gsub("$(%d+)", [[", v[%1], "]])
.. [=====[
}
]=====]
return load(c, "=" .. name, "t", { concat = concat })
end
local function expand(name, map)
local skip = {}
local c = { "local row = ... or {}\n" }
for _, field in ipairs(map) do
local entity = field.entity
if not skip[entity] then
skip[entity] = true
local exps = {}
local keys = {}
local nils = {}
for _, key in ipairs(map) do
if key.entity == entity then
insert(exps, 'row["' .. key.from .. '"] ~= null')
if key.to ~= "ws_id" then
insert(keys, fmt('["%s"] = row["%s"]', key.to, key.from))
end
insert(nils, fmt('row["%s"] = nil', key.from))
end
end
insert(c, (([[
if $EXPS then
row["$ENTITY"] = { $KEYS }
else
row["$ENTITY"] = null
end
$NILS
]]):gsub("$(%a+)", {
ENTITY = entity,
EXPS = concat(exps, " and "),
KEYS = concat(keys, ", "),
NILS = concat(nils, "; "),
})))
end
end
insert(c, "return row")
return load(concat(c), "=" .. name, "t", { null = null })
end
local function collapse(name, map)
local skip = {}
local c = { [[
local t = { ... }
local row = {}
for _, a in ipairs(t) do
for k, v in pairs(a) do
row[k] = v
end
end
]] }
for _, field in ipairs(map) do
local entity = field.entity
if not skip[entity] then
skip[entity] = true
local keys = {}
local nulls = {}
for _, key in ipairs(map) do
if key.entity == entity then
insert(keys, fmt('row["%s"] = row["%s"]["%s"]', key.from, entity, key.to))
insert(nulls, fmt('row["%s"] = null', key.from))
end
end
insert(c, (([[
if row["$ENTITY"] ~= nil and row["$ENTITY"] ~= null then
$KEYS
row["$ENTITY"] = nil
elseif row["$ENTITY"] == null then
$NULLS
row["$ENTITY"] = nil
end
]]):gsub("$(%a+)", {
ENTITY = entity,
KEYS = concat(keys, "; "),
NULLS = concat(nulls, "; "),
})))
end
end
insert(c, "return row")
local env = { ipairs = ipairs, pairs = pairs, null = null }
return load(concat(c), "=" .. name, "t", env)
end
local function escape_identifier(connector, identifier, field)
identifier = connector:escape_identifier(identifier)
if field and field.timestamp then
return concat { "EXTRACT(EPOCH FROM ", identifier, " AT TIME ZONE 'UTC') AS ", identifier }
end
return identifier
end
local function escape_literal(connector, literal, field)
if literal == nil or literal == null then
return "NULL"
end
if field then
if field.timestamp then
return concat { "TO_TIMESTAMP(", connector:escape_literal(tonumber(fmt("%.3f", literal))), ") AT TIME ZONE 'UTC'" }
end
if field.type == "array" or field.type == "set" then
if not literal[1] then
return connector:escape_literal("{}")
end
local elements = field.elements
if elements.timestamp then
local timestamps = {}
for i, v in ipairs(literal) do
timestamps[i] = concat { "TO_TIMESTAMP(", connector:escape_literal(tonumber(fmt("%.3f", v))), ") AT TIME ZONE 'UTC'" }
end
return encode_array(timestamps)
end
local et = elements.type
if et == "array" or et == "set" then
local el = elements
repeat
el = el.elements
et = el.type
until et ~= "array" and et ~= "set"
if et == "map" or et == "record" then
return error("postgres strategy to escape multidimensional arrays of maps or records is not implemented")
end
elseif et == "map" or et == "record" then
local jsons = {}
for i, v in ipairs(literal) do
jsons[i] = cjson.encode(v)
end
return encode_array(jsons) .. '::JSONB[]'
elseif et == "string" and elements.uuid then
return encode_array(literal) .. '::UUID[]'
end
return encode_array(literal)
elseif field.type == "map" or field.type == "record" then
return encode_json(literal)
end
end
return connector:escape_literal(literal)
end
local function toerror(strategy, err, primary_key, entity)
local schema = strategy.schema
local errors = strategy.errors
if find(err, "violates unique constraint", 1, true) then
log(NOTICE, err)
if find(err, "cache_key", 1, true) then
local keys = {}
for _, k in ipairs(schema.cache_key) do
local field = schema.fields[k]
if field.type == "foreign" and entity[k] ~= null then
keys[k] = field.schema:extract_pk_values(entity[k])
else
keys[k] = entity[k]
end
end
return nil, errors:unique_violation(keys)
end
for field_name, field in schema:each_field() do
if field.unique then
if find(err, field_name, 1, true) then
return nil, errors:unique_violation({
[field_name] = entity[field_name]
})
end
end
end
if not primary_key then
primary_key = {}
if entity then
for _, key in ipairs(schema.primary_key) do
primary_key[key] = entity[key]
end
end
end
return nil, errors:primary_key_violation(primary_key)
elseif find(err, "violates not-null constraint", 1, true) then
-- not-null constraint is currently only enforced on primary key
log(NOTICE, err)
if not primary_key then
primary_key = {}
if entity then
for _, key in ipairs(schema.primary_key) do
primary_key[key] = entity[key]
end
end
end
return nil, errors:primary_key_violation(primary_key)
elseif find(err, "violates foreign key constraint .*_ws_id_fkey") then
if schema.name == "workspaces" then
local found, e = find(err, "is still referenced from table", 1, true)
if not found then
return error("could not parse foreign key violation error message: " .. err)
end
return nil, errors:foreign_key_violation_restricted(schema.name, sub(err, e + 3, -3))
else
local ws_id = err:match("ws_id%)=%(([^)]*)%)") or "null"
return nil, errors:invalid_workspace(ws_id)
end
elseif find(err, "violates foreign key constraint", 1, true) then
log(NOTICE, err)
if find(err, "is not present in table", 1, true) then
local foreign_field_name
local foreign_schema
for field_name, field in schema:each_field() do
if field.type == "foreign" then
local escaped_identifier = escape_identifier(strategy.connector,
field.schema.name)
if find(err, escaped_identifier, 1, true) then
foreign_field_name = field_name
foreign_schema = field.schema
break
end
end
end
if not foreign_schema then
return error("could not determine foreign schema for violated foreign key error")
end
local foreign_key = {}
for _, key in ipairs(foreign_schema.primary_key) do
if entity[foreign_field_name] then
foreign_key[key] = entity[foreign_field_name][key]
else
if primary_key[key] then
foreign_key[key] = primary_key[key]
elseif primary_key[foreign_field_name] then
foreign_key[key] = primary_key[foreign_field_name][key]
end
end
end
return nil, errors:foreign_key_violation_invalid_reference(foreign_key,
foreign_field_name,
foreign_schema.name)
else
local found, e = find(err, "is still referenced from table", 1, true)
if not found then
return error("could not parse foreign key violation error message: " .. err)
end
return nil, errors:foreign_key_violation_restricted(schema.name, sub(err, e + 3, -3))
end
end
return nil, errors:database_error(err)
end
local function get_ttl_value(strategy, attributes, options)
local ttl_value = options and options.ttl
local is_update = options and options.update
local fields = strategy.fields
if ttl_value == 0 or not ttl_value then
return null
end
if not is_update and
attributes.created_at and
fields.created_at and
fields.created_at.timestamp and
fields.created_at.auto then
return ttl_value + attributes.created_at
end
if is_update and
attributes.updated_at and
fields.updated_at and
fields.updated_at.timestamp and
fields.updated_at.auto then
return ttl_value + attributes.updated_at
end
return ttl_value + now_updated()
end
local function get_ws_id()
local phase = get_phase()
if phase ~= "init" and phase ~= "init_worker" then
return ngx.ctx.workspace or kong.default_workspace
end
end
local function execute(strategy, statement_name, attributes, options)
local ws_id
local has_ws_id = strategy.schema.workspaceable
if has_ws_id then
if options and options.workspace then
if options.workspace ~= null then
ws_id = options.workspace
end
else
ws_id = get_ws_id()
end
if not ws_id then
statement_name = statement_name .. "_global"
end
end
local connector = strategy.connector
local statement = strategy.statements[statement_name]
if not attributes then
return connector:query(statement[1], statement[2])
end
local fields = strategy.fields
local argn = statement.argn
local argv = statement.argv
local argc = statement.argc
clear_tab(argv)
local is_update = options and options.update
local has_ttl = strategy.schema.ttl
if has_ws_id then
assert(ws_id == nil or type(ws_id) == "string")
argv[0] = escape_literal(connector, ws_id, "ws_id")
end
for i = 1, argc do
local name = argn[i]
local value
if has_ttl and name == "ttl" then
value = (options and options.ttl)
and get_ttl_value(strategy, attributes, options)
elseif i == argc and is_update and attributes[UNIQUE] then
value = attributes[UNIQUE]
if type(value) == "table" then
value = value[name]
end
else
value = attributes[name]
end
argv[i] = (value == nil and is_update)
and escape_identifier(connector, name)
or escape_literal(connector, value, fields[name])
end
local sql = statement.make(argv)
return connector:query(sql, statement.operation)
end
local function page(self, size, token, foreign_key, foreign_entity_name, options)
if not size then
size = self.connector:get_page_size(options)
end
local limit = size + 1
local statement_name
local attributes = {
[LIMIT] = limit,
}
local suffix = token and "_next" or "_first"
if foreign_entity_name then
statement_name = "page_for_" .. foreign_entity_name .. suffix
attributes[foreign_entity_name] = foreign_key
elseif options and options.tags then
statement_name = options.tags_cond == "or" and
"page_by_tags_or" .. suffix or
"page_by_tags_and" .. suffix
attributes.tags = options.tags
else
statement_name = "page" .. suffix
end
if options and options.export then
statement_name = statement_name .. "_for_export"
end
if token then
local token_decoded = decode_base64(token)
if not token_decoded then
return nil, self.errors:invalid_offset(token, "bad base64 encoding")
end
token_decoded = cjson_safe.decode(token_decoded)
if not token_decoded then
return nil, self.errors:invalid_offset(token, "bad json encoding")
end
for i, field_name in ipairs(self.schema.primary_key) do
attributes[field_name] = token_decoded[i]
end
end
local res, err = execute(self, statement_name, self.collapse(attributes), options)
if not res then
return toerror(self, err)
end
local rows = new_tab(size, 0)
for i = 1, limit do
local row = res[i]
if not row then
break
end
if i == limit then
row = res[size]
local offset = {}
for _, field_name in ipairs(self.schema.primary_key) do
insert(offset, row[field_name])
end
offset = cjson.encode(offset)
offset = encode_base64(offset, true)
return rows, nil, offset
end
rows[i] = self.expand(row)
end
return rows
end
local function make_select_for(foreign_entity_name)
return function(self, foreign_key, size, token, options)
return page(self, size, token, foreign_key, foreign_entity_name, options)
end
end
local _mt = {}
_mt.__index = _mt
function _mt:truncate(options)
local res, err = execute(self, "truncate", nil, options)
if not res then
return toerror(self, err)
end
return true, nil
end
function _mt:insert(entity, options)
local res, err = execute(self, "insert", self.collapse(entity), options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, nil
end
return toerror(self, err, nil, entity)
end
function _mt:select(primary_key, options)
local res, err = execute(self, "select", self.collapse(primary_key), options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, nil
end
return toerror(self, err, primary_key)
end
function _mt:select_by_field(field_name, unique_value, options)
local statement_name = "select_by_" .. field_name
local filter = {
[field_name] = unique_value,
}
local res, err = execute(self, statement_name, self.collapse(filter), options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, nil
end
return toerror(self, err, filter)
end
local function update_options(options)
return {
update = true,
ttl = options and options.ttl,
workspace = options and options.workspace ~= null and options.workspace,
}
end
function _mt:update(primary_key, entity, options)
local res, err = execute(self, "update",
self.collapse(primary_key, entity),
update_options(options))
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, self.errors:not_found(primary_key)
end
return toerror(self, err, primary_key, entity)
end
function _mt:update_by_field(field_name, unique_value, entity, options)
local filter
if type(unique_value) == "table" then
filter = self.collapse({ [field_name] = unique_value })
else
filter = unique_value
end
local res, err = execute(self, "update_by_" .. field_name,
self.collapse({ [UNIQUE] = filter }, entity),
update_options(options))
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, self.errors:not_found_by_field {
[field_name] = unique_value,
}
end
return toerror(self, err, { [field_name] = unique_value }, entity)
end
function _mt:upsert(primary_key, entity, options)
local collapsed_entity = self.collapse(entity, primary_key)
local res, err = execute(self, "upsert", collapsed_entity, options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, self.errors:not_found(primary_key)
end
return toerror(self, err, primary_key, entity)
end
function _mt:upsert_by_field(field_name, unique_value, entity, options)
local collapsed_entity = self.collapse(entity, {
[field_name] = unique_value
})
local res, err = execute(self, "upsert_by_" .. field_name, collapsed_entity, options)
if res then
local row = res[1]
if row then
return self.expand(row), nil
end
return nil, self.errors:not_found_by_field {
[field_name] = unique_value,
}
end
return toerror(self, err, { [field_name] = unique_value }, entity)
end
function _mt:delete(primary_key, options)
local res, err = execute(self, "delete", self.collapse(primary_key), options)
if res then
if res.affected_rows == 0 then
return nil, nil
end
return true, nil
end
return toerror(self, err, primary_key)
end
function _mt:delete_by_field(field_name, unique_value, options)
local statement_name = "delete_by_" .. field_name
local filter = {
[field_name] = unique_value,
}
local res, err = execute(self, statement_name, self.collapse(filter), options)
if res then
if res.affected_rows == 0 then
return nil, nil
end
return true, nil
end
return toerror(self, err, filter)
end
function _mt:page(size, token, options)
return page(self, size, token, nil, nil, options)
end
function _mt:escape_literal(literal, field_name)
return escape_literal(self.connector, literal, self.fields[field_name])
end
local function format_on_condition(on_condition)
if not on_condition then
return nil
end
on_condition = upper(on_condition)
if on_condition ~= "RESTRICT" and
on_condition ~= "CASCADE" and
on_condition ~= "NULL" and
on_condition ~= "DEFAULT" then
on_condition = nil
end
return on_condition
end
local function where_clause(where, ...)
local inputs = pack(...)
return function(add_ws)
local exps = {}
for i = 1, inputs.n do
local exp = inputs[i]
if exp then
if add_ws then
insert(exps, exp)
else
if not exp:match("%(\"ws_id\" = ") then
insert(exps, exp)
end
end
end
end
if #exps == 0 then
return ""
end
return where .. concat(exps, "\n" .. rep(" ", #where - 4) .. "AND ") .. "\n"
end
end
local function conflict_list(has_ws_id, ...)
local inputs = pack(...)
return function(add_ws)
local exps = inputs
if add_ws and has_ws_id then
insert(exps, 1, '"ws_id"')
end
return concat(exps, ", ")
end
end
-- placeholders in queries must always be constructed as a single string,
-- to avoid ending up genering code like this: `concat { "... $", "2 AND ..." }`
local function placeholder(n)
return "$" .. n
end
local _M = {}
function _M.new(connector, schema, errors)
local primary_key = schema.primary_key
local primary_key_fields = {}
for _, field_name in ipairs(primary_key) do
primary_key_fields[field_name] = true
end
local has_ttl = schema.ttl == true
local has_tags = schema.fields.tags ~= nil
local has_composite_cache_key = schema.cache_key and #schema.cache_key > 1
local has_ws_id = schema.workspaceable == true
local fields = {}
local fields_hash = {}
local table_name = schema.table_name
local table_name_escaped = escape_identifier(connector, table_name)
local foreign_key_list = {}
local foreign_keys = {}
local unique_fields = {}
for field_name, field in schema:each_field() do
if field.type == "foreign" then
local foreign_schema = field.schema
local foreign_key_names = {}
local foreign_key_escaped = {}
local foreign_col_names = {}
local is_unique_foreign = field.unique == true
for _, foreign_field_name in ipairs(foreign_schema.primary_key) do
local foreign_field
for foreign_schema_field_name, foreign_schema_field in foreign_schema:each_field() do
if foreign_schema_field_name == foreign_field_name then
foreign_field = foreign_schema_field
break
end
end
local name = field_name .. "_" .. foreign_field_name
fields_hash[name] = foreign_field
local prepared_field = {
referenced_table = foreign_schema.name,
referenced_column = foreign_field_name,
on_update = format_on_condition(field.on_update),
on_delete = format_on_condition(field.on_delete),
name = name,
name_escaped = escape_identifier(connector, name),
name_expression = escape_identifier(connector, name, foreign_field),
field_name = field_name,
is_used_in_primary_key = primary_key_fields[field_name] ~= nil,
is_part_of_composite_key = #foreign_schema.primary_key > 1,
is_unique = foreign_field.unique == true,
is_unique_across_ws = foreign_field.unique_across_ws == true,
is_endpoint_key = schema.endpoint_key == field_name,
is_unique_foreign = is_unique_foreign,
}
if prepared_field.is_used_in_primary_key then
primary_key_fields[field_name] = prepared_field
end
insert(fields, prepared_field)
insert(foreign_key_names, name)
insert(foreign_key_escaped, prepared_field.name_escaped)
insert(foreign_col_names, escape_identifier(connector, foreign_field_name))
insert(foreign_key_list, {
from = name,
entity = field_name,
to = foreign_field_name
})
end
foreign_keys[field_name] = {
names = foreign_key_names,
escaped = foreign_key_escaped,
}
else
fields_hash[field_name] = field
local is_used_in_primary_key = primary_key_fields[field_name] ~= nil
local is_part_of_composite_key = is_used_in_primary_key and #primary_key > 1 or false
local prepared_field = {
name = field_name,
name_escaped = escape_identifier(connector, field_name),
name_expression = escape_identifier(connector, field_name, field),
is_used_in_primary_key = is_used_in_primary_key,
is_part_of_composite_key = is_part_of_composite_key,
is_unique = field.unique == true,
is_unique_across_ws = field.unique_across_ws == true,
is_endpoint_key = schema.endpoint_key == field_name,
}
if prepared_field.is_used_in_primary_key then
primary_key_fields[field_name] = prepared_field
end
insert(fields, prepared_field)
end
end
local primary_key_names = {}
local primary_key_placeholders = {}
local insert_names = {}
local insert_columns = {}
local insert_expressions = {}
local select_expressions = {}
local update_expressions = {}
local update_names = {}
local update_placeholders = {}
local upsert_expressions = {}
local page_next_names = {}
for i, field in ipairs(fields) do
local name = field.name
local name_escaped = field.name_escaped
local name_expression = field.name_expression
local is_used_in_primary_key = field.is_used_in_primary_key
local is_part_of_composite_key = field.is_part_of_composite_key
local is_unique = field.is_unique
local is_unique_foreign = field.is_unique_foreign
local is_endpoint_key = field.is_endpoint_key
local referenced_table = field.referenced_table
insert(insert_names, name)
insert(insert_columns, name_escaped)
insert(insert_expressions, "$" .. i)
insert(select_expressions, name_expression)
if not is_used_in_primary_key then
insert(update_names, name)
insert(update_expressions, name_escaped .. " = $" .. #update_names)
insert(upsert_expressions, name_escaped .. " = " .. "EXCLUDED." .. name_escaped)
end
if ((not is_used_in_primary_key) or is_part_of_composite_key)
and ((referenced_table and not is_part_of_composite_key)
or is_unique_foreign
or is_unique
or (is_endpoint_key and not is_unique))
then
-- treat endpoint_key like a unique key anyway,
-- they are indexed (example: target.target)
insert(unique_fields, field)
end
end
local update_args_names = {}
for _, update_name in ipairs(update_names) do
insert(update_args_names, update_name)
end
local cache_key_escaped
if has_composite_cache_key then
cache_key_escaped = escape_identifier(connector, "cache_key")
insert(update_names, "cache_key")
insert(update_args_names, "cache_key")
insert(update_expressions, cache_key_escaped .. " = $" .. #update_names)
insert(upsert_expressions, cache_key_escaped .. " = " .. "EXCLUDED." .. cache_key_escaped)
end
local ws_id_escaped
if has_ws_id then
ws_id_escaped = escape_identifier(connector, "ws_id")
insert(select_expressions, ws_id_escaped)
insert(update_names, "ws_id")
insert(update_args_names, "ws_id")
insert(update_expressions, ws_id_escaped .. " = $0")
insert(upsert_expressions, ws_id_escaped .. " = " .. "EXCLUDED." .. ws_id_escaped)
end
local ttl_escaped
if has_ttl then
ttl_escaped = escape_identifier(connector, "ttl")
insert(update_names, "ttl")
insert(update_args_names, "ttl")
insert(update_expressions, ttl_escaped .. " = $" .. #update_names)
insert(upsert_expressions, ttl_escaped .. " = " .. "EXCLUDED." .. ttl_escaped)
end
local primary_key_escaped = {}
for i, key in ipairs(primary_key) do
local primary_key_field = primary_key_fields[key]
insert(page_next_names, primary_key_field.name)
insert(primary_key_names, primary_key_field.name)
insert(primary_key_escaped, primary_key_field.name_escaped)
insert(update_args_names, primary_key_field.name)
insert(update_placeholders, "$" .. #update_args_names)
insert(primary_key_placeholders, "$" .. i)
end