-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbmanager.lua
840 lines (710 loc) · 25.4 KB
/
dbmanager.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
--[[
Library: DB Manager
Author: https://github.com/lodsdev
Version: 1.1.2
MIT License
Copyright (c) 2012-2022 Scott Chacon and others
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local VERSION = 112
addEventHandler("onResourceStart", resourceRoot, function()
if (not (hasObjectPermissionTo(getThisResource(), 'function.fetchRemote', false))) then
error("[DEBUG - DBManager]: You need to add 'function.fetchRemote' permission to check for new releases!")
end
fetchRemote("https://api.github.com/repos/lodsdev/db-manager/releases/latest", function(data, status)
assert(status == 0 and data, "[DBManager] Can't fetch 'api.github.com' for new releases! (Status code: " .. tostring(status) .. ")")
local responseData = fromJSON(data)
if (responseData) then
local tag_name = responseData.tag_name:gsub("%.", "")
local latestVersion = tonumber(tag_name)
if (latestVersion > VERSION) then
outputDebugString("[DEBUG - DBManager]: New version available! (v" .. responseData.tag_name .. ")")
outputDebugString("[DEBUG - DBManager]: Download: " .. responseData.html_url)
end
end
end)
end)
local cacheUUID = {}
local function generateUUID()
local function hex(num)
local hexstr = '0123456789abcdef'
local s = ''
while (num > 0) do
local mod = math.fmod(num, 16)
s = string.sub(hexstr, mod+1, mod+1) .. s
num = math.floor(num / 16)
end
if (s == '') then s = '0' end
return s
end
local function create()
math.randomseed(os.time())
math.random()
math.random()
math.random()
local id0 = hex(math.random(0, 0xffff) + 0x10000)
local id1 = hex(math.random(0, 0xffff) + 0x10000)
local id2 = hex(math.random(0, 0xffff) + 0x10000)
local id3 = hex(math.random(0, 0xffff) + 0x10000)
local id4 = hex(math.random(0, 0xffff) + 0x10000)
local id5 = hex(math.random(0, 0xffff) + 0x10000)
local id6 = hex(math.random(0, 0xffff) + 0x10000)
local id7 = hex(math.random(0, 0xffff) + 0x10000)
return id0 .. id1 .. '-' .. id2 .. '-' .. id3 .. '-' .. id4 .. '-' .. id5 .. id6 .. id7
end
local uuid = create()
while (cacheUUID[uuid]) do
uuid = create()
end
cacheUUID[uuid] = true
return uuid
end
local function isTable(tbl)
return type(tbl) == 'table'
end
local function isString(str)
return type(str) == 'string'
end
local function isBoolean(bool)
return type(bool) == 'boolean'
end
local function isNil(nilValue)
return type(nilValue) == 'nil'
end
local function isNumber(number)
return type(number) == 'number'
end
local function isJSON(value)
return ((isString(value) and value:gmatch('%[%[.+%]%]')) and fromJSON(value) or value)
end
local function async(f, callback, ...)
local asyncCoroutine = coroutine.create(f)
local function step(...)
if (coroutine.status(asyncCoroutine) == 'dead') then
if (callback) then
callback(...)
end
else
local success, result = coroutine.resume(asyncCoroutine, ...)
if (success) then
step(result)
else
error(result, 2)
end
end
end
step(...)
end
local function tblFind(tbl, value)
if (not tbl or not value) then return nil end
for k, v in pairs(tbl) do
if (v == value) then
return k, v
end
end
end
local function prepareAndExecQuery(db, query, ...)
local params = { ... }
local queryString = dbPrepareString(db, query, unpack(params))
if (not queryString) then
return false
end
local queryExec = dbExec(db, queryString)
if (not queryExec) then
return false
end
return true
end
local function addZeroForLessThan10(number)
if(number < 10) then
return 0 .. number
else
return number
end
end
local function generateDateTime()
local dateTimeTable = os.date('*t')
local dateTime = dateTimeTable.year .. addZeroForLessThan10(dateTimeTable.month) ..
addZeroForLessThan10(dateTimeTable.day) .. addZeroForLessThan10(dateTimeTable.hour) .. addZeroForLessThan10(dateTimeTable.min) .. addZeroForLessThan10(dateTimeTable.sec)
return dateTime
end
local function toSQLValue(value)
if (isNumber(value)) then
return tostring(value)
elseif (isBoolean(value)) then
return value and 1 or 0
elseif (isTable(value)) then
return toJSON(value)
elseif (isNil(value)) then
return 'NULL'
else
return value
end
end
local function formatTblFromDB(tbl)
local newTbl = {}
for k, v in ipairs(tbl) do
if (not newTbl[k]) then
newTbl[k] = {}
end
for key, value in pairs(v) do
newTbl[k][key] = isJSON(value)
end
end
return newTbl
end
local CONSTRAINTS_DATA = {
allowNull = 'NOT NULL',
unique = 'UNIQUE',
defaultValue = 'DEFAULT',
check = 'CHECK',
primaryKey = 'PRIMARY KEY',
foreingKey = 'FOREIGN KEY',
autoIncrement = 'AUTO_INCREMENT',
references = 'REFERENCES',
onDelete = 'ON DELETE',
onUpdate = 'ON UPDATE',
comment = 'COMMENT',
}
local CONSTRAINT_ORDER = {
"type",
"autoIncrement",
"allowNull",
"unique",
"defaultValue",
"check",
"references",
"onDelete",
"onUpdate",
"comment",
"primaryKey",
"foreignKey"
}
local function addConstraintToQuery(query, key, value)
local constraintsToAdd = {}
for i = 1, #CONSTRAINT_ORDER do
local constraint = CONSTRAINT_ORDER[i]
if (constraint ~= 'type' and value[constraint] ~= nil) then
if (constraint == 'allowNull' and not value[constraint]) then
constraintsToAdd[#constraintsToAdd+1] = CONSTRAINTS_DATA[constraint]
elseif (constraint ~= 'primaryKey' and constraint ~= 'allowNull') then
local constraintValue = isBoolean(value[constraint]) and '' or ' ' .. value[constraint]
constraintsToAdd[#constraintsToAdd+1] = CONSTRAINTS_DATA[constraint] .. constraintValue
end
end
end
return query .. ' ' .. table.concat(constraintsToAdd, ' ')
end
local DEBUG_RUNNING_DEFAULT = 'DBManager RUNNING (Default): '
local crud = {
sync = function(self)
return async(function()
local exec = prepareAndExecQuery(self.db:getConnection(), self.queryDefine)
if (not exec) then
error('DBManager: Error in query', 2)
end
return exec
end, function()
local valuesInDB = self.valuesInDB
local strValues = table.concat(valuesInDB, ', ')
local querySelect = 'SELECT ' .. strValues .. ' FROM `' .. self.tableName .. '` AS `' .. self.tableName .. '`'
local prepareQuery = dbPrepareString(self.db:getConnection(), querySelect)
if (not prepareQuery) then
return false
end
local result, numAffectedRows, lastInsertId = dbPoll(dbQuery(self.db:getConnection(), prepareQuery), -1)
self.datas = (#result > 0) and formatTblFromDB(result) or {}
outputDebugString(DEBUG_RUNNING_DEFAULT .. querySelect)
return result, numAffectedRows, lastInsertId
end)
end,
create = function(self, data)
local values = {}
local queryParts = { 'INSERT INTO `', self.tableName, '` (' }
local dataValues = {}
if (self.primaryKey) then
queryParts[#queryParts+1] = '`' .. self.primaryKey .. '`'
values[#values+1] = '?'
dataValues[#dataValues+1] = #self.datas + 1
end
local i = 0
for key, value in pairs(data) do
if (#values > 0) then
queryParts[#queryParts+1] = ', '
end
queryParts[#queryParts+1] = '`'
queryParts[#queryParts+1] = key
queryParts[#queryParts+1] = '`'
values[#values+1] = '?'
dataValues[#dataValues+1] = toSQLValue(value)
i = i + 1
end
queryParts[#queryParts+1] = ') VALUES (' .. table.concat(values, ', ') .. ')'
local query = table.concat(queryParts)
local exec = prepareAndExecQuery(self.db:getConnection(), query, unpack(dataValues))
if (not exec) then
error('DBManager: Error in query, can\'t create data', 2)
end
self.datas[#self.datas + 1] = data
outputDebugString('DB Manager RUNNING: ' .. query)
return data
end,
select = function(self, whereClauses, attributes, justOne)
if (not whereClauses or not isTable(whereClauses)) then
error('DBManager: Invalid whereClauses (select)', 2)
end
local rows = self.datas
local valuesInDB = self.valuesInDB
local results = {}
local resultsWithAttributes = {}
for _, attribute in ipairs(attributes or {}) do
if (not tblFind(valuesInDB, attribute)) then
error('DBManager: Invalid attribute (select)', 2)
end
end
for _, row in pairs(rows) do
local valid = true
for key, value in pairs(whereClauses) do
if (not tblFind(valuesInDB, key)) then
error('DBManager: Invalid attribute (select)', 2)
end
if (row[key] ~= value) then
valid = false
break
end
end
if (valid) then
results[#results+1] = row
if (justOne) then
break
end
end
end
if (attributes and (#attributes > 0)) then
for _, row in ipairs(results) do
local result = {}
for _, attribute in ipairs(attributes) do
result[attribute] = row[attribute]
end
resultsWithAttributes[#resultsWithAttributes+1] = result
end
results = resultsWithAttributes
end
return results
end,
findAll = function(self, options)
local whereClauses = options and options.where or {}
local attributes = options and options.attributes or {}
local orderBy = options and options.orderBy or nil
local limit = options and options.limit or nil
local offset = options and options.offset or 0
local order = options and options.order or 'ASC'
local results = self:select(whereClauses, attributes)
if (not results) then
error('DBManager: Invalid results (findAll), please open the issue in GitHub', 2)
end
if (orderBy) then
local orderType = (order == 'ASC') and 1 or -1
table.sort(results, function(a, b)
return orderType * (a[orderBy] < b[orderBy] and -1 or 1) < 0
end)
end
if (limit) then
for i = #results, 1, -1 do
if (i <= offset or i > (offset + limit)) then
table.remove(results, i)
end
end
end
return results
end,
findOne = function(self, options)
if (not options) then
error('DBManager: Invalid options (findOne)', 2)
end
local whereClauses = options.where or {}
local attributes = options.attributes or {}
local results = self:select(whereClauses, attributes, true)
if (not results) then
error('DBManager: Invalid results (findOne), please open the issue in GitHub', 2)
end
return results[1]
end,
findByPk = function(self, pk, options)
if (not self.primaryKey) then
error('DBManager: Invalid primaryKey (findByPk)', 2)
end
if (not pk) then
error('DBManager: Invalid pk (findByPk)', 2)
end
local whereClauses = options and options.where or {}
local attributes = options and options.attributes or {}
whereClauses[self.primaryKey] = pk
local results = self:select(whereClauses, attributes, true)
if (not results) then
error('DBManager: Invalid results (findByPk), please open the issue in GitHub', 2)
end
return results
end,
update = function(self, data, options)
if (not options or not isTable(options)) then
error('DBManager: Invalid options (update)', 2)
end
local whereClauses = options.where or {}
local queryParts = { 'UPDATE `', self.tableName, '` SET ' }
local values = {}
for key, value in pairs(data) do
if (#values > 0) then
queryParts[#queryParts+1] = ', '
end
queryParts[#queryParts+1] = '`'
queryParts[#queryParts+1] = key
queryParts[#queryParts+1] = '` = ?'
values[#values+1] = toSQLValue(value)
end
if (self.db.data.dialect == 'sqlite') then
queryParts[#queryParts+1] = ', `updated_at` = CURRENT_TIMESTAMP'
end
queryParts[#queryParts+1] = ' WHERE '
local i = 0
for key, value in pairs(whereClauses) do
if (i > 0) then
queryParts[#queryParts+1] = ' AND '
end
queryParts[#queryParts+1] = '`'
queryParts[#queryParts+1] = key
queryParts[#queryParts+1] = '` = ?'
values[#values+1] = toSQLValue(value)
i = i + 1
end
local query = table.concat(queryParts)
local exec = prepareAndExecQuery(self.db:getConnection(), query, unpack(values))
if (not exec) then
error('DBManager: ERROR when updating data, please open the issue in GitHub', 2)
end
local rows = self.datas
local valuesInDB = self.valuesInDB
for _, row in ipairs(rows) do
local valid = true
for key, value in pairs(whereClauses) do
if (not tblFind(valuesInDB, key)) then
error('DBManager: Invalid attribute (update)', 2)
end
if (row[key] ~= value) then
valid = false
break
end
end
if (valid) then
for key, value in pairs(data) do
if (not tblFind(valuesInDB, key)) then
error('DBManager: Invalid attribute (update)', 2)
end
row[key] = value
end
end
end
return true
end,
updateAll = function(self, data)
if (not data or not isTable(data)) then
error('DBManager: Invalid data (updateAll)', 2)
end
local queryParts = { 'UPDATE `', self.tableName, '` SET ' }
local values = {}
for key, value in pairs(data) do
if (#values > 0) then
queryParts[#queryParts+1] = ', '
end
queryParts[#queryParts+1] = '`'
queryParts[#queryParts+1] = key
queryParts[#queryParts+1] = '` = ?'
values[#values+1] = toSQLValue(value)
end
if (self.db.data.dialect == 'sqlite') then
queryParts[#queryParts+1] = ', `updated_at` = CURRENT_TIMESTAMP'
end
local query = table.concat(queryParts)
local exec = prepareAndExecQuery(self.db:getConnection(), query, unpack(values))
if (not exec) then
error('DBManager: ERROR when updating data, please open the issue in GitHub', 2)
end
local rows = self.datas
for _, row in ipairs(rows) do
for key, value in pairs(data) do
if (not tblFind(self.valuesInDB, key)) then
error('DBManager: Invalid attribute (updateAll)', 2)
end
row[key] = value
end
end
return true
end,
destroy = function(self, options)
if (not options or not isTable(options)) then
error('DBManager: Invalid options (destroy)', 2)
end
local whereClauses = options.where or {}
local truncate = options.truncate or false
local queryParts = { 'DELETE FROM `', self.tableName, '` WHERE '}
local values = {}
if (truncate) then
queryParts = { 'TRUNCATE TABLE `', self.tableName, '`' }
else
local i = 0
for key, value in pairs(whereClauses) do
if (i > 0) then
queryParts[#queryParts+1] = ' AND '
end
queryParts[#queryParts+1] = '`'
queryParts[#queryParts+1] = key
queryParts[#queryParts+1] = '` = ?'
values[#values+1] = toSQLValue(value)
i = i + 1
end
end
local query = table.concat(queryParts)
local exec = prepareAndExecQuery(self.db:getConnection(), query, unpack(values))
if (not exec) then
error('DBManager: ERROR when destroying data, please open the issue in GitHub', 2)
end
if (not truncate) then
local valuesInDB = self.valuesInDB
for i = #self.datas, 1, -1 do
local row = self.datas[i]
local valid = true
for key, value in ipairs(whereClauses) do
if (not tblFind(valuesInDB, key)) then
error('DBManager: Invalid attribute (destroy)', 2)
end
if (row[key] ~= value) then
valid = false
break
end
end
if (valid) then
table.remove(self.datas, i)
end
end
else
self.datas = {}
end
return true
end,
drop = function(self)
local query = 'DROP TABLE `' .. self.tableName .. '`'
local exec = prepareAndExecQuery(self.db:getConnection(), query)
if (not exec) then
error('DBManager: ERROR when dropping table, please open the issue in GitHub', 2)
end
self.datas = {}
self.db:removeTable(self.tableName)
return true
end,
every = function(self, callback)
for i, data in ipairs(self.datas) do
callback(data, i)
end
end,
}
local private = {}
setmetatable(private, {__mode = 'k'})
DBManager = {
STRING = function(length)
return (length) and 'VARCHAR(' .. length .. ')' or 'VARCHAR(255)'
end,
BINARY = function(length)
return (length) and 'BINARY(' .. length .. ')' or 'BINARY'
end,
TEXT = function(t)
return (t == 'tiny') and 'TINYTEXT' or 'TEXT'
end,
BOOLEAN = function()
return 'BOOLEAN'
end,
INTEGER = function()
return 'INTEGER'
end,
INT = function(length)
return (length) and 'INT(' .. length .. ')' or 'INT'
end,
BIGINT = function(length)
return (length) and 'BIGINT(' .. length .. ')' or 'BIGINT'
end,
FLOAT = function(length, decimals)
if (length) then
return 'FLOAT(' .. length .. ')'
elseif (length and decimals) then
return 'FLOAT(' .. length .. ', ' .. decimals .. ')'
else
return 'FLOAT'
end
end,
DOUBLE = function(length, decimals)
if (length) then
return 'DOUBLE(' .. length .. ')'
elseif (length and decimals) then
return 'DOUBLE(' .. length .. ', ' .. decimals .. ')'
else
return 'DOUBLE'
end
end,
DECIMAL = function(length, decimals)
if (length and decimals) then
return 'DECIMAL(' .. length .. ', ' .. decimals .. ')'
else
return 'DECIMAL'
end
end,
BLOB = function(t)
return (t == 'tiny') and 'TINYBLOB' or 'BLOB'
end,
DATE = function()
return 'DATE'
end,
TIME = function()
return 'TIME'
end,
DATETIME = function()
return 'DATETIME'
end,
DATEONLY = function()
return 'DATE'
end,
NOW = function ()
return generateDateTime()
end,
UUID = generateUUID,
models = {}
}
function DBManager:new(data)
local instance = {}
if (not data) then
error('DBManager: Data is required', 2)
end
instance.data = data
if (instance.data.dialect == 'mysql') then
instance.data.charset = instance.data.charset or 'utf8'
instance.data.options = instance.data.options or ''
instance.CONNECTION = dbConnect(
instance.data.dialect,
'host=' .. instance.data.host .. ';port=' .. instance.data.port .. ';dbname=' .. instance.data.database .. ';charset=' .. instance.data.charset,
instance.data.username,
instance.data.password,
instance.data.options
)
elseif (data.dialect == 'sqlite') then
instance.CONNECTION = dbConnect(instance.data.dialect, instance.data.storage or 'database.db')
end
setmetatable(instance, { __index = self })
return instance
end
function DBManager:getConnection()
return self.CONNECTION
end
function DBManager:close()
local connection = self:getConnection()
if (isElement(connection)) then
destroyElement(connection)
return true
end
return false
end
function DBManager:query(queryString)
local preparatedString = dbPrepareString(self:getConnection(), queryString)
if (not preparatedString) then
return false
end
local query = dbQuery(self:getConnection(), preparatedString)
if (not query) then
return false
end
local result, numAffectedRows, lastInsertId = dbPoll(query, -1)
if (not result) then
return false
end
return result, numAffectedRows, lastInsertId
end
function DBManager:define(tableName, modelDefinition)
local instance = {}
instance.modelDefinition = modelDefinition
instance.tableName = tableName
instance.db = self
instance.dataTypes = {}
instance.primaryKey = ""
instance.valuesInDB = {}
instance.datas = {}
local queryDefine = "CREATE TABLE IF NOT EXISTS `" .. instance.tableName .. "` ("
local i = 0
for key, value in pairs(modelDefinition) do
if (i > 0) then
queryDefine = queryDefine .. ", "
end
queryDefine = queryDefine .. "`" .. key .. "`"
if (isTable(value)) then
if (value.type) then
instance.dataTypes[key] = value.type
queryDefine = queryDefine .. " " .. value.type
end
if (instance.primaryKey == "" and value.primaryKey) then
instance.primaryKey = key
elseif (instance.primaryKey ~= "" and value.primaryKey) then
error('DBManager: Only one primary key is allowed', 2)
end
queryDefine = addConstraintToQuery(queryDefine, key, value)
else
instance.dataTypes[key] = value
queryDefine = queryDefine .. " " .. value
end
instance.valuesInDB[#instance.valuesInDB+1] = key
i = i + 1
end
if (instance.primaryKey == "") then
error('DBManager: No primary key defined', 2)
end
if (instance.db.dialect == 'mysql') then
queryDefine = queryDefine .. ", `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP"
queryDefine = queryDefine .. ", `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
else
queryDefine = queryDefine .. ", `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP"
queryDefine = queryDefine .. ", `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP"
end
instance.valuesInDB[#instance.valuesInDB+1] = 'created_at'
instance.valuesInDB[#instance.valuesInDB+1] = 'updated_at'
instance.queryDefine = queryDefine .. ", PRIMARY KEY (`" .. instance.primaryKey .. "`))"
self.models[tableName] = instance
setmetatable(instance, { __index = crud })
return instance
end
function DBManager:removeTable(tableName)
for i, model in ipairs(allModels) do
if (model.tableName == tableName) then
table.remove(allModels, i)
end
end
end
function DBManager:sync()
for _, model in pairs(self.models) do
model:sync()
end
end
function DBManager:drop()
for _, model in pairs(self.models) do
model:drop()
end
end