-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathstmt.lua
More file actions
413 lines (372 loc) · 11.3 KB
/
stmt.lua
File metadata and controls
413 lines (372 loc) · 11.3 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
---@brief [[
--- sqlstmt is a collection of methods to deal with sqlite statements.
---@brief ]]
---@tag sqlstmt
local clib = require "sqlite.defs"
local flags = clib.flags
---@class sqlstmt @Object to deal with sqlite statements
---@field pstmt sqlite_blob sqlite_pstmt
---@field conn sqlite_blob sqlite3 object
---@field str string original statement
local sqlstmt = {}
sqlstmt.__index = sqlstmt
--- TODO: refactor and make parser.lua required here only.
---Parse a statement
---@param conn sqlite3: the database connection.
---@param str string: the sqlite statement to be parsed.
---@return sqlstmt: collection of methods, applicable to the parsed statement.
---@see sqlstmt:__parse
---@usage local sqlstmt = sqlstmt:parse(db, "insert into todos (title,desc) values(:title, :desc)")
function sqlstmt:parse(conn, str)
assert(clib.type_of(conn) == clib.type_of_db_ptr, "Invalid connection passed to sqlstmt:parse")
assert(type(str) == "string", "Invalid second argument passed to sqlstmt:parse")
local o = setmetatable({
str = str,
conn = conn,
finalized = false,
}, sqlstmt)
local pstmt = clib.get_new_stmt_ptr()
local code = clib.prepare_v2(o.conn, o.str, #o.str, pstmt, nil)
assert(
code == flags.ok,
("sqlite.lua: sql statement parse, , stmt: `%s`, err: `(`%s`)`"):format(o.str, clib.last_errmsg(o.conn))
)
o.pstmt = pstmt[0]
return o
end
---Resets the parsed statement. required for parsed statements to be re-executed.
---NOTE: Any statement variables that had values bound to them using the
---sqlstmt:bind functions retain their values.
---@return number: falgs.ok or errcode
---@TODO should we error out when errcode?
function sqlstmt:reset()
return clib.reset(self.pstmt)
end
---Frees the prepared statement
---@return boolean: if no error true.
function sqlstmt:finalize()
self.errcode = clib.finalize(self.pstmt)
self.finalized = self.errcode == flags.ok
assert(
self.finalized,
string.format(
"sqlite.lua: couldn't finalize statement, ERRMSG: %s stmt = (%s)",
clib.to_str(clib.errmsg(self.conn)),
self.str
)
)
return self.finalized
end
---Called before evaluating the (next iteration) of the prepared statement.
---@return sqlite_flags: Possible Flags: { flags.busy, flags.done, flags.row, flags.error, flags.misuse }
function sqlstmt:step()
local step_code = clib.step(self.pstmt)
assert(
step_code ~= flags.error or step_code ~= flags.misuse,
string.format("sqlite.lua: error in step(), ERRMSG: %s. Please report issue.", clib.to_str(clib.errmsg(self.conn)))
)
return step_code
end
---Number of keys/columns in results
---@return number: column count in the results.
function sqlstmt:nkeys()
return clib.column_count(self.pstmt)
end
---Number of rows/items in results.
---@return number: rows count in the results.
function sqlstmt:nrows()
local count = 0
self:each(function()
count = count + 1
end)
return count
end
---key-name/column-name at {idx} in results.
---@param idx number: (0-index)
---@return string: keyname/column name at {idx}
---@TODO should accept 1-index
function sqlstmt:key(idx)
return clib.to_str(clib.column_name(self.pstmt, idx))
end
---key-names/column-names in results.
---@return table: key-names/column-names.
---@see sqlstmt:nkeys
---@see sqlstmt:key
function sqlstmt:keys()
local keys = {}
for i = 0, self:nkeys() - 1 do
table.insert(keys, i + 1, self:key(i))
end
return keys
end
local sqlite_datatypes = {
[1] = "int", -- bind_double
[2] = "double", -- bind_text
[3] = "text", -- bind_null
[4] = "blob", -- bind_null
[5] = "null", -- bind_null
}
---Key/Column lua datatype at {idx}
---@param idx number: (0-index)
---@return string: key/column type at {idx}
---@TODO should accept 1-index
function sqlstmt:convert_type(idx)
local convert_dt = {
["INTEGER"] = "number",
["FLOAT"] = "number",
["DOUBLE"] = "number",
["TEXT"] = "string",
["BLOB"] = "binary",
["NULL"] = nil,
}
return convert_dt[clib.to_str(clib.column_decltype(self.pstmt, idx))]
end
---Keys/Columns types visible in current result.
---@return table: list of types, ordered by key location.
---@see sqlstmt:type
---@see sqlstmt:nkeys
function sqlstmt:types()
local types = {}
for i = 0, self:nkeys() - 1 do
table.insert(types, i + 1, self:convert_type(i))
end
return types
end
---Value at {idx}
---@param idx number: (0-index)
---@return string: value at {idx}
---@TODO should accept 1-index
function sqlstmt:val(idx)
local ktype = clib.column_type(self.pstmt, idx)
if ktype == 5 then
return
end
local val = clib["column_" .. sqlite_datatypes[ktype]](self.pstmt, idx)
return ktype == 3 and clib.to_str(val) or val
end
---Ordered list of current result values.
---@return table: list of values, ordered by key location.
---@see sqlstmt:val
---@see sqlstmt:nkeys
function sqlstmt:vals()
local vals = {}
for i = 0, self:nkeys() - 1 do
table.insert(vals, i + 1, self:val(i))
end
return vals
end
---Key/value pair in current result.
---@return table: key/value pair of a row.
---@see sqlstmt:key
---@see sqlstmt:val
---@see sqlstmt:nkeys
function sqlstmt:kv()
local ret = {}
for i = 0, self:nkeys() - 1 do
ret[self:key(i)] = self:val(i)
end
return ret
end
---Key/type pair in current result.
---@return table: key/type pair of a row.
---@see sqlstmt:key
---@see sqlstmt:val
---@see sqlstmt:nkeys
function sqlstmt:kt()
local ret = {}
for i = 0, self:nkeys() - 1 do
ret[self:key(i)] = self:convert_type(i)
end
return ret
end
---sqlstmt:next:
---If code == flags.row it returns
---If code == flags.done it reset the parsed statement
function sqlstmt:next()
local code = self:step()
if code == flags.row then
return self
elseif code == flags.done then
self:reset()
else
return nil, code
end
end
---sqlstmt:iter
---@see sqlstmt:next
function sqlstmt:iter()
return self:next(), self.pstmt
end
---Loops through results with {callback} until there is no row left.
---@param callback function: a function to be called on each number of row.
---@usage sqlstmt:each(function(s) print(s:val(1)) end)
---@see sqlstmt:step
function sqlstmt:each(callback)
assert(type(callback) == "function", "sqlstmt:each expected a function, got something else.")
while self:step() == flags.row do
callback(self)
end
end
---Loops through the results and if {callback} pass to it row, else return nested kv pairs.
---@param callback function: a function to be called with each row.
---@return table: if no callback then nested key-value pairs
---@see sqlstmt:kv
---@see sqlstmt:each
function sqlstmt:kvrows(callback)
local kv = {}
self:each(function()
local row = self:kv()
if callback then
return callback(row)
else
table.insert(kv, row)
end
end)
if not callback then
return kv
end
end
---Like sqlstmt:kvrows but passed list of values instead of kv pairs.
---@param callback function: a function to be called with each row.
---@return table: if no callback then nested lists of values in each row.
---@see sqlstmt:vals
---@see sqlstmt:each
function sqlstmt:vrows(callback)
local vals = {}
self:each(function(s)
local row = s:vals()
if callback then
return callback(row)
else
table.insert(vals, row)
end
end)
if not callback then
return vals
end
end
local bind_type_to_func = {
["number"] = "double", -- bind_double
["string"] = "text", -- bind_text
["nil"] = "null", -- bind_null
}
---Bind {args[2]} at {args[1]} or kv pairs {args[1]}.
---If {args[1]} is a number and {args[2]} is a value then it binds by index.
---Else first argument is a table, then it binds the table to indicies, and it
---works with named and unnamed.
---@varargs if {args[1]} number and {args[2]} or {args[1]} table
---@see sqlstmt:nparam
---@see sqlstmt:param
---@see sqlstmt:bind
function sqlstmt:bind(...)
local args = { ... }
-- bind by table
if type(args[1]) == "table" then
local names = args[1]
local parameter_index_cache = {}
local anon_indices = {}
for i = 1, self:nparam() do
local name = self:param(i)
if name == "?" then
table.insert(anon_indices, i)
else
parameter_index_cache[name:sub(2, -1)] = i
end
end
for k, v in pairs(names) do
local index = parameter_index_cache[k] or table.remove(anon_indices, 1)
if ((type(v) == "function") and flags.ok or self:bind(index, v)) ~= flags.ok then
error("sqlite.lua error at stmt:bind(), failed to bind a given value '%s'. Please report issue."):format(v)
end
end
return flags.ok
end
-- bind by index
if type(args[1]) == "number" and args[2] then
local idx, value = args[1], args[2]
local func = bind_type_to_func[type(value)]
local len = func == "text" and #value or nil
if not func then
return error [[
sqlite.lua error at stmt:bind(): Unrecognized or unsupported type.
Please report issue.
]]
end
if len then
return clib["bind_" .. func](self.pstmt, idx, value, len, nil)
else
if value then
return clib["bind_" .. func](self.pstmt, idx, value)
else
return clib["bind_" .. func](self.pstmt, idx)
end
end
end
end
---Binds a blob at {idx} with {size}
---@param idx number: index starting at 1
---@param pointer sqlite_blob: blob to bind
---@param size number: pointer size
---@return sqlite_flags
function sqlstmt:bind_blob(idx, pointer, size)
return clib.bind_blob64(self.pstmt, idx, pointer, size, nil) -- Always 64? or two functions
end
---Binds zeroblob at {idx} with {size}
---@param idx number: index starting at 1
---@param size number: zeroblob size
---@return sqlite_flags
function sqlstmt:bind_zeroblob(idx, size)
return clib.bind_zeroblob64(self.pstmt, idx, size)
end
---The number of parameter to bind.
---@return number: number of params in {sqlstmt.pstmt}
function sqlstmt:nparam()
if not self.parm_count then
self.parm_count = clib.bind_parameter_count(self.pstmt)
end
return self.parm_count
end
---The parameter key/name at {idx}
---@param idx number: index starting at 1
---@return string: param key ":key" at {idx}
function sqlstmt:param(idx)
return clib.to_str(clib.bind_parameter_name(self.pstmt, idx)) or "?"
end
---Parameters keys/names
---@return table: paramters key/names in {sqlstmt.pstmt}
---@see sqlstmt:nparam
---@see sqlstmt:param
function sqlstmt:params()
local res = {}
for i = 1, self:nparam() do
table.insert(res, self:param(i))
end
return res
end
---Clear the current bindings.
---@return sqlite_flags
function sqlstmt:bind_clear()
self.current_bind_index = nil
return clib.clear_bindings(self.pstmt)
end
---Bind the value at the next index until all values are bound
---@param value any: value to bind
---@return sqlite_flags
---@TODO does it return sqlite_flag in all cases? @conni
function sqlstmt:bind_next(value)
if not self.current_bind_index then
self.current_bind_index = 1
end
if self.current_bind_index <= self:nparam() then
local ret = self:bind(self.current_bind_index, value)
self.current_bind_index = self.current_bind_index + 1
return ret
end
return flags.error -- TODO(conni): should error out?
end
---Expand the resulting statement after binding, used for debugging purpose.
---@return string: the resulting statement that can be finalized.
function sqlstmt:expand()
return clib.to_str(clib.expanded_sql(self.pstmt))
end
return sqlstmt