-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.lua
497 lines (446 loc) · 12 KB
/
db.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
-------------------------------------------------------------------------------
-- Frigo is a simple ORM working on top of LuaSQL.
--
-- @author Bertrand Mansion ([email protected])
-- @copyright 2008 Bertrand Mansion
-------------------------------------------------------------------------------
module('frigo.db', package.seeall)
_COPYRIGHT = "Copyright (C) 2008 Bertrand Mansion"
_DESCRIPTION = "Frigo DB is a simple wrapper for common LuaSQL manipulations."
_VERSION = "0.0.1"
function new(driver, options)
assert(driver, "driver required to make luasql connection")
local options = options or {}
local connection = {
driver = driver, -- luasql driver type
prepared_queries = {}, -- prepared statements
last_query = "", -- last executed query
infocache = {}, -- cache database meta info
relations = {}, -- related objects cache
mappings = {}, -- maps object module names
notfound = {}, -- keep track of modules not found
options = options, -- prefix for custom objects modules
}
-- loads the custom SQL adapter for the given driver
local adapter = require("frigo.adapter." .. driver)
for k, v in pairs(adapter) do
if k ~= "_M" then
connection[k] = v
end
end
-- connection object receives this module as metatable.__index
setmetatable(connection, {__index = _M})
return connection
end
function connect(self, database, username, password, ...)
if self.conn then
error("database is already connected")
end
-- starts the luasql driver
local luasql = require("luasql." .. self.driver)
local env, err = luasql[self.driver]()
if not env then
error(err)
end
-- connects with luasql
local conn, err = env:connect(database, username, password, ...)
if not conn then
error(err)
end
self.conn = conn
return self
end
function close(self)
-- closes the luasql connection
self.conn:close()
-- performs some cleanup
self.conn = nil
self.last_query = ""
self.loaded = {}
local prefix = ""
if self.options["prefix"] then
prefix = self.options["prefix"] .. "."
end
for k,_ in pairs(self.relations) do
package.loaded[prefix..k] = nil
end
self:freePrepared()
end
function lastInsertId(self)
return self.conn:getlastautoid()
end
function identifier(self, str)
return '"' .. str:gsub('"', '""') .. '"'
end
function escape(self, str)
return str:gsub("'", "''")
end
function quote(self, val)
if type(val) == "number" then
if string.find(val, "[%.,]") then
return "'" .. string.gsub(val, ",", ".") .. "'"
else
return val
end
elseif type(val) == "nil" then
return 'NULL'
elseif type(val) == "boolean" then
return val and "1" or "0";
else
return "'" .. self.escape(self, val) .. "'"
end
end
function cast(self, ctype, value)
if value ~= nil then
if ctype == 'integer' then
value = tonumber(value)
if value ~= nil then
value = math.floor(value + 0.5)
end
elseif ctype == 'float' then
value = tonumber(value)
if value ~= nil then
value = tonumber(value)
end
else
value = tostring(value)
end
end
return value
end
function prepare(self, q)
local tokens = {}
q:gsub("([^%?]*)%?", function(c) table.insert(tokens, c) end)
if #tokens > 0 then
q:gsub("%?([^%?]*)$", function(c) table.insert(tokens, c) end)
table.insert(self.prepared_queries, tokens)
else
table.insert(self.prepared_queries, {q})
end
return #self.prepared_queries
end
function execute(self, stmt, ...)
if type(stmt) == "string" then
last_query = stmt
else
last_query = self:buildQuery(stmt, ...)
end
local cursor, msg = assert(self.conn:execute(last_query))
return cursor or error(msg .. " SQL = { " .. last_query .. " }", 2)
end
function buildQuery(self, stmt, ...)
local stmt = assert(self.prepared_queries[stmt], "prepared statement not found")
local values = {...}
if values[1] and type(values[1]) == "table" then
values = values[1]
end
local count = #values
local query = ""
if (#stmt-1) ~= count then
error("prepared statement expected " .. (#stmt-1) .. " values, got " .. count)
end
if count > 0 then
for i=1, count do
local value = self:quote(values[i])
query = query .. stmt[i] .. value
end
if stmt[count+1] then
query = query .. stmt[count+1]
end
return query
else
return stmt[1]
end
end
function freePrepared(self, stmt)
if not stmt then
self.prepared_queries = {}
else
self.prepared_queries[stmt] = nil
end
end
function limitQuery(self, q, from, count, ...)
return q
end
function getOne(self, q, ...)
local stmt = self:prepare(q)
local cursor = self:execute(stmt, ...)
self:freePrepared(stmt)
local row = cursor:fetch({}, "n")
cursor:close()
if row then
return row[1]
else
return nil
end
end
function getRow(self, q, mode, ...)
local stmt = self:prepare(q)
local cursor = self:execute(stmt, ...)
self:freePrepared(stmt)
local row = cursor:fetch({}, mode)
cursor:close()
return row
end
function getCol(self, q, col, ...)
local stmt = self:prepare(q)
local cursor = self:execute(stmt, ...)
self:freePrepared(stmt)
local mode = "a"
if type(col) == "number" then mode = "n" end
local row = cursor:fetch({}, mode)
if not row then return nil end
if not row[col] then error("no such field") end
local i = 0
local results = {}
while row do
i = i + 1
results[i] = row[col]
row = cursor:fetch({}, mode)
end
cursor:close()
return results
end
function getAssoc(self, q, group, mode, ...)
local stmt = self:prepare(q)
local cursor = self:execute(stmt, ...)
self:freePrepared(stmt)
local cols = cursor:getcolnames()
if #cols < 2 then
cursor:close()
error("truncated")
elseif #cols == 2 then
local results = {}
local row = cursor:fetch({}, "n")
while row do
if group then
if not results[row[1]] then
results[row[1]] = {}
end
table.insert(results[row[1]], row[2])
else
results[row[1]] = row[2]
end
row = cursor:fetch({}, "n")
end
cursor:close()
return results
else
local results = {}
local row = cursor:fetch({}, "n")
while row do
if group then
if not results[row[1]] then
results[row[1]] = {}
end
if mode == "a" then
local r = {}
for i = 2, #row do
r[cols[i]] = row[i]
end
table.insert(results[row[1]], r)
else
local r = {}
for i = 2, #row do
table.insert(r, row[i])
end
table.insert(results[row[1]], r)
end
else
if not results[row[1]] then
results[row[1]] = {}
end
if mode == "a" then
local r = {}
for i = 2, #row do
r[cols[i]] = row[i]
end
results[row[1]] = r
else
local r = {}
for i = 2, #row do
table.insert(r, row[i])
end
results[row[1]] = r
end
end
row = cursor:fetch({}, "n")
end
cursor:close()
return results
end
end
function getAll(self, q, mode, ...)
local stmt = self:prepare(q)
local cursor = self:execute(stmt, ...)
self:freePrepared(stmt)
local results = {}
local row = cursor:fetch({}, mode)
local i = 0
while row do
i = i + 1
results[i] = row
row = cursor:fetch({}, mode)
end
cursor:close()
return results
end
function tableExists(self, tablename)
local list = self:tablelist()
if list[tablename] then return true end
return false
end
function factory(self, o)
local object = require"frigo.object"
return object:new(self, o)
end
function alias(self, tablename, colname)
return tablename .. "." .. colname .. " AS " .. tablename .. '_' .. colname
end
function find(self, query, ...)
local found = {}
local aliases = {}
local q = string.gsub(query, '{([%w_]+)%:?([^}]*)}', function(t, a)
table.insert(found, t)
if a ~= "" then
aliases[t] = a
end
local info = self:tableinfo(t)
local replace = {}
for _,col in pairs(info.cols) do
local tab = aliases[t] or t
local alias = self:alias(tab, col.column)
table.insert(replace, alias)
end
return table.concat(replace, ", ")
end
)
local stmt = self:prepare(q)
local state = { cursor = self:execute(stmt, ...), row = {} }
self:freePrepared(stmt)
local iterator = function(state)
state.row = state.cursor:fetch(state.row, "a")
if not state.row then
state.cursor:close()
else
local objs = {}
for _, tablename in ipairs(found) do
local info = self:tableinfo(tablename)
local obj = self:factory{ __table = tablename }
obj.__exists = true
obj:trigger("onLoad")
for _, col in pairs(info.cols) do
local tab = aliases[tablename] or tablename
obj:setValue(col.column, state.row[tab .. "_" .. col.column])
end
obj.__dirty = false
obj:trigger("onLoaded")
table.insert(objs, obj)
end
if #objs > 1 then
return objs
else
return objs[1]
end
end
end
return iterator, state
end
function buildFindQuery(self, tablename, options)
local options = options or {}
local query = "SELECT {".. tablename .. "} FROM "
if options.using then
if string.find(options.using, self:identifier(tablename)) then
query = query .. options.using
else
query = query .. self:identifier(tablename) .. ", " .. options.using
end
else
query = query .. self:identifier(tablename)
end
if options.where then
query = query .. " WHERE " .. options.where
end
if options.groupby then
query = query .. " GROUP BY " .. options.groupby
end
if options.having then
query = query .. " HAVING " .. options.having
end
if options.orderby then
query = query .. " ORDER BY " .. options.orderby
end
return query
end
function findOne(self, tablename, options, ...)
local query = self:buildFindQuery(tablename, options)
query = self:limitQuery(query, 1)
for obj in self:find(query, ...) do
return obj
end
end
function findAll(self, tablename, options, ...)
local query = self:buildFindQuery(tablename, options)
if options and options.limit and options.offset then
query = self:limitQuery(query, options.limit, options.offset)
end
local objs = {}
for obj in self:find(query, ...) do
table.insert(objs, obj)
end
return objs
end
function findId(self, tablename, ...)
local info = self:tableinfo(tablename)
local pk = info.pk
if #pk ~= select('#', ...) then
error("number of arguments mismatch")
end
local where = {}
for _, k in pairs(pk) do
table.insert(where, self:identifier(k) .. " = ?")
end
return self:findOne(tablename, {where = table.concat(where, " AND ")}, ...)
end
function preload(self, tablename, prefix)
local mod = tablename
if prefix then
mod = prefix .. "." .. mod
elseif self.mappings[tablename] then
mod = self.mappings[tablename]
elseif self.options["prefix"] then
mod = self.options["prefix"] .. "." .. mod
end
if self.notfound[mod] then return {} end
local status, model = pcall(require, mod)
if not status then
self.notfound[mod] = true
return {}
end
self.mappings[tablename] = mod
-- add relations defined in the module
if model.relations then
for table2, relation in pairs(model.relations) do
self:addRelation(tablename, table2, relation)
end
model.relations = nil
end
return model
end
function addRelation(self, table1, table2, relation)
if not self:getRelation(table1, table2) then
local rel = require"frigo.relation"
local relation = rel.new(table1, table2, relation)
if not self.relations[table1] then
self.relations[table1] = {}
end
self.relations[table1][table2] = relation
end
end
function getRelation(self, table1, table2)
if not table2 then
return self.relations[table1]
elseif self.relations[table1] and self.relations[table1][table2] then
return self.relations[table1][table2]
end
end