-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasslib.lua
More file actions
917 lines (887 loc) · 27.9 KB
/
classlib.lua
File metadata and controls
917 lines (887 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
--classlib.lua
local loadstring = loadstring
-------OOP
local getmetatable,setmetatable,setfenv = getmetatable,setmetatable,setfenv
local tonumber,tostring = tonumber,tostring
local _call = call
local function call(...)
local _source = source
local retValue = {_call(...)}
source = _source
return unpack(retValue)
end
-------Utils
local strToIntCache = {
["vector2"]=2,
["vector3"]=3,
["vector4"]=4,
}
oopUtil = {
classReg = {},
classMetaReg = {},
instanceReg = setmetatable({},{__mode="kv"}),
eventHandler = {},
transfromEventName = function(eventName,isReverse)
return isReverse and (eventName:sub(3,3):lower()..eventName:sub(4)) or ("on"..eventName:sub(1,1):upper()..eventName:sub(2))
end,
getVectorType = function(vec)
if type(vec) == "userdata" then
local typeName = getUserdataType(vec)
if typeName == "vector" then
return strToIntCache[typeName]
end
end
return false
end,
deepCopyWithMeta = function(obj)
local function Func(obj)
if type(obj) ~= "table" then return obj end
local NewTable = {}
for k,v in pairs(obj) do
NewTable[Func(k)] = Func(v)
end
return setmetatable(NewTable,getmetatable(obj))
end
return Func(obj)
end,
splitKeyValue = function(theTable)
local keyTable = {}
local valueTable = {}
for key,value in pairs(theTable) do
keyTable[#keyTable+1] = key
valueTable[#valueTable+1] = value
end
return keyTable,valueTable
end;
deepCopy = function(obj)
local function Func(obj)
if type(obj) ~= "table" then return obj end
local NewTable = {}
for k,v in pairs(obj) do
NewTable[Func(k)] = Func(v)
end
return NewTable
end
return Func(obj)
end,
shallowCopy = function(obj)
local InTable = {}
for k,v in pairs(obj) do
InTable[k] = v
end
return InTable
end,
assimilate = function(t1,t2,except)
if not t1 or not t2 then return end
local exceptTable = {}
if type(except) == "table" then
for i=1,#except do
exceptTable[ except[i] ] = true
end
end
for k,v in pairs(t2) do
if not exceptTable[k] then
t1[k] = v
end
end
end,
spreadFunctionsForClass = function(class,classTemplate)
oopUtil.assimilate(class,classTemplate,{"expose","constructor"})
oopUtil.assimilate(class,classTemplate)
end,
configToSql = function(self,dbType)
local strTable = {}
local specialKeys = {}
local theDataType
for columnName,dType in pairs(self) do
if type(dType) == "string" then
local extraTags = ""
if string.find(dType,";") then
local items = split(dType,";")
theDataType = sqlDataType[items[1]] or items[1]
for i=2,#items do
local tag = items[i]:lower():gsub(" ","")
if tag:sub(1,7) == "primary" then
extraTags = extraTags.." Primary Key "
elseif tag:sub(1,6) == "unique" then
extraTags = extraTags.." Unique "
elseif tag:sub(1,7) == "foreign" then
specialKeys[#specialKeys+1] = "Foreign Key (`"..columnName.."`) References "..items[i]:sub(8)
elseif tag == "notnull" then
extraTags = extraTags.." Not Null "
elseif tag == "defaultnull" then
extraTags = extraTags.." Default Null "
elseif tag == "autoincrement" or tag == "auto_increment" then
extraTags = extraTags.." Auto_Increment "
end
end
else
theDataType = sqlDataType[dType] or dType
end
strTable[#strTable+1] = "`"..columnName.."` "..theDataType.." "..extraTags
end
end
for i=1,#specialKeys do
strTable[#strTable+1] = specialKeys[i]
end
return table.concat(strTable,",")
end,
}
function class(name) return function(classTable)
oopUtil.classReg[name] = classTable --register class with class name
oopUtil.classMetaReg[name] = {__index = {}} --register class metatable with class name
local meta = {
__call = function(classTemplate,...)
local newInstance = {}
setmetatable(newInstance,oopUtil.classMetaReg[name])
if classTemplate.constructor then
classTemplate.constructor(newInstance,...)
else
local copyData = ...
if type(copyData) ~= "table" then return newInstance end
for k,v in pairs(copyData) do
newInstance[k] = v
end
end
return newInstance
end,
}
if classTable.extend then
if type(classTable.extend) ~= "table" then
local extendClass = oopUtil.classReg[classTable.extend]
for extKey,extFunction in pairs(extendClass) do
if classTable[extKey] == nil then classTable[extKey] = extFunction end --Don't overwrite child's function when copying parent's functions
end
else
for key,extend in ipairs(classTable.extend) do
local extendClass = oopUtil.classReg[extend]
for extKey,extFunction in pairs(extendClass) do
if classTable[extKey] == nil then classTable[extKey] = extFunction end --Don't overwrite child's function when copying parent's functions
end
end
end
end
if classTable.inject then
for theType,space in pairs(classTable.inject) do
local injectedData = oopUtil.classReg[theType]
if not injectedData then injectedData = {} end
for name,fnc in pairs(space or {}) do
injectedData[name] = fnc
end
for name,fnc in pairs(space or {}) do
injectedData[name] = fnc
end
end
end
meta.__index = {class=name}
setmetatable(classTable,meta)
oopUtil.spreadFunctionsForClass(oopUtil.classMetaReg[name].__index,classTable)
oopUtil.classMetaReg[name].__index.class = name
oopUtil.classMetaReg[name].__index.instance = true
if not classTable.expose then
_G[name] = classTable
elseif oopUtil.classMetaReg[classTable.expose] then
oopUtil.classMetaReg[classTable.expose].__index[name] = function(self,...) return classTable(...) end
end
end
end
oopUtil.class = class
--Types:
sqlDataType = {
integer = "int",
int = "int",
int8 = "tinyint",
int16 = "smallint",
int24 = "mediumint",
int32 = "int",
int64 = "bigint",
uint = "int unsigned",
uint8 = "tinyint unsigned",
uint16 = "smallint unsigned",
uint24 = "mediumint unsigned",
uint32 = "int unsigned",
uint64 = "bigint unsigned",
-- 字符串类型
char = "char",
varchar = "varchar",
text = "text",
mediumtext = "mediumtext",
longtext = "longtext",
-- 浮点数类型
float = "float",
double = "double",
decimal = "decimal",
-- 日期时间类型
date = "date",
time = "time",
datetime = "datetime",
timestamp = "timestamp",
-- 布尔类型
boolean = "boolean",
bool = "bool",
-- 二进制类型
blob = "blob",
mediumblob = "mediumblob",
longblob = "longblob",
}
class "MORM" {
Open = function(self,...)
return oopUtil.classReg.DataBase(...)
end;
}
class "DataBase" {
expose = "MORM",
constructor = function(self,dbType,...)
-- 检查数据库类型参数
if not dbType then
outputDebugString("@DataBase.constructor, database type is required", 3)
return nil
end
-- 尝试连接数据库
self.db = dbConnect(dbType,...)
if not self.db then
outputDebugString("@DataBase.constructor, failed to connect to database", 3)
return nil
end
self.dbString = {}
self.dbType = dbType
self.dbPendingFill = nil
end;
--[[
AutoMigrate: 自动迁移数据库结构
参数:
tableName: 表名
classTemplate: 类模板,包含列定义
功能:
检查表是否存在,如果不存在则创建新表
如果表存在,则检查是否需要添加新列
]]
AutoMigrate = function(self,...)
if select("#",...) == 2 then
local first,second = ...
--"tableName", classTemplate
if type(first) == "string" then
local tableName, classTemplate = first, second
-- 检查表是否存在
local checkQuery = dbPrepareString(self.db, "SELECT name FROM sqlite_master WHERE type='table' AND name='??'", tableName)
local handle = dbQuery(self.db, checkQuery)
local result = dbPoll(handle, -1)
if #result == 0 then
-- 表不存在,创建新表
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Create Table If Not Exists `??` (??)", tableName, oopUtil.configToSql(classTemplate, self.dbType))
else
-- 表存在,检查是否需要更新结构
-- 这里可以添加更复杂的表结构比较逻辑
-- 简化实现:总是尝试添加新列
for columnName, dataType in pairs(classTemplate) do
if type(dataType) == "string" and columnName ~= "class" and columnName ~= "instance" then
-- 检查列是否存在
local columnCheckQuery = dbPrepareString(self.db, "PRAGMA table_info(`??`)", tableName)
local columnHandle = dbQuery(self.db, columnCheckQuery)
local columns = dbPoll(columnHandle, -1)
local columnExists = false
for _, columnInfo in ipairs(columns) do
if columnInfo.name == columnName then
columnExists = true
break
end
end
if not columnExists then
-- 添加新列
local sqlDataType = sqlDataType[dataType] or dataType
local addColumnQuery = dbPrepareString(self.db, "ALTER TABLE `??` ADD COLUMN `??` ??", tableName, columnName, sqlDataType)
self.dbString[#self.dbString+1] = addColumnQuery
end
end
end
end
end
end
return self
end;
--[[
Create: 创建表或插入数据
参数:
tableName: 表名(可选)
template: 类模板或实例
功能:
如果template是实例,则插入数据到表中
如果template是类模板,则创建新表
]]
Create = function(self,...)
local tableName,template
if select("#",...) == 1 then
template = ...
if not(type(template) == "table" and template.class) then outputDebugString("@Create at argument 1, expect a Class/Instance got "..type(template),3) return false end
if not self.dbString.table then --if table name is not specified
if not(type(template.class) == "string") then outputDebugString("@Create, table name is not specified",3) return false end
end
tableName = self.dbString.table or template.class
else
tableName,template = ...
if not(type(tableName) == "string") then outputDebugString("@Create at argument 1, expect a string got "..type(tableName),3) end
if not(type(template) == "table") then outputDebugString("@Create at argument 2, expect a Class/table got "..type(template),3) end
tableName = self.dbString.table or tableName
end
if template.instance then --If is instance, just insert
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Insert Into `??` ",tableName)
local ks,vs = oopUtil.splitKeyValue(template)
local keys,values = {},{}
for i=1,#ks do
keys[#keys+1] = dbPrepareString(self.db,"`??`",ks[i])
values[#values+1] = dbPrepareString(self.db,"?",vs[i])
end
self.dbString[#self.dbString+1] = "("..table.concat(keys,",")..") Values ("..table.concat(values,",")..")"
else
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Create Table If Not Exists `??` (??)",self.dbString.table or template.class,oopUtil.configToSql(template,self.dbType))
end
return self
end;
--[[
Select: 添加SELECT子句
参数:
selectColumn: 要选择的列(可选,默认为"*")
功能:
为查询添加SELECT子句
如果已指定表名,则同时添加FROM子句
返回值:
返回self,支持链式调用
]]
Select = function(self,selectColumn)
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Select ?? ",selectColumn or "*")
if self.dbString.table then
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"From `??` ",self.dbString.table)
end
return self
end;
--[[
From: 添加FROM子句
参数:
fromTable: 表名(可选,如果已通过Table函数指定)
功能:
为查询添加FROM子句
返回值:
返回self,支持链式调用
]]
From = function(self,fromTable)
if not fromTable then
if not self.dbString.table then outputDebugString("@From, table name is not specified",3) return false end
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"From `??` ",self.dbString.table)
else
if self.dbString.table then outputDebugString("@From, table name is already specified",3) return false end
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"From `??` ",fromTable)
end
return self
end;
--[[
Where: 添加WHERE子句
参数:
columnName: 列名
value: 值
功能:
为查询添加WHERE子句
返回值:
返回self,支持链式调用
]]
Where = function(self,columnName,value)
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Where `??` = ? ",columnName,value)
return self
end;
--[[
OrderBy: 添加ORDER BY子句
参数:
columnName: 列名
order: 排序方式(ASC/DESC,默认ASC)
功能:
为查询添加ORDER BY子句
返回值:
返回self,支持链式调用
]]
OrderBy = function(self, columnName, order)
if not columnName then
outputDebugString("@OrderBy, column name is required", 3)
return false
end
local orderBy = order and order:upper() or "ASC"
if orderBy ~= "ASC" and orderBy ~= "DESC" then
orderBy = "ASC"
end
self.dbString[#self.dbString+1] = dbPrepareString(self.db, "ORDER BY `??` ??", columnName, orderBy)
return self
end;
--[[
Limit: 添加LIMIT子句
参数:
limit: 限制的行数
offset: 偏移量(可选)
功能:
为查询添加LIMIT子句
返回值:
返回self,支持链式调用
]]
Limit = function(self, limit, offset)
if not limit then
outputDebugString("@Limit, limit is required", 3)
return false
end
if offset then
self.dbString[#self.dbString+1] = dbPrepareString(self.db, "LIMIT ? OFFSET ?", limit, offset)
else
self.dbString[#self.dbString+1] = dbPrepareString(self.db, "LIMIT ?", limit)
end
return self
end;
--[[
Find: 查找数据
参数:
instance: 实例或实例列表
功能:
根据实例的属性值构建WHERE条件进行查询
如果instance是单个实例,则构建AND条件
如果instance是实例列表,则构建OR条件
查询结果将填充到实例中
返回值:
返回self,支持链式调用
]]
Find = function(self,...)
local argCount = select("#",...)
if argCount == 1 then
local instance = ...
if not(type(instance) == "table") then outputDebugString("@Find at argument 1, expect a table/Instance got "..type(instance),3) return false end
if instance.instance == true then --If is instance
if not self.dbString.table then self.dbString.table = instance.class end
self:Select()
local where = {}
for key,value in pairs(instance) do
where[#where+1] = dbPrepareString(self.db," `??` = ? ",key,value)
end
self.dbString[#self.dbString+1] = "Where"..table.concat(where,"and")
self.dbPendingFill = {instance}
else --Otherwise, Instance List
if not self.dbString.table then self.dbString.table = instance[1].class end
local conditions = {}
for i=1,#instance do
local where = {}
for key,value in pairs(instance[i]) do
where[#where+1] = dbPrepareString(self.db," `??` = ? ",key,value)
end
conditions[#conditions+1] = " ("..table.concat(where,"and")..") "
end
self:Select()
self.dbString[#self.dbString+1] = "Where"..table.concat(conditions,"or")
self.dbPendingFill = instance
end
end
return self
end;
--[[
Update: 更新数据
参数:
可以有多种参数组合:
1. template: 实例或类模板
2. key, value: 列名和值
3. tableNameOrTemplate, template: 表名或模板,以及模板
4. tableNameOrTemplate, key, value: 表名或模板,列名和值
功能:
构建UPDATE语句更新数据
返回值:
返回self,支持链式调用
]]
Update = function(self,...)
local argCount = select("#",...)
if argCount == 1 then
local template = ...
if not(type(template) == "table") then outputDebugString("@Update at argument 1, expect a Class/Instance got "..type(template),3) return false end
if not self.dbString.table then
if not(type(template.class) == "string") then outputDebugString("@Update, table name is not specified",3) return false end
self.dbString.table = template.class
end
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Update `??` SET ",self.dbString.table)
local kvPair = {}
for key,value in pairs(template) do
local vType = type(value)
if vType ~= "userdata" and vType ~= "function" then
kvPair[#kvPair+1] = dbPrepareString(self.db," `??` = ? ",key,value)
end
end
self.dbString[#self.dbString+1] = table.concat(kvPair,",")
elseif argCount == 2 then
local key,value = ...
if type(value) == "table" then
local tableNameOrTemplate,template = ...
if not (type(tableNameOrTemplate) == "string" or (type(tableNameOrTemplate) == "table" and tableNameOrTemplate.class)) then outputDebugString("@Update at argument 1, expect a Class/string got "..type(tableNameOrTemplate),3) end
if not(type(template) == "table") then outputDebugString("@Update at argument 2, expect a table/Instance got "..type(template),3) return false end
if not self.dbString.table then
if type(tableNameOrTemplate) == "string" then
self.dbString.table = tableNameOrTemplate
else
self.dbString.table = tableNameOrTemplate.class
end
end --Skip if table is already specified
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Update `??` SET ",self.dbString.table)
local kvPair = {}
for key,value in pairs(template) do
local vType = type(value)
if vType ~= "userdata" and vType ~= "function" then
kvPair[#kvPair+1] = dbPrepareString(self.db," `??` = ? ",key,value)
end
end
self.dbString[#self.dbString+1] = table.concat(kvPair,",")
else
if not (type(key) == "string") then outputDebugString("@Update at argument 1, expected a string got "..type(key),3) return false end
if not self.dbString.table then outputDebugString("@Update, table name is not specified",3) return false end
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Update `??` SET `??` = ? ",self.dbString.table,key,value)
end
elseif argCount == 3 then
local tableNameOrTemplate,key,value = ...
if not (type(tableNameOrTemplate) == "string" or (type(tableNameOrTemplate) == "table" and tableNameOrTemplate.class)) then outputDebugString("@Update at argument 1, expect a Class/string got "..type(tableNameOrTemplate),3) end
if not (type(key) == "string") then outputDebugString("@Update at argument 2, expected a string got "..type(key),3) return false end
if not self.dbString.table then
if type(tableNameOrTemplate) == "string" then
self.dbString.table = tableNameOrTemplate
else
self.dbString.table = tableNameOrTemplate.class
end
end --Skip if table is already specified
if not self.dbString.table then outputDebugString("@Update, table name is not specified",3) return false end
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Update`??` SET `??` = ? ",self.dbString.table,key,value)
end
return self
end;
--[[
Delete: 删除表
参数:
tableName: 表名
功能:
删除指定的表
返回值:
返回self,支持链式调用
]]
Delete = function(self,tableName)
self.dbString[#self.dbString+1] = dbPrepareString(self.db,"Drop Table If Exists ?",tableName)
return self
end;
--[[
Query: 执行数据库查询
参数:
timedout: 超时时间(可选,默认-1)
callback: 回调函数(可选,异步执行)
功能:
执行构建好的SQL查询语句
支持同步和异步执行
如果设置了dbPendingFill,则将查询结果填充到指定的实例中
返回值:
异步执行时返回true/false
同步执行时返回查询结果或nil
]]
Query = function(self,timedout,callback)
-- 检查数据库连接
if not self.db then
outputDebugString("@Query, no database connection", 3)
if callback then
callback(self, nil)
return false
else
return nil
end
end
-- 检查是否有查询语句
if #self.dbString == 0 then
outputDebugString("@Query, no query statement", 3)
if callback then
callback(self, nil)
return false
else
return nil
end
end
local _self = self
local pendingFill = self.dbPendingFill
self.dbPendingFill = nil
local queryString = table.concat(self.dbString)
if callback then
-- 异步查询
local handle = dbQuery(function(handle)
self = _self
local pollData, err = dbPoll(handle,timedout or -1)
if err then
outputDebugString("@Query, database error: " .. tostring(err), 3)
callback(self, nil)
return
end
if pollData and pendingFill then --Pending To Fill
local successCount = 0
for i=1,#pendingFill do --Loop Pending To Fill List
local p = 1
while(pollData[p]) do --Loop Retrieved Data List
local isCopyData = true
for key,value in pairs(pendingFill[i]) do --Compare Data
if pollData[p][key] ~= value then isCopyData = false break end --Continue
end
if isCopyData then
for key,value in pairs(pollData[p]) do --Copy Data
pendingFill[i][key] = value
end
successCount = successCount+1
table.remove(pollData,p) --Remove copied data
p = #pollData
end
p = p+1
end
end
callback(self,successCount)
else
callback(self,pollData)
end
end,self.db,queryString)
if not handle then
outputDebugString("@Query, failed to execute query", 3)
callback(self, nil)
return false
end
print(queryString)
self.dbString = {}
return true
else
-- 同步查询
local handle = dbQuery(self.db,queryString)
if not handle then
outputDebugString("@Query, failed to execute query", 3)
self.dbString = {}
return nil
end
print(queryString)
self.dbString = {}
local pollData, err = dbPoll(handle,timedout or -1)
if err then
outputDebugString("@Query, database error: " .. tostring(err), 3)
return nil
end
if pollData and pendingFill then --Pending To Fill
local successCount = 0
for i=1,#pendingFill do --Loop Pending To Fill List
local p = 1
while(pollData[p]) do --Loop Retrieved Data List
local isCopyData = true
for key,value in pairs(pendingFill[i]) do --Compare Data
if pollData[p][key] ~= value then isCopyData = false break end --Continue
end
if isCopyData then
for key,value in pairs(pollData[p]) do --Copy Data
pendingFill[i][key] = value
end
successCount = successCount+1
table.remove(pollData,p) --Remove copied data
p = #pollData
end
p = p+1
end
end
return successCount
end
return pollData
end
end;
--[[
Raw: 添加原始SQL语句
参数:
raw: 原始SQL语句
...: 参数
功能:
添加原始SQL语句到查询字符串中
返回值:
返回self,支持链式调用
]]
Raw = function(self,raw,...)
if not(type(raw) == "string") then return outputDebugString("@Raw at argument 1, expect a string got "..type(raw),3) end
self.dbString[#self.dbString+1] = dbPrepareString(self.db,raw,...)
return self
end;
--[[
Table: 指定表名
参数:
tableNameOrTemplate: 表名或类模板
功能:
指定要操作的表名
这个表名具有最高优先级
返回值:
返回self,支持链式调用
]]
Table = function(self,tableNameOrTemplate)
--Use this table if specified by :Table("tableName"), and this has the top priority.
if not (type(tableNameOrTemplate) == "string" or (type(tableNameOrTemplate) == "table" and tableNameOrTemplate.class)) then outputDebugString("@Table at argument 1, expect a Class/string got "..type(tableNameOrTemplate),3) end
self.dbString.table = (type(tableNameOrTemplate) == "string") and tableNameOrTemplate or tableNameOrTemplate.class
return self
end;
--[[
Alert: 修改列定义
参数:
tableName: 表名
columnName: 列名
newDefinition: 新的列定义
功能:
修改指定列的定义
返回值:
返回self,支持链式调用
]]
Alert = function(self, tableName, columnName, newDefinition)
if not tableName or not columnName or not newDefinition then
outputDebugString("@Alert, missing required parameters", 3)
return false
end
-- 构造ALTER TABLE语句
local sql = "ALTER TABLE `" .. tableName .. "` ALTER COLUMN `" .. columnName .. "` " .. newDefinition
self.dbString[#self.dbString+1] = dbPrepareString(self.db, sql)
return self
end;
--[[
BeginTransaction: 开始事务
功能:
开始一个新的数据库事务
返回值:
返回self,支持链式调用
]]
BeginTransaction = function(self)
if not self.db then
outputDebugString("@BeginTransaction, no database connection", 3)
return false
end
-- 开始事务
local success = dbExec(self.db, "BEGIN")
if not success then
outputDebugString("@BeginTransaction, failed to begin transaction", 3)
return false
end
return self
end;
--[[
Commit: 提交事务
功能:
提交当前事务的所有更改
返回值:
返回self,支持链式调用
]]
Commit = function(self)
if not self.db then
outputDebugString("@Commit, no database connection", 3)
return false
end
-- 提交事务
local success = dbExec(self.db, "COMMIT")
if not success then
outputDebugString("@Commit, failed to commit transaction", 3)
return false
end
return self
end;
--[[
Rollback: 回滚事务
功能:
回滚当前事务的所有更改
返回值:
返回self,支持链式调用
]]
Rollback = function(self)
if not self.db then
outputDebugString("@Rollback, no database connection", 3)
return false
end
-- 回滚事务
local success = dbExec(self.db, "ROLLBACK")
if not success then
outputDebugString("@Rollback, failed to rollback transaction", 3)
return false
end
return self
end;
--[[
Drop: 删除表或列
参数:
tableName: 表名
columnName: 列名(可选)
功能:
如果指定了列名,则删除指定的列
否则删除整个表
返回值:
返回self,支持链式调用
]]
Drop = function(self, tableName, columnName)
if not tableName then
outputDebugString("@Drop, table name is required", 3)
return false
end
if columnName then
-- 删除列
local sql = "ALTER TABLE `" .. tableName .. "` DROP COLUMN `" .. columnName .. "`"
self.dbString[#self.dbString+1] = dbPrepareString(self.db, sql)
else
-- 删除表
self.dbString[#self.dbString+1] = dbPrepareString(self.db, "DROP TABLE IF EXISTS `??`", tableName)
end
return self
end;
--[[
Change: 修改列名和定义
参数:
tableName: 表名
columnName: 列名
newDefinition: 新的列定义
功能:
修改指定列的名称和定义
返回值:
返回self,支持链式调用
]]
Change = function(self, tableName, columnName, newDefinition)
if not tableName or not columnName or not newDefinition then
outputDebugString("@Change, missing required parameters", 3)
return false
end
-- 构造CHANGE COLUMN语句
local sql = "ALTER TABLE `" .. tableName .. "` CHANGE COLUMN `" .. columnName .. "` `" .. columnName .. "` " .. newDefinition
self.dbString[#self.dbString+1] = dbPrepareString(self.db, sql)
return self
end;
--[[
Add: 添加列
参数:
tableName: 表名
columnName: 列名
columnDefinition: 列定义
功能:
向指定表添加新列
返回值:
返回self,支持链式调用
]]
Add = function(self, tableName, columnName, columnDefinition)
if not tableName or not columnName or not columnDefinition then
outputDebugString("@Add, missing required parameters", 3)
return false
end
-- 构造ADD COLUMN语句
local sql = "ALTER TABLE `" .. tableName .. "` ADD COLUMN `" .. columnName .. "` " .. columnDefinition
self.dbString[#self.dbString+1] = dbPrepareString(self.db, sql)
return self
end;
--[[
Modify: 修改列定义
参数:
tableName: 表名
columnName: 列名
newDefinition: 新的列定义
功能:
修改指定列的定义
返回值:
返回self,支持链式调用
]]
Modify = function(self, tableName, columnName, newDefinition)
if not tableName or not columnName or not newDefinition then
outputDebugString("@Modify, missing required parameters", 3)
return false
end
-- 构造MODIFY COLUMN语句
local sql = "ALTER TABLE `" .. tableName .. "` MODIFY COLUMN `" .. columnName .. "` " .. newDefinition
self.dbString[#self.dbString+1] = dbPrepareString(self.db, sql)
return self
end;
}
morm = MORM()