1 /************************************************************************
2 * lsqlite3                                                              *
3 * Copyright (C) 2002-2016 Tiago Dionizio, Doug Currie                   *
4 * All rights reserved.                                                  *
5 * Author    : Tiago Dionizio <tiago.dionizio@ist.utl.pt>                *
6 * Author    : Doug Currie <doug.currie@alum.mit.edu>                    *
7 * Library   : lsqlite3 - an SQLite 3 database binding for Lua 5         *
8 *                                                                       *
9 * Permission is hereby granted, free of charge, to any person obtaining *
10 * a copy of this software and associated documentation files (the       *
11 * "Software"), to deal in the Software without restriction, including   *
12 * without limitation the rights to use, copy, modify, merge, publish,   *
13 * distribute, sublicense, and/or sell copies of the Software, and to    *
14 * permit persons to whom the Software is furnished to do so, subject to *
15 * the following conditions:                                             *
16 *                                                                       *
17 * The above copyright notice and this permission notice shall be        *
18 * included in all copies or substantial portions of the Software.       *
19 *                                                                       *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       *
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*
23 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  *
24 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  *
25 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *
26 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *
27 ************************************************************************/
28 
29 #include <stdlib.h>
30 #include <string.h>
31 #include <assert.h>
32 
33 #define LUA_LIB
34 #include <lua.h>
35 #include <lauxlib.h>
36 
37 #if LUA_VERSION_NUM > 501
38 /*
39 ** Lua 5.2
40 */
41 //#define lua_strlen lua_rawlen
42 /* luaL_typerror always used with arg at ndx == NULL */
43 #define luaL_typerror(L,ndx,str) luaL_error(L,"bad argument %d (%s expected, got nil)",ndx,str)
44 /* luaL_register used once, so below expansion is OK for this case */
45 //#define luaL_register(L,name,reg) lua_newtable(L);luaL_setfuncs(L,reg,0)
46 /* luaL_openlib always used with name == NULL */
47 #define luaL_openlib(L,name,reg,nup) luaL_setfuncs(L,reg,nup)
48 
49 #if LUA_VERSION_NUM > 502
50 /*
51 ** Lua 5.3
52 */
53 #define luaL_checkint(L,n)  ((int)luaL_checkinteger(L, (n)))
54 #endif
55 #endif
56 
57 #include <sqlite3.h>
58 
59 /* compile time features */
60 #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK)
61     #define SQLITE_OMIT_PROGRESS_CALLBACK 0
62 #endif
63 #if !defined(LSQLITE_OMIT_UPDATE_HOOK)
64     #define LSQLITE_OMIT_UPDATE_HOOK 0
65 #endif
66 #if defined(LSQLITE_OMIT_OPEN_V2)
67     #define SQLITE3_OPEN(L,filename,flags) sqlite3_open(L,filename)
68 #else
69     #define SQLITE3_OPEN(L,filename,flags) sqlite3_open_v2(L,filename,flags,NULL)
70 #endif
71 
72 typedef struct sdb sdb;
73 typedef struct sdb_vm sdb_vm;
74 typedef struct sdb_bu sdb_bu;
75 typedef struct sdb_func sdb_func;
76 
77 /* to use as C user data so i know what function sqlite is calling */
78 struct sdb_func {
79     /* references to associated lua values */
80     int fn_step;
81     int fn_finalize;
82     int udata;
83 
84     sdb *db;
85     char aggregate;
86 
87     sdb_func *next;
88 };
89 
90 /* information about database */
91 struct sdb {
92     /* associated lua state */
93     lua_State *L;
94     /* sqlite database handle */
95     sqlite3 *db;
96 
97     /* sql functions stack usage */
98     sdb_func *func;         /* top SQL function being called */
99 
100     /* references */
101     int busy_cb;        /* busy callback */
102     int busy_udata;
103 
104     int progress_cb;    /* progress handler */
105     int progress_udata;
106 
107     int trace_cb;       /* trace callback */
108     int trace_udata;
109 
110 #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
111 
112     int update_hook_cb; /* update_hook callback */
113     int update_hook_udata;
114 
115     int commit_hook_cb; /* commit_hook callback */
116     int commit_hook_udata;
117 
118     int rollback_hook_cb; /* rollback_hook callback */
119     int rollback_hook_udata;
120 
121 #endif
122 };
123 
124 static const char *sqlite_meta      = ":sqlite3";
125 static const char *sqlite_vm_meta   = ":sqlite3:vm";
126 static const char *sqlite_bu_meta   = ":sqlite3:bu";
127 static const char *sqlite_ctx_meta  = ":sqlite3:ctx";
128 static int sqlite_ctx_meta_ref;
129 
130 /* Lua 5.3 introduced an integer type, but depending on the implementation, it could be 32
131 ** or 64 bits (or something else?). This helper macro tries to do "the right thing."
132 */
133 
134 #if LUA_VERSION_NUM > 502
135 #define PUSH_INT64(L,i64in,fallback) \
136     do { \
137         sqlite_int64 i64 = i64in; \
138         lua_Integer i = (lua_Integer )i64; \
139         if (i == i64) lua_pushinteger(L, i);\
140         else { \
141             lua_Number n = (lua_Number)i64; \
142             if (n == i64) lua_pushnumber(L, n); \
143             else fallback; \
144         } \
145     } while (0)
146 #else
147 #define PUSH_INT64(L,i64in,fallback) \
148     do { \
149         sqlite_int64 i64 = i64in; \
150         lua_Number n = (lua_Number)i64; \
151         if (n == i64) lua_pushnumber(L, n); \
152         else fallback; \
153     } while (0)
154 #endif
155 
156 /*
157 ** =======================================================
158 ** Database Virtual Machine Operations
159 ** =======================================================
160 */
161 
vm_push_column(lua_State * L,sqlite3_stmt * vm,int idx)162 static void vm_push_column(lua_State *L, sqlite3_stmt *vm, int idx) {
163     switch (sqlite3_column_type(vm, idx)) {
164         case SQLITE_INTEGER:
165             PUSH_INT64(L, sqlite3_column_int64(vm, idx)
166                      , lua_pushlstring(L, (const char*)sqlite3_column_text(vm, idx)
167                                         , sqlite3_column_bytes(vm, idx)));
168             break;
169         case SQLITE_FLOAT:
170             lua_pushnumber(L, sqlite3_column_double(vm, idx));
171             break;
172         case SQLITE_TEXT:
173             lua_pushlstring(L, (const char*)sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx));
174             break;
175         case SQLITE_BLOB:
176             lua_pushlstring(L, sqlite3_column_blob(vm, idx), sqlite3_column_bytes(vm, idx));
177             break;
178         case SQLITE_NULL:
179             lua_pushnil(L);
180             break;
181         default:
182             lua_pushnil(L);
183             break;
184     }
185 }
186 
187 /* virtual machine information */
188 struct sdb_vm {
189     sdb *db;                /* associated database handle */
190     sqlite3_stmt *vm;       /* virtual machine */
191 
192     /* sqlite3_step info */
193     int columns;            /* number of columns in result */
194     char has_values;        /* true when step succeeds */
195 
196     char temp;              /* temporary vm used in db:rows */
197 };
198 
199 /* called with db,sql text on the lua stack */
newvm(lua_State * L,sdb * db)200 static sdb_vm *newvm(lua_State *L, sdb *db) {
201     sdb_vm *svm = (sdb_vm*)lua_newuserdata(L, sizeof(sdb_vm)); /* db sql svm_ud -- */
202 
203     luaL_getmetatable(L, sqlite_vm_meta);
204     lua_setmetatable(L, -2);        /* set metatable */
205 
206     svm->db = db;
207     svm->columns = 0;
208     svm->has_values = 0;
209     svm->vm = NULL;
210     svm->temp = 0;
211 
212     /* add an entry on the database table: svm -> db to keep db live while svm is live */
213     lua_pushlightuserdata(L, db);     /* db sql svm_ud db_lud -- */
214     lua_rawget(L, LUA_REGISTRYINDEX); /* db sql svm_ud reg[db_lud] -- */
215     lua_pushlightuserdata(L, svm);    /* db sql svm_ud reg[db_lud] svm_lud -- */
216     lua_pushvalue(L, -5);             /* db sql svm_ud reg[db_lud] svm_lud db -- */
217     lua_rawset(L, -3);                /* (reg[db_lud])[svm_lud] = db ; set the db for this vm */
218     lua_pop(L, 1);                    /* db sql svm_ud -- */
219 
220     return svm;
221 }
222 
cleanupvm(lua_State * L,sdb_vm * svm)223 static int cleanupvm(lua_State *L, sdb_vm *svm) {
224 
225     /* remove entry in database table - no harm if not present in the table */
226     lua_pushlightuserdata(L, svm->db);
227     lua_rawget(L, LUA_REGISTRYINDEX);
228     lua_pushlightuserdata(L, svm);
229     lua_pushnil(L);
230     lua_rawset(L, -3);
231     lua_pop(L, 1);
232 
233     svm->columns = 0;
234     svm->has_values = 0;
235 
236     if (!svm->vm) return 0;
237 
238     lua_pushinteger(L, sqlite3_finalize(svm->vm));
239     svm->vm = NULL;
240     return 1;
241 }
242 
stepvm(lua_State * L,sdb_vm * svm)243 static int stepvm(lua_State *L, sdb_vm *svm) {
244     return sqlite3_step(svm->vm);
245 }
246 
lsqlite_getvm(lua_State * L,int index)247 static sdb_vm *lsqlite_getvm(lua_State *L, int index) {
248     sdb_vm *svm = (sdb_vm*)luaL_checkudata(L, index, sqlite_vm_meta);
249     if (svm == NULL) luaL_argerror(L, index, "bad sqlite virtual machine");
250     return svm;
251 }
252 
lsqlite_checkvm(lua_State * L,int index)253 static sdb_vm *lsqlite_checkvm(lua_State *L, int index) {
254     sdb_vm *svm = lsqlite_getvm(L, index);
255     if (svm->vm == NULL) luaL_argerror(L, index, "attempt to use closed sqlite virtual machine");
256     return svm;
257 }
258 
dbvm_isopen(lua_State * L)259 static int dbvm_isopen(lua_State *L) {
260     sdb_vm *svm = lsqlite_getvm(L, 1);
261     lua_pushboolean(L, svm->vm != NULL ? 1 : 0);
262     return 1;
263 }
264 
dbvm_tostring(lua_State * L)265 static int dbvm_tostring(lua_State *L) {
266     char buff[39];
267     sdb_vm *svm = lsqlite_getvm(L, 1);
268     if (svm->vm == NULL)
269         strcpy(buff, "closed");
270     else
271         sprintf(buff, "%p", svm);
272     lua_pushfstring(L, "sqlite virtual machine (%s)", buff);
273     return 1;
274 }
275 
dbvm_gc(lua_State * L)276 static int dbvm_gc(lua_State *L) {
277     sdb_vm *svm = lsqlite_getvm(L, 1);
278     if (svm->vm != NULL)  /* ignore closed vms */
279         cleanupvm(L, svm);
280     return 0;
281 }
282 
dbvm_step(lua_State * L)283 static int dbvm_step(lua_State *L) {
284     int result;
285     sdb_vm *svm = lsqlite_checkvm(L, 1);
286 
287     result = stepvm(L, svm);
288     svm->has_values = result == SQLITE_ROW ? 1 : 0;
289     svm->columns = sqlite3_data_count(svm->vm);
290 
291     lua_pushinteger(L, result);
292     return 1;
293 }
294 
dbvm_finalize(lua_State * L)295 static int dbvm_finalize(lua_State *L) {
296     sdb_vm *svm = lsqlite_checkvm(L, 1);
297     return cleanupvm(L, svm);
298 }
299 
dbvm_reset(lua_State * L)300 static int dbvm_reset(lua_State *L) {
301     sdb_vm *svm = lsqlite_checkvm(L, 1);
302     sqlite3_reset(svm->vm);
303     lua_pushinteger(L, sqlite3_errcode(svm->db->db));
304     return 1;
305 }
306 
dbvm_check_contents(lua_State * L,sdb_vm * svm)307 static void dbvm_check_contents(lua_State *L, sdb_vm *svm) {
308     if (!svm->has_values) {
309         luaL_error(L, "misuse of function");
310     }
311 }
312 
dbvm_check_index(lua_State * L,sdb_vm * svm,int index)313 static void dbvm_check_index(lua_State *L, sdb_vm *svm, int index) {
314     if (index < 0 || index >= svm->columns) {
315         luaL_error(L, "index out of range [0..%d]", svm->columns - 1);
316     }
317 }
318 
dbvm_check_bind_index(lua_State * L,sdb_vm * svm,int index)319 static void dbvm_check_bind_index(lua_State *L, sdb_vm *svm, int index) {
320     if (index < 1 || index > sqlite3_bind_parameter_count(svm->vm)) {
321         luaL_error(L, "bind index out of range [1..%d]", sqlite3_bind_parameter_count(svm->vm));
322     }
323 }
324 
dbvm_last_insert_rowid(lua_State * L)325 static int dbvm_last_insert_rowid(lua_State *L) {
326     sdb_vm *svm = lsqlite_checkvm(L, 1);
327     /* conversion warning: int64 -> luaNumber */
328     sqlite_int64 rowid = sqlite3_last_insert_rowid(svm->db->db);
329     PUSH_INT64(L, rowid, lua_pushfstring(L, "%ll", rowid));
330     return 1;
331 }
332 
333 /*
334 ** =======================================================
335 ** Virtual Machine - generic info
336 ** =======================================================
337 */
dbvm_columns(lua_State * L)338 static int dbvm_columns(lua_State *L) {
339     sdb_vm *svm = lsqlite_checkvm(L, 1);
340     lua_pushinteger(L, sqlite3_column_count(svm->vm));
341     return 1;
342 }
343 
344 /*
345 ** =======================================================
346 ** Virtual Machine - getters
347 ** =======================================================
348 */
349 
dbvm_get_value(lua_State * L)350 static int dbvm_get_value(lua_State *L) {
351     sdb_vm *svm = lsqlite_checkvm(L, 1);
352     int index = luaL_checkint(L, 2);
353     dbvm_check_contents(L, svm);
354     dbvm_check_index(L, svm, index);
355     vm_push_column(L, svm->vm, index);
356     return 1;
357 }
358 
dbvm_get_name(lua_State * L)359 static int dbvm_get_name(lua_State *L) {
360     sdb_vm *svm = lsqlite_checkvm(L, 1);
361     int index = luaL_checknumber(L, 2);
362     dbvm_check_index(L, svm, index);
363     lua_pushstring(L, sqlite3_column_name(svm->vm, index));
364     return 1;
365 }
366 
dbvm_get_type(lua_State * L)367 static int dbvm_get_type(lua_State *L) {
368     sdb_vm *svm = lsqlite_checkvm(L, 1);
369     int index = luaL_checknumber(L, 2);
370     dbvm_check_index(L, svm, index);
371     lua_pushstring(L, sqlite3_column_decltype(svm->vm, index));
372     return 1;
373 }
374 
dbvm_get_values(lua_State * L)375 static int dbvm_get_values(lua_State *L) {
376     sdb_vm *svm = lsqlite_checkvm(L, 1);
377     sqlite3_stmt *vm = svm->vm;
378     int columns = svm->columns;
379     int n;
380     dbvm_check_contents(L, svm);
381 
382     lua_createtable(L, columns, 0);
383     for (n = 0; n < columns;) {
384         vm_push_column(L, vm, n++);
385         lua_rawseti(L, -2, n);
386     }
387     return 1;
388 }
389 
dbvm_get_names(lua_State * L)390 static int dbvm_get_names(lua_State *L) {
391     sdb_vm *svm = lsqlite_checkvm(L, 1);
392     sqlite3_stmt *vm = svm->vm;
393     int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
394     int n;
395 
396     lua_createtable(L, columns, 0);
397     for (n = 0; n < columns;) {
398         lua_pushstring(L, sqlite3_column_name(vm, n++));
399         lua_rawseti(L, -2, n);
400     }
401     return 1;
402 }
403 
dbvm_get_types(lua_State * L)404 static int dbvm_get_types(lua_State *L) {
405     sdb_vm *svm = lsqlite_checkvm(L, 1);
406     sqlite3_stmt *vm = svm->vm;
407     int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
408     int n;
409 
410     lua_createtable(L, columns, 0);
411     for (n = 0; n < columns;) {
412         lua_pushstring(L, sqlite3_column_decltype(vm, n++));
413         lua_rawseti(L, -2, n);
414     }
415     return 1;
416 }
417 
dbvm_get_uvalues(lua_State * L)418 static int dbvm_get_uvalues(lua_State *L) {
419     sdb_vm *svm = lsqlite_checkvm(L, 1);
420     sqlite3_stmt *vm = svm->vm;
421     int columns = svm->columns;
422     int n;
423     dbvm_check_contents(L, svm);
424 
425     lua_checkstack(L, columns);
426     for (n = 0; n < columns; ++n)
427         vm_push_column(L, vm, n);
428     return columns;
429 }
430 
dbvm_get_unames(lua_State * L)431 static int dbvm_get_unames(lua_State *L) {
432     sdb_vm *svm = lsqlite_checkvm(L, 1);
433     sqlite3_stmt *vm = svm->vm;
434     int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
435     int n;
436 
437     lua_checkstack(L, columns);
438     for (n = 0; n < columns; ++n)
439         lua_pushstring(L, sqlite3_column_name(vm, n));
440     return columns;
441 }
442 
dbvm_get_utypes(lua_State * L)443 static int dbvm_get_utypes(lua_State *L) {
444     sdb_vm *svm = lsqlite_checkvm(L, 1);
445     sqlite3_stmt *vm = svm->vm;
446     int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
447     int n;
448 
449     lua_checkstack(L, columns);
450     for (n = 0; n < columns; ++n)
451         lua_pushstring(L, sqlite3_column_decltype(vm, n));
452     return columns;
453 }
454 
dbvm_get_named_values(lua_State * L)455 static int dbvm_get_named_values(lua_State *L) {
456     sdb_vm *svm = lsqlite_checkvm(L, 1);
457     sqlite3_stmt *vm = svm->vm;
458     int columns = svm->columns;
459     int n;
460     dbvm_check_contents(L, svm);
461 
462     lua_createtable(L, 0, columns);
463     for (n = 0; n < columns; ++n) {
464         lua_pushstring(L, sqlite3_column_name(vm, n));
465         vm_push_column(L, vm, n);
466         lua_rawset(L, -3);
467     }
468     return 1;
469 }
470 
dbvm_get_named_types(lua_State * L)471 static int dbvm_get_named_types(lua_State *L) {
472     sdb_vm *svm = lsqlite_checkvm(L, 1);
473     sqlite3_stmt *vm = svm->vm;
474     int columns = sqlite3_column_count(vm);
475     int n;
476 
477     lua_createtable(L, 0, columns);
478     for (n = 0; n < columns; ++n) {
479         lua_pushstring(L, sqlite3_column_name(vm, n));
480         lua_pushstring(L, sqlite3_column_decltype(vm, n));
481         lua_rawset(L, -3);
482     }
483     return 1;
484 }
485 
486 /*
487 ** =======================================================
488 ** Virtual Machine - Bind
489 ** =======================================================
490 */
491 
dbvm_bind_index(lua_State * L,sqlite3_stmt * vm,int index,int lindex)492 static int dbvm_bind_index(lua_State *L, sqlite3_stmt *vm, int index, int lindex) {
493     switch (lua_type(L, lindex)) {
494         case LUA_TSTRING:
495             return sqlite3_bind_text(vm, index, lua_tostring(L, lindex), lua_strlen(L, lindex), SQLITE_TRANSIENT);
496         case LUA_TNUMBER:
497 #if LUA_VERSION_NUM > 502
498             if (lua_isinteger(L, lindex))
499                 return sqlite3_bind_int64(vm, index, lua_tointeger(L, lindex));
500 #endif
501             return sqlite3_bind_double(vm, index, lua_tonumber(L, lindex));
502         case LUA_TBOOLEAN:
503             return sqlite3_bind_int(vm, index, lua_toboolean(L, lindex) ? 1 : 0);
504         case LUA_TNONE:
505         case LUA_TNIL:
506             return sqlite3_bind_null(vm, index);
507         default:
508             luaL_error(L, "index (%d) - invalid data type for bind (%s)", index, lua_typename(L, lua_type(L, lindex)));
509             return SQLITE_MISUSE; /*!*/
510     }
511 }
512 
513 
dbvm_bind_parameter_count(lua_State * L)514 static int dbvm_bind_parameter_count(lua_State *L) {
515     sdb_vm *svm = lsqlite_checkvm(L, 1);
516     lua_pushinteger(L, sqlite3_bind_parameter_count(svm->vm));
517     return 1;
518 }
519 
dbvm_bind_parameter_name(lua_State * L)520 static int dbvm_bind_parameter_name(lua_State *L) {
521     sdb_vm *svm = lsqlite_checkvm(L, 1);
522     int index = luaL_checknumber(L, 2);
523     dbvm_check_bind_index(L, svm, index);
524     lua_pushstring(L, sqlite3_bind_parameter_name(svm->vm, index));
525     return 1;
526 }
527 
dbvm_bind(lua_State * L)528 static int dbvm_bind(lua_State *L) {
529     sdb_vm *svm = lsqlite_checkvm(L, 1);
530     sqlite3_stmt *vm = svm->vm;
531     int index = luaL_checkint(L, 2);
532     int result;
533 
534     dbvm_check_bind_index(L, svm, index);
535     result = dbvm_bind_index(L, vm, index, 3);
536 
537     lua_pushinteger(L, result);
538     return 1;
539 }
540 
dbvm_bind_blob(lua_State * L)541 static int dbvm_bind_blob(lua_State *L) {
542     sdb_vm *svm = lsqlite_checkvm(L, 1);
543     int index = luaL_checkint(L, 2);
544     const char *value = luaL_checkstring(L, 3);
545     int len = lua_strlen(L, 3);
546 
547     lua_pushinteger(L, sqlite3_bind_blob(svm->vm, index, value, len, SQLITE_TRANSIENT));
548     return 1;
549 }
550 
dbvm_bind_values(lua_State * L)551 static int dbvm_bind_values(lua_State *L) {
552     sdb_vm *svm = lsqlite_checkvm(L, 1);
553     sqlite3_stmt *vm = svm->vm;
554     int top = lua_gettop(L);
555     int result, n;
556 
557     if (top - 1 != sqlite3_bind_parameter_count(vm))
558         luaL_error(L,
559             "incorrect number of parameters to bind (%d given, %d to bind)",
560             top - 1,
561             sqlite3_bind_parameter_count(vm)
562         );
563 
564     for (n = 2; n <= top; ++n) {
565         if ((result = dbvm_bind_index(L, vm, n - 1, n)) != SQLITE_OK) {
566             lua_pushinteger(L, result);
567             return 1;
568         }
569     }
570 
571     lua_pushinteger(L, SQLITE_OK);
572     return 1;
573 }
574 
dbvm_bind_names(lua_State * L)575 static int dbvm_bind_names(lua_State *L) {
576     sdb_vm *svm = lsqlite_checkvm(L, 1);
577     sqlite3_stmt *vm = svm->vm;
578     int count = sqlite3_bind_parameter_count(vm);
579     const char *name;
580     int result, n;
581     luaL_checktype(L, 2, LUA_TTABLE);
582 
583     for (n = 1; n <= count; ++n) {
584         name = sqlite3_bind_parameter_name(vm, n);
585         if (name && (name[0] == ':' || name[0] == '$')) {
586             lua_pushstring(L, ++name);
587             lua_gettable(L, 2);
588             result = dbvm_bind_index(L, vm, n, -1);
589             lua_pop(L, 1);
590         }
591         else {
592             lua_pushinteger(L, n);
593             lua_gettable(L, 2);
594             result = dbvm_bind_index(L, vm, n, -1);
595             lua_pop(L, 1);
596         }
597 
598         if (result != SQLITE_OK) {
599             lua_pushinteger(L, result);
600             return 1;
601         }
602     }
603 
604     lua_pushinteger(L, SQLITE_OK);
605     return 1;
606 }
607 
608 /*
609 ** =======================================================
610 ** Database (internal management)
611 ** =======================================================
612 */
613 
614 /*
615 ** When creating database handles, always creates a `closed' database handle
616 ** before opening the actual database; so, if there is a memory error, the
617 ** database is not left opened.
618 **
619 ** Creates a new 'table' and leaves it in the stack
620 */
newdb(lua_State * L)621 static sdb *newdb (lua_State *L) {
622     sdb *db = (sdb*)lua_newuserdata(L, sizeof(sdb));
623     db->L = L;
624     db->db = NULL;  /* database handle is currently `closed' */
625     db->func = NULL;
626 
627     db->busy_cb =
628     db->busy_udata =
629     db->progress_cb =
630     db->progress_udata =
631     db->trace_cb =
632     db->trace_udata =
633 #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
634     db->update_hook_cb =
635     db->update_hook_udata =
636     db->commit_hook_cb =
637     db->commit_hook_udata =
638     db->rollback_hook_cb =
639     db->rollback_hook_udata =
640 #endif
641      LUA_NOREF;
642 
643     luaL_getmetatable(L, sqlite_meta);
644     lua_setmetatable(L, -2);        /* set metatable */
645 
646     /* to keep track of 'open' virtual machines */
647     lua_pushlightuserdata(L, db);
648     lua_newtable(L);
649     lua_rawset(L, LUA_REGISTRYINDEX);
650 
651     return db;
652 }
653 
cleanupdb(lua_State * L,sdb * db)654 static int cleanupdb(lua_State *L, sdb *db) {
655     sdb_func *func;
656     sdb_func *func_next;
657     int top;
658     int result;
659 
660     /* free associated virtual machines */
661     lua_pushlightuserdata(L, db);
662     lua_rawget(L, LUA_REGISTRYINDEX);
663 
664     /* close all used handles */
665     top = lua_gettop(L);
666     lua_pushnil(L);
667     while (lua_next(L, -2)) {
668         sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */
669         cleanupvm(L, svm);
670 
671         lua_settop(L, top);
672         lua_pushnil(L);
673     }
674 
675     lua_pop(L, 1); /* pop vm table */
676 
677     /* remove entry in lua registry table */
678     lua_pushlightuserdata(L, db);
679     lua_pushnil(L);
680     lua_rawset(L, LUA_REGISTRYINDEX);
681 
682     /* 'free' all references */
683     luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
684     luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
685     luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
686     luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
687     luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
688     luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
689 #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
690     luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
691     luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);
692     luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
693     luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);
694     luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
695     luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);
696 #endif
697 
698     /* close database */
699     result = sqlite3_close(db->db);
700     db->db = NULL;
701 
702     /* free associated memory with created functions */
703     func = db->func;
704     while (func) {
705         func_next = func->next;
706         luaL_unref(L, LUA_REGISTRYINDEX, func->fn_step);
707         luaL_unref(L, LUA_REGISTRYINDEX, func->fn_finalize);
708         luaL_unref(L, LUA_REGISTRYINDEX, func->udata);
709         free(func);
710         func = func_next;
711     }
712     db->func = NULL;
713     return result;
714 }
715 
lsqlite_getdb(lua_State * L,int index)716 static sdb *lsqlite_getdb(lua_State *L, int index) {
717     sdb *db = (sdb*)luaL_checkudata(L, index, sqlite_meta);
718     if (db == NULL) luaL_typerror(L, index, "sqlite database");
719     return db;
720 }
721 
lsqlite_checkdb(lua_State * L,int index)722 static sdb *lsqlite_checkdb(lua_State *L, int index) {
723     sdb *db = lsqlite_getdb(L, index);
724     if (db->db == NULL) luaL_argerror(L, index, "attempt to use closed sqlite database");
725     return db;
726 }
727 
728 
729 /*
730 ** =======================================================
731 ** User Defined Functions - Context Methods
732 ** =======================================================
733 */
734 typedef struct {
735     sqlite3_context *ctx;
736     int ud;
737 } lcontext;
738 
lsqlite_make_context(lua_State * L)739 static lcontext *lsqlite_make_context(lua_State *L) {
740     lcontext *ctx = (lcontext*)lua_newuserdata(L, sizeof(lcontext));
741     lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_ctx_meta_ref);
742     lua_setmetatable(L, -2);
743     ctx->ctx = NULL;
744     ctx->ud = LUA_NOREF;
745     return ctx;
746 }
747 
lsqlite_getcontext(lua_State * L,int index)748 static lcontext *lsqlite_getcontext(lua_State *L, int index) {
749     lcontext *ctx = (lcontext*)luaL_checkudata(L, index, sqlite_ctx_meta);
750     if (ctx == NULL) luaL_typerror(L, index, "sqlite context");
751     return ctx;
752 }
753 
lsqlite_checkcontext(lua_State * L,int index)754 static lcontext *lsqlite_checkcontext(lua_State *L, int index) {
755     lcontext *ctx = lsqlite_getcontext(L, index);
756     if (ctx->ctx == NULL) luaL_argerror(L, index, "invalid sqlite context");
757     return ctx;
758 }
759 
lcontext_tostring(lua_State * L)760 static int lcontext_tostring(lua_State *L) {
761     char buff[39];
762     lcontext *ctx = lsqlite_getcontext(L, 1);
763     if (ctx->ctx == NULL)
764         strcpy(buff, "closed");
765     else
766         sprintf(buff, "%p", ctx->ctx);
767     lua_pushfstring(L, "sqlite function context (%s)", buff);
768     return 1;
769 }
770 
lcontext_check_aggregate(lua_State * L,lcontext * ctx)771 static void lcontext_check_aggregate(lua_State *L, lcontext *ctx) {
772     sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx);
773     if (!func->aggregate) {
774         luaL_error(L, "attempt to call aggregate method from scalar function");
775     }
776 }
777 
lcontext_user_data(lua_State * L)778 static int lcontext_user_data(lua_State *L) {
779     lcontext *ctx = lsqlite_checkcontext(L, 1);
780     sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx);
781     lua_rawgeti(L, LUA_REGISTRYINDEX, func->udata);
782     return 1;
783 }
784 
lcontext_get_aggregate_context(lua_State * L)785 static int lcontext_get_aggregate_context(lua_State *L) {
786     lcontext *ctx = lsqlite_checkcontext(L, 1);
787     lcontext_check_aggregate(L, ctx);
788     lua_rawgeti(L, LUA_REGISTRYINDEX, ctx->ud);
789     return 1;
790 }
791 
lcontext_set_aggregate_context(lua_State * L)792 static int lcontext_set_aggregate_context(lua_State *L) {
793     lcontext *ctx = lsqlite_checkcontext(L, 1);
794     lcontext_check_aggregate(L, ctx);
795     lua_settop(L, 2);
796     luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
797     ctx->ud = luaL_ref(L, LUA_REGISTRYINDEX);
798     return 0;
799 }
800 
lcontext_aggregate_count(lua_State * L)801 static int lcontext_aggregate_count(lua_State *L) {
802     lcontext *ctx = lsqlite_checkcontext(L, 1);
803     lcontext_check_aggregate(L, ctx);
804     lua_pushinteger(L, sqlite3_aggregate_count(ctx->ctx));
805     return 1;
806 }
807 
808 #if 0
809 void *sqlite3_get_auxdata(sqlite3_context*, int);
810 void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*));
811 #endif
812 
lcontext_result(lua_State * L)813 static int lcontext_result(lua_State *L) {
814     lcontext *ctx = lsqlite_checkcontext(L, 1);
815     switch (lua_type(L, 2)) {
816         case LUA_TNUMBER:
817 #if LUA_VERSION_NUM > 502
818             if (lua_isinteger(L, 2))
819                 sqlite3_result_int64(ctx->ctx, luaL_checkinteger(L, 2));
820             else
821 #endif
822             sqlite3_result_double(ctx->ctx, luaL_checknumber(L, 2));
823             break;
824         case LUA_TSTRING:
825             sqlite3_result_text(ctx->ctx, luaL_checkstring(L, 2), lua_strlen(L, 2), SQLITE_TRANSIENT);
826             break;
827         case LUA_TNIL:
828         case LUA_TNONE:
829             sqlite3_result_null(ctx->ctx);
830             break;
831         default:
832             luaL_error(L, "invalid result type %s", lua_typename(L, 2));
833             break;
834     }
835 
836     return 0;
837 }
838 
lcontext_result_blob(lua_State * L)839 static int lcontext_result_blob(lua_State *L) {
840     lcontext *ctx = lsqlite_checkcontext(L, 1);
841     const char *blob = luaL_checkstring(L, 2);
842     int size = lua_strlen(L, 2);
843     sqlite3_result_blob(ctx->ctx, (const void*)blob, size, SQLITE_TRANSIENT);
844     return 0;
845 }
846 
lcontext_result_double(lua_State * L)847 static int lcontext_result_double(lua_State *L) {
848     lcontext *ctx = lsqlite_checkcontext(L, 1);
849     double d = luaL_checknumber(L, 2);
850     sqlite3_result_double(ctx->ctx, d);
851     return 0;
852 }
853 
lcontext_result_error(lua_State * L)854 static int lcontext_result_error(lua_State *L) {
855     lcontext *ctx = lsqlite_checkcontext(L, 1);
856     const char *err = luaL_checkstring(L, 2);
857     int size = lua_strlen(L, 2);
858     sqlite3_result_error(ctx->ctx, err, size);
859     return 0;
860 }
861 
lcontext_result_int(lua_State * L)862 static int lcontext_result_int(lua_State *L) {
863     lcontext *ctx = lsqlite_checkcontext(L, 1);
864     int i = luaL_checkint(L, 2);
865     sqlite3_result_int(ctx->ctx, i);
866     return 0;
867 }
868 
lcontext_result_null(lua_State * L)869 static int lcontext_result_null(lua_State *L) {
870     lcontext *ctx = lsqlite_checkcontext(L, 1);
871     sqlite3_result_null(ctx->ctx);
872     return 0;
873 }
874 
lcontext_result_text(lua_State * L)875 static int lcontext_result_text(lua_State *L) {
876     lcontext *ctx = lsqlite_checkcontext(L, 1);
877     const char *text = luaL_checkstring(L, 2);
878     int size = lua_strlen(L, 2);
879     sqlite3_result_text(ctx->ctx, text, size, SQLITE_TRANSIENT);
880     return 0;
881 }
882 
883 /*
884 ** =======================================================
885 ** Database Methods
886 ** =======================================================
887 */
888 
db_isopen(lua_State * L)889 static int db_isopen(lua_State *L) {
890     sdb *db = lsqlite_getdb(L, 1);
891     lua_pushboolean(L, db->db != NULL ? 1 : 0);
892     return 1;
893 }
894 
db_last_insert_rowid(lua_State * L)895 static int db_last_insert_rowid(lua_State *L) {
896     sdb *db = lsqlite_checkdb(L, 1);
897     /* conversion warning: int64 -> luaNumber */
898     sqlite_int64 rowid = sqlite3_last_insert_rowid(db->db);
899     PUSH_INT64(L, rowid, lua_pushfstring(L, "%ll", rowid));
900     return 1;
901 }
902 
db_changes(lua_State * L)903 static int db_changes(lua_State *L) {
904     sdb *db = lsqlite_checkdb(L, 1);
905     lua_pushinteger(L, sqlite3_changes(db->db));
906     return 1;
907 }
908 
db_total_changes(lua_State * L)909 static int db_total_changes(lua_State *L) {
910     sdb *db = lsqlite_checkdb(L, 1);
911     lua_pushinteger(L, sqlite3_total_changes(db->db));
912     return 1;
913 }
914 
db_errcode(lua_State * L)915 static int db_errcode(lua_State *L) {
916     sdb *db = lsqlite_checkdb(L, 1);
917     lua_pushinteger(L, sqlite3_errcode(db->db));
918     return 1;
919 }
920 
db_errmsg(lua_State * L)921 static int db_errmsg(lua_State *L) {
922     sdb *db = lsqlite_checkdb(L, 1);
923     lua_pushstring(L, sqlite3_errmsg(db->db));
924     return 1;
925 }
926 
db_interrupt(lua_State * L)927 static int db_interrupt(lua_State *L) {
928     sdb *db = lsqlite_checkdb(L, 1);
929     sqlite3_interrupt(db->db);
930     return 0;
931 }
932 
933 /*
934 ** Registering SQL functions:
935 */
936 
db_push_value(lua_State * L,sqlite3_value * value)937 static void db_push_value(lua_State *L, sqlite3_value *value) {
938     switch (sqlite3_value_type(value)) {
939         case SQLITE_TEXT:
940             lua_pushlstring(L, (const char*)sqlite3_value_text(value), sqlite3_value_bytes(value));
941             break;
942 
943         case SQLITE_INTEGER:
944             PUSH_INT64(L, sqlite3_value_int64(value)
945                         , lua_pushlstring(L, (const char*)sqlite3_value_text(value)
946                                             , sqlite3_value_bytes(value)));
947             break;
948 
949         case SQLITE_FLOAT:
950             lua_pushnumber(L, sqlite3_value_double(value));
951             break;
952 
953         case SQLITE_BLOB:
954             lua_pushlstring(L, sqlite3_value_blob(value), sqlite3_value_bytes(value));
955             break;
956 
957         case SQLITE_NULL:
958             lua_pushnil(L);
959             break;
960 
961         default:
962             /* things done properly (SQLite + Lua SQLite)
963             ** this should never happen */
964             lua_pushnil(L);
965             break;
966     }
967 }
968 
969 /*
970 ** callback functions used when calling registered sql functions
971 */
972 
973 /* scalar function to be called
974 ** callback params: context, values... */
db_sql_normal_function(sqlite3_context * context,int argc,sqlite3_value ** argv)975 static void db_sql_normal_function(sqlite3_context *context, int argc, sqlite3_value **argv) {
976     sdb_func *func = (sdb_func*)sqlite3_user_data(context);
977     lua_State *L = func->db->L;
978     int n;
979     lcontext *ctx;
980 
981     int top = lua_gettop(L);
982 
983     /* ensure there is enough space in the stack */
984     lua_checkstack(L, argc + 3);
985 
986     lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_step);   /* function to call */
987 
988     if (!func->aggregate) {
989         ctx = lsqlite_make_context(L); /* push context - used to set results */
990     }
991     else {
992         /* reuse context userdata value */
993         void *p = sqlite3_aggregate_context(context, 1);
994         /* i think it is OK to use assume that using a light user data
995         ** as an entry on LUA REGISTRY table will be unique */
996         lua_pushlightuserdata(L, p);
997         lua_rawget(L, LUA_REGISTRYINDEX);       /* context table */
998 
999         if (lua_isnil(L, -1)) { /* not yet created? */
1000             lua_pop(L, 1);
1001             ctx = lsqlite_make_context(L);
1002             lua_pushlightuserdata(L, p);
1003             lua_pushvalue(L, -2);
1004             lua_rawset(L, LUA_REGISTRYINDEX);
1005         }
1006         else
1007             ctx = lsqlite_getcontext(L, -1);
1008     }
1009 
1010     /* push params */
1011     for (n = 0; n < argc; ++n) {
1012         db_push_value(L, argv[n]);
1013     }
1014 
1015     /* set context */
1016     ctx->ctx = context;
1017 
1018     if (lua_pcall(L, argc + 1, 0, 0)) {
1019         const char *errmsg = lua_tostring(L, -1);
1020         int size = lua_strlen(L, -1);
1021         sqlite3_result_error(context, errmsg, size);
1022     }
1023 
1024     /* invalidate context */
1025     ctx->ctx = NULL;
1026 
1027     if (!func->aggregate) {
1028         luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
1029     }
1030 
1031     lua_settop(L, top);
1032 }
1033 
db_sql_finalize_function(sqlite3_context * context)1034 static void db_sql_finalize_function(sqlite3_context *context) {
1035     sdb_func *func = (sdb_func*)sqlite3_user_data(context);
1036     lua_State *L = func->db->L;
1037     void *p = sqlite3_aggregate_context(context, 1); /* minimal mem usage */
1038     lcontext *ctx;
1039     int top = lua_gettop(L);
1040 
1041     lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_finalize);   /* function to call */
1042 
1043     /* i think it is OK to use assume that using a light user data
1044     ** as an entry on LUA REGISTRY table will be unique */
1045     lua_pushlightuserdata(L, p);
1046     lua_rawget(L, LUA_REGISTRYINDEX);       /* context table */
1047 
1048     if (lua_isnil(L, -1)) { /* not yet created? - shouldn't happen in finalize function */
1049         lua_pop(L, 1);
1050         ctx = lsqlite_make_context(L);
1051         lua_pushlightuserdata(L, p);
1052         lua_pushvalue(L, -2);
1053         lua_rawset(L, LUA_REGISTRYINDEX);
1054     }
1055     else
1056         ctx = lsqlite_getcontext(L, -1);
1057 
1058     /* set context */
1059     ctx->ctx = context;
1060 
1061     if (lua_pcall(L, 1, 0, 0)) {
1062         sqlite3_result_error(context, lua_tostring(L, -1), -1);
1063     }
1064 
1065     /* invalidate context */
1066     ctx->ctx = NULL;
1067 
1068     /* cleanup context */
1069     luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
1070     /* remove it from registry */
1071     lua_pushlightuserdata(L, p);
1072     lua_pushnil(L);
1073     lua_rawset(L, LUA_REGISTRYINDEX);
1074 
1075     lua_settop(L, top);
1076 }
1077 
1078 /*
1079 ** Register a normal function
1080 ** Params: db, function name, number arguments, [ callback | step, finalize], user data
1081 ** Returns: true on sucess
1082 **
1083 ** Normal function:
1084 ** Params: context, params
1085 **
1086 ** Aggregate function:
1087 ** Params of step: context, params
1088 ** Params of finalize: context
1089 */
db_register_function(lua_State * L,int aggregate)1090 static int db_register_function(lua_State *L, int aggregate) {
1091     sdb *db = lsqlite_checkdb(L, 1);
1092     const char *name;
1093     int args;
1094     int result;
1095     sdb_func *func;
1096 
1097     /* safety measure */
1098     if (aggregate) aggregate = 1;
1099 
1100     name = luaL_checkstring(L, 2);
1101     args = luaL_checkint(L, 3);
1102     luaL_checktype(L, 4, LUA_TFUNCTION);
1103     if (aggregate) luaL_checktype(L, 5, LUA_TFUNCTION);
1104 
1105     /* maybe an alternative way to allocate memory should be used/avoided */
1106     func = (sdb_func*)malloc(sizeof(sdb_func));
1107     if (func == NULL) {
1108         luaL_error(L, "out of memory");
1109     }
1110 
1111     result = sqlite3_create_function(
1112         db->db, name, args, SQLITE_UTF8, func,
1113         aggregate ? NULL : db_sql_normal_function,
1114         aggregate ? db_sql_normal_function : NULL,
1115         aggregate ? db_sql_finalize_function : NULL
1116     );
1117 
1118     if (result == SQLITE_OK) {
1119         /* safety measures for userdata field to be present in the stack */
1120         lua_settop(L, 5 + aggregate);
1121 
1122         /* save registered function in db function list */
1123         func->db = db;
1124         func->aggregate = aggregate;
1125         func->next = db->func;
1126         db->func = func;
1127 
1128         /* save the setp/normal function callback */
1129         lua_pushvalue(L, 4);
1130         func->fn_step = luaL_ref(L, LUA_REGISTRYINDEX);
1131         /* save user data */
1132         lua_pushvalue(L, 5+aggregate);
1133         func->udata = luaL_ref(L, LUA_REGISTRYINDEX);
1134 
1135         if (aggregate) {
1136             lua_pushvalue(L, 5);
1137             func->fn_finalize = luaL_ref(L, LUA_REGISTRYINDEX);
1138         }
1139         else
1140             func->fn_finalize = LUA_NOREF;
1141     }
1142     else {
1143         /* free allocated memory */
1144         free(func);
1145     }
1146 
1147     lua_pushboolean(L, result == SQLITE_OK ? 1 : 0);
1148     return 1;
1149 }
1150 
db_create_function(lua_State * L)1151 static int db_create_function(lua_State *L) {
1152     return db_register_function(L, 0);
1153 }
1154 
db_create_aggregate(lua_State * L)1155 static int db_create_aggregate(lua_State *L) {
1156     return db_register_function(L, 1);
1157 }
1158 
1159 /* create_collation; contributed by Thomas Lauer
1160 */
1161 
1162 typedef struct {
1163     lua_State *L;
1164     int ref;
1165 } scc;
1166 
collwrapper(scc * co,int l1,const void * p1,int l2,const void * p2)1167 static int collwrapper(scc *co,int l1,const void *p1,
1168                         int l2,const void *p2) {
1169     int res=0;
1170     lua_State *L=co->L;
1171     lua_rawgeti(L,LUA_REGISTRYINDEX,co->ref);
1172     lua_pushlstring(L,p1,l1);
1173     lua_pushlstring(L,p2,l2);
1174     if (lua_pcall(L,2,1,0)==0) res=lua_tonumber(L,-1);
1175     lua_pop(L,1);
1176     return res;
1177 }
1178 
collfree(scc * co)1179 static void collfree(scc *co) {
1180     if (co) {
1181         luaL_unref(co->L,LUA_REGISTRYINDEX,co->ref);
1182         free(co);
1183     }
1184 }
1185 
db_create_collation(lua_State * L)1186 static int db_create_collation(lua_State *L) {
1187     sdb *db=lsqlite_checkdb(L,1);
1188     const char *collname=luaL_checkstring(L,2);
1189     scc *co=NULL;
1190     int (*collfunc)(scc *,int,const void *,int,const void *)=NULL;
1191     lua_settop(L,3); /* default args to nil, and exclude extras */
1192     if (lua_isfunction(L,3)) collfunc=collwrapper;
1193     else if (!lua_isnil(L,3))
1194         luaL_error(L,"create_collation: function or nil expected");
1195     if (collfunc != NULL) {
1196         co=(scc *)malloc(sizeof(scc)); /* userdata is a no-no as it
1197                                           will be garbage-collected */
1198         if (co) {
1199             co->L=L;
1200             /* lua_settop(L,3) above means we don't need: lua_pushvalue(L,3); */
1201             co->ref=luaL_ref(L,LUA_REGISTRYINDEX);
1202         }
1203         else luaL_error(L,"create_collation: could not allocate callback");
1204     }
1205     sqlite3_create_collation_v2(db->db, collname, SQLITE_UTF8,
1206         (void *)co,
1207         (int(*)(void*,int,const void*,int,const void*))collfunc,
1208         (void(*)(void*))collfree);
1209     return 0;
1210 }
1211 
1212 /* Thanks to Wolfgang Oertl...
1213 */
db_load_extension(lua_State * L)1214 static int db_load_extension(lua_State *L) {
1215     sdb *db=lsqlite_checkdb(L,1);
1216     const char *extname=luaL_optstring(L,2,NULL);
1217     const char *entrypoint=luaL_optstring(L,3,NULL);
1218     int result;
1219     char *errmsg = NULL;
1220 
1221     if (extname == NULL) {
1222         result = sqlite3_enable_load_extension(db->db,0); /* disable extension loading */
1223     }
1224     else {
1225         sqlite3_enable_load_extension(db->db,1); /* enable extension loading */
1226         result = sqlite3_load_extension(db->db,extname,entrypoint,&errmsg);
1227     }
1228 
1229     if (result == SQLITE_OK) {
1230         lua_pushboolean(L,1);
1231         return 1;
1232     }
1233 
1234     lua_pushboolean(L,0); /* so, assert(load_extension(...)) works */
1235     lua_pushstring(L,errmsg);
1236     sqlite3_free(errmsg);
1237     return 2;
1238 }
1239 
1240 /*
1241 ** trace callback:
1242 ** Params: database, callback function, userdata
1243 **
1244 ** callback function:
1245 ** Params: userdata, sql
1246 */
db_trace_callback(void * user,const char * sql)1247 static void db_trace_callback(void *user, const char *sql) {
1248     sdb *db = (sdb*)user;
1249     lua_State *L = db->L;
1250     int top = lua_gettop(L);
1251 
1252     /* setup lua callback call */
1253     lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_cb);    /* get callback */
1254     lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_udata); /* get callback user data */
1255     lua_pushstring(L, sql); /* traced sql statement */
1256 
1257     /* call lua function */
1258     lua_pcall(L, 2, 0, 0);
1259     /* ignore any error generated by this function */
1260 
1261     lua_settop(L, top);
1262 }
1263 
db_trace(lua_State * L)1264 static int db_trace(lua_State *L) {
1265     sdb *db = lsqlite_checkdb(L, 1);
1266 
1267     if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1268         luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
1269         luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
1270 
1271         db->trace_cb =
1272         db->trace_udata = LUA_NOREF;
1273 
1274         /* clear trace handler */
1275         sqlite3_trace(db->db, NULL, NULL);
1276     }
1277     else {
1278         luaL_checktype(L, 2, LUA_TFUNCTION);
1279 
1280         /* make sure we have an userdata field (even if nil) */
1281         lua_settop(L, 3);
1282 
1283         luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
1284         luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
1285 
1286         db->trace_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1287         db->trace_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1288 
1289         /* set trace handler */
1290         sqlite3_trace(db->db, db_trace_callback, db);
1291     }
1292 
1293     return 0;
1294 }
1295 
1296 #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
1297 
1298 /*
1299 ** update_hook callback:
1300 ** Params: database, callback function, userdata
1301 **
1302 ** callback function:
1303 ** Params: userdata, {one of SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE},
1304 **          database name, table name (containing the affected row), rowid of the row
1305 */
db_update_hook_callback(void * user,int op,char const * dbname,char const * tblname,sqlite3_int64 rowid)1306 static void db_update_hook_callback(void *user, int op, char const *dbname, char const *tblname, sqlite3_int64 rowid) {
1307     sdb *db = (sdb*)user;
1308     lua_State *L = db->L;
1309     int top = lua_gettop(L);
1310     //lua_Number n;
1311 
1312     /* setup lua callback call */
1313     lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_cb);    /* get callback */
1314     lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_udata); /* get callback user data */
1315     lua_pushinteger(L, op);
1316     lua_pushstring(L, dbname); /* update_hook database name */
1317     lua_pushstring(L, tblname); /* update_hook database name */
1318 
1319     PUSH_INT64(L, rowid, lua_pushfstring(L, "%ll", rowid));
1320 
1321     /* call lua function */
1322     lua_pcall(L, 5, 0, 0);
1323     /* ignore any error generated by this function */
1324 
1325     lua_settop(L, top);
1326 }
1327 
db_update_hook(lua_State * L)1328 static int db_update_hook(lua_State *L) {
1329     sdb *db = lsqlite_checkdb(L, 1);
1330 
1331     if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1332         luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
1333         luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);
1334 
1335         db->update_hook_cb =
1336         db->update_hook_udata = LUA_NOREF;
1337 
1338         /* clear update_hook handler */
1339         sqlite3_update_hook(db->db, NULL, NULL);
1340     }
1341     else {
1342         luaL_checktype(L, 2, LUA_TFUNCTION);
1343 
1344         /* make sure we have an userdata field (even if nil) */
1345         lua_settop(L, 3);
1346 
1347         luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
1348         luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);
1349 
1350         db->update_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1351         db->update_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1352 
1353         /* set update_hook handler */
1354         sqlite3_update_hook(db->db, db_update_hook_callback, db);
1355     }
1356 
1357     return 0;
1358 }
1359 
1360 /*
1361 ** commit_hook callback:
1362 ** Params: database, callback function, userdata
1363 **
1364 ** callback function:
1365 ** Params: userdata
1366 ** Returned value: Return false or nil to continue the COMMIT operation normally.
1367 **  return true (non false, non nil), then the COMMIT is converted into a ROLLBACK.
1368 */
db_commit_hook_callback(void * user)1369 static int db_commit_hook_callback(void *user) {
1370     sdb *db = (sdb*)user;
1371     lua_State *L = db->L;
1372     int top = lua_gettop(L);
1373     int rollback = 0;
1374 
1375     /* setup lua callback call */
1376     lua_rawgeti(L, LUA_REGISTRYINDEX, db->commit_hook_cb);    /* get callback */
1377     lua_rawgeti(L, LUA_REGISTRYINDEX, db->commit_hook_udata); /* get callback user data */
1378 
1379     /* call lua function */
1380     if (!lua_pcall(L, 1, 1, 0))
1381         rollback = lua_toboolean(L, -1); /* use result if there was no error */
1382 
1383     lua_settop(L, top);
1384     return rollback;
1385 }
1386 
db_commit_hook(lua_State * L)1387 static int db_commit_hook(lua_State *L) {
1388     sdb *db = lsqlite_checkdb(L, 1);
1389 
1390     if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1391         luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
1392         luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);
1393 
1394         db->commit_hook_cb =
1395         db->commit_hook_udata = LUA_NOREF;
1396 
1397         /* clear commit_hook handler */
1398         sqlite3_commit_hook(db->db, NULL, NULL);
1399     }
1400     else {
1401         luaL_checktype(L, 2, LUA_TFUNCTION);
1402 
1403         /* make sure we have an userdata field (even if nil) */
1404         lua_settop(L, 3);
1405 
1406         luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
1407         luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);
1408 
1409         db->commit_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1410         db->commit_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1411 
1412         /* set commit_hook handler */
1413         sqlite3_commit_hook(db->db, db_commit_hook_callback, db);
1414     }
1415 
1416     return 0;
1417 }
1418 
1419 /*
1420 ** rollback hook callback:
1421 ** Params: database, callback function, userdata
1422 **
1423 ** callback function:
1424 ** Params: userdata
1425 */
db_rollback_hook_callback(void * user)1426 static void db_rollback_hook_callback(void *user) {
1427     sdb *db = (sdb*)user;
1428     lua_State *L = db->L;
1429     int top = lua_gettop(L);
1430 
1431     /* setup lua callback call */
1432     lua_rawgeti(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);    /* get callback */
1433     lua_rawgeti(L, LUA_REGISTRYINDEX, db->rollback_hook_udata); /* get callback user data */
1434 
1435     /* call lua function */
1436     lua_pcall(L, 1, 0, 0);
1437     /* ignore any error generated by this function */
1438 
1439     lua_settop(L, top);
1440 }
1441 
db_rollback_hook(lua_State * L)1442 static int db_rollback_hook(lua_State *L) {
1443     sdb *db = lsqlite_checkdb(L, 1);
1444 
1445     if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1446         luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
1447         luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);
1448 
1449         db->rollback_hook_cb =
1450         db->rollback_hook_udata = LUA_NOREF;
1451 
1452         /* clear rollback_hook handler */
1453         sqlite3_rollback_hook(db->db, NULL, NULL);
1454     }
1455     else {
1456         luaL_checktype(L, 2, LUA_TFUNCTION);
1457 
1458         /* make sure we have an userdata field (even if nil) */
1459         lua_settop(L, 3);
1460 
1461         luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
1462         luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);
1463 
1464         db->rollback_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1465         db->rollback_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1466 
1467         /* set rollback_hook handler */
1468         sqlite3_rollback_hook(db->db, db_rollback_hook_callback, db);
1469     }
1470 
1471     return 0;
1472 }
1473 
1474 #endif /* #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK */
1475 
1476 #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK
1477 
1478 /*
1479 ** progress handler:
1480 ** Params: database, number of opcodes, callback function, userdata
1481 **
1482 ** callback function:
1483 ** Params: userdata
1484 ** returns: 0 to return immediatly and return SQLITE_ABORT, non-zero to continue
1485 */
db_progress_callback(void * user)1486 static int db_progress_callback(void *user) {
1487     int result = 1; /* abort by default */
1488     sdb *db = (sdb*)user;
1489     lua_State *L = db->L;
1490     int top = lua_gettop(L);
1491 
1492     lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_cb);
1493     lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_udata);
1494 
1495     /* call lua function */
1496     if (!lua_pcall(L, 1, 1, 0))
1497         result = lua_toboolean(L, -1);
1498 
1499     lua_settop(L, top);
1500     return result;
1501 }
1502 
db_progress_handler(lua_State * L)1503 static int db_progress_handler(lua_State *L) {
1504     sdb *db = lsqlite_checkdb(L, 1);
1505 
1506     if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1507         luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
1508         luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
1509 
1510         db->progress_cb =
1511         db->progress_udata = LUA_NOREF;
1512 
1513         /* clear busy handler */
1514         sqlite3_progress_handler(db->db, 0, NULL, NULL);
1515     }
1516     else {
1517         int nop = luaL_checkint(L, 2);  /* number of opcodes */
1518         luaL_checktype(L, 3, LUA_TFUNCTION);
1519 
1520         /* make sure we have an userdata field (even if nil) */
1521         lua_settop(L, 4);
1522 
1523         luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
1524         luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
1525 
1526         db->progress_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1527         db->progress_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1528 
1529         /* set progress callback */
1530         sqlite3_progress_handler(db->db, nop, db_progress_callback, db);
1531     }
1532 
1533     return 0;
1534 }
1535 
1536 #else /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */
1537 
db_progress_handler(lua_State * L)1538 static int db_progress_handler(lua_State *L) {
1539     lua_pushliteral(L, "progress callback support disabled at compile time");
1540     lua_error(L);
1541     return 0;
1542 }
1543 
1544 #endif /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */
1545 
1546 /* Online Backup API */
1547 #if 0
1548 sqlite3_backup *sqlite3_backup_init(
1549   sqlite3 *pDest,                        /* Destination database handle */
1550   const char *zDestName,                 /* Destination database name */
1551   sqlite3 *pSource,                      /* Source database handle */
1552   const char *zSourceName                /* Source database name */
1553 );
1554 int sqlite3_backup_step(sqlite3_backup *p, int nPage);
1555 int sqlite3_backup_finish(sqlite3_backup *p);
1556 int sqlite3_backup_remaining(sqlite3_backup *p);
1557 int sqlite3_backup_pagecount(sqlite3_backup *p);
1558 #endif
1559 
1560 struct sdb_bu {
1561     sqlite3_backup *bu;     /* backup structure */
1562 };
1563 
cleanupbu(lua_State * L,sdb_bu * sbu)1564 static int cleanupbu(lua_State *L, sdb_bu *sbu) {
1565 
1566     if (!sbu->bu) return 0; /* already finished */
1567 
1568     /* remove table from registry */
1569     lua_pushlightuserdata(L, sbu->bu);
1570     lua_pushnil(L);
1571     lua_rawset(L, LUA_REGISTRYINDEX);
1572 
1573     lua_pushinteger(L, sqlite3_backup_finish(sbu->bu));
1574     sbu->bu = NULL;
1575 
1576     return 1;
1577 }
1578 
lsqlite_backup_init(lua_State * L)1579 static int lsqlite_backup_init(lua_State *L) {
1580 
1581     sdb *target_db = lsqlite_checkdb(L, 1);
1582     const char *target_nm = luaL_checkstring(L, 2);
1583     sdb *source_db = lsqlite_checkdb(L, 3);
1584     const char *source_nm = luaL_checkstring(L, 4);
1585 
1586     sqlite3_backup *bu = sqlite3_backup_init(target_db->db, target_nm, source_db->db, source_nm);
1587 
1588     if (NULL != bu) {
1589         sdb_bu *sbu = (sdb_bu*)lua_newuserdata(L, sizeof(sdb_bu));
1590 
1591         luaL_getmetatable(L, sqlite_bu_meta);
1592         lua_setmetatable(L, -2);        /* set metatable */
1593         sbu->bu = bu;
1594 
1595         /* create table from registry */
1596         /* to prevent referenced databases from being garbage collected while bu is live */
1597         lua_pushlightuserdata(L, bu);
1598         lua_createtable(L, 2, 0);
1599         /* add source and target dbs to table at indices 1 and 2 */
1600         lua_pushvalue(L, 1); /* target db */
1601         lua_rawseti(L, -2, 1);
1602         lua_pushvalue(L, 3); /* source db */
1603         lua_rawseti(L, -2, 2);
1604         /* put table in registry with key lightuserdata bu */
1605         lua_rawset(L, LUA_REGISTRYINDEX);
1606 
1607         return 1;
1608     }
1609     else {
1610         return 0;
1611     }
1612 }
1613 
lsqlite_getbu(lua_State * L,int index)1614 static sdb_bu *lsqlite_getbu(lua_State *L, int index) {
1615     sdb_bu *sbu = (sdb_bu*)luaL_checkudata(L, index, sqlite_bu_meta);
1616     if (sbu == NULL) luaL_typerror(L, index, "sqlite database backup");
1617     return sbu;
1618 }
1619 
lsqlite_checkbu(lua_State * L,int index)1620 static sdb_bu *lsqlite_checkbu(lua_State *L, int index) {
1621     sdb_bu *sbu = lsqlite_getbu(L, index);
1622     if (sbu->bu == NULL) luaL_argerror(L, index, "attempt to use closed sqlite database backup");
1623     return sbu;
1624 }
1625 
dbbu_gc(lua_State * L)1626 static int dbbu_gc(lua_State *L) {
1627     sdb_bu *sbu = lsqlite_getbu(L, 1);
1628     if (sbu->bu != NULL) {
1629         cleanupbu(L, sbu);
1630         lua_pop(L, 1);
1631     }
1632     /* else ignore if already finished */
1633     return 0;
1634 }
1635 
dbbu_step(lua_State * L)1636 static int dbbu_step(lua_State *L) {
1637     sdb_bu *sbu = lsqlite_checkbu(L, 1);
1638     int nPage = luaL_checkint(L, 2);
1639     lua_pushinteger(L, sqlite3_backup_step(sbu->bu, nPage));
1640     return 1;
1641 }
1642 
dbbu_remaining(lua_State * L)1643 static int dbbu_remaining(lua_State *L) {
1644     sdb_bu *sbu = lsqlite_checkbu(L, 1);
1645     lua_pushinteger(L, sqlite3_backup_remaining(sbu->bu));
1646     return 1;
1647 }
1648 
dbbu_pagecount(lua_State * L)1649 static int dbbu_pagecount(lua_State *L) {
1650     sdb_bu *sbu = lsqlite_checkbu(L, 1);
1651     lua_pushinteger(L, sqlite3_backup_pagecount(sbu->bu));
1652     return 1;
1653 }
1654 
dbbu_finish(lua_State * L)1655 static int dbbu_finish(lua_State *L) {
1656     sdb_bu *sbu = lsqlite_checkbu(L, 1);
1657     return cleanupbu(L, sbu);
1658 }
1659 
1660 /* end of Online Backup API */
1661 
1662 /*
1663 ** busy handler:
1664 ** Params: database, callback function, userdata
1665 **
1666 ** callback function:
1667 ** Params: userdata, number of tries
1668 ** returns: 0 to return immediatly and return SQLITE_BUSY, non-zero to try again
1669 */
db_busy_callback(void * user,int tries)1670 static int db_busy_callback(void *user, int tries) {
1671     int retry = 0; /* abort by default */
1672     sdb *db = (sdb*)user;
1673     lua_State *L = db->L;
1674     int top = lua_gettop(L);
1675 
1676     lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_cb);
1677     lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_udata);
1678     lua_pushinteger(L, tries);
1679 
1680     /* call lua function */
1681     if (!lua_pcall(L, 2, 1, 0))
1682         retry = lua_toboolean(L, -1);
1683 
1684     lua_settop(L, top);
1685     return retry;
1686 }
1687 
db_busy_handler(lua_State * L)1688 static int db_busy_handler(lua_State *L) {
1689     sdb *db = lsqlite_checkdb(L, 1);
1690 
1691     if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1692         luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1693         luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1694 
1695         db->busy_cb =
1696         db->busy_udata = LUA_NOREF;
1697 
1698         /* clear busy handler */
1699         sqlite3_busy_handler(db->db, NULL, NULL);
1700     }
1701     else {
1702         luaL_checktype(L, 2, LUA_TFUNCTION);
1703         /* make sure we have an userdata field (even if nil) */
1704         lua_settop(L, 3);
1705 
1706         luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1707         luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1708 
1709         db->busy_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1710         db->busy_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1711 
1712         /* set busy handler */
1713         sqlite3_busy_handler(db->db, db_busy_callback, db);
1714     }
1715 
1716     return 0;
1717 }
1718 
db_busy_timeout(lua_State * L)1719 static int db_busy_timeout(lua_State *L) {
1720     sdb *db = lsqlite_checkdb(L, 1);
1721     int timeout = luaL_checkint(L, 2);
1722     sqlite3_busy_timeout(db->db, timeout);
1723 
1724     /* if there was a timeout callback registered, it is now
1725     ** invalid/useless. free any references we may have */
1726     luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1727     luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1728     db->busy_cb =
1729     db->busy_udata = LUA_NOREF;
1730 
1731     return 0;
1732 }
1733 
1734 /*
1735 ** Params: db, sql, callback, user
1736 ** returns: code [, errmsg]
1737 **
1738 ** Callback:
1739 ** Params: user, number of columns, values, names
1740 ** Returns: 0 to continue, other value will cause abort
1741 */
db_exec_callback(void * user,int columns,char ** data,char ** names)1742 static int db_exec_callback(void* user, int columns, char **data, char **names) {
1743     int result = SQLITE_ABORT; /* abort by default */
1744     lua_State *L = (lua_State*)user;
1745     int n;
1746 
1747     int top = lua_gettop(L);
1748 
1749     lua_pushvalue(L, 3); /* function to call */
1750     lua_pushvalue(L, 4); /* user data */
1751     lua_pushinteger(L, columns); /* total number of rows in result */
1752 
1753     /* column values */
1754     lua_pushvalue(L, 6);
1755     for (n = 0; n < columns;) {
1756         lua_pushstring(L, data[n++]);
1757         lua_rawseti(L, -2, n);
1758     }
1759 
1760     /* columns names */
1761     lua_pushvalue(L, 5);
1762     if (lua_isnil(L, -1)) {
1763         lua_pop(L, 1);
1764         lua_createtable(L, columns, 0);
1765         lua_pushvalue(L, -1);
1766         lua_replace(L, 5);
1767         for (n = 0; n < columns;) {
1768             lua_pushstring(L, names[n++]);
1769             lua_rawseti(L, -2, n);
1770         }
1771     }
1772 
1773     /* call lua function */
1774     if (!lua_pcall(L, 4, 1, 0)) {
1775 
1776 #if LUA_VERSION_NUM > 502
1777         if (lua_isinteger(L, -1))
1778             result = lua_tointeger(L, -1);
1779         else
1780 #endif
1781         if (lua_isnumber(L, -1))
1782             result = lua_tonumber(L, -1);
1783     }
1784 
1785     lua_settop(L, top);
1786     return result;
1787 }
1788 
db_exec(lua_State * L)1789 static int db_exec(lua_State *L) {
1790     sdb *db = lsqlite_checkdb(L, 1);
1791     const char *sql = luaL_checkstring(L, 2);
1792     int result;
1793 
1794     if (!lua_isnoneornil(L, 3)) {
1795         /* stack:
1796         **  3: callback function
1797         **  4: userdata
1798         **  5: column names
1799         **  6: reusable column values
1800         */
1801         luaL_checktype(L, 3, LUA_TFUNCTION);
1802         lua_settop(L, 4);   /* 'trap' userdata - nil extra parameters */
1803         lua_pushnil(L);     /* column names not known at this point */
1804         lua_newtable(L);    /* column values table */
1805 
1806         result = sqlite3_exec(db->db, sql, db_exec_callback, L, NULL);
1807     }
1808     else {
1809         /* no callbacks */
1810         result = sqlite3_exec(db->db, sql, NULL, NULL, NULL);
1811     }
1812 
1813     lua_pushinteger(L, result);
1814     return 1;
1815 }
1816 
1817 /*
1818 ** Params: db, sql
1819 ** returns: code, compiled length or error message
1820 */
db_prepare(lua_State * L)1821 static int db_prepare(lua_State *L) {
1822     sdb *db = lsqlite_checkdb(L, 1);
1823     const char *sql = luaL_checkstring(L, 2);
1824     int sql_len = lua_strlen(L, 2);
1825     const char *sqltail;
1826     sdb_vm *svm;
1827     lua_settop(L,2); /* db,sql is on top of stack for call to newvm */
1828     svm = newvm(L, db);
1829 
1830     if (sqlite3_prepare_v2(db->db, sql, sql_len, &svm->vm, &sqltail) != SQLITE_OK) {
1831         lua_pushnil(L);
1832         lua_pushinteger(L, sqlite3_errcode(db->db));
1833         if (cleanupvm(L, svm) == 1)
1834             lua_pop(L, 1); /* this should not happen since sqlite3_prepare_v2 will not set ->vm on error */
1835         return 2;
1836     }
1837 
1838     /* vm already in the stack */
1839     lua_pushstring(L, sqltail);
1840     return 2;
1841 }
1842 
db_do_next_row(lua_State * L,int packed)1843 static int db_do_next_row(lua_State *L, int packed) {
1844     int result;
1845     sdb_vm *svm = lsqlite_checkvm(L, 1);
1846     sqlite3_stmt *vm;
1847     int columns;
1848     int i;
1849 
1850     result = stepvm(L, svm);
1851     vm = svm->vm; /* stepvm may change svm->vm if re-prepare is needed */
1852     svm->has_values = result == SQLITE_ROW ? 1 : 0;
1853     svm->columns = columns = sqlite3_data_count(vm);
1854 
1855     if (result == SQLITE_ROW) {
1856         if (packed) {
1857             if (packed == 1) {
1858                 lua_createtable(L, columns, 0);
1859                 for (i = 0; i < columns;) {
1860                     vm_push_column(L, vm, i);
1861                     lua_rawseti(L, -2, ++i);
1862                 }
1863             }
1864             else {
1865                 lua_createtable(L, 0, columns);
1866                 for (i = 0; i < columns; ++i) {
1867                     lua_pushstring(L, sqlite3_column_name(vm, i));
1868                     vm_push_column(L, vm, i);
1869                     lua_rawset(L, -3);
1870                 }
1871             }
1872             return 1;
1873         }
1874         else {
1875             lua_checkstack(L, columns);
1876             for (i = 0; i < columns; ++i)
1877                 vm_push_column(L, vm, i);
1878             return svm->columns;
1879         }
1880     }
1881 
1882     if (svm->temp) {
1883         /* finalize and check for errors */
1884         result = sqlite3_finalize(vm);
1885         svm->vm = NULL;
1886         cleanupvm(L, svm);
1887     }
1888     else if (result == SQLITE_DONE) {
1889         result = sqlite3_reset(vm);
1890     }
1891 
1892     if (result != SQLITE_OK) {
1893         lua_pushstring(L, sqlite3_errmsg(svm->db->db));
1894         lua_error(L);
1895     }
1896     return 0;
1897 }
1898 
db_next_row(lua_State * L)1899 static int db_next_row(lua_State *L) {
1900     return db_do_next_row(L, 0);
1901 }
1902 
db_next_packed_row(lua_State * L)1903 static int db_next_packed_row(lua_State *L) {
1904     return db_do_next_row(L, 1);
1905 }
1906 
db_next_named_row(lua_State * L)1907 static int db_next_named_row(lua_State *L) {
1908     return db_do_next_row(L, 2);
1909 }
1910 
dbvm_do_rows(lua_State * L,int (* f)(lua_State *))1911 static int dbvm_do_rows(lua_State *L, int(*f)(lua_State *)) {
1912     /* sdb_vm *svm =  */
1913     lsqlite_checkvm(L, 1);
1914     lua_pushvalue(L,1);
1915     lua_pushcfunction(L, f);
1916     lua_insert(L, -2);
1917     return 2;
1918 }
1919 
dbvm_rows(lua_State * L)1920 static int dbvm_rows(lua_State *L) {
1921     return dbvm_do_rows(L, db_next_packed_row);
1922 }
1923 
dbvm_nrows(lua_State * L)1924 static int dbvm_nrows(lua_State *L) {
1925     return dbvm_do_rows(L, db_next_named_row);
1926 }
1927 
dbvm_urows(lua_State * L)1928 static int dbvm_urows(lua_State *L) {
1929     return dbvm_do_rows(L, db_next_row);
1930 }
1931 
db_do_rows(lua_State * L,int (* f)(lua_State *))1932 static int db_do_rows(lua_State *L, int(*f)(lua_State *)) {
1933     sdb *db = lsqlite_checkdb(L, 1);
1934     const char *sql = luaL_checkstring(L, 2);
1935     sdb_vm *svm;
1936     lua_settop(L,2); /* db,sql is on top of stack for call to newvm */
1937     svm = newvm(L, db);
1938     svm->temp = 1;
1939 
1940     if (sqlite3_prepare_v2(db->db, sql, -1, &svm->vm, NULL) != SQLITE_OK) {
1941         lua_pushstring(L, sqlite3_errmsg(svm->db->db));
1942         if (cleanupvm(L, svm) == 1)
1943             lua_pop(L, 1); /* this should not happen since sqlite3_prepare_v2 will not set ->vm on error */
1944         lua_error(L);
1945     }
1946 
1947     lua_pushcfunction(L, f);
1948     lua_insert(L, -2);
1949     return 2;
1950 }
1951 
db_rows(lua_State * L)1952 static int db_rows(lua_State *L) {
1953     return db_do_rows(L, db_next_packed_row);
1954 }
1955 
db_nrows(lua_State * L)1956 static int db_nrows(lua_State *L) {
1957     return db_do_rows(L, db_next_named_row);
1958 }
1959 
1960 /* unpacked version of db:rows */
db_urows(lua_State * L)1961 static int db_urows(lua_State *L) {
1962     return db_do_rows(L, db_next_row);
1963 }
1964 
db_tostring(lua_State * L)1965 static int db_tostring(lua_State *L) {
1966     char buff[32];
1967     sdb *db = lsqlite_getdb(L, 1);
1968     if (db->db == NULL)
1969         strcpy(buff, "closed");
1970     else
1971         sprintf(buff, "%p", lua_touserdata(L, 1));
1972     lua_pushfstring(L, "sqlite database (%s)", buff);
1973     return 1;
1974 }
1975 
db_close(lua_State * L)1976 static int db_close(lua_State *L) {
1977     sdb *db = lsqlite_checkdb(L, 1);
1978     lua_pushinteger(L, cleanupdb(L, db));
1979     return 1;
1980 }
1981 
db_close_vm(lua_State * L)1982 static int db_close_vm(lua_State *L) {
1983     sdb *db = lsqlite_checkdb(L, 1);
1984     /* cleanup temporary only tables? */
1985     int temp = lua_toboolean(L, 2);
1986 
1987     /* free associated virtual machines */
1988     lua_pushlightuserdata(L, db);
1989     lua_rawget(L, LUA_REGISTRYINDEX);
1990 
1991     /* close all used handles */
1992     lua_pushnil(L);
1993     while (lua_next(L, -2)) {
1994         sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */
1995 
1996         if ((!temp || svm->temp) && svm->vm)
1997         {
1998             sqlite3_finalize(svm->vm);
1999             svm->vm = NULL;
2000         }
2001 
2002         /* leave key in the stack */
2003         lua_pop(L, 1);
2004     }
2005     return 0;
2006 }
2007 
db_gc(lua_State * L)2008 static int db_gc(lua_State *L) {
2009     sdb *db = lsqlite_getdb(L, 1);
2010     if (db->db != NULL)  /* ignore closed databases */
2011         cleanupdb(L, db);
2012     return 0;
2013 }
2014 
2015 /*
2016 ** =======================================================
2017 ** General library functions
2018 ** =======================================================
2019 */
2020 
lsqlite_version(lua_State * L)2021 static int lsqlite_version(lua_State *L) {
2022     lua_pushstring(L, sqlite3_libversion());
2023     return 1;
2024 }
2025 
lsqlite_complete(lua_State * L)2026 static int lsqlite_complete(lua_State *L) {
2027     const char *sql = luaL_checkstring(L, 1);
2028     lua_pushboolean(L, sqlite3_complete(sql));
2029     return 1;
2030 }
2031 
2032 #ifndef WIN32
lsqlite_temp_directory(lua_State * L)2033 static int lsqlite_temp_directory(lua_State *L) {
2034     const char *oldtemp = sqlite3_temp_directory;
2035 
2036     if (!lua_isnone(L, 1)) {
2037         const char *temp = luaL_optstring(L, 1, NULL);
2038         if (sqlite3_temp_directory) {
2039             sqlite3_free((char*)sqlite3_temp_directory);
2040         }
2041         if (temp) {
2042             sqlite3_temp_directory = sqlite3_mprintf("%s", temp);
2043         }
2044         else {
2045             sqlite3_temp_directory = NULL;
2046         }
2047     }
2048     lua_pushstring(L, oldtemp);
2049     return 1;
2050 }
2051 #endif
2052 
lsqlite_do_open(lua_State * L,const char * filename,int flags)2053 static int lsqlite_do_open(lua_State *L, const char *filename, int flags) {
2054     sdb *db = newdb(L); /* create and leave in stack */
2055 
2056     if (SQLITE3_OPEN(filename, &db->db, flags) == SQLITE_OK) {
2057         /* database handle already in the stack - return it */
2058         return 1;
2059     }
2060 
2061     /* failed to open database */
2062     lua_pushnil(L);                             /* push nil */
2063     lua_pushinteger(L, sqlite3_errcode(db->db));
2064     lua_pushstring(L, sqlite3_errmsg(db->db));  /* push error message */
2065 
2066     /* clean things up */
2067     cleanupdb(L, db);
2068 
2069     /* return */
2070     return 3;
2071 }
2072 
lsqlite_open(lua_State * L)2073 static int lsqlite_open(lua_State *L) {
2074     const char *filename = luaL_checkstring(L, 1);
2075     int flags = luaL_optinteger(L, 2, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
2076     return lsqlite_do_open(L, filename, flags);
2077 }
2078 
lsqlite_open_memory(lua_State * L)2079 static int lsqlite_open_memory(lua_State *L) {
2080     return lsqlite_do_open(L, ":memory:", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
2081 }
2082 
lsqlite_newindex(lua_State * L)2083 static int lsqlite_newindex(lua_State *L) {
2084     lua_pushliteral(L, "attempt to change readonly table");
2085     lua_error(L);
2086     return 0;
2087 }
2088 
2089 #ifndef LSQLITE_VERSION
2090 /* should be defined in rockspec, but just in case... */
2091 #define LSQLITE_VERSION "unknown"
2092 #endif
2093 
2094 /* Version number of this library
2095 */
lsqlite_lversion(lua_State * L)2096 static int lsqlite_lversion(lua_State *L) {
2097     lua_pushstring(L, LSQLITE_VERSION);
2098     return 1;
2099 }
2100 
2101 /*
2102 ** =======================================================
2103 ** Register functions
2104 ** =======================================================
2105 */
2106 
2107 #define SC(s)   { #s, SQLITE_ ## s },
2108 #define LSC(s)  { #s, LSQLITE_ ## s },
2109 
2110 static const struct {
2111     const char* name;
2112     int value;
2113 } sqlite_constants[] = {
2114     /* error codes */
2115     SC(OK)          SC(ERROR)       SC(INTERNAL)    SC(PERM)
2116     SC(ABORT)       SC(BUSY)        SC(LOCKED)      SC(NOMEM)
2117     SC(READONLY)    SC(INTERRUPT)   SC(IOERR)       SC(CORRUPT)
2118     SC(NOTFOUND)    SC(FULL)        SC(CANTOPEN)    SC(PROTOCOL)
2119     SC(EMPTY)       SC(SCHEMA)      SC(TOOBIG)      SC(CONSTRAINT)
2120     SC(MISMATCH)    SC(MISUSE)      SC(NOLFS)
2121     SC(FORMAT)      SC(NOTADB)
2122 
2123     /* sqlite_step specific return values */
2124     SC(RANGE)       SC(ROW)         SC(DONE)
2125 
2126     /* column types */
2127     SC(INTEGER)     SC(FLOAT)       SC(TEXT)        SC(BLOB)
2128     SC(NULL)
2129 
2130     /* Authorizer Action Codes */
2131     SC(CREATE_INDEX       )
2132     SC(CREATE_TABLE       )
2133     SC(CREATE_TEMP_INDEX  )
2134     SC(CREATE_TEMP_TABLE  )
2135     SC(CREATE_TEMP_TRIGGER)
2136     SC(CREATE_TEMP_VIEW   )
2137     SC(CREATE_TRIGGER     )
2138     SC(CREATE_VIEW        )
2139     SC(DELETE             )
2140     SC(DROP_INDEX         )
2141     SC(DROP_TABLE         )
2142     SC(DROP_TEMP_INDEX    )
2143     SC(DROP_TEMP_TABLE    )
2144     SC(DROP_TEMP_TRIGGER  )
2145     SC(DROP_TEMP_VIEW     )
2146     SC(DROP_TRIGGER       )
2147     SC(DROP_VIEW          )
2148     SC(INSERT             )
2149     SC(PRAGMA             )
2150     SC(READ               )
2151     SC(SELECT             )
2152     SC(TRANSACTION        )
2153     SC(UPDATE             )
2154     SC(ATTACH             )
2155     SC(DETACH             )
2156     SC(ALTER_TABLE        )
2157     SC(REINDEX            )
2158     SC(ANALYZE            )
2159     SC(CREATE_VTABLE      )
2160     SC(DROP_VTABLE        )
2161     SC(FUNCTION           )
2162     SC(SAVEPOINT          )
2163 
2164     /* file open flags */
2165     SC(OPEN_READONLY)
2166     SC(OPEN_READWRITE)
2167     SC(OPEN_CREATE)
2168     SC(OPEN_URI)
2169     SC(OPEN_MEMORY)
2170     SC(OPEN_NOMUTEX)
2171     SC(OPEN_FULLMUTEX)
2172     SC(OPEN_SHAREDCACHE)
2173     SC(OPEN_PRIVATECACHE)
2174 
2175     /* terminator */
2176     { NULL, 0 }
2177 };
2178 
2179 /* ======================================================= */
2180 
2181 static const luaL_Reg dblib[] = {
2182     {"isopen",              db_isopen               },
2183     {"last_insert_rowid",   db_last_insert_rowid    },
2184     {"changes",             db_changes              },
2185     {"total_changes",       db_total_changes        },
2186     {"errcode",             db_errcode              },
2187     {"error_code",          db_errcode              },
2188     {"errmsg",              db_errmsg               },
2189     {"error_message",       db_errmsg               },
2190     {"interrupt",           db_interrupt            },
2191 
2192     {"create_function",     db_create_function      },
2193     {"create_aggregate",    db_create_aggregate     },
2194     {"create_collation",    db_create_collation     },
2195     {"load_extension",      db_load_extension       },
2196 
2197     {"trace",               db_trace                },
2198     {"progress_handler",    db_progress_handler     },
2199     {"busy_timeout",        db_busy_timeout         },
2200     {"busy_handler",        db_busy_handler         },
2201 #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
2202     {"update_hook",         db_update_hook          },
2203     {"commit_hook",         db_commit_hook          },
2204     {"rollback_hook",       db_rollback_hook        },
2205 #endif
2206 
2207     {"prepare",             db_prepare              },
2208     {"rows",                db_rows                 },
2209     {"urows",               db_urows                },
2210     {"nrows",               db_nrows                },
2211 
2212     {"exec",                db_exec                 },
2213     {"execute",             db_exec                 },
2214     {"close",               db_close                },
2215     {"close_vm",            db_close_vm             },
2216 
2217     {"__tostring",          db_tostring             },
2218     {"__gc",                db_gc                   },
2219 
2220     {NULL, NULL}
2221 };
2222 
2223 static const luaL_Reg vmlib[] = {
2224     {"isopen",              dbvm_isopen             },
2225 
2226     {"step",                dbvm_step               },
2227     {"reset",               dbvm_reset              },
2228     {"finalize",            dbvm_finalize           },
2229 
2230     {"columns",             dbvm_columns            },
2231 
2232     {"bind",                dbvm_bind               },
2233     {"bind_values",         dbvm_bind_values        },
2234     {"bind_names",          dbvm_bind_names         },
2235     {"bind_blob",           dbvm_bind_blob          },
2236     {"bind_parameter_count",dbvm_bind_parameter_count},
2237     {"bind_parameter_name", dbvm_bind_parameter_name},
2238 
2239     {"get_value",           dbvm_get_value          },
2240     {"get_values",          dbvm_get_values         },
2241     {"get_name",            dbvm_get_name           },
2242     {"get_names",           dbvm_get_names          },
2243     {"get_type",            dbvm_get_type           },
2244     {"get_types",           dbvm_get_types          },
2245     {"get_uvalues",         dbvm_get_uvalues        },
2246     {"get_unames",          dbvm_get_unames         },
2247     {"get_utypes",          dbvm_get_utypes         },
2248 
2249     {"get_named_values",    dbvm_get_named_values   },
2250     {"get_named_types",     dbvm_get_named_types    },
2251 
2252     {"rows",                dbvm_rows               },
2253     {"urows",               dbvm_urows              },
2254     {"nrows",               dbvm_nrows              },
2255 
2256     {"last_insert_rowid",   dbvm_last_insert_rowid  },
2257 
2258     /* compatibility names (added by request) */
2259     {"idata",               dbvm_get_values         },
2260     {"inames",              dbvm_get_names          },
2261     {"itypes",              dbvm_get_types          },
2262     {"data",                dbvm_get_named_values   },
2263     {"type",                dbvm_get_named_types    },
2264 
2265     {"__tostring",          dbvm_tostring           },
2266     {"__gc",                dbvm_gc                 },
2267 
2268     { NULL, NULL }
2269 };
2270 
2271 static const luaL_Reg ctxlib[] = {
2272     {"user_data",               lcontext_user_data              },
2273 
2274     {"get_aggregate_data",      lcontext_get_aggregate_context  },
2275     {"set_aggregate_data",      lcontext_set_aggregate_context  },
2276     {"aggregate_count",         lcontext_aggregate_count        },
2277 
2278     {"result",                  lcontext_result                 },
2279     {"result_null",             lcontext_result_null            },
2280     {"result_number",           lcontext_result_double          },
2281     {"result_double",           lcontext_result_double          },
2282     {"result_int",              lcontext_result_int             },
2283     {"result_text",             lcontext_result_text            },
2284     {"result_blob",             lcontext_result_blob            },
2285     {"result_error",            lcontext_result_error           },
2286 
2287     {"__tostring",              lcontext_tostring               },
2288     {NULL, NULL}
2289 };
2290 
2291 static const luaL_Reg dbbulib[] = {
2292 
2293     {"step",        dbbu_step       },
2294     {"remaining",   dbbu_remaining  },
2295     {"pagecount",   dbbu_pagecount  },
2296     {"finish",      dbbu_finish     },
2297 
2298 //  {"__tostring",  dbbu_tostring   },
2299     {"__gc",        dbbu_gc         },
2300     {NULL, NULL}
2301 };
2302 
2303 static const luaL_Reg sqlitelib[] = {
2304     {"lversion",        lsqlite_lversion        },
2305     {"version",         lsqlite_version         },
2306     {"complete",        lsqlite_complete        },
2307 #ifndef WIN32
2308     {"temp_directory",  lsqlite_temp_directory  },
2309 #endif
2310     {"open",            lsqlite_open            },
2311     {"open_memory",     lsqlite_open_memory     },
2312 
2313     {"backup_init",     lsqlite_backup_init     },
2314 
2315     {"__newindex",      lsqlite_newindex        },
2316     {NULL, NULL}
2317 };
2318 
create_meta(lua_State * L,const char * name,const luaL_Reg * lib)2319 static void create_meta(lua_State *L, const char *name, const luaL_Reg *lib) {
2320     luaL_newmetatable(L, name);
2321     lua_pushstring(L, "__index");
2322     lua_pushvalue(L, -2);               /* push metatable */
2323     lua_rawset(L, -3);                  /* metatable.__index = metatable */
2324 
2325     /* register metatable functions */
2326     luaL_openlib(L, NULL, lib, 0);
2327 
2328     /* remove metatable from stack */
2329     lua_pop(L, 1);
2330 }
2331 
luaopen_sqlite3(lua_State * L)2332 static int luaopen_sqlite3 ( lua_State * L )
2333 {
2334 	luaL_newlib(L, sqlitelib);
2335 	return 1;
2336 }
2337 
luaopen_lsqlite3(lua_State * L)2338 LUALIB_API int luaopen_lsqlite3(lua_State *L) {
2339     create_meta(L, sqlite_meta, dblib);
2340     create_meta(L, sqlite_vm_meta, vmlib);
2341     create_meta(L, sqlite_bu_meta, dbbulib);
2342     create_meta(L, sqlite_ctx_meta, ctxlib);
2343 
2344     luaL_getmetatable(L, sqlite_ctx_meta);
2345     sqlite_ctx_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX);
2346 
2347     /* register (local) sqlite metatable */
2348 	//luaL_register(L, "sqlite3", sqlitelib);
2349 	luaL_requiref(L, "sqlite3", luaopen_sqlite3, 1);
2350     {
2351         int i = 0;
2352         /* add constants to global table */
2353         while (sqlite_constants[i].name) {
2354             lua_pushstring(L, sqlite_constants[i].name);
2355             lua_pushinteger(L, sqlite_constants[i].value);
2356             lua_rawset(L, -3);
2357             ++i;
2358         }
2359     }
2360 
2361     /* set sqlite's metatable to itself - set as readonly (__newindex) */
2362     lua_pushvalue(L, -1);
2363     lua_setmetatable(L, -2);
2364 
2365     return 1;
2366 }
2367