-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathem.lua
1883 lines (1508 loc) · 37.6 KB
/
em.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
-- Copyright (c) 2022 nya.works <bug@nya.works>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
------------------
-- Module Setup --
------------------
-- required dependencies
local sqlite3 = require("lsqlite3")
-- optional dependencies
local jsonlib = nil
pcall(function()
jsonlib = require("json")
end)
-- module
local em = {}
-- version
em.version = { 0, 3, 0 }
em.version_string = table.concat(em.version, ".")
-- registers
em.default_key = nil
em.on_change = nil
em.retry = false
-- flags
em.json = not not jsonlib
-- module variables
local entities = {}
local transaction = nil
local check_statement = nil
local pending_changes = false
-- entity metatable
local entity = {}
local entity_mt = { __index = entity }
-- lua compatibility
local unpack = unpack or table.unpack or error("No unpack()")
-----------------------
-- Utility functions --
-----------------------
-- Enquote something for safer SQL
local function quote(name)
return "\""..name.."\""
end
local function step(statement)
local code
local attempts = 0
local retry = em.retry
local done = false
repeat
attempts = attempts + 1
code = statement:step()
if transaction or code ~= sqlite3.BUSY then
done = true
elseif type(retry) == "number" and attempts >= retry then
done = true
elseif (type(retry) == "function" or type(retry) == "table") and retry(attempts) then
done = true
else
done = retry
end
until done
return code
end
-- Execute a statement that only has zero or one result
local function execute(statement, f)
local code, rv
if f then
code = step(statement)
if code == sqlite3.DONE then
statement:reset()
return nil
elseif code ~= sqlite3.ROW then
statement:reset()
error("Unexpected step code "..code)
end
rv = f(statement)
end
code = step(statement)
if code ~= sqlite3.DONE then
statement:reset()
error("Unexpected step code "..code)
end
statement:reset()
return rv
end
-- Execute a statement that only has zero or more results
local function execute_multi(statement, f)
local code, results
code = step(statement)
results = {}
f = f or statement.get_values
while code == sqlite3.ROW do
table.insert(results, f(statement))
code = statement:step()
end
if code == sqlite3.DONE then
statement:reset()
return results
else
statement:reset()
error("Unexpected step code "..code)
end
end
local function get_first(statement)
local values = statement:get_values()
return values and values[1]
end
-- confirm that a sqlite3 call worked
local function confirm(code, error_msg, acceptable)
acceptable = acceptable or { [sqlite3.OK] = true }
if acceptable[code] then
return
end
if error_msg == nil then
error_msg = "Sqlite error"
end
error(error_msg.." (#"..code..")", 2)
end
em.confirm = confirm
local function table_remove(t, e)
local idx = 1
while t[idx] ~= nil and t[idx] ~= e do
idx = idx + 1
end
if t[idx] then
table.remove(t, idx)
end
end
local function mark_dirty(entity, row)
entity.dirty[row] = true
if not pending_changes then
pending_changes = true
if em.on_change then
em.on_change()
end
end
end
-- creates a cache
local cache_mt = { __mode = "v" }
local function cache()
return setmetatable({}, cache_mt)
end
-------------------
-- Field classes --
-------------------
local function class(default_options)
return function(name, options)
local result = {}
if options == nil and name ~= nil and (type(name) == "table" or not name:match("[a-zA-Z]")) then
options = name
name = nil
end
if default_options then
for k,v in pairs(default_options) do
result[k] = v
end
end
if name then
result.name = name
end
if options then
if type(options) == "string" then
local optstr = options
if result.class == "ID" then
options = {
required = optstr:match("!") and true or nil,
}
else
options = {
required = not optstr:match("?"),
unique = optstr:match("!") and true or nil,
}
end
if result.class =="ENTITY" and optstr:match("*") then
result.virtual = true
end
end
for k,v in pairs(options) do
result[k] = v
end
end
return result
end
end
-- Standard classes
local classes = {
text = class{class="TEXT", required=true},
numeric = class{class="NUMERIC", required=true},
int = class{class="INT", required=true},
real = class{class="REAL", required=true},
blob = class{class="BLOB", required=true},
id = class{class="ID", sqltype="INTEGER", unique=true},
}
-- Optional json class
if jsonlib then
classes.json = class{class="JSON", sqltype="TEXT", required=true}
end
-- verbose
em.class = classes
-- shortcut
em.c = classes
-- Entity classes (foreign keys), can accept name or table object
local function entity_class(entity, ...)
if type(entity) == "table" then
entity = entity.name
end
return class{class="ENTITY", entity=entity, name=entity, required=true }(...)
end
em.fkey = entity_class
local bad_types = {
["table"] = true,
["function"] = true,
["userdata"] = true,
["thread"] = true,
}
local function make_transform(f)
return function(field, value)
if value == nil then
if field.required then
error("Field "..field.name.." is required but was set to nil.")
end
return nil, nil
end
if bad_types[type(value)] then
error("Field "..field.name.." cannot be set to a "..type(value)..".")
end
local processed = f(value)
if processed == nil then
error("Field "..field.name.." cannot be set to value "..tostring(value)..".")
end
return processed, processed
end
end
local transforms = {
TEXT = make_transform(tostring),
NUMERIC = make_transform(tonumber),
INT = make_transform(function (value)
return math.floor(tonumber(value))
end),
ENTITY = function(field, value)
if value == nil then
if field.required then
error("Field "..field.name.." is required but was set to nil.")
end
return nil, nil
end
local _value = value
if type(value) == "table" then
local ventity = value.entity
if field.entity ~= ventity.name then
error("Field "..entity.name.."."..key.." cannot store entity "..entity.name)
end
local pkey = ventity.key
_value = value[pkey]
end
if type(value) == "table" and value.rowid then
return _value, _value
else
return value, _value
end
end,
}
transforms.BLOB = transforms.TEXT
transforms.REAL = transforms.NUMERIC
transforms.ID = transforms.INT
if jsonlib then
transforms.JSON = function(field, value, entity, row)
local json = nil
local obj = nil
local json_mt = {}
local new_table = function(source)
local storage = {}
local result = setmetatable({__storage = storage}, json_mt)
for k,v in pairs(source) do
if type(v) == "table" then
v = new_table(v)
end
storage[k] = v
end
return result
end
json_mt.__index = function(self, key)
return self.__storage[key]
end
json_mt.__newindex = function(self, key, value)
if type(value) == "table" and getmetatable(value) ~= json_mt then
value = new_table(value)
end
if type(value) == "function" or type(value) == "thread" or type(value) == "userdata" then
error("cannot store "..type(value).." in json objects")
end
json = nil
if entity and row then
mark_dirty(entity, row)
end
self.__storage[key] = value
end
if value == nil then
if field.required then
error("Field "..field.name.." is required but was set to nil.")
end
return nil, nil
end
local unwind
unwind = function(table)
local result = {}
for k,v in pairs(table.__storage) do
if type(v) == "table" then
v = unwind(v)
end
result[k] = v
end
return result
end
if type(value) == "string" then
json = value
elseif type(value) == "table" then
obj = new_table(value)
end
local f = function(parsed)
if parsed then
if obj == nil then
obj = new_table(jsonlib.decode(json))
end
return obj
else
if json == nil then
json = jsonlib.encode(unwind(obj))
end
return json
end
end
return f, f(false)
end
end
local function transform_value(field, value, entity, row)
return transforms[field.class](field, value, entity, row)
end
----------------------
-- module functions --
----------------------
-- close the db
function em.close()
if em.db ~= nil then
em.db:close()
em.db = nil
check_statement = nil
end
end
function em.test(what, ...)
return check_statement[what](check_statement, ...)
end
local function prepare(lines)
local sql = table.concat(lines, " ")
local statement = nil
return function(option)
if option == "sql" then
return sql
elseif option ~= nil then
error("Expected nil or 'sql'")
end
if statement and not statement:isopen() then
statement = nil
end
if statement == nil then
if em.db == nil then
error("Database is closed")
end
local code
statement, code = em.db:prepare(sql)
if statement == nil then
error("Failed to prepare statement (code "..code.."): "..sql)
end
end
return statement
end
end
-- global prepared statements
check_statement = prepare{"SELECT count(1) FROM \"sqlite_master\" WHERE type='table' AND name=?"}
local function prepare_statements(entity)
local name = entity.name
name = quote(name)
local field_names = {}
local field_params = {}
for i,v in ipairs(entity.field_names) do
field_names[i] = quote(v)
field_params[i] = "?"
end
local unique_checks = {}
for i,v in ipairs(entity.unique_fields) do
unique_checks[i] = quote(v).." = ?"
end
local key = quote(entity.key)
local statements = {
insert = prepare{
"INSERT INTO "..name,
"("..table.concat(field_names, ",")..")",
"VALUES ("..table.concat(field_params, ", ")..")",
},
update = prepare{
"UPDATE "..name,
"SET ("..table.concat(field_names, ",")..")",
"= ("..table.concat(field_params, ", ")..")",
"WHERE rowid = ?",
},
delete = prepare{
"DELETE FROM "..name.." WHERE rowid = ?",
},
get = prepare{
"SELECT "..table.concat(field_names, ",")..",\"rowid\"",
"FROM "..name,
"WHERE "..key.." = ?",
},
}
if #unique_checks > 0 then
statements.is_unique = prepare{
"SELECT EXISTS(SELECT 1 FROM "..name.." WHERE "..table.concat(unique_checks, " OR ")..")",
}
local reuse = #unique_checks == 1 and statements.is_unique
statements.has = {}
for i,v in ipairs(entity.unique_fields) do
statements.has[v] = reuse or prepare{
"SELECT EXISTS(SELECT 1 FROM "..name.." WHERE "..quote(v).." = ?)",
}
end
statements.exists = statements.has[entity.key]
end
entity.statements = statements
end
-- open the db
function em.open(filename)
em.close()
if filename then
em.db = sqlite3.open(filename)
else
em.db = sqlite3.open_memory()
end
end
local function get_vfkey(parent, vfkey)
if vfkey.get then
return vfkey.get
end
local child = entities[vfkey.entity]
if child == nil then
return nil
end
local pname = parent.name
local fkey = vfkey.key
if fkey ~= nil then
fkey = child.fields[fkey]
if fkey == nil then
error("Parent table "..parent.name.."."..vfkey.name.." refers to nonexistent child field "..child.name.."."..vfkey.key)
end
else
for name,field in pairs(child.fields) do
if field.class == "ENTITY" and field.entity == pname and not field.virtual then
if fkey == nil then
fkey = field
else
error("Parent table "..parent.name.."."..vfkey.name.." refers ambiguously to child table "..child.name.." which has multiple fkeys to parent")
end
end
end
if fkey == nil then
error("Parent table "..parent.name.."."..vfkey.name.." refers to non-child "..child.name)
end
end
if fkey.unique then
if vfkey.multi == true then
error("Parent table "..parent.name.."."..vfkey.name.." refers to child "..child.name.."."..fkey.name.." (expected multi, got singular)")
end
vfkey.multi = false
else
if vfkey.multi == false then
error("Parent table "..parent.name.."."..vfkey.name.." refers to child "..child.name.."."..fkey.name.." (expected singular, got multi)")
end
vfkey.multi = true
end
local fkey_name = fkey.name
local where = child:query({fkey_name, "=", ":key"})
vfkey.get = function(pkey)
if vfkey.multi then
return where{key=pkey}
else
local result = child.caches[fkey_name][pkey]
if result == nil then
result = where{key=pkey}[1]
end
return result
end
end
return vfkey.get
end
-- create a new table
function em.new(entity_name, key, fields, options)
if entities[entity_name] then
error("Table "..entity_name.." already exists")
end
local self = setmetatable({}, entity_mt)
-- initial parsing
local parsed = {}
local field_names = {}
if type(key) == "function" then
key = key()
end
if type(key) == "table" then
if key.name == nil then
if type(em.default_key) == "string" then
key.name = em.default_key
else
error("Table "..entity_name.." key is missing a name")
end
end
parsed[key.name] = key
table.insert(field_names, key.name)
key = key.name
end
-- allow key-only tables
fields = fields or {}
if fields[1] then
-- ordered fields
for i,field in ipairs(fields) do
local name = string.lower(field.name)
if name == nil then
error("Table "..entity_name.." field #"..i.." is missing a name")
end
parsed[name] = field
table.insert(field_names, name)
end
else
-- unordered fields - pkey goes first
if key ~= nil and key ~= "rowid" then
field_names[1] = key
end
for name,field in pairs(fields) do
name = string.lower(name)
parsed[name] = field
if name ~= key then
table.insert(field_names, name)
end
end
end
fields = parsed
if #field_names == 0 then
error("Table "..entity_name.." has no fields")
end
-- broad verifications
if fields.rowid then
error("Cannot overwrite rowid field")
end
if key == nil then
key = "rowid"
elseif key ~= "rowid" and fields[key] == nil then
error("Table "..entity_name.." is missing key field "..key)
end
-- parse fields
local unique_fields = {}
local dependencies = {}
local queue = {}
for i,name in ipairs(field_names) do
local field = fields[name]
if type(name) ~= "string" then
error("Fields must be strings")
end
-- string fields for convenience
if type(field) == "string" then
local tag, flags = field:match("^(.-)([?!*]*)$")
local class = classes[tag]
if class == nil then
class = entity_class(tag, flags)
else
class = class(flags)
end
field = class
elseif type(field) == "function" then
field = field()
elseif type(field) == "table" and getmetatable(field) == entity_mt then
field = entity_class(field, { required = true })
elseif type(field) ~= "table" or field.class == nil then
error("Invalid field type for "..entity_name.."."..name)
end
field.name = name
fields[name] = field
if name == key then
field.unique = true
end
if field.unique then
table.insert(unique_fields, name)
end
if field.class == "ENTITY" and field.required then
table.insert(queue, field.entity)
end
if field.class == "ID" then
if key ~= name then
error("ID can only be used for primary keys")
end
end
end
for name,field in pairs(fields) do
if field.virtual then
table_remove(field_names, name)
if field.unique then
table_remove(unique_fields, name)
end
field.required = false
end
end
while #queue > 0 do
local name = table.remove(queue)
if name == entity_name then
error("Circular dependency between "..entity_name.." and itself")
end
local entity = entities[name]
if entity ~= nil and not dependencies[entity] then
dependencies[entity] = true
if entity.fields == nil then
error("Bad table "..name.." from "..entity_name)
end
for _,field in pairs(entity.fields) do
if field.class == "ENTITY" and field.required then
if field.entity == entity_name then
error("Circular dependency between "..entity_name.." and "..entity.name)
end
table.insert(queue, field.entity)
end
end
end
end
local caches = {}
for i,name in ipairs(unique_fields) do
caches[name] = cache()
end
self.name = entity_name
self.key = key
self.fields = fields
self.field_names = field_names
self.unique_fields = unique_fields
self.cache = caches[key]
self.rows = cache()
self.caches = caches
self.keep = {}
self.dirty = {}
prepare_statements(self)
entities[entity_name] = self
return self
end
-- get an existing table
function em.get(name)
return entities[name]
end
-- pairs() function for entities
function em.entities()
return function(_, prev)
return next(entities, prev)
end, nil, nil
end
-- begin a transaction
function em.begin(strict)
if transaction then
if strict then
error("Already began a transaction")
end
transaction.level = transaction.level + 1
return
end
confirm(em.db:exec("BEGIN TRANSACTION"), "Failed to begin transaction")
transaction = {
level = 1,
update = {},
}
end
-- commit a transaction
function em.commit(force)
if not transaction then
error("No transaction")
end
if not force then
local level = transaction.level - 1
if level > 0 then
transaction.level = level
return
end
end
confirm(em.db:exec("COMMIT TRANSACTION"), "Failed to commit transaction")
for hook in pairs(transaction.update) do
hook(true)
end
transaction = nil
end
-- flush all changed to the db
function em.raw_flush()
local next_flush = entities
local to_flush
local total = -1
local skip_fkeys = true -- gets inverted for first iteration
local prev
repeat
to_flush = next_flush
next_flush = {}
prev = total
total = 0
skip_fkeys = not skip_fkeys
for n,entity in pairs(to_flush) do
local remaining = entity:flush(skip_fkeys)
if remaining > 0 then
next_flush[n] = entity
total = total + remaining
end
end
until not skip_fkeys and (total == 0 or total == prev)
if total > 0 then
error("Was not able to flush all records, likely caused by an uncaught circular dependency")
end
pending_changes = false
end
function em.flush()
em.begin(true)
local success, err = pcall(em.raw_flush)
if success then
em.commit(true)
else
em.rollback()
error("Failed to flush:\n"..err)
end
end
-- rollback changes
function em.rollback()
confirm(em.db:exec("ROLLBACK TRANSACTION"), "Failed to rollback transaction")
for hook in pairs(transaction.update) do
hook(false)
end
transaction = nil
end
-- check if currently in a transaction
function em.transaction()
return transaction ~= nil
end
function em.pending_changes()
return pending_changes
end
-----------------------------------
-- Entity creation and functions --
-----------------------------------
local function new_row(entity, data, reread)
-- current values
local values = {}
-- values per the current transaction
local updated = {}
-- whether we've been deleted or not
local deleted = false
-- whether our flush() has been committed or not
local dirty = transaction and data.rowid == nil
-- cache fields
local fields = entity.fields
-- for later
local initial_lookup = {}
-- row object
local mt = {}
local row = setmetatable({}, mt)
for k,v in pairs(fields) do
if v.required and data[k] == nil then
error("Required field "..k.." is missing ("..entity.name..")")
end
local value, lookup = transform_value(v, data[k], entity, row)
initial_lookup[k] = lookup
if reread then
updated[k] = value
else
values[k] = value
end
end
if reread then
updated.rowid = data.rowid
else
values.rowid = data.rowid
end
-- commit/rollback hook
local function hook(is_commit)
if is_commit then
for k,v in pairs(updated) do
values[k] = v
end
local rowid = values.rowid
entity.rows[rowid] = row
updated = {}