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