Previous 199869 Revisions Next

r34323 Saturday 10th January, 2015 at 13:53:39 UTC by Miodrag Milanović
Added more resent lsqlite3 version and fixed compile
[3rdparty/lsqlite3]lsqlite3.c
[src/emu]luaengine.c luaengine.h
[src/lib]lib.mak

trunk/3rdparty/lsqlite3/lsqlite3.c
r242834r242835
11/************************************************************************
22* lsqlite3                                                              *
3* Copyright (C) 2002-2007 Tiago Dionizio, Doug Currie                   *
3* Copyright (C) 2002-2013 Tiago Dionizio, Doug Currie                   *
44* All rights reserved.                                                  *
55* Author    : Tiago Dionizio <tiago.dionizio@ist.utl.pt>                *
66* Author    : Doug Currie <doug.currie@alum.mit.edu>                    *
r242834r242835
3030#include <string.h>
3131#include <assert.h>
3232
33#include "lua.h"
34#include "lauxlib.h"
33#define LUA_LIB
34#include "lua/lua.h"
35#include "lua/lauxlib.h"
3536
36#include "sqlite3.h"
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#endif
3749
50#include "sqlite3/sqlite3.h"
51
3852/* compile time features */
3953#if !defined(SQLITE_OMIT_PROGRESS_CALLBACK)
40    #define SQLITE_OMIT_PROGRESS_CALLBACK 0
54   #define SQLITE_OMIT_PROGRESS_CALLBACK 0
4155#endif
56#if !defined(LSQLITE_OMIT_UPDATE_HOOK)
57   #define LSQLITE_OMIT_UPDATE_HOOK 0
58#endif
4259
4360typedef struct sdb sdb;
4461typedef struct sdb_vm sdb_vm;
r242834r242835
4663
4764/* to use as C user data so i know what function sqlite is calling */
4865struct sdb_func {
49    /* references to associated lua values */
50    int fn_step;
51    int fn_finalize;
52    int udata;
66   /* references to associated lua values */
67   int fn_step;
68   int fn_finalize;
69   int udata;
5370
54    sdb *db;
55    char aggregate;
71   sdb *db;
72   char aggregate;
5673
57    sdb_func *next;
74   sdb_func *next;
5875};
5976
6077/* information about database */
6178struct sdb {
62    /* associated lua state */
63    lua_State *L;
64    /* sqlite database handle */
65    sqlite3 *db;
79   /* associated lua state */
80   lua_State *L;
81   /* sqlite database handle */
82   sqlite3 *db;
6683
67    /* sql functions stack usage */
68    sdb_func *func;         /* top SQL function being called */
84   /* sql functions stack usage */
85   sdb_func *func;         /* top SQL function being called */
6986
70    /* references */
71    int busy_cb;        /* busy callback */
72    int busy_udata;
87   /* references */
88   int busy_cb;        /* busy callback */
89   int busy_udata;
7390
74    int progress_cb;    /* progress handler */
75    int progress_udata;
91   int progress_cb;    /* progress handler */
92   int progress_udata;
7693
77    int trace_cb;       /* trace callback */
78    int trace_udata;
94   int trace_cb;       /* trace callback */
95   int trace_udata;
96
97#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
98
99   int update_hook_cb; /* update_hook callback */
100   int update_hook_udata;
101
102   int commit_hook_cb; /* commit_hook callback */
103   int commit_hook_udata;
104
105   int rollback_hook_cb; /* rollback_hook callback */
106   int rollback_hook_udata;
107
108#endif
79109};
80110
81111static const char *sqlite_meta      = ":sqlite3";
r242834r242835
90120*/
91121
92122static void vm_push_column(lua_State *L, sqlite3_stmt *vm, int idx) {
93    switch (sqlite3_column_type(vm, idx)) {
94        case SQLITE_INTEGER:
95            {
96                sqlite_int64 i64 = sqlite3_column_int64(vm, idx);
97                lua_Number n = (lua_Number)i64;
98                if (n == i64)
99                    lua_pushnumber(L, n);
100                else
101                    lua_pushlstring(L, sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx));
102            }
103            break;
104        case SQLITE_FLOAT:
105            lua_pushnumber(L, sqlite3_column_double(vm, idx));
106            break;
107        case SQLITE_TEXT:
108            lua_pushlstring(L, sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx));
109            break;
110        case SQLITE_BLOB:
111            lua_pushlstring(L, sqlite3_column_blob(vm, idx), sqlite3_column_bytes(vm, idx));
112            break;
113        case SQLITE_NULL:
114            lua_pushnil(L);
115            break;
116        default:
117            lua_pushnil(L);
118            break;
119    }
123   switch (sqlite3_column_type(vm, idx)) {
124      case SQLITE_INTEGER:
125         {
126            sqlite_int64 i64 = sqlite3_column_int64(vm, idx);
127            lua_Number n = (lua_Number)i64;
128            if (n == i64)
129               lua_pushnumber(L, n);
130            else
131               lua_pushlstring(L, (const char*)sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx));
132         }
133         break;
134      case SQLITE_FLOAT:
135         lua_pushnumber(L, sqlite3_column_double(vm, idx));
136         break;
137      case SQLITE_TEXT:
138         lua_pushlstring(L, (const char*)sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx));
139         break;
140      case SQLITE_BLOB:
141         lua_pushlstring(L, (const char*)sqlite3_column_blob(vm, idx), sqlite3_column_bytes(vm, idx));
142         break;
143      case SQLITE_NULL:
144         lua_pushnil(L);
145         break;
146      default:
147         lua_pushnil(L);
148         break;
149   }
120150}
121151
122152/* virtual machine information */
123153struct sdb_vm {
124    sdb *db;                /* associated database handle */
125    sqlite3_stmt *vm;       /* virtual machine */
154   sdb *db;                /* associated database handle */
155   sqlite3_stmt *vm;       /* virtual machine */
126156
127    /* sqlite3_step info */
128    int columns;            /* number of columns in result */
129    char has_values;        /* true when step succeeds */
157   /* sqlite3_step info */
158   int columns;            /* number of columns in result */
159   char has_values;        /* true when step succeeds */
130160
131    char temp;              /* temporary vm used in db:rows */
161   char temp;              /* temporary vm used in db:rows */
132162};
133163
134164/* called with sql text on the lua stack */
135165static sdb_vm *newvm(lua_State *L, sdb *db) {
136    sdb_vm *svm = (sdb_vm*)lua_newuserdata(L, sizeof(sdb_vm));
166   sdb_vm *svm = (sdb_vm*)lua_newuserdata(L, sizeof(sdb_vm));
137167
138    luaL_getmetatable(L, sqlite_vm_meta);
139    lua_setmetatable(L, -2);        /* set metatable */
168   luaL_getmetatable(L, sqlite_vm_meta);
169   lua_setmetatable(L, -2);        /* set metatable */
140170
141    svm->db = db;
142    svm->columns = 0;
143    svm->has_values = 0;
144    svm->vm = NULL;
145    svm->temp = 0;
171   svm->db = db;
172   svm->columns = 0;
173   svm->has_values = 0;
174   svm->vm = NULL;
175   svm->temp = 0;
146176
147    /* add an entry on the database table: svm -> sql text */
148    lua_pushlightuserdata(L, db);
149    lua_rawget(L, LUA_REGISTRYINDEX);
150    lua_pushlightuserdata(L, svm);
151    lua_pushvalue(L, -4); /* the sql text */
152    lua_rawset(L, -3);
153    lua_pop(L, 1);
177   /* add an entry on the database table: svm -> sql text */
178   lua_pushlightuserdata(L, db);
179   lua_rawget(L, LUA_REGISTRYINDEX);
180   lua_pushlightuserdata(L, svm);
181   lua_pushvalue(L, -4); /* the sql text */
182   lua_rawset(L, -3);
183   lua_pop(L, 1);
154184
155    return svm;
185   return svm;
156186}
157187
158188static int cleanupvm(lua_State *L, sdb_vm *svm) {
159    /* remove entry in database table - no harm if not present in the table */
160    lua_pushlightuserdata(L, svm->db);
161    lua_rawget(L, LUA_REGISTRYINDEX);
162    lua_pushlightuserdata(L, svm);
163    lua_pushnil(L);
164    lua_rawset(L, -3);
165    lua_pop(L, 1);
189   /* remove entry in database table - no harm if not present in the table */
190   lua_pushlightuserdata(L, svm->db);
191   lua_rawget(L, LUA_REGISTRYINDEX);
192   lua_pushlightuserdata(L, svm);
193   lua_pushnil(L);
194   lua_rawset(L, -3);
195   lua_pop(L, 1);
166196
167    svm->columns = 0;
168    svm->has_values = 0;
197   svm->columns = 0;
198   svm->has_values = 0;
169199
170    if (!svm->vm) return 0;
200   if (!svm->vm) return 0;
171201
172    lua_pushnumber(L, sqlite3_finalize(svm->vm));
173    svm->vm = NULL;
174    return 1;
202   lua_pushnumber(L, sqlite3_finalize(svm->vm));
203   svm->vm = NULL;
204   return 1;
175205}
176206
177207static int stepvm(lua_State *L, sdb_vm *svm) {
178    int result;
179    int loop_limit = 3;
180    while ( loop_limit-- ) {
181        result = sqlite3_step(svm->vm);
182        if ( result==SQLITE_ERROR ) {
183          result = sqlite3_reset (svm->vm);
184        }
185        if ( result==SQLITE_SCHEMA ) {
186            sqlite3_stmt *vn;
187            const char *sql;
188            /* recover sql text */
189            lua_pushlightuserdata(L, svm->db);
190            lua_rawget(L, LUA_REGISTRYINDEX);
191            lua_pushlightuserdata(L, svm);
192            lua_rawget(L, -2); /* sql text */
193            sql = luaL_checkstring(L, -1);
194            /* re-prepare */
195            result = sqlite3_prepare(svm->db->db, sql, -1, &vn, NULL);
196            if (result != SQLITE_OK) break;
197            sqlite3_transfer_bindings(svm->vm, vn);
198            sqlite3_finalize(svm->vm);
199            svm->vm = vn;
200            lua_pop(L,2);
201        } else {
202          break;
203        }
204    }
205    return result;
208   // MAME: fixed Visual Studio compiler warning lsqlite3.c(235) : warning C4701: potentially uninitialized local variable 'result' used
209   int result = 0;
210   int loop_limit = 3;
211   while ( loop_limit-- ) {
212      result = sqlite3_step(svm->vm);
213      if ( result==SQLITE_ERROR ) {
214         result = sqlite3_reset (svm->vm);
215      }
216      if ( result==SQLITE_SCHEMA ) {
217         sqlite3_stmt *vn;
218         const char *sql;
219         /* recover sql text */
220         lua_pushlightuserdata(L, svm->db);
221         lua_rawget(L, LUA_REGISTRYINDEX);
222         lua_pushlightuserdata(L, svm);
223         lua_rawget(L, -2); /* sql text */
224         sql = luaL_checkstring(L, -1);
225         /* re-prepare */
226         result = sqlite3_prepare(svm->db->db, sql, -1, &vn, NULL);
227         if (result != SQLITE_OK) break;
228         sqlite3_transfer_bindings(svm->vm, vn);
229         sqlite3_finalize(svm->vm);
230         svm->vm = vn;
231         lua_pop(L,2);
232      } else {
233         break;
234      }
235   }
236   return result;
206237}
207238
208239static sdb_vm *lsqlite_getvm(lua_State *L, int index) {
209    sdb_vm *svm = (sdb_vm*)luaL_checkudata(L, index, sqlite_vm_meta);
210    if (svm == NULL) luaL_argerror(L, index, "bad sqlite virtual machine");
211    return svm;
240   sdb_vm *svm = (sdb_vm*)luaL_checkudata(L, index, sqlite_vm_meta);
241   if (svm == NULL) luaL_argerror(L, index, "bad sqlite virtual machine");
242   return svm;
212243}
213244
214245static sdb_vm *lsqlite_checkvm(lua_State *L, int index) {
215    sdb_vm *svm = lsqlite_getvm(L, index);
216    if (svm->vm == NULL) luaL_argerror(L, index, "attempt to use closed sqlite virtual machine");
217    return svm;
246   sdb_vm *svm = lsqlite_getvm(L, index);
247   if (svm->vm == NULL) luaL_argerror(L, index, "attempt to use closed sqlite virtual machine");
248   return svm;
218249}
219250
220251static int dbvm_isopen(lua_State *L) {
221    sdb_vm *svm = lsqlite_getvm(L, 1);
222    lua_pushboolean(L, svm->vm != NULL ? 1 : 0);
223    return 1;
252   sdb_vm *svm = lsqlite_getvm(L, 1);
253   lua_pushboolean(L, svm->vm != NULL ? 1 : 0);
254   return 1;
224255}
225256
226257static int dbvm_tostring(lua_State *L) {
227    char buff[39];
228    sdb_vm *svm = lsqlite_getvm(L, 1);
229    if (svm->vm == NULL)
230        strcpy(buff, "closed");
231    else
232        sprintf(buff, "%p", svm);
233    lua_pushfstring(L, "sqlite virtual machine (%s)", buff);
234    return 1;
258   char buff[39];
259   sdb_vm *svm = lsqlite_getvm(L, 1);
260   if (svm->vm == NULL)
261      strcpy(buff, "closed");
262   else
263      sprintf(buff, "%p", svm);
264   lua_pushfstring(L, "sqlite virtual machine (%s)", buff);
265   return 1;
235266}
236267
237268static int dbvm_gc(lua_State *L) {
238    sdb_vm *svm = lsqlite_getvm(L, 1);
239    if (svm->vm != NULL)  /* ignore closed vms */
240        cleanupvm(L, svm);
241    return 0;
269   sdb_vm *svm = lsqlite_getvm(L, 1);
270   if (svm->vm != NULL)  /* ignore closed vms */
271      cleanupvm(L, svm);
272   return 0;
242273}
243274
244275static int dbvm_step(lua_State *L) {
245    int result;
246    sdb_vm *svm = lsqlite_checkvm(L, 1);
276   int result;
277   sdb_vm *svm = lsqlite_checkvm(L, 1);
247278
248    result = stepvm(L, svm);
249    svm->has_values = result == SQLITE_ROW ? 1 : 0;
250    svm->columns = sqlite3_data_count(svm->vm);
279   result = stepvm(L, svm);
280   svm->has_values = result == SQLITE_ROW ? 1 : 0;
281   svm->columns = sqlite3_data_count(svm->vm);
251282
252    lua_pushnumber(L, result);
253    return 1;
283   lua_pushnumber(L, result);
284   return 1;
254285}
255286
256287static int dbvm_finalize(lua_State *L) {
257    sdb_vm *svm = lsqlite_checkvm(L, 1);
258    return cleanupvm(L, svm);
288   sdb_vm *svm = lsqlite_checkvm(L, 1);
289   return cleanupvm(L, svm);
259290}
260291
261292static int dbvm_reset(lua_State *L) {
262    sdb_vm *svm = lsqlite_checkvm(L, 1);
263    sqlite3_reset(svm->vm);
264    lua_pushnumber(L, sqlite3_errcode(svm->db->db));
265    return 1;
293   sdb_vm *svm = lsqlite_checkvm(L, 1);
294   sqlite3_reset(svm->vm);
295   lua_pushnumber(L, sqlite3_errcode(svm->db->db));
296   return 1;
266297}
267298
268299static void dbvm_check_contents(lua_State *L, sdb_vm *svm) {
269    if (!svm->has_values) {
270        luaL_error(L, "misuse of function");
271    }
300   if (!svm->has_values) {
301      luaL_error(L, "misuse of function");
302   }
272303}
273304
274305static void dbvm_check_index(lua_State *L, sdb_vm *svm, int index) {
275    if (index < 0 || index >= svm->columns) {
276        luaL_error(L, "index out of range [0..%d]", svm->columns - 1);
277    }
306   if (index < 0 || index >= svm->columns) {
307      luaL_error(L, "index out of range [0..%d]", svm->columns - 1);
308   }
278309}
279310
280311static void dbvm_check_bind_index(lua_State *L, sdb_vm *svm, int index) {
281    if (index < 1 || index > sqlite3_bind_parameter_count(svm->vm)) {
282        luaL_error(L, "bind index out of range [1..%d]", sqlite3_bind_parameter_count(svm->vm));
283    }
312   if (index < 1 || index > sqlite3_bind_parameter_count(svm->vm)) {
313      luaL_error(L, "bind index out of range [1..%d]", sqlite3_bind_parameter_count(svm->vm));
314   }
284315}
285316
286317/*
r242834r242835
289320** =======================================================
290321*/
291322static int dbvm_columns(lua_State *L) {
292    sdb_vm *svm = lsqlite_checkvm(L, 1);
293    lua_pushnumber(L, sqlite3_column_count(svm->vm));
294    return 1;
323   sdb_vm *svm = lsqlite_checkvm(L, 1);
324   lua_pushnumber(L, sqlite3_column_count(svm->vm));
325   return 1;
295326}
296327
297328/*
r242834r242835
301332*/
302333
303334static int dbvm_get_value(lua_State *L) {
304    sdb_vm *svm = lsqlite_checkvm(L, 1);
305    int index = luaL_checkint(L, 2);
306    dbvm_check_contents(L, svm);
307    dbvm_check_index(L, svm, index);
308    vm_push_column(L, svm->vm, index);
309    return 1;
335   sdb_vm *svm = lsqlite_checkvm(L, 1);
336   int index = luaL_checkint(L, 2);
337   dbvm_check_contents(L, svm);
338   dbvm_check_index(L, svm, index);
339   vm_push_column(L, svm->vm, index);
340   return 1;
310341}
311342
312343static int dbvm_get_name(lua_State *L) {
313    sdb_vm *svm = lsqlite_checkvm(L, 1);
314    int index = luaL_checknumber(L, 2);
315    dbvm_check_index(L, svm, index);
316    lua_pushstring(L, sqlite3_column_name(svm->vm, index));
317    return 1;
344   sdb_vm *svm = lsqlite_checkvm(L, 1);
345   int index = luaL_checknumber(L, 2);
346   dbvm_check_index(L, svm, index);
347   lua_pushstring(L, sqlite3_column_name(svm->vm, index));
348   return 1;
318349}
319350
320351static int dbvm_get_type(lua_State *L) {
321    sdb_vm *svm = lsqlite_checkvm(L, 1);
322    int index = luaL_checknumber(L, 2);
323    dbvm_check_index(L, svm, index);
324    lua_pushstring(L, sqlite3_column_decltype(svm->vm, index));
325    return 1;
352   sdb_vm *svm = lsqlite_checkvm(L, 1);
353   int index = luaL_checknumber(L, 2);
354   dbvm_check_index(L, svm, index);
355   lua_pushstring(L, sqlite3_column_decltype(svm->vm, index));
356   return 1;
326357}
327358
328359static int dbvm_get_values(lua_State *L) {
329    sdb_vm *svm = lsqlite_checkvm(L, 1);
330    sqlite3_stmt *vm = svm->vm;
331    int columns = svm->columns;
332    int n;
333    dbvm_check_contents(L, svm);
360   sdb_vm *svm = lsqlite_checkvm(L, 1);
361   sqlite3_stmt *vm = svm->vm;
362   int columns = svm->columns;
363   int n;
364   dbvm_check_contents(L, svm);
334365
335    lua_newtable(L);
336    for (n = 0; n < columns;) {
337        vm_push_column(L, vm, n++);
338        lua_rawseti(L, -2, n);
339    }
340    return 1;
366   lua_newtable(L);
367   for (n = 0; n < columns;) {
368      vm_push_column(L, vm, n++);
369      lua_rawseti(L, -2, n);
370   }
371   return 1;
341372}
342373
343374static int dbvm_get_names(lua_State *L) {
344    sdb_vm *svm = lsqlite_checkvm(L, 1);
345    sqlite3_stmt *vm = svm->vm;
346    int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
347    int n;
375   sdb_vm *svm = lsqlite_checkvm(L, 1);
376   sqlite3_stmt *vm = svm->vm;
377   int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
378   int n;
348379
349    lua_newtable(L);
350    for (n = 0; n < columns;) {
351        lua_pushstring(L, sqlite3_column_name(vm, n++));
352        lua_rawseti(L, -2, n);
353    }
354    return 1;
380   lua_newtable(L);
381   for (n = 0; n < columns;) {
382      lua_pushstring(L, sqlite3_column_name(vm, n++));
383      lua_rawseti(L, -2, n);
384   }
385   return 1;
355386}
356387
357388static int dbvm_get_types(lua_State *L) {
358    sdb_vm *svm = lsqlite_checkvm(L, 1);
359    sqlite3_stmt *vm = svm->vm;
360    int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
361    int n;
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;
362393
363    lua_newtable(L);
364    for (n = 0; n < columns;) {
365        lua_pushstring(L, sqlite3_column_decltype(vm, n++));
366        lua_rawseti(L, -2, n);
367    }
368    return 1;
394   lua_newtable(L);
395   for (n = 0; n < columns;) {
396      lua_pushstring(L, sqlite3_column_decltype(vm, n++));
397      lua_rawseti(L, -2, n);
398   }
399   return 1;
369400}
370401
371402static int dbvm_get_uvalues(lua_State *L) {
372    sdb_vm *svm = lsqlite_checkvm(L, 1);
373    sqlite3_stmt *vm = svm->vm;
374    int columns = svm->columns;
375    int n;
376    dbvm_check_contents(L, svm);
403   sdb_vm *svm = lsqlite_checkvm(L, 1);
404   sqlite3_stmt *vm = svm->vm;
405   int columns = svm->columns;
406   int n;
407   dbvm_check_contents(L, svm);
377408
378    lua_checkstack(L, columns);
379    for (n = 0; n < columns; ++n)
380        vm_push_column(L, vm, n);
381    return columns;
409   lua_checkstack(L, columns);
410   for (n = 0; n < columns; ++n)
411      vm_push_column(L, vm, n);
412   return columns;
382413}
383414
384415static int dbvm_get_unames(lua_State *L) {
385    sdb_vm *svm = lsqlite_checkvm(L, 1);
386    sqlite3_stmt *vm = svm->vm;
387    int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
388    int n;
416   sdb_vm *svm = lsqlite_checkvm(L, 1);
417   sqlite3_stmt *vm = svm->vm;
418   int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
419   int n;
389420
390    lua_checkstack(L, columns);
391    for (n = 0; n < columns; ++n)
392        lua_pushstring(L, sqlite3_column_name(vm, n));
393    return columns;
421   lua_checkstack(L, columns);
422   for (n = 0; n < columns; ++n)
423      lua_pushstring(L, sqlite3_column_name(vm, n));
424   return columns;
394425}
395426
396427static int dbvm_get_utypes(lua_State *L) {
397    sdb_vm *svm = lsqlite_checkvm(L, 1);
398    sqlite3_stmt *vm = svm->vm;
399    int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
400    int n;
428   sdb_vm *svm = lsqlite_checkvm(L, 1);
429   sqlite3_stmt *vm = svm->vm;
430   int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */
431   int n;
401432
402    lua_checkstack(L, columns);
403    for (n = 0; n < columns; ++n)
404        lua_pushstring(L, sqlite3_column_decltype(vm, n));
405    return columns;
433   lua_checkstack(L, columns);
434   for (n = 0; n < columns; ++n)
435      lua_pushstring(L, sqlite3_column_decltype(vm, n));
436   return columns;
406437}
407438
408439static int dbvm_get_named_values(lua_State *L) {
409    sdb_vm *svm = lsqlite_checkvm(L, 1);
410    sqlite3_stmt *vm = svm->vm;
411    int columns = svm->columns;
412    int n;
413    dbvm_check_contents(L, svm);
440   sdb_vm *svm = lsqlite_checkvm(L, 1);
441   sqlite3_stmt *vm = svm->vm;
442   int columns = svm->columns;
443   int n;
444   dbvm_check_contents(L, svm);
414445
415    lua_newtable(L);
416    for (n = 0; n < columns; ++n) {
417        lua_pushstring(L, sqlite3_column_name(vm, n));
418        vm_push_column(L, vm, n);
419        lua_rawset(L, -3);
420    }
421    return 1;
446   lua_newtable(L);
447   for (n = 0; n < columns; ++n) {
448      lua_pushstring(L, sqlite3_column_name(vm, n));
449      vm_push_column(L, vm, n);
450      lua_rawset(L, -3);
451   }
452   return 1;
422453}
423454
424455static int dbvm_get_named_types(lua_State *L) {
425    sdb_vm *svm = lsqlite_checkvm(L, 1);
426    sqlite3_stmt *vm = svm->vm;
427    int columns = sqlite3_column_count(vm);
428    int n;
456   sdb_vm *svm = lsqlite_checkvm(L, 1);
457   sqlite3_stmt *vm = svm->vm;
458   int columns = sqlite3_column_count(vm);
459   int n;
429460
430    lua_newtable(L);
431    for (n = 0; n < columns; ++n) {
432        lua_pushstring(L, sqlite3_column_name(vm, n));
433        lua_pushstring(L, sqlite3_column_decltype(vm, n));
434        lua_rawset(L, -3);
435    }
436    return 1;
461   lua_newtable(L);
462   for (n = 0; n < columns; ++n) {
463      lua_pushstring(L, sqlite3_column_name(vm, n));
464      lua_pushstring(L, sqlite3_column_decltype(vm, n));
465      lua_rawset(L, -3);
466   }
467   return 1;
437468}
438469
439470/*
r242834r242835
443474*/
444475
445476static int dbvm_bind_index(lua_State *L, sqlite3_stmt *vm, int index, int lindex) {
446    switch (lua_type(L, lindex)) {
447        case LUA_TSTRING:
448            return sqlite3_bind_text(vm, index, lua_tostring(L, lindex), lua_strlen(L, lindex), SQLITE_TRANSIENT);
449        case LUA_TNUMBER:
450            return sqlite3_bind_double(vm, index, lua_tonumber(L, lindex));
451        case LUA_TNONE:
452        case LUA_TNIL:
453        /* allow boolean values so i have a way to know which
454        ** values were actually not set */
455        case LUA_TBOOLEAN:
456            return sqlite3_bind_null(vm, index);
457        default:
458            luaL_error(L, "index (%d) - invalid data type for bind (%s)", index, lua_typename(L, lindex));
459            return SQLITE_MISUSE; /*!*/
460    }
477   switch (lua_type(L, lindex)) {
478      case LUA_TSTRING:
479         return sqlite3_bind_text(vm, index, lua_tostring(L, lindex), lua_strlen(L, lindex), SQLITE_TRANSIENT);
480      case LUA_TNUMBER:
481         return sqlite3_bind_double(vm, index, lua_tonumber(L, lindex));
482      case LUA_TBOOLEAN:
483         return sqlite3_bind_int(vm, index, lua_toboolean(L, lindex) ? 1 : 0);
484      case LUA_TNONE:
485      case LUA_TNIL:
486         return sqlite3_bind_null(vm, index);
487      default:
488         luaL_error(L, "index (%d) - invalid data type for bind (%s)", index, lua_typename(L, lua_type(L, lindex)));
489         return SQLITE_MISUSE; /*!*/
490   }
461491}
462492
463493
464494static int dbvm_bind_parameter_count(lua_State *L) {
465    sdb_vm *svm = lsqlite_checkvm(L, 1);
466    lua_pushnumber(L, sqlite3_bind_parameter_count(svm->vm));
467    return 1;
495   sdb_vm *svm = lsqlite_checkvm(L, 1);
496   lua_pushnumber(L, sqlite3_bind_parameter_count(svm->vm));
497   return 1;
468498}
469499
470500static int dbvm_bind_parameter_name(lua_State *L) {
471    sdb_vm *svm = lsqlite_checkvm(L, 1);
472    int index = luaL_checknumber(L, 2);
473    dbvm_check_bind_index(L, svm, index);
474    lua_pushstring(L, sqlite3_bind_parameter_name(svm->vm, index));
475    return 1;
501   sdb_vm *svm = lsqlite_checkvm(L, 1);
502   int index = luaL_checknumber(L, 2);
503   dbvm_check_bind_index(L, svm, index);
504   lua_pushstring(L, sqlite3_bind_parameter_name(svm->vm, index));
505   return 1;
476506}
477507
478508static int dbvm_bind(lua_State *L) {
479    sdb_vm *svm = lsqlite_checkvm(L, 1);
480    sqlite3_stmt *vm = svm->vm;
481    int index = luaL_checkint(L, 2);
482    int result;
509   sdb_vm *svm = lsqlite_checkvm(L, 1);
510   sqlite3_stmt *vm = svm->vm;
511   int index = luaL_checkint(L, 2);
512   int result;
483513
484    dbvm_check_bind_index(L, svm, index);
485    result = dbvm_bind_index(L, vm, index, 3);
514   dbvm_check_bind_index(L, svm, index);
515   result = dbvm_bind_index(L, vm, index, 3);
486516
487    lua_pushnumber(L, result);
488    return 1;
517   lua_pushnumber(L, result);
518   return 1;
489519}
490520
491521static int dbvm_bind_blob(lua_State *L) {
492    sdb_vm *svm = lsqlite_checkvm(L, 1);
493    int index = luaL_checkint(L, 2);
494    const char *value = luaL_checkstring(L, 3);
495    int len = lua_strlen(L, 3);
522   sdb_vm *svm = lsqlite_checkvm(L, 1);
523   int index = luaL_checkint(L, 2);
524   const char *value = luaL_checkstring(L, 3);
525   int len = lua_strlen(L, 3);
496526
497    lua_pushnumber(L, sqlite3_bind_blob(svm->vm, index, value, len, SQLITE_TRANSIENT));
498    return 1;
527   lua_pushnumber(L, sqlite3_bind_blob(svm->vm, index, value, len, SQLITE_TRANSIENT));
528   return 1;
499529}
500530
501531static int dbvm_bind_values(lua_State *L) {
502    sdb_vm *svm = lsqlite_checkvm(L, 1);
503    sqlite3_stmt *vm = svm->vm;
504    int top = lua_gettop(L);
505    int result, n;
532   sdb_vm *svm = lsqlite_checkvm(L, 1);
533   sqlite3_stmt *vm = svm->vm;
534   int top = lua_gettop(L);
535   int result, n;
506536
507    if (top - 1 != sqlite3_bind_parameter_count(vm))
508        luaL_error(L,
509            "incorrect number of parameters to bind (%d given, %d to bind)",
510            top - 1,
511            sqlite3_bind_parameter_count(vm)
512        );
537   if (top - 1 != sqlite3_bind_parameter_count(vm))
538      luaL_error(L,
539         "incorrect number of parameters to bind (%d given, %d to bind)",
540         top - 1,
541         sqlite3_bind_parameter_count(vm)
542      );
513543
514    for (n = 2; n <= top; ++n) {
515        if ((result = dbvm_bind_index(L, vm, n - 1, n)) != SQLITE_OK) {
516            lua_pushnumber(L, result);
517            return 1;
518        }
519    }
544   for (n = 2; n <= top; ++n) {
545      if ((result = dbvm_bind_index(L, vm, n - 1, n)) != SQLITE_OK) {
546         lua_pushnumber(L, result);
547         return 1;
548      }
549   }
520550
521    lua_pushnumber(L, SQLITE_OK);
522    return 1;
551   lua_pushnumber(L, SQLITE_OK);
552   return 1;
523553}
524554
525555static int dbvm_bind_names(lua_State *L) {
526    sdb_vm *svm = lsqlite_checkvm(L, 1);
527    sqlite3_stmt *vm = svm->vm;
528    int count = sqlite3_bind_parameter_count(vm);
529    const char *name;
530    int result, n;
531    luaL_checktype(L, 2, LUA_TTABLE);
556   sdb_vm *svm = lsqlite_checkvm(L, 1);
557   sqlite3_stmt *vm = svm->vm;
558   int count = sqlite3_bind_parameter_count(vm);
559   const char *name;
560   int result, n;
561   luaL_checktype(L, 2, LUA_TTABLE);
532562
533    for (n = 1; n <= count; ++n) {
534        name = sqlite3_bind_parameter_name(vm, n);
535        if (name && (name[0] == ':' || name[0] == '$')) {
536            lua_pushstring(L, ++name);
537            lua_gettable(L, 2);
538            result = dbvm_bind_index(L, vm, n, -1);
539        }
540        else {
541            lua_pushnumber(L, n);
542            lua_gettable(L, 2);
543            result = dbvm_bind_index(L, vm, n, -1);
544            lua_pop(L, 1);
545        }
563   for (n = 1; n <= count; ++n) {
564      name = sqlite3_bind_parameter_name(vm, n);
565      if (name && (name[0] == ':' || name[0] == '$')) {
566         lua_pushstring(L, ++name);
567         lua_gettable(L, 2);
568         result = dbvm_bind_index(L, vm, n, -1);
569         lua_pop(L, 1);
570      }
571      else {
572         lua_pushnumber(L, n);
573         lua_gettable(L, 2);
574         result = dbvm_bind_index(L, vm, n, -1);
575         lua_pop(L, 1);
576      }
546577
547        if (result != SQLITE_OK) {
548            lua_pushnumber(L, result);
549            return 1;
550        }
551    }
578      if (result != SQLITE_OK) {
579         lua_pushnumber(L, result);
580         return 1;
581      }
582   }
552583
553    lua_pushnumber(L, SQLITE_OK);
554    return 1;
584   lua_pushnumber(L, SQLITE_OK);
585   return 1;
555586}
556587
557588/*
r242834r242835
568599** Creates a new 'table' and leaves it in the stack
569600*/
570601static sdb *newdb (lua_State *L) {
571    sdb *db = (sdb*)lua_newuserdata(L, sizeof(sdb));
572    db->L = L;
573    db->db = NULL;  /* database handle is currently `closed' */
574    db->func = NULL;
602   sdb *db = (sdb*)lua_newuserdata(L, sizeof(sdb));
603   db->L = L;
604   db->db = NULL;  /* database handle is currently `closed' */
605   db->func = NULL;
575606
576    db->busy_cb =
577    db->busy_udata =
578    db->progress_cb =
579    db->progress_udata =
580    db->trace_cb =
581    db->trace_udata = LUA_NOREF;
607   db->busy_cb =
608   db->busy_udata =
609   db->progress_cb =
610   db->progress_udata =
611   db->trace_cb =
612   db->trace_udata =
613#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
614   db->update_hook_cb =
615   db->update_hook_udata =
616   db->commit_hook_cb =
617   db->commit_hook_udata =
618   db->rollback_hook_cb =
619   db->rollback_hook_udata =
620#endif
621      LUA_NOREF;
582622
583    luaL_getmetatable(L, sqlite_meta);
584    lua_setmetatable(L, -2);        /* set metatable */
623   luaL_getmetatable(L, sqlite_meta);
624   lua_setmetatable(L, -2);        /* set metatable */
585625
586    /* to keep track of 'open' virtual machines */
587    lua_pushlightuserdata(L, db);
588    lua_newtable(L);
589    lua_rawset(L, LUA_REGISTRYINDEX);
626   /* to keep track of 'open' virtual machines */
627   lua_pushlightuserdata(L, db);
628   lua_newtable(L);
629   lua_rawset(L, LUA_REGISTRYINDEX);
590630
591    return db;
631   return db;
592632}
593633
594634static int cleanupdb(lua_State *L, sdb *db) {
595    sdb_func *func;
596    sdb_func *func_next;
597    int top;
598    int result;
635   sdb_func *func;
636   sdb_func *func_next;
637   int top;
638   int result;
599639
600    /* free associated virtual machines */
601    lua_pushlightuserdata(L, db);
602    lua_rawget(L, LUA_REGISTRYINDEX);
640   /* free associated virtual machines */
641   lua_pushlightuserdata(L, db);
642   lua_rawget(L, LUA_REGISTRYINDEX);
603643
604    /* close all used handles */
605    top = lua_gettop(L);
606    lua_pushnil(L);
607    while (lua_next(L, -2)) {
608        sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */
609        cleanupvm(L, svm);
644   /* close all used handles */
645   top = lua_gettop(L);
646   lua_pushnil(L);
647   while (lua_next(L, -2)) {
648      sdb_vm *svm = (sdb_vm *)lua_touserdata(L, -2); /* key: vm; val: sql text */
649      cleanupvm(L, svm);
610650
611        lua_settop(L, top);
612        lua_pushnil(L);
613    }
651      lua_settop(L, top);
652      lua_pushnil(L);
653   }
614654
615    lua_pop(L, 1); /* pop vm table */
655   lua_pop(L, 1); /* pop vm table */
616656
617    /* remove entry in lua registry table */
618    lua_pushlightuserdata(L, db);
619    lua_pushnil(L);
620    lua_rawset(L, LUA_REGISTRYINDEX);
657   /* remove entry in lua registry table */
658   lua_pushlightuserdata(L, db);
659   lua_pushnil(L);
660   lua_rawset(L, LUA_REGISTRYINDEX);
621661
622    /* 'free' all references */
623    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
624    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
625    luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
626    luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
627    luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
628    luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
662   /* 'free' all references */
663   luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
664   luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
665   luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
666   luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
667   luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
668   luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
669#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
670   luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
671   luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);
672   luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
673   luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);
674   luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
675   luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);
676#endif
629677
630    /* close database */
631    result = sqlite3_close(db->db);
632    db->db = NULL;
678   /* close database */
679   result = sqlite3_close(db->db);
680   db->db = NULL;
633681
634    /* free associated memory with created functions */
635    func = db->func;
636    while (func) {
637        func_next = func->next;
638        luaL_unref(L, LUA_REGISTRYINDEX, func->fn_step);
639        luaL_unref(L, LUA_REGISTRYINDEX, func->fn_finalize);
640        luaL_unref(L, LUA_REGISTRYINDEX, func->udata);
641        free(func);
642        func = func_next;
643    }
644    db->func = NULL;
645    return result;
682   /* free associated memory with created functions */
683   func = db->func;
684   while (func) {
685      func_next = func->next;
686      luaL_unref(L, LUA_REGISTRYINDEX, func->fn_step);
687      luaL_unref(L, LUA_REGISTRYINDEX, func->fn_finalize);
688      luaL_unref(L, LUA_REGISTRYINDEX, func->udata);
689      free(func);
690      func = func_next;
691   }
692   db->func = NULL;
693   return result;
646694}
647695
648696static sdb *lsqlite_getdb(lua_State *L, int index) {
649    sdb *db = (sdb*)luaL_checkudata(L, index, sqlite_meta);
650    if (db == NULL) luaL_typerror(L, index, "sqlite database");
651    return db;
697   sdb *db = (sdb*)luaL_checkudata(L, index, sqlite_meta);
698   if (db == NULL) luaL_typerror(L, index, "sqlite database");
699   return db;
652700}
653701
654702static sdb *lsqlite_checkdb(lua_State *L, int index) {
655    sdb *db = lsqlite_getdb(L, index);
656    if (db->db == NULL) luaL_argerror(L, index, "attempt to use closed sqlite database");
657    return db;
703   sdb *db = lsqlite_getdb(L, index);
704   if (db->db == NULL) luaL_argerror(L, index, "attempt to use closed sqlite database");
705   return db;
658706}
659707
660708
r242834r242835
664712** =======================================================
665713*/
666714typedef struct {
667    sqlite3_context *ctx;
668    int ud;
715   sqlite3_context *ctx;
716   int ud;
669717} lcontext;
670718
671719static lcontext *lsqlite_make_context(lua_State *L) {
672    lcontext *ctx = (lcontext*)lua_newuserdata(L, sizeof(lcontext));
673    lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_ctx_meta_ref);
674    lua_setmetatable(L, -2);
675    ctx->ctx = NULL;
676    ctx->ud = LUA_NOREF;
677    return ctx;
720   lcontext *ctx = (lcontext*)lua_newuserdata(L, sizeof(lcontext));
721   lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_ctx_meta_ref);
722   lua_setmetatable(L, -2);
723   ctx->ctx = NULL;
724   ctx->ud = LUA_NOREF;
725   return ctx;
678726}
679727
680728static lcontext *lsqlite_getcontext(lua_State *L, int index) {
681    lcontext *ctx = (lcontext*)luaL_checkudata(L, index, sqlite_ctx_meta);
682    if (ctx == NULL) luaL_typerror(L, index, "sqlite context");
683    return ctx;
729   lcontext *ctx = (lcontext*)luaL_checkudata(L, index, sqlite_ctx_meta);
730   if (ctx == NULL) luaL_typerror(L, index, "sqlite context");
731   return ctx;
684732}
685733
686734static lcontext *lsqlite_checkcontext(lua_State *L, int index) {
687    lcontext *ctx = lsqlite_getcontext(L, index);
688    if (ctx->ctx == NULL) luaL_argerror(L, index, "invalid sqlite context");
689    return ctx;
735   lcontext *ctx = lsqlite_getcontext(L, index);
736   if (ctx->ctx == NULL) luaL_argerror(L, index, "invalid sqlite context");
737   return ctx;
690738}
691739
692740static int lcontext_tostring(lua_State *L) {
693    char buff[39];
694    lcontext *ctx = lsqlite_getcontext(L, 1);
695    if (ctx->ctx == NULL)
696        strcpy(buff, "closed");
697    else
698        sprintf(buff, "%p", ctx->ctx);
699    lua_pushfstring(L, "sqlite function context (%s)", buff);
700    return 1;
741   char buff[39];
742   lcontext *ctx = lsqlite_getcontext(L, 1);
743   if (ctx->ctx == NULL)
744      strcpy(buff, "closed");
745   else
746      sprintf(buff, "%p", ctx->ctx);
747   lua_pushfstring(L, "sqlite function context (%s)", buff);
748   return 1;
701749}
702750
703751static void lcontext_check_aggregate(lua_State *L, lcontext *ctx) {
704    sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx);
705    if (!func->aggregate) {
706        luaL_error(L, "attempt to call aggregate method from scalar function");
707    }
752   sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx);
753   if (!func->aggregate) {
754      luaL_error(L, "attempt to call aggregate method from scalar function");
755   }
708756}
709757
710758static int lcontext_user_data(lua_State *L) {
711    lcontext *ctx = lsqlite_checkcontext(L, 1);
712    sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx);
713    lua_rawgeti(L, LUA_REGISTRYINDEX, func->udata);
714    return 1;
759   lcontext *ctx = lsqlite_checkcontext(L, 1);
760   sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx);
761   lua_rawgeti(L, LUA_REGISTRYINDEX, func->udata);
762   return 1;
715763}
716764
717765static int lcontext_get_aggregate_context(lua_State *L) {
718    lcontext *ctx = lsqlite_checkcontext(L, 1);
719    lcontext_check_aggregate(L, ctx);
720    lua_rawgeti(L, LUA_REGISTRYINDEX, ctx->ud);
721    return 1;
766   lcontext *ctx = lsqlite_checkcontext(L, 1);
767   lcontext_check_aggregate(L, ctx);
768   lua_rawgeti(L, LUA_REGISTRYINDEX, ctx->ud);
769   return 1;
722770}
723771
724772static int lcontext_set_aggregate_context(lua_State *L) {
725    lcontext *ctx = lsqlite_checkcontext(L, 1);
726    lcontext_check_aggregate(L, ctx);
727    lua_settop(L, 2);
728    luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
729    ctx->ud = luaL_ref(L, LUA_REGISTRYINDEX);
730    return 0;
773   lcontext *ctx = lsqlite_checkcontext(L, 1);
774   lcontext_check_aggregate(L, ctx);
775   lua_settop(L, 2);
776   luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
777   ctx->ud = luaL_ref(L, LUA_REGISTRYINDEX);
778   return 0;
731779}
732780
733781static int lcontext_aggregate_count(lua_State *L) {
734    lcontext *ctx = lsqlite_checkcontext(L, 1);
735    lcontext_check_aggregate(L, ctx);
736    lua_pushnumber(L, sqlite3_aggregate_count(ctx->ctx));
737    return 1;
782   lcontext *ctx = lsqlite_checkcontext(L, 1);
783   lcontext_check_aggregate(L, ctx);
784   lua_pushnumber(L, sqlite3_aggregate_count(ctx->ctx));
785   return 1;
738786}
739787
740788#if 0
r242834r242835
743791#endif
744792
745793static int lcontext_result(lua_State *L) {
746    lcontext *ctx = lsqlite_checkcontext(L, 1);
747    switch (lua_type(L, 2)) {
748        case LUA_TNUMBER:
749            sqlite3_result_double(ctx->ctx, luaL_checknumber(L, 2));
750            break;
751        case LUA_TSTRING:
752            sqlite3_result_text(ctx->ctx, luaL_checkstring(L, 2), lua_strlen(L, 2), SQLITE_TRANSIENT);
753            break;
754        case LUA_TNIL:
755        case LUA_TNONE:
756            sqlite3_result_null(ctx->ctx);
757            break;
758        default:
759            luaL_error(L, "invalid result type %s", lua_typename(L, 2));
760            break;
761    }
794   lcontext *ctx = lsqlite_checkcontext(L, 1);
795   switch (lua_type(L, 2)) {
796      case LUA_TNUMBER:
797         sqlite3_result_double(ctx->ctx, luaL_checknumber(L, 2));
798         break;
799      case LUA_TSTRING:
800         sqlite3_result_text(ctx->ctx, luaL_checkstring(L, 2), lua_strlen(L, 2), SQLITE_TRANSIENT);
801         break;
802      case LUA_TNIL:
803      case LUA_TNONE:
804         sqlite3_result_null(ctx->ctx);
805         break;
806      default:
807         luaL_error(L, "invalid result type %s", lua_typename(L, 2));
808         break;
809   }
762810
763    return 0;
811   return 0;
764812}
765813
766814static int lcontext_result_blob(lua_State *L) {
767    lcontext *ctx = lsqlite_checkcontext(L, 1);
768    const char *blob = luaL_checkstring(L, 2);
769    int size = lua_strlen(L, 2);
770    sqlite3_result_blob(ctx->ctx, (const void*)blob, size, SQLITE_TRANSIENT);
771    return 0;
815   lcontext *ctx = lsqlite_checkcontext(L, 1);
816   const char *blob = luaL_checkstring(L, 2);
817   int size = lua_strlen(L, 2);
818   sqlite3_result_blob(ctx->ctx, (const void*)blob, size, SQLITE_TRANSIENT);
819   return 0;
772820}
773821
774822static int lcontext_result_double(lua_State *L) {
775    lcontext *ctx = lsqlite_checkcontext(L, 1);
776    double d = luaL_checknumber(L, 2);
777    sqlite3_result_double(ctx->ctx, d);
778    return 0;
823   lcontext *ctx = lsqlite_checkcontext(L, 1);
824   double d = luaL_checknumber(L, 2);
825   sqlite3_result_double(ctx->ctx, d);
826   return 0;
779827}
780828
781829static int lcontext_result_error(lua_State *L) {
782    lcontext *ctx = lsqlite_checkcontext(L, 1);
783    const char *err = luaL_checkstring(L, 2);
784    int size = lua_strlen(L, 2);
785    sqlite3_result_error(ctx->ctx, err, size);
786    return 0;
830   lcontext *ctx = lsqlite_checkcontext(L, 1);
831   const char *err = luaL_checkstring(L, 2);
832   int size = lua_strlen(L, 2);
833   sqlite3_result_error(ctx->ctx, err, size);
834   return 0;
787835}
788836
789837static int lcontext_result_int(lua_State *L) {
790    lcontext *ctx = lsqlite_checkcontext(L, 1);
791    int i = luaL_checkint(L, 2);
792    sqlite3_result_int(ctx->ctx, i);
793    return 0;
838   lcontext *ctx = lsqlite_checkcontext(L, 1);
839   int i = luaL_checkint(L, 2);
840   sqlite3_result_int(ctx->ctx, i);
841   return 0;
794842}
795843
796844static int lcontext_result_null(lua_State *L) {
797    lcontext *ctx = lsqlite_checkcontext(L, 1);
798    sqlite3_result_null(ctx->ctx);
799    return 0;
845   lcontext *ctx = lsqlite_checkcontext(L, 1);
846   sqlite3_result_null(ctx->ctx);
847   return 0;
800848}
801849
802850static int lcontext_result_text(lua_State *L) {
803    lcontext *ctx = lsqlite_checkcontext(L, 1);
804    const char *text = luaL_checkstring(L, 2);
805    int size = lua_strlen(L, 2);
806    sqlite3_result_text(ctx->ctx, text, size, SQLITE_TRANSIENT);
807    return 0;
851   lcontext *ctx = lsqlite_checkcontext(L, 1);
852   const char *text = luaL_checkstring(L, 2);
853   int size = lua_strlen(L, 2);
854   sqlite3_result_text(ctx->ctx, text, size, SQLITE_TRANSIENT);
855   return 0;
808856}
809857
810858/*
r242834r242835
814862*/
815863
816864static int db_isopen(lua_State *L) {
817    sdb *db = lsqlite_getdb(L, 1);
818    lua_pushboolean(L, db->db != NULL ? 1 : 0);
819    return 1;
865   sdb *db = lsqlite_getdb(L, 1);
866   lua_pushboolean(L, db->db != NULL ? 1 : 0);
867   return 1;
820868}
821869
822870static int db_last_insert_rowid(lua_State *L) {
823    sdb *db = lsqlite_checkdb(L, 1);
824    /* conversion warning: int64 -> luaNumber */
825    sqlite_int64 rowid = sqlite3_last_insert_rowid(db->db);
826    lua_Number n = (lua_Number)rowid;
827    if (n == rowid)
828        lua_pushnumber(L, n);
829    else
830        lua_pushfstring(L, "%ll", rowid);
831    return 1;
871   sdb *db = lsqlite_checkdb(L, 1);
872   /* conversion warning: int64 -> luaNumber */
873   sqlite_int64 rowid = sqlite3_last_insert_rowid(db->db);
874   lua_Number n = (lua_Number)rowid;
875   if (n == rowid)
876      lua_pushnumber(L, n);
877   else
878      lua_pushfstring(L, "%ll", rowid);
879   return 1;
832880}
833881
834882static int db_changes(lua_State *L) {
835    sdb *db = lsqlite_checkdb(L, 1);
836    lua_pushnumber(L, sqlite3_changes(db->db));
837    return 1;
883   sdb *db = lsqlite_checkdb(L, 1);
884   lua_pushnumber(L, sqlite3_changes(db->db));
885   return 1;
838886}
839887
840888static int db_total_changes(lua_State *L) {
841    sdb *db = lsqlite_checkdb(L, 1);
842    lua_pushnumber(L, sqlite3_total_changes(db->db));
843    return 1;
889   sdb *db = lsqlite_checkdb(L, 1);
890   lua_pushnumber(L, sqlite3_total_changes(db->db));
891   return 1;
844892}
845893
846894static int db_errcode(lua_State *L) {
847    sdb *db = lsqlite_checkdb(L, 1);
848    lua_pushnumber(L, sqlite3_errcode(db->db));
849    return 1;
895   sdb *db = lsqlite_checkdb(L, 1);
896   lua_pushnumber(L, sqlite3_errcode(db->db));
897   return 1;
850898}
851899
852900static int db_errmsg(lua_State *L) {
853    sdb *db = lsqlite_checkdb(L, 1);
854    lua_pushstring(L, sqlite3_errmsg(db->db));
855    return 1;
901   sdb *db = lsqlite_checkdb(L, 1);
902   lua_pushstring(L, sqlite3_errmsg(db->db));
903   return 1;
856904}
857905
858906static int db_interrupt(lua_State *L) {
859    sdb *db = lsqlite_checkdb(L, 1);
860    sqlite3_interrupt(db->db);
861    return 0;
907   sdb *db = lsqlite_checkdb(L, 1);
908   sqlite3_interrupt(db->db);
909   return 0;
862910}
863911
864912/*
r242834r242835
866914*/
867915
868916static void db_push_value(lua_State *L, sqlite3_value *value) {
869    switch (sqlite3_value_type(value)) {
870        case SQLITE_TEXT:
871            lua_pushlstring(L, sqlite3_value_text(value), sqlite3_value_bytes(value));
872            break;
917   switch (sqlite3_value_type(value)) {
918      case SQLITE_TEXT:
919         lua_pushlstring(L, (const char*)sqlite3_value_text(value), sqlite3_value_bytes(value));
920         break;
873921
874        case SQLITE_INTEGER:
875            {
876                sqlite_int64 i64 = sqlite3_value_int64(value);
877                lua_Number n = (lua_Number)i64;
878                if (n == i64)
879                    lua_pushnumber(L, n);
880                else
881                    lua_pushlstring(L, sqlite3_value_text(value), sqlite3_value_bytes(value));
882            }
883            break;
922      case SQLITE_INTEGER:
923         {
924            sqlite_int64 i64 = sqlite3_value_int64(value);
925            lua_Number n = (lua_Number)i64;
926            if (n == i64)
927               lua_pushnumber(L, n);
928            else
929               lua_pushlstring(L, (const char*)sqlite3_value_text(value), sqlite3_value_bytes(value));
930         }
931         break;
884932
885        case SQLITE_FLOAT:
886            lua_pushnumber(L, sqlite3_value_double(value));
887            break;
933      case SQLITE_FLOAT:
934         lua_pushnumber(L, sqlite3_value_double(value));
935         break;
888936
889        case SQLITE_BLOB:
890            lua_pushlstring(L, sqlite3_value_blob(value), sqlite3_value_bytes(value));
891            break;
937      case SQLITE_BLOB:
938         lua_pushlstring(L, (const char*)sqlite3_value_blob(value), sqlite3_value_bytes(value));
939         break;
892940
893        case SQLITE_NULL:
894            lua_pushnil(L);
895            break;
941      case SQLITE_NULL:
942         lua_pushnil(L);
943         break;
896944
897        default:
898            /* things done properly (SQLite + Lua SQLite)
899            ** this should never happen */
900            lua_pushnil(L);
901            break;
902    }
945      default:
946         /* things done properly (SQLite + Lua SQLite)
947         ** this should never happen */
948         lua_pushnil(L);
949         break;
950   }
903951}
904952
905953/*
r242834r242835
909957/* scalar function to be called
910958** callback params: context, values... */
911959static void db_sql_normal_function(sqlite3_context *context, int argc, sqlite3_value **argv) {
912    sdb_func *func = (sdb_func*)sqlite3_user_data(context);
913    lua_State *L = func->db->L;
914    int n;
915    lcontext *ctx;
960   sdb_func *func = (sdb_func*)sqlite3_user_data(context);
961   lua_State *L = func->db->L;
962   int n;
963   lcontext *ctx;
916964
917    int top = lua_gettop(L);
965   int top = lua_gettop(L);
918966
919    /* ensure there is enough space in the stack */
920    lua_checkstack(L, argc + 3);
967   /* ensure there is enough space in the stack */
968   lua_checkstack(L, argc + 3);
921969
922    lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_step);   /* function to call */
970   lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_step);   /* function to call */
923971
924    if (!func->aggregate) {
925        ctx = lsqlite_make_context(L); /* push context - used to set results */
926    }
927    else {
928        // reuse context userdata value
972   if (!func->aggregate) {
973      ctx = lsqlite_make_context(L); /* push context - used to set results */
974   }
975   else {
976      /* reuse context userdata value */
977      void *p = sqlite3_aggregate_context(context, 1);
978      /* i think it is OK to use assume that using a light user data
979      ** as an entry on LUA REGISTRY table will be unique */
980      lua_pushlightuserdata(L, p);
981      lua_rawget(L, LUA_REGISTRYINDEX);       /* context table */
929982
930        void *p = sqlite3_aggregate_context(context, 1);
931        /* i think it is OK to use assume that using a light user data
932        ** as an entry on LUA REGISTRY table will be unique */
933        lua_pushlightuserdata(L, p);
934        lua_rawget(L, LUA_REGISTRYINDEX);       /* context table */
983      if (lua_isnil(L, -1)) { /* not yet created? */
984         lua_pop(L, 1);
985         ctx = lsqlite_make_context(L);
986         lua_pushlightuserdata(L, p);
987         lua_pushvalue(L, -2);
988         lua_rawset(L, LUA_REGISTRYINDEX);
989      }
990      else
991         ctx = lsqlite_getcontext(L, -1);
992   }
935993
936        if (lua_isnil(L, -1)) { /* not yet created? */
937            lua_pop(L, 1);
938            ctx = lsqlite_make_context(L);
939            lua_pushlightuserdata(L, p);
940            lua_pushvalue(L, -2);
941            lua_rawset(L, LUA_REGISTRYINDEX);
942        }
943        else
944            ctx = lsqlite_getcontext(L, -1);
945    }
994   /* push params */
995   for (n = 0; n < argc; ++n) {
996      db_push_value(L, argv[n]);
997   }
946998
947    /* push params */
948    for (n = 0; n < argc; ++n) {
949        db_push_value(L, argv[n]);
950    }
999   /* set context */
1000   ctx->ctx = context;
9511001
952    // set context
953    ctx->ctx = context;
1002   if (lua_pcall(L, argc + 1, 0, 0)) {
1003      const char *errmsg = lua_tostring(L, -1);
1004      int size = lua_strlen(L, -1);
1005      sqlite3_result_error(context, errmsg, size);
1006   }
9541007
955    if (lua_pcall(L, argc + 1, 0, 0)) {
956        const char *errmsg = lua_tostring(L, -1);
957        int size = lua_strlen(L, -1);
958        sqlite3_result_error(context, errmsg, size);
959    }
1008   /* invalidate context */
1009   ctx->ctx = NULL;
9601010
961    // invalidate context
962    ctx->ctx = NULL;
1011   if (!func->aggregate) {
1012      luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
1013   }
9631014
964    if (!func->aggregate) {
965        luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
966    }
967
968    lua_settop(L, top);
1015   lua_settop(L, top);
9691016}
9701017
9711018static void db_sql_finalize_function(sqlite3_context *context) {
972    sdb_func *func = (sdb_func*)sqlite3_user_data(context);
973    lua_State *L = func->db->L;
974    void *p = sqlite3_aggregate_context(context, 1); /* minimal mem usage */
975    lcontext *ctx;
976    int top = lua_gettop(L);
1019   sdb_func *func = (sdb_func*)sqlite3_user_data(context);
1020   lua_State *L = func->db->L;
1021   void *p = sqlite3_aggregate_context(context, 1); /* minimal mem usage */
1022   lcontext *ctx;
1023   int top = lua_gettop(L);
9771024
978    lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_finalize);   /* function to call */
1025   lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_finalize);   /* function to call */
9791026
980    /* i think it is OK to use assume that using a light user data
981    ** as an entry on LUA REGISTRY table will be unique */
982    lua_pushlightuserdata(L, p);
983    lua_rawget(L, LUA_REGISTRYINDEX);       /* context table */
1027   /* i think it is OK to use assume that using a light user data
1028   ** as an entry on LUA REGISTRY table will be unique */
1029   lua_pushlightuserdata(L, p);
1030   lua_rawget(L, LUA_REGISTRYINDEX);       /* context table */
9841031
985    if (lua_isnil(L, -1)) { /* not yet created? - shouldn't happen in finalize function */
986        lua_pop(L, 1);
987        ctx = lsqlite_make_context(L);
988        lua_pushlightuserdata(L, p);
989        lua_pushvalue(L, -2);
990        lua_rawset(L, LUA_REGISTRYINDEX);
991    }
992    else
993        ctx = lsqlite_getcontext(L, -1);
1032   if (lua_isnil(L, -1)) { /* not yet created? - shouldn't happen in finalize function */
1033      lua_pop(L, 1);
1034      ctx = lsqlite_make_context(L);
1035      lua_pushlightuserdata(L, p);
1036      lua_pushvalue(L, -2);
1037      lua_rawset(L, LUA_REGISTRYINDEX);
1038   }
1039   else
1040      ctx = lsqlite_getcontext(L, -1);
9941041
995    // set context
996    ctx->ctx = context;
1042   /* set context */
1043   ctx->ctx = context;
9971044
998    if (lua_pcall(L, 1, 0, 0)) {
999        sqlite3_result_error(context, lua_tostring(L, -1), -1);
1000    }
1045   if (lua_pcall(L, 1, 0, 0)) {
1046      sqlite3_result_error(context, lua_tostring(L, -1), -1);
1047   }
10011048
1002    // invalidate context
1003    ctx->ctx = NULL;
1049   /* invalidate context */
1050   ctx->ctx = NULL;
10041051
1005    /* cleanup context */
1006    luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
1007    /* remove it from registry */
1008    lua_pushlightuserdata(L, p);
1009    lua_pushnil(L);
1010    lua_rawset(L, LUA_REGISTRYINDEX);
1052   /* cleanup context */
1053   luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud);
1054   /* remove it from registry */
1055   lua_pushlightuserdata(L, p);
1056   lua_pushnil(L);
1057   lua_rawset(L, LUA_REGISTRYINDEX);
10111058
1012    lua_settop(L, top);
1059   lua_settop(L, top);
10131060}
10141061
10151062/*
r242834r242835
10251072** Params of finalize: context
10261073*/
10271074static int db_register_function(lua_State *L, int aggregate) {
1028    sdb *db = lsqlite_checkdb(L, 1);
1029    const char *name;
1030    int args;
1031    int result;
1032    sdb_func *func;
1075   sdb *db = lsqlite_checkdb(L, 1);
1076   const char *name;
1077   int args;
1078   int result;
1079   sdb_func *func;
10331080
1034    /* safety measure */
1035    if (aggregate) aggregate = 1;
1081   /* safety measure */
1082   if (aggregate) aggregate = 1;
10361083
1037    name = luaL_checkstring(L, 2);
1038    args = luaL_checkint(L, 3);
1039    luaL_checktype(L, 4, LUA_TFUNCTION);
1040    if (aggregate) luaL_checktype(L, 5, LUA_TFUNCTION);
1084   name = luaL_checkstring(L, 2);
1085   args = luaL_checkint(L, 3);
1086   luaL_checktype(L, 4, LUA_TFUNCTION);
1087   if (aggregate) luaL_checktype(L, 5, LUA_TFUNCTION);
10411088
1042    /* maybe an alternative way to allocate memory should be used/avoided */
1043    func = (sdb_func*)malloc(sizeof(sdb_func));
1044    if (func == NULL) {
1045        luaL_error(L, "out of memory");
1046    }
1089   /* maybe an alternative way to allocate memory should be used/avoided */
1090   func = (sdb_func*)malloc(sizeof(sdb_func));
1091   if (func == NULL) {
1092      luaL_error(L, "out of memory");
1093   }
10471094
1048    result = sqlite3_create_function(
1049        db->db, name, args, SQLITE_UTF8, func,
1050        aggregate ? NULL : db_sql_normal_function,
1051        aggregate ? db_sql_normal_function : NULL,
1052        aggregate ? db_sql_finalize_function : NULL
1053    );
1095   result = sqlite3_create_function(
1096      db->db, name, args, SQLITE_UTF8, func,
1097      aggregate ? NULL : db_sql_normal_function,
1098      aggregate ? db_sql_normal_function : NULL,
1099      aggregate ? db_sql_finalize_function : NULL
1100   );
10541101
1055    if (result == SQLITE_OK) {
1056        /* safety measures for userdata field to be present in the stack */
1057        lua_settop(L, 5 + aggregate);
1102   if (result == SQLITE_OK) {
1103      /* safety measures for userdata field to be present in the stack */
1104      lua_settop(L, 5 + aggregate);
10581105
1059        /* save registered function in db function list */
1060        func->db = db;
1061        func->aggregate = aggregate;
1062        func->next = db->func;
1063        db->func = func;
1106      /* save registered function in db function list */
1107      func->db = db;
1108      func->aggregate = aggregate;
1109      func->next = db->func;
1110      db->func = func;
10641111
1065        /* save the setp/normal function callback */
1066        lua_pushvalue(L, 4);
1067        func->fn_step = luaL_ref(L, LUA_REGISTRYINDEX);
1068        /* save user data */
1069        lua_pushvalue(L, 5+aggregate);
1070        func->udata = luaL_ref(L, LUA_REGISTRYINDEX);
1112      /* save the setp/normal function callback */
1113      lua_pushvalue(L, 4);
1114      func->fn_step = luaL_ref(L, LUA_REGISTRYINDEX);
1115      /* save user data */
1116      lua_pushvalue(L, 5+aggregate);
1117      func->udata = luaL_ref(L, LUA_REGISTRYINDEX);
10711118
1072        if (aggregate) {
1073            lua_pushvalue(L, 5);
1074            func->fn_finalize = luaL_ref(L, LUA_REGISTRYINDEX);
1075        }
1076        else
1077            func->fn_finalize = LUA_NOREF;
1078    }
1079    else {
1080        /* free allocated memory */
1081        free(func);
1082    }
1119      if (aggregate) {
1120         lua_pushvalue(L, 5);
1121         func->fn_finalize = luaL_ref(L, LUA_REGISTRYINDEX);
1122      }
1123      else
1124         func->fn_finalize = LUA_NOREF;
1125   }
1126   else {
1127      /* free allocated memory */
1128      free(func);
1129   }
10831130
1084    lua_pushboolean(L, result == SQLITE_OK ? 1 : 0);
1085    return 1;
1131   lua_pushboolean(L, result == SQLITE_OK ? 1 : 0);
1132   return 1;
10861133}
10871134
10881135static int db_create_function(lua_State *L) {
1089    return db_register_function(L, 0);
1136   return db_register_function(L, 0);
10901137}
10911138
10921139static int db_create_aggregate(lua_State *L) {
1093    return db_register_function(L, 1);
1140   return db_register_function(L, 1);
10941141}
10951142
10961143/* create_collation; contributed by Thomas Lauer
10971144*/
10981145
10991146typedef struct {
1100    lua_State *L;
1101    int ref;
1147   lua_State *L;
1148   int ref;
11021149} scc;
11031150
11041151static int collwrapper(scc *co,int l1,const void *p1,
1105                        int l2,const void *p2) {
1106    int res=0;
1107    lua_State *L=co->L;
1108    lua_rawgeti(L,LUA_REGISTRYINDEX,co->ref);
1109    lua_pushlstring(L,p1,l1);
1110    lua_pushlstring(L,p2,l2);
1111    if (lua_pcall(L,2,1,0)==0) res=(int)lua_tonumber(L,-1);
1112    lua_pop(L,1);
1113    return res;
1152                  int l2,const void *p2) {
1153   int res=0;
1154   lua_State *L=co->L;
1155   lua_rawgeti(L,LUA_REGISTRYINDEX,co->ref);
1156   lua_pushlstring(L,(const char*)p1,l1);
1157   lua_pushlstring(L,(const char*)p2,l2);
1158   if (lua_pcall(L,2,1,0)==0) res=lua_tonumber(L,-1);
1159   lua_pop(L,1);
1160   return res;
11141161}
11151162
11161163static void collfree(scc *co) {
1117    if (co) {
1118        luaL_unref(co->L,LUA_REGISTRYINDEX,co->ref);
1119        free(co);
1120    }
1164   if (co) {
1165      luaL_unref(co->L,LUA_REGISTRYINDEX,co->ref);
1166      free(co);
1167   }
11211168}
11221169
11231170static int db_create_collation(lua_State *L) {
1124    sdb *db=lsqlite_checkdb(L,1);
1125    const char *collname=luaL_checkstring(L,2);
1126    scc *co=NULL;
1127    int (*collfunc)(scc *,int,const void *,int,const void *)=NULL;
1128    lua_settop(L,3); /* default args to nil, and exclude extras */
1129    if (lua_isfunction(L,3)) collfunc=collwrapper;
1130    else if (!lua_isnil(L,3))
1131        luaL_error(L,"create_collation: function or nil expected");
1132    if (collfunc != NULL) {
1133        co=(scc *)malloc(sizeof(scc)); // userdata is a no-no as it
1134                                         // will be garbage-collected
1135        if (co) {
1136            co->L=L;
1137            /* lua_settop(L,3) above means we don't need: lua_pushvalue(L,3); */
1138            co->ref=luaL_ref(L,LUA_REGISTRYINDEX);
1139        }
1140        else luaL_error(L,"create_collation: could not allocate callback");
1141    }
1142    sqlite3_create_collation_v2(db->db, collname, SQLITE_UTF8,
1143        (void *)co,
1144        (int(*)(void*,int,const void*,int,const void*))collfunc,
1145        (void(*)(void*))collfree);
1146    return 0;
1171   sdb *db=lsqlite_checkdb(L,1);
1172   const char *collname=luaL_checkstring(L,2);
1173   scc *co=NULL;
1174   int (*collfunc)(scc *,int,const void *,int,const void *)=NULL;
1175   lua_settop(L,3); /* default args to nil, and exclude extras */
1176   if (lua_isfunction(L,3)) collfunc=collwrapper;
1177   else if (!lua_isnil(L,3))
1178      luaL_error(L,"create_collation: function or nil expected");
1179   if (collfunc != NULL) {
1180      co=(scc *)malloc(sizeof(scc)); /* userdata is a no-no as it
1181                                          will be garbage-collected */
1182      if (co) {
1183         co->L=L;
1184         /* lua_settop(L,3) above means we don't need: lua_pushvalue(L,3); */
1185         co->ref=luaL_ref(L,LUA_REGISTRYINDEX);
1186      }
1187      else luaL_error(L,"create_collation: could not allocate callback");
1188   }
1189   sqlite3_create_collation_v2(db->db, collname, SQLITE_UTF8,
1190      (void *)co,
1191      (int(*)(void*,int,const void*,int,const void*))collfunc,
1192      (void(*)(void*))collfree);
1193   return 0;
11471194}
11481195
11491196/*
r242834r242835
11541201** Params: userdata, sql
11551202*/
11561203static void db_trace_callback(void *user, const char *sql) {
1157    sdb *db = (sdb*)user;
1158    lua_State *L = db->L;
1159    int top = lua_gettop(L);
1204   sdb *db = (sdb*)user;
1205   lua_State *L = db->L;
1206   int top = lua_gettop(L);
11601207
1161    /* setup lua callback call */
1162    lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_cb);    /* get callback */
1163    lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_udata); /* get callback user data */
1164    lua_pushstring(L, sql); /* traced sql statement */
1208   /* setup lua callback call */
1209   lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_cb);    /* get callback */
1210   lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_udata); /* get callback user data */
1211   lua_pushstring(L, sql); /* traced sql statement */
11651212
1166    /* call lua function */
1167    lua_pcall(L, 2, 0, 0);
1168    /* ignore any error generated by this function */
1213   /* call lua function */
1214   lua_pcall(L, 2, 0, 0);
1215   /* ignore any error generated by this function */
11691216
1170    lua_settop(L, top);
1217   lua_settop(L, top);
11711218}
11721219
11731220static int db_trace(lua_State *L) {
1174    sdb *db = lsqlite_checkdb(L, 1);
1221   sdb *db = lsqlite_checkdb(L, 1);
11751222
1176    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1177        luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
1178        luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
1223   if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1224      luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
1225      luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
11791226
1180        db->trace_cb =
1181        db->trace_udata = LUA_NOREF;
1227      db->trace_cb =
1228      db->trace_udata = LUA_NOREF;
11821229
1183        /* clear busy handler */
1184        sqlite3_trace(db->db, NULL, NULL);
1185    }
1186    else {
1187        luaL_checktype(L, 2, LUA_TFUNCTION);
1230      /* clear trace handler */
1231      sqlite3_trace(db->db, NULL, NULL);
1232   }
1233   else {
1234      luaL_checktype(L, 2, LUA_TFUNCTION);
11881235
1189        /* make sure we have an userdata field (even if nil) */
1190        lua_settop(L, 3);
1236      /* make sure we have an userdata field (even if nil) */
1237      lua_settop(L, 3);
11911238
1192        luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
1193        luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
1239      luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
1240      luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
11941241
1195        db->trace_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1196        db->trace_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1242      db->trace_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1243      db->trace_cb = luaL_ref(L, LUA_REGISTRYINDEX);
11971244
1198        /* set busy handler */
1199        sqlite3_trace(db->db, db_trace_callback, db);
1200    }
1245      /* set trace handler */
1246      sqlite3_trace(db->db, db_trace_callback, db);
1247   }
12011248
1202    return 0;
1249   return 0;
12031250}
12041251
1252#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
12051253
1254/*
1255** update_hook callback:
1256** Params: database, callback function, userdata
1257**
1258** callback function:
1259** Params: userdata, {one of SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE},
1260**          database name, table name (containing the affected row), rowid of the row
1261*/
1262static void db_update_hook_callback(void *user, int op, char const *dbname, char const *tblname, sqlite3_int64 rowid) {
1263   sdb *db = (sdb*)user;
1264   lua_State *L = db->L;
1265   int top = lua_gettop(L);
1266   lua_Number n;
1267
1268   /* setup lua callback call */
1269   lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_cb);    /* get callback */
1270   lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_udata); /* get callback user data */
1271   lua_pushnumber(L, (lua_Number )op);
1272   lua_pushstring(L, dbname); /* update_hook database name */
1273   lua_pushstring(L, tblname); /* update_hook database name */
1274   n = (lua_Number)rowid;
1275   if (n == rowid)
1276      lua_pushnumber(L, n);
1277   else
1278      lua_pushfstring(L, "%ll", rowid);
1279
1280   /* call lua function */
1281   lua_pcall(L, 5, 0, 0);
1282   /* ignore any error generated by this function */
1283
1284   lua_settop(L, top);
1285}
1286
1287static int db_update_hook(lua_State *L) {
1288   sdb *db = lsqlite_checkdb(L, 1);
1289
1290   if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1291      luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
1292      luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);
1293
1294      db->update_hook_cb =
1295      db->update_hook_udata = LUA_NOREF;
1296
1297      /* clear update_hook handler */
1298      sqlite3_update_hook(db->db, NULL, NULL);
1299   }
1300   else {
1301      luaL_checktype(L, 2, LUA_TFUNCTION);
1302
1303      /* make sure we have an userdata field (even if nil) */
1304      lua_settop(L, 3);
1305
1306      luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
1307      luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);
1308
1309      db->update_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1310      db->update_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1311
1312      /* set update_hook handler */
1313      sqlite3_update_hook(db->db, db_update_hook_callback, db);
1314   }
1315
1316   return 0;
1317}
1318
1319/*
1320** commit_hook callback:
1321** Params: database, callback function, userdata
1322**
1323** callback function:
1324** Params: userdata
1325** Returned value: Return false or nil to continue the COMMIT operation normally.
1326**  return true (non false, non nil), then the COMMIT is converted into a ROLLBACK.
1327*/
1328static int db_commit_hook_callback(void *user) {
1329   sdb *db = (sdb*)user;
1330   lua_State *L = db->L;
1331   int top = lua_gettop(L);
1332   int rollback = 0;
1333
1334   /* setup lua callback call */
1335   lua_rawgeti(L, LUA_REGISTRYINDEX, db->commit_hook_cb);    /* get callback */
1336   lua_rawgeti(L, LUA_REGISTRYINDEX, db->commit_hook_udata); /* get callback user data */
1337
1338   /* call lua function */
1339   if (!lua_pcall(L, 1, 1, 0))
1340      rollback = lua_toboolean(L, -1); /* use result if there was no error */
1341
1342   lua_settop(L, top);
1343   return rollback;
1344}
1345
1346static int db_commit_hook(lua_State *L) {
1347   sdb *db = lsqlite_checkdb(L, 1);
1348
1349   if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1350      luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
1351      luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);
1352
1353      db->commit_hook_cb =
1354      db->commit_hook_udata = LUA_NOREF;
1355
1356      /* clear commit_hook handler */
1357      sqlite3_commit_hook(db->db, NULL, NULL);
1358   }
1359   else {
1360      luaL_checktype(L, 2, LUA_TFUNCTION);
1361
1362      /* make sure we have an userdata field (even if nil) */
1363      lua_settop(L, 3);
1364
1365      luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
1366      luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);
1367
1368      db->commit_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1369      db->commit_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1370
1371      /* set commit_hook handler */
1372      sqlite3_commit_hook(db->db, db_commit_hook_callback, db);
1373   }
1374
1375   return 0;
1376}
1377
1378/*
1379** rollback hook callback:
1380** Params: database, callback function, userdata
1381**
1382** callback function:
1383** Params: userdata
1384*/
1385static void db_rollback_hook_callback(void *user) {
1386   sdb *db = (sdb*)user;
1387   lua_State *L = db->L;
1388   int top = lua_gettop(L);
1389
1390   /* setup lua callback call */
1391   lua_rawgeti(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);    /* get callback */
1392   lua_rawgeti(L, LUA_REGISTRYINDEX, db->rollback_hook_udata); /* get callback user data */
1393
1394   /* call lua function */
1395   lua_pcall(L, 1, 0, 0);
1396   /* ignore any error generated by this function */
1397
1398   lua_settop(L, top);
1399}
1400
1401static int db_rollback_hook(lua_State *L) {
1402   sdb *db = lsqlite_checkdb(L, 1);
1403
1404   if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1405      luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
1406      luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);
1407
1408      db->rollback_hook_cb =
1409      db->rollback_hook_udata = LUA_NOREF;
1410
1411      /* clear rollback_hook handler */
1412      sqlite3_rollback_hook(db->db, NULL, NULL);
1413   }
1414   else {
1415      luaL_checktype(L, 2, LUA_TFUNCTION);
1416
1417      /* make sure we have an userdata field (even if nil) */
1418      lua_settop(L, 3);
1419
1420      luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
1421      luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);
1422
1423      db->rollback_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1424      db->rollback_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1425
1426      /* set rollback_hook handler */
1427      sqlite3_rollback_hook(db->db, db_rollback_hook_callback, db);
1428   }
1429
1430   return 0;
1431}
1432
1433#endif /* #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK */
1434
12061435#if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK
12071436
12081437/*
r242834r242835
12141443** returns: 0 to return immediatly and return SQLITE_ABORT, non-zero to continue
12151444*/
12161445static int db_progress_callback(void *user) {
1217    int result = 1; /* abort by default */
1218    sdb *db = (sdb*)user;
1219    lua_State *L = db->L;
1220    int top = lua_gettop(L);
1446   int result = 1; /* abort by default */
1447   sdb *db = (sdb*)user;
1448   lua_State *L = db->L;
1449   int top = lua_gettop(L);
12211450
1222    lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_cb);
1223    lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_udata);
1451   lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_cb);
1452   lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_udata);
12241453
1225    /* call lua function */
1226    if (!lua_pcall(L, 1, 1, 0))
1227        result = lua_toboolean(L, -1);
1454   /* call lua function */
1455   if (!lua_pcall(L, 1, 1, 0))
1456      result = lua_toboolean(L, -1);
12281457
1229    lua_settop(L, top);
1230    return result;
1458   lua_settop(L, top);
1459   return result;
12311460}
12321461
12331462static int db_progress_handler(lua_State *L) {
1234    sdb *db = lsqlite_checkdb(L, 1);
1463   sdb *db = lsqlite_checkdb(L, 1);
12351464
1236    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1237        luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
1238        luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
1465   if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1466      luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
1467      luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
12391468
1240        db->progress_cb =
1241        db->progress_udata = LUA_NOREF;
1469      db->progress_cb =
1470      db->progress_udata = LUA_NOREF;
12421471
1243        /* clear busy handler */
1244        sqlite3_progress_handler(db->db, 0, NULL, NULL);
1245    }
1246    else {
1247        int nop = luaL_checkint(L, 2);  /* number of opcodes */
1248        luaL_checktype(L, 3, LUA_TFUNCTION);
1472      /* clear busy handler */
1473      sqlite3_progress_handler(db->db, 0, NULL, NULL);
1474   }
1475   else {
1476      int nop = luaL_checkint(L, 2);  /* number of opcodes */
1477      luaL_checktype(L, 3, LUA_TFUNCTION);
12491478
1250        /* make sure we have an userdata field (even if nil) */
1251        lua_settop(L, 4);
1479      /* make sure we have an userdata field (even if nil) */
1480      lua_settop(L, 4);
12521481
1253        luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
1254        luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
1482      luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
1483      luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
12551484
1256        db->progress_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1257        db->progress_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1485      db->progress_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1486      db->progress_cb = luaL_ref(L, LUA_REGISTRYINDEX);
12581487
1259        /* set progress callback */
1260        sqlite3_progress_handler(db->db, nop, db_progress_callback, db);
1261    }
1488      /* set progress callback */
1489      sqlite3_progress_handler(db->db, nop, db_progress_callback, db);
1490   }
12621491
1263    return 0;
1492   return 0;
12641493}
12651494
12661495#else /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */
12671496
12681497static int db_progress_handler(lua_State *L) {
1269    lua_pushliteral(L, "progress callback support disabled at compile time");
1270    lua_error(L);
1271    return 0;
1498   lua_pushliteral(L, "progress callback support disabled at compile time");
1499   lua_error(L);
1500   return 0;
12721501}
12731502
12741503#endif /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */
r242834r242835
12821511** returns: 0 to return immediatly and return SQLITE_BUSY, non-zero to try again
12831512*/
12841513static int db_busy_callback(void *user, int tries) {
1285    int retry = 0; /* abort by default */
1286    sdb *db = (sdb*)user;
1287    lua_State *L = db->L;
1288    int top = lua_gettop(L);
1514   int retry = 0; /* abort by default */
1515   sdb *db = (sdb*)user;
1516   lua_State *L = db->L;
1517   int top = lua_gettop(L);
12891518
1290    lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_cb);
1291    lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_udata);
1292    lua_pushnumber(L, tries);
1519   lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_cb);
1520   lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_udata);
1521   lua_pushnumber(L, tries);
12931522
1294    /* call lua function */
1295    if (!lua_pcall(L, 2, 1, 0))
1296        retry = lua_toboolean(L, -1);
1523   /* call lua function */
1524   if (!lua_pcall(L, 2, 1, 0))
1525      retry = lua_toboolean(L, -1);
12971526
1298    lua_settop(L, top);
1299    return retry;
1527   lua_settop(L, top);
1528   return retry;
13001529}
13011530
13021531static int db_busy_handler(lua_State *L) {
1303    sdb *db = lsqlite_checkdb(L, 1);
1532   sdb *db = lsqlite_checkdb(L, 1);
13041533
1305    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1306        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1307        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1534   if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
1535      luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1536      luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
13081537
1309        db->busy_cb =
1310        db->busy_udata = LUA_NOREF;
1538      db->busy_cb =
1539      db->busy_udata = LUA_NOREF;
13111540
1312        /* clear busy handler */
1313        sqlite3_busy_handler(db->db, NULL, NULL);
1314    }
1315    else {
1316        luaL_checktype(L, 2, LUA_TFUNCTION);
1317        /* make sure we have an userdata field (even if nil) */
1318        lua_settop(L, 3);
1541      /* clear busy handler */
1542      sqlite3_busy_handler(db->db, NULL, NULL);
1543   }
1544   else {
1545      luaL_checktype(L, 2, LUA_TFUNCTION);
1546      /* make sure we have an userdata field (even if nil) */
1547      lua_settop(L, 3);
13191548
1320        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1321        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1549      luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1550      luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
13221551
1323        db->busy_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1324        db->busy_cb = luaL_ref(L, LUA_REGISTRYINDEX);
1552      db->busy_udata = luaL_ref(L, LUA_REGISTRYINDEX);
1553      db->busy_cb = luaL_ref(L, LUA_REGISTRYINDEX);
13251554
1326        /* set busy handler */
1327        sqlite3_busy_handler(db->db, db_busy_callback, db);
1328    }
1555      /* set busy handler */
1556      sqlite3_busy_handler(db->db, db_busy_callback, db);
1557   }
13291558
1330    return 0;
1559   return 0;
13311560}
13321561
13331562static int db_busy_timeout(lua_State *L) {
1334    sdb *db = lsqlite_checkdb(L, 1);
1335    int timeout = luaL_checkint(L, 2);
1336    sqlite3_busy_timeout(db->db, timeout);
1563   sdb *db = lsqlite_checkdb(L, 1);
1564   int timeout = luaL_checkint(L, 2);
1565   sqlite3_busy_timeout(db->db, timeout);
13371566
1338    /* if there was a timeout callback registered, it is now
1339    ** invalid/useless. free any references we may have */
1340    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1341    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1342    db->busy_cb =
1343    db->busy_udata = LUA_NOREF;
1567   /* if there was a timeout callback registered, it is now
1568   ** invalid/useless. free any references we may have */
1569   luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
1570   luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
1571   db->busy_cb =
1572   db->busy_udata = LUA_NOREF;
13441573
1345    return 0;
1574   return 0;
13461575}
13471576
13481577/*
r242834r242835
13541583** Returns: 0 to continue, other value will cause abort
13551584*/
13561585static int db_exec_callback(void* user, int columns, char **data, char **names) {
1357    int result = SQLITE_ABORT; /* abort by default */
1358    sdb *db = (sdb*)user;
1359    lua_State *L = db->L;
1360    int n;
1586   int result = SQLITE_ABORT; /* abort by default */
1587   lua_State *L = (lua_State*)user;
1588   int n;
13611589
1362    int top = lua_gettop(L);
1590   int top = lua_gettop(L);
13631591
1364    lua_pushvalue(L, 3); /* function to call */
1365    lua_pushvalue(L, 4); /* user data */
1366    lua_pushnumber(L, columns); /* total number of rows in result */
1592   lua_pushvalue(L, 3); /* function to call */
1593   lua_pushvalue(L, 4); /* user data */
1594   lua_pushnumber(L, columns); /* total number of rows in result */
13671595
1368    /* column values */
1369    lua_pushvalue(L, 6);
1370    for (n = 0; n < columns;) {
1371        lua_pushstring(L, data[n++]);
1372        lua_rawseti(L, -2, n);
1373    }
1596   /* column values */
1597   lua_pushvalue(L, 6);
1598   for (n = 0; n < columns;) {
1599      lua_pushstring(L, data[n++]);
1600      lua_rawseti(L, -2, n);
1601   }
13741602
1375    /* columns names */
1376    lua_pushvalue(L, 5);
1377    if (lua_isnil(L, -1)) {
1378        lua_pop(L, 1);
1379        lua_newtable(L);
1380        lua_pushvalue(L, -1);
1381        lua_replace(L, 5);
1382        for (n = 0; n < columns;) {
1383            lua_pushstring(L, names[n++]);
1384            lua_rawseti(L, -2, n);
1385        }
1386    }
1603   /* columns names */
1604   lua_pushvalue(L, 5);
1605   if (lua_isnil(L, -1)) {
1606      lua_pop(L, 1);
1607      lua_newtable(L);
1608      lua_pushvalue(L, -1);
1609      lua_replace(L, 5);
1610      for (n = 0; n < columns;) {
1611         lua_pushstring(L, names[n++]);
1612         lua_rawseti(L, -2, n);
1613      }
1614   }
13871615
1388    /* call lua function */
1389    if (!lua_pcall(L, 4, 1, 0)) {
1390        if (lua_isnumber(L, -1))
1391            result = lua_tonumber(L, -1);
1392    }
1616   /* call lua function */
1617   if (!lua_pcall(L, 4, 1, 0)) {
1618      if (lua_isnumber(L, -1))
1619         result = lua_tonumber(L, -1);
1620   }
13931621
1394    lua_settop(L, top);
1395    return result;
1622   lua_settop(L, top);
1623   return result;
13961624}
13971625
13981626static int db_exec(lua_State *L) {
1399    sdb *db = lsqlite_checkdb(L, 1);
1400    const char *sql = luaL_checkstring(L, 2);
1401    int result;
1627   sdb *db = lsqlite_checkdb(L, 1);
1628   const char *sql = luaL_checkstring(L, 2);
1629   int result;
14021630
1403    if (!lua_isnoneornil(L, 3)) {
1404        /* stack:
1405        **  3: callback function
1406        **  4: userdata
1407        **  5: column names
1408        **  6: reusable column values
1409        */
1410        luaL_checktype(L, 3, LUA_TFUNCTION);
1411        lua_settop(L, 4);   /* 'trap' userdata - nil extra parameters */
1412        lua_pushnil(L);     /* column names not known at this point */
1413        lua_newtable(L);    /* column values table */
1631   if (!lua_isnoneornil(L, 3)) {
1632      /* stack:
1633      **  3: callback function
1634      **  4: userdata
1635      **  5: column names
1636      **  6: reusable column values
1637      */
1638      luaL_checktype(L, 3, LUA_TFUNCTION);
1639      lua_settop(L, 4);   /* 'trap' userdata - nil extra parameters */
1640      lua_pushnil(L);     /* column names not known at this point */
1641      lua_newtable(L);    /* column values table */
14141642
1415        result = sqlite3_exec(db->db, sql, db_exec_callback, db, NULL);
1416    }
1417    else {
1418        /* no callbacks */
1419        result = sqlite3_exec(db->db, sql, NULL, NULL, NULL);
1420    }
1643      result = sqlite3_exec(db->db, sql, db_exec_callback, L, NULL);
1644   }
1645   else {
1646      /* no callbacks */
1647      result = sqlite3_exec(db->db, sql, NULL, NULL, NULL);
1648   }
14211649
1422    lua_pushnumber(L, result);
1423    return 1;
1650   lua_pushnumber(L, result);
1651   return 1;
14241652}
14251653
14261654/*
r242834r242835
14281656** returns: code, compiled length or error message
14291657*/
14301658static int db_prepare(lua_State *L) {
1431    sdb *db = lsqlite_checkdb(L, 1);
1432    const char *sql = luaL_checkstring(L, 2);
1433    int sql_len = lua_strlen(L, 2);
1434    const char *sqltail;
1435    sdb_vm *svm;
1436    lua_settop(L,2); /* sql is on top of stack for call to newvm */
1437    svm = newvm(L, db);
1659   sdb *db = lsqlite_checkdb(L, 1);
1660   const char *sql = luaL_checkstring(L, 2);
1661   int sql_len = lua_strlen(L, 2);
1662   const char *sqltail;
1663   sdb_vm *svm;
1664   lua_settop(L,2); /* sql is on top of stack for call to newvm */
1665   svm = newvm(L, db);
14381666
1439    if (sqlite3_prepare(db->db, sql, sql_len, &svm->vm, &sqltail) != SQLITE_OK) {
1440        cleanupvm(L, svm);
1667   if (sqlite3_prepare(db->db, sql, sql_len, &svm->vm, &sqltail) != SQLITE_OK) {
1668      cleanupvm(L, svm);
14411669
1442        lua_pushnil(L);
1443        lua_pushnumber(L, sqlite3_errcode(db->db));
1444        return 2;
1445    }
1670      lua_pushnil(L);
1671      lua_pushnumber(L, sqlite3_errcode(db->db));
1672      return 2;
1673   }
14461674
1447    /* vm already in the stack */
1448    lua_pushstring(L, sqltail);
1449    return 2;
1675   /* vm already in the stack */
1676   lua_pushstring(L, sqltail);
1677   return 2;
14501678}
14511679
14521680static int db_do_next_row(lua_State *L, int packed) {
1453    int result;
1454    sdb_vm *svm = lsqlite_checkvm(L, 1);
1455    sqlite3_stmt *vm;
1456    int columns;
1457    int i;
1681   int result;
1682   sdb_vm *svm = lsqlite_checkvm(L, 1);
1683   sqlite3_stmt *vm;
1684   int columns;
1685   int i;
14581686
1459    result = stepvm(L, svm);
1460    vm = svm->vm; /* stepvm may change svm->vm if re-prepare is needed */
1461    svm->has_values = result == SQLITE_ROW ? 1 : 0;
1462    svm->columns = columns = sqlite3_data_count(vm);
1687   result = stepvm(L, svm);
1688   vm = svm->vm; /* stepvm may change svm->vm if re-prepare is needed */
1689   svm->has_values = result == SQLITE_ROW ? 1 : 0;
1690   svm->columns = columns = sqlite3_data_count(vm);
14631691
1464    if (result == SQLITE_ROW) {
1465        if (packed) {
1466            lua_newtable(L);
1467            if (packed == 1) {
1468                for (i = 0; i < columns;) {
1469                    vm_push_column(L, vm, i);
1470                    lua_rawseti(L, -2, ++i);
1471                }
1472            }
1473            else {
1474                for (i = 0; i < columns; ++i) {
1475                    lua_pushstring(L, sqlite3_column_name(vm, i));
1476                    vm_push_column(L, vm, i);
1477                    lua_rawset(L, -3);
1478                }
1479            }
1480            return 1;
1481        }
1482        else {
1483            lua_checkstack(L, columns);
1484            for (i = 0; i < columns; ++i)
1485                vm_push_column(L, vm, i);
1486            return svm->columns;
1487        }
1488    }
1692   if (result == SQLITE_ROW) {
1693      if (packed) {
1694         lua_newtable(L);
1695         if (packed == 1) {
1696            for (i = 0; i < columns;) {
1697               vm_push_column(L, vm, i);
1698               lua_rawseti(L, -2, ++i);
1699            }
1700         }
1701         else {
1702            for (i = 0; i < columns; ++i) {
1703               lua_pushstring(L, sqlite3_column_name(vm, i));
1704               vm_push_column(L, vm, i);
1705               lua_rawset(L, -3);
1706            }
1707         }
1708         return 1;
1709      }
1710      else {
1711         lua_checkstack(L, columns);
1712         for (i = 0; i < columns; ++i)
1713            vm_push_column(L, vm, i);
1714         return svm->columns;
1715      }
1716   }
14891717
1490    if (svm->temp) {
1491        /* finalize and check for errors */
1492        result = sqlite3_finalize(vm);
1493        svm->vm = NULL;
1494        cleanupvm(L, svm);
1495    }
1496    else if (result == SQLITE_DONE) {
1497        result = sqlite3_reset(vm);
1498    }
1718   if (svm->temp) {
1719      /* finalize and check for errors */
1720      result = sqlite3_finalize(vm);
1721      svm->vm = NULL;
1722      cleanupvm(L, svm);
1723   }
1724   else if (result == SQLITE_DONE) {
1725      result = sqlite3_reset(vm);
1726   }
14991727
1500    if (result != SQLITE_OK) {
1501        lua_pushstring(L, sqlite3_errmsg(svm->db->db));
1502        lua_error(L);
1503    }
1504    return 0;
1728   if (result != SQLITE_OK) {
1729      lua_pushstring(L, sqlite3_errmsg(svm->db->db));
1730      lua_error(L);
1731   }
1732   return 0;
15051733}
15061734
15071735static int db_next_row(lua_State *L) {
1508    return db_do_next_row(L, 0);
1736   return db_do_next_row(L, 0);
15091737}
15101738
15111739static int db_next_packed_row(lua_State *L) {
1512    return db_do_next_row(L, 1);
1740   return db_do_next_row(L, 1);
15131741}
15141742
15151743static int db_next_named_row(lua_State *L) {
1516    return db_do_next_row(L, 2);
1744   return db_do_next_row(L, 2);
15171745}
15181746
15191747static int dbvm_do_rows(lua_State *L, int(*f)(lua_State *)) {
1520    //sdb_vm *svm =
1521    lsqlite_checkvm(L, 1);
1522    lua_pushvalue(L,1);
1523    lua_pushcfunction(L, f);
1524    lua_insert(L, -2);
1525    return 2;
1748   /* sdb_vm *svm =  */
1749   lsqlite_checkvm(L, 1);
1750   lua_pushvalue(L,1);
1751   lua_pushcfunction(L, f);
1752   lua_insert(L, -2);
1753   return 2;
15261754}
15271755
15281756static int dbvm_rows(lua_State *L) {
1529    return dbvm_do_rows(L, db_next_packed_row);
1757   return dbvm_do_rows(L, db_next_packed_row);
15301758}
15311759
15321760static int dbvm_nrows(lua_State *L) {
1533    return dbvm_do_rows(L, db_next_named_row);
1761   return dbvm_do_rows(L, db_next_named_row);
15341762}
15351763
15361764static int dbvm_urows(lua_State *L) {
1537    return dbvm_do_rows(L, db_next_row);
1765   return dbvm_do_rows(L, db_next_row);
15381766}
15391767
15401768static int db_do_rows(lua_State *L, int(*f)(lua_State *)) {
1541    sdb *db = lsqlite_checkdb(L, 1);
1542    const char *sql = luaL_checkstring(L, 2);
1543    sdb_vm *svm;
1544    lua_settop(L,2); /* sql is on top of stack for call to newvm */
1545    svm = newvm(L, db);
1546    svm->temp = 1;
1769   sdb *db = lsqlite_checkdb(L, 1);
1770   const char *sql = luaL_checkstring(L, 2);
1771   sdb_vm *svm;
1772   lua_settop(L,2); /* sql is on top of stack for call to newvm */
1773   svm = newvm(L, db);
1774   svm->temp = 1;
15471775
1548    if (sqlite3_prepare(db->db, sql, -1, &svm->vm, NULL) != SQLITE_OK) {
1549        cleanupvm(L, svm);
1776   if (sqlite3_prepare(db->db, sql, -1, &svm->vm, NULL) != SQLITE_OK) {
1777      cleanupvm(L, svm);
15501778
1551        lua_pushstring(L, sqlite3_errmsg(svm->db->db));
1552        lua_error(L);
1553    }
1779      lua_pushstring(L, sqlite3_errmsg(svm->db->db));
1780      lua_error(L);
1781   }
15541782
1555    lua_pushcfunction(L, f);
1556    lua_insert(L, -2);
1557    return 2;
1783   lua_pushcfunction(L, f);
1784   lua_insert(L, -2);
1785   return 2;
15581786}
15591787
15601788static int db_rows(lua_State *L) {
1561    return db_do_rows(L, db_next_packed_row);
1789   return db_do_rows(L, db_next_packed_row);
15621790}
15631791
15641792static int db_nrows(lua_State *L) {
1565    return db_do_rows(L, db_next_named_row);
1793   return db_do_rows(L, db_next_named_row);
15661794}
15671795
15681796/* unpacked version of db:rows */
15691797static int db_urows(lua_State *L) {
1570    return db_do_rows(L, db_next_row);
1798   return db_do_rows(L, db_next_row);
15711799}
15721800
15731801static int db_tostring(lua_State *L) {
1574    char buff[32];
1575    sdb *db = lsqlite_getdb(L, 1);
1576    if (db->db == NULL)
1577        strcpy(buff, "closed");
1578    else
1579        sprintf(buff, "%p", lua_touserdata(L, 1));
1580    lua_pushfstring(L, "sqlite database (%s)", buff);
1581    return 1;
1802   char buff[32];
1803   sdb *db = lsqlite_getdb(L, 1);
1804   if (db->db == NULL)
1805      strcpy(buff, "closed");
1806   else
1807      sprintf(buff, "%p", lua_touserdata(L, 1));
1808   lua_pushfstring(L, "sqlite database (%s)", buff);
1809   return 1;
15821810}
15831811
15841812static int db_close(lua_State *L) {
1585    sdb *db = lsqlite_checkdb(L, 1);
1586    lua_pushnumber(L, cleanupdb(L, db));
1587    return 1;
1813   sdb *db = lsqlite_checkdb(L, 1);
1814   lua_pushnumber(L, cleanupdb(L, db));
1815   return 1;
15881816}
15891817
15901818static int db_close_vm(lua_State *L) {
1591    sdb *db = lsqlite_checkdb(L, 1);
1592    /* cleanup temporary only tables? */
1593    int temp = lua_toboolean(L, 2);
1819   sdb *db = lsqlite_checkdb(L, 1);
1820   /* cleanup temporary only tables? */
1821   int temp = lua_toboolean(L, 2);
15941822
1595    /* free associated virtual machines */
1596    lua_pushlightuserdata(L, db);
1597    lua_rawget(L, LUA_REGISTRYINDEX);
1823   /* free associated virtual machines */
1824   lua_pushlightuserdata(L, db);
1825   lua_rawget(L, LUA_REGISTRYINDEX);
15981826
1599    /* close all used handles */
1600    lua_pushnil(L);
1601    while (lua_next(L, -2)) {
1602        sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */
1827   /* close all used handles */
1828   lua_pushnil(L);
1829   while (lua_next(L, -2)) {
1830      sdb_vm *svm = (sdb_vm *)lua_touserdata(L, -2); /* key: vm; val: sql text */
16031831
1604        if ((!temp || svm->temp) && svm->vm)
1605        {
1606            sqlite3_finalize(svm->vm);
1607            svm->vm = NULL;
1608        }
1832      if ((!temp || svm->temp) && svm->vm)
1833      {
1834         sqlite3_finalize(svm->vm);
1835         svm->vm = NULL;
1836      }
16091837
1610        /* leave key in the stack */
1611        lua_pop(L, 1);
1612    }
1613    return 0;
1838      /* leave key in the stack */
1839      lua_pop(L, 1);
1840   }
1841   return 0;
16141842}
16151843
16161844static int db_gc(lua_State *L) {
1617    sdb *db = lsqlite_getdb(L, 1);
1618    if (db->db != NULL)  /* ignore closed databases */
1619        cleanupdb(L, db);
1620    return 0;
1845   sdb *db = lsqlite_getdb(L, 1);
1846   if (db->db != NULL)  /* ignore closed databases */
1847      cleanupdb(L, db);
1848   return 0;
16211849}
16221850
16231851/*
r242834r242835
16271855*/
16281856
16291857static int lsqlite_version(lua_State *L) {
1630    lua_pushstring(L, sqlite3_libversion());
1631    return 1;
1858   lua_pushstring(L, sqlite3_libversion());
1859   return 1;
16321860}
16331861
16341862static int lsqlite_complete(lua_State *L) {
1635    const char *sql = luaL_checkstring(L, 1);
1636    lua_pushboolean(L, sqlite3_complete(sql));
1637    return 1;
1863   const char *sql = luaL_checkstring(L, 1);
1864   lua_pushboolean(L, sqlite3_complete(sql));
1865   return 1;
16381866}
16391867
16401868#ifndef WIN32
16411869static int lsqlite_temp_directory(lua_State *L) {
1642    const char *oldtemp = sqlite3_temp_directory;
1870   const char *oldtemp = sqlite3_temp_directory;
16431871
1644    if (!lua_isnone(L, 1)) {
1645        const char *temp = luaL_optstring(L, 1, NULL);
1646        if (sqlite3_temp_directory) {
1647            sqlite3_free((char*)sqlite3_temp_directory);
1648        }
1649        if (temp) {
1650            sqlite3_temp_directory = sqlite3_mprintf("%s", temp);
1651        }
1652        else {
1653            sqlite3_temp_directory = NULL;
1654        }
1655    }
1656    lua_pushstring(L, oldtemp);
1657    return 1;
1872   if (!lua_isnone(L, 1)) {
1873      const char *temp = luaL_optstring(L, 1, NULL);
1874      if (sqlite3_temp_directory) {
1875         sqlite3_free((char*)sqlite3_temp_directory);
1876      }
1877      if (temp) {
1878         sqlite3_temp_directory = sqlite3_mprintf("%s", temp);
1879      }
1880      else {
1881         sqlite3_temp_directory = NULL;
1882      }
1883   }
1884   lua_pushstring(L, oldtemp);
1885   return 1;
16581886}
16591887#endif
16601888
16611889static int lsqlite_do_open(lua_State *L, const char *filename) {
1662    sdb *db = newdb(L); /* create and leave in stack */
1890   sdb *db = newdb(L); /* create and leave in stack */
16631891
1664    if (sqlite3_open(filename, &db->db) == SQLITE_OK) {
1665        /* database handle already in the stack - return it */
1666        return 1;
1667    }
1892   if (sqlite3_open(filename, &db->db) == SQLITE_OK) {
1893      /* database handle already in the stack - return it */
1894      return 1;
1895   }
16681896
1669    /* failed to open database */
1670    lua_pushnil(L);                             /* push nil */
1671    lua_pushnumber(L, sqlite3_errcode(db->db));
1672    lua_pushstring(L, sqlite3_errmsg(db->db));  /* push error message */
1897   /* failed to open database */
1898   lua_pushnil(L);                             /* push nil */
1899   lua_pushnumber(L, sqlite3_errcode(db->db));
1900   lua_pushstring(L, sqlite3_errmsg(db->db));  /* push error message */
16731901
1674    /* clean things up */
1675    cleanupdb(L, db);
1902   /* clean things up */
1903   cleanupdb(L, db);
16761904
1677    /* return */
1678    return 3;
1905   /* return */
1906   return 3;
16791907}
16801908
16811909static int lsqlite_open(lua_State *L) {
1682    const char *filename = luaL_checkstring(L, 1);
1683    return lsqlite_do_open(L, filename);
1910   const char *filename = luaL_checkstring(L, 1);
1911   return lsqlite_do_open(L, filename);
16841912}
16851913
16861914static int lsqlite_open_memory(lua_State *L) {
1687    return lsqlite_do_open(L, ":memory:");
1915   return lsqlite_do_open(L, ":memory:");
16881916}
16891917
16901918static int lsqlite_newindex(lua_State *L) {
1691    lua_pushliteral(L, "attempt to change readonly table");
1692    lua_error(L);
1693    return 0;
1919   lua_pushliteral(L, "attempt to change readonly table");
1920   lua_error(L);
1921   return 0;
16941922}
16951923
16961924/*
r242834r242835
17031931#define LSC(s)  { #s, LSQLITE_ ## s },
17041932
17051933static const struct {
1706    const char* name;
1707    int value;
1934   const char* name;
1935   int value;
17081936} sqlite_constants[] = {
1709    /* error codes */
1710    SC(OK)          SC(ERROR)       SC(INTERNAL)    SC(PERM)
1711    SC(ABORT)       SC(BUSY)        SC(LOCKED)      SC(NOMEM)
1712    SC(READONLY)    SC(INTERRUPT)   SC(IOERR)       SC(CORRUPT)
1713    SC(NOTFOUND)    SC(FULL)        SC(CANTOPEN)    SC(PROTOCOL)
1714    SC(EMPTY)       SC(SCHEMA)      SC(TOOBIG)      SC(CONSTRAINT)
1715    SC(MISMATCH)    SC(MISUSE)      SC(NOLFS)
1716    SC(FORMAT)      SC(NOTADB)
1937   /* error codes */
1938   SC(OK)          SC(ERROR)       SC(INTERNAL)    SC(PERM)
1939   SC(ABORT)       SC(BUSY)        SC(LOCKED)      SC(NOMEM)
1940   SC(READONLY)    SC(INTERRUPT)   SC(IOERR)       SC(CORRUPT)
1941   SC(NOTFOUND)    SC(FULL)        SC(CANTOPEN)    SC(PROTOCOL)
1942   SC(EMPTY)       SC(SCHEMA)      SC(TOOBIG)      SC(CONSTRAINT)
1943   SC(MISMATCH)    SC(MISUSE)      SC(NOLFS)
1944   SC(FORMAT)      SC(NOTADB)
17171945
1718    /* sqlite_step specific return values */
1719    SC(RANGE)       SC(ROW)         SC(DONE)
1946   /* sqlite_step specific return values */
1947   SC(RANGE)       SC(ROW)         SC(DONE)
17201948
1721    /* column types */
1722    SC(INTEGER)     SC(FLOAT)       SC(TEXT)        SC(BLOB)
1723    SC(NULL)
1949   /* column types */
1950   SC(INTEGER)     SC(FLOAT)       SC(TEXT)        SC(BLOB)
1951   SC(NULL)
17241952
1725    /* terminator */
1726    { NULL, 0 }
1953   /* Authorizer Action Codes */
1954   SC(CREATE_INDEX       )
1955   SC(CREATE_TABLE       )
1956   SC(CREATE_TEMP_INDEX  )
1957   SC(CREATE_TEMP_TABLE  )
1958   SC(CREATE_TEMP_TRIGGER)
1959   SC(CREATE_TEMP_VIEW   )
1960   SC(CREATE_TRIGGER     )
1961   SC(CREATE_VIEW        )
1962   SC(DELETE             )
1963   SC(DROP_INDEX         )
1964   SC(DROP_TABLE         )
1965   SC(DROP_TEMP_INDEX    )
1966   SC(DROP_TEMP_TABLE    )
1967   SC(DROP_TEMP_TRIGGER  )
1968   SC(DROP_TEMP_VIEW     )
1969   SC(DROP_TRIGGER       )
1970   SC(DROP_VIEW          )
1971   SC(INSERT             )
1972   SC(PRAGMA             )
1973   SC(READ               )
1974   SC(SELECT             )
1975   SC(TRANSACTION        )
1976   SC(UPDATE             )
1977   SC(ATTACH             )
1978   SC(DETACH             )
1979   SC(ALTER_TABLE        )
1980   SC(REINDEX            )
1981   SC(ANALYZE            )
1982   SC(CREATE_VTABLE      )
1983   SC(DROP_VTABLE        )
1984   SC(FUNCTION           )
1985   SC(SAVEPOINT          )
1986
1987   /* terminator */
1988   { NULL, 0 }
17271989};
17281990
17291991/* ======================================================= */
17301992
1731static const luaL_reg dblib[] = {
1732    {"isopen",              db_isopen               },
1733    {"last_insert_rowid",   db_last_insert_rowid    },
1734    {"changes",             db_changes              },
1735    {"total_changes",       db_total_changes        },
1736    {"errcode",             db_errcode              },
1737    {"error_code",          db_errcode              },
1738    {"errmsg",              db_errmsg               },
1739    {"error_message",       db_errmsg               },
1740    {"interrupt",           db_interrupt            },
1993static const luaL_Reg dblib[] = {
1994   {"isopen",              db_isopen               },
1995   {"last_insert_rowid",   db_last_insert_rowid    },
1996   {"changes",             db_changes              },
1997   {"total_changes",       db_total_changes        },
1998   {"errcode",             db_errcode              },
1999   {"error_code",          db_errcode              },
2000   {"errmsg",              db_errmsg               },
2001   {"error_message",       db_errmsg               },
2002   {"interrupt",           db_interrupt            },
17412003
1742    {"create_function",     db_create_function      },
1743    {"create_aggregate",    db_create_aggregate     },
1744    {"create_collation",    db_create_collation     },
2004   {"create_function",     db_create_function      },
2005   {"create_aggregate",    db_create_aggregate     },
2006   {"create_collation",    db_create_collation     },
17452007
1746    {"trace",               db_trace                },
1747    {"progress_handler",    db_progress_handler     },
1748    {"busy_timeout",        db_busy_timeout         },
1749    {"busy_handler",        db_busy_handler         },
2008   {"trace",               db_trace                },
2009   {"progress_handler",    db_progress_handler     },
2010   {"busy_timeout",        db_busy_timeout         },
2011   {"busy_handler",        db_busy_handler         },
2012#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
2013   {"update_hook",         db_update_hook          },
2014   {"commit_hook",         db_commit_hook          },
2015   {"rollback_hook",       db_rollback_hook        },
2016#endif
17502017
1751    {"prepare",             db_prepare              },
1752    {"rows",                db_rows                 },
1753    {"urows",               db_urows                },
1754    {"nrows",               db_nrows                },
2018   {"prepare",             db_prepare              },
2019   {"rows",                db_rows                 },
2020   {"urows",               db_urows                },
2021   {"nrows",               db_nrows                },
17552022
1756    {"exec",                db_exec                 },
1757    {"execute",             db_exec                 },
1758    {"close",               db_close                },
1759    {"close_vm",            db_close_vm             },
2023   {"exec",                db_exec                 },
2024   {"execute",             db_exec                 },
2025   {"close",               db_close                },
2026   {"close_vm",            db_close_vm             },
17602027
1761    {"__tostring",          db_tostring             },
1762    {"__gc",                db_gc                   },
2028   {"__tostring",          db_tostring             },
2029   {"__gc",                db_gc                   },
17632030
1764    {NULL, NULL}
2031   {NULL, NULL}
17652032};
17662033
1767static const luaL_reg vmlib[] = {
1768    {"isopen",              dbvm_isopen             },
2034static const luaL_Reg vmlib[] = {
2035   {"isopen",              dbvm_isopen             },
17692036
1770    {"step",                dbvm_step               },
1771    {"reset",               dbvm_reset              },
1772    {"finalize",            dbvm_finalize           },
2037   {"step",                dbvm_step               },
2038   {"reset",               dbvm_reset              },
2039   {"finalize",            dbvm_finalize           },
17732040
1774    {"columns",             dbvm_columns            },
2041   {"columns",             dbvm_columns            },
17752042
1776    {"bind",                dbvm_bind               },
1777    {"bind_values",         dbvm_bind_values        },
1778    {"bind_names",          dbvm_bind_names         },
1779    {"bind_blob",           dbvm_bind_blob          },
1780    {"bind_parameter_count",dbvm_bind_parameter_count},
1781    {"bind_parameter_name", dbvm_bind_parameter_name},
2043   {"bind",                dbvm_bind               },
2044   {"bind_values",         dbvm_bind_values        },
2045   {"bind_names",          dbvm_bind_names         },
2046   {"bind_blob",           dbvm_bind_blob          },
2047   {"bind_parameter_count",dbvm_bind_parameter_count},
2048   {"bind_parameter_name", dbvm_bind_parameter_name},
17822049
1783    {"get_value",           dbvm_get_value          },
1784    {"get_values",          dbvm_get_values         },
1785    {"get_name",            dbvm_get_name           },
1786    {"get_names",           dbvm_get_names          },
1787    {"get_type",            dbvm_get_type           },
1788    {"get_types",           dbvm_get_types          },
1789    {"get_uvalues",         dbvm_get_uvalues        },
1790    {"get_unames",          dbvm_get_unames         },
1791    {"get_utypes",          dbvm_get_utypes         },
2050   {"get_value",           dbvm_get_value          },
2051   {"get_values",          dbvm_get_values         },
2052   {"get_name",            dbvm_get_name           },
2053   {"get_names",           dbvm_get_names          },
2054   {"get_type",            dbvm_get_type           },
2055   {"get_types",           dbvm_get_types          },
2056   {"get_uvalues",         dbvm_get_uvalues        },
2057   {"get_unames",          dbvm_get_unames         },
2058   {"get_utypes",          dbvm_get_utypes         },
17922059
1793    {"get_named_values",    dbvm_get_named_values   },
1794    {"get_named_types",     dbvm_get_named_types    },
2060   {"get_named_values",    dbvm_get_named_values   },
2061   {"get_named_types",     dbvm_get_named_types    },
17952062
1796    {"rows",                dbvm_rows               },
1797    {"urows",               dbvm_urows              },
1798    {"nrows",               dbvm_nrows              },
2063   {"rows",                dbvm_rows               },
2064   {"urows",               dbvm_urows              },
2065   {"nrows",               dbvm_nrows              },
17992066
1800    /* compatibility names (added by request) */
1801    {"idata",               dbvm_get_values         },
1802    {"inames",              dbvm_get_names          },
1803    {"itypes",              dbvm_get_types          },
1804    {"data",                dbvm_get_named_values   },
1805    {"type",                dbvm_get_named_types    },
2067   /* compatibility names (added by request) */
2068   {"idata",               dbvm_get_values         },
2069   {"inames",              dbvm_get_names          },
2070   {"itypes",              dbvm_get_types          },
2071   {"data",                dbvm_get_named_values   },
2072   {"type",                dbvm_get_named_types    },
18062073
1807    {"__tostring",          dbvm_tostring           },
1808    {"__gc",                dbvm_gc                 },
2074   {"__tostring",          dbvm_tostring           },
2075   {"__gc",                dbvm_gc                 },
18092076
1810    { NULL, NULL }
2077   { NULL, NULL }
18112078};
18122079
1813static const luaL_reg ctxlib[] = {
1814    {"user_data",               lcontext_user_data              },
2080static const luaL_Reg ctxlib[] = {
2081   {"user_data",               lcontext_user_data              },
18152082
1816    {"get_aggregate_data",      lcontext_get_aggregate_context  },
1817    {"set_aggregate_data",      lcontext_set_aggregate_context  },
1818    {"aggregate_count",         lcontext_aggregate_count        },
2083   {"get_aggregate_data",      lcontext_get_aggregate_context  },
2084   {"set_aggregate_data",      lcontext_set_aggregate_context  },
2085   {"aggregate_count",         lcontext_aggregate_count        },
18192086
1820    {"result",                  lcontext_result                 },
1821    {"result_null",             lcontext_result_null            },
1822    {"result_number",           lcontext_result_double          },
1823    {"result_double",           lcontext_result_double          },
1824    {"result_int",              lcontext_result_int             },
1825    {"result_text",             lcontext_result_text            },
1826    {"result_blob",             lcontext_result_blob            },
1827    {"result_error",            lcontext_result_error           },
2087   {"result",                  lcontext_result                 },
2088   {"result_null",             lcontext_result_null            },
2089   {"result_number",           lcontext_result_double          },
2090   {"result_double",           lcontext_result_double          },
2091   {"result_int",              lcontext_result_int             },
2092   {"result_text",             lcontext_result_text            },
2093   {"result_blob",             lcontext_result_blob            },
2094   {"result_error",            lcontext_result_error           },
18282095
1829    {"__tostring",              lcontext_tostring               },
1830    {NULL, NULL}
2096   {"__tostring",              lcontext_tostring               },
2097   {NULL, NULL}
18312098};
18322099
1833static const luaL_reg sqlitelib[] = {
1834    {"version",         lsqlite_version         },
1835    {"complete",        lsqlite_complete        },
2100static const luaL_Reg sqlitelib[] = {
2101   {"version",         lsqlite_version         },
2102   {"complete",        lsqlite_complete        },
18362103#ifndef WIN32
1837    {"temp_directory",  lsqlite_temp_directory  },
2104   {"temp_directory",  lsqlite_temp_directory  },
18382105#endif
1839    {"open",            lsqlite_open            },
1840    {"open_memory",     lsqlite_open_memory     },
2106   {"open",            lsqlite_open            },
2107   {"open_memory",     lsqlite_open_memory     },
18412108
1842    {"__newindex",      lsqlite_newindex        },
1843    {NULL, NULL}
2109   {"__newindex",      lsqlite_newindex        },
2110   {NULL, NULL}
18442111};
18452112
1846static void create_meta(lua_State *L, const char *name, const luaL_reg *lib) {
1847    luaL_newmetatable(L, name);
1848    lua_pushstring(L, "__index");
1849    lua_pushvalue(L, -2);               /* push metatable */
1850    lua_rawset(L, -3);                  /* metatable.__index = metatable */
2113static void create_meta(lua_State *L, const char *name, const luaL_Reg *lib) {
2114   luaL_newmetatable(L, name);
2115   lua_pushstring(L, "__index");
2116   lua_pushvalue(L, -2);               /* push metatable */
2117   lua_rawset(L, -3);                  /* metatable.__index = metatable */
18512118
1852    /* register metatable functions */
1853    luaL_openlib(L, NULL, lib, 0);
2119   /* register metatable functions */
2120   luaL_openlib(L, NULL, lib, 0);
18542121
1855    /* remove metatable from stack */
1856    lua_pop(L, 1);
2122   /* remove metatable from stack */
2123   lua_pop(L, 1);
18572124}
18582125
2126static int luaopen_sqlite3 ( lua_State * L )
2127{
2128   luaL_newlib(L, sqlitelib);
2129   return 1;
2130}
2131
18592132LUALIB_API int luaopen_lsqlite3(lua_State *L) {
1860    create_meta(L, sqlite_meta, dblib);
1861    create_meta(L, sqlite_vm_meta, vmlib);
1862    create_meta(L, sqlite_ctx_meta, ctxlib);
2133   create_meta(L, sqlite_meta, dblib);
2134   create_meta(L, sqlite_vm_meta, vmlib);
2135   create_meta(L, sqlite_ctx_meta, ctxlib);
18632136
1864    luaL_getmetatable(L, sqlite_ctx_meta);
1865    sqlite_ctx_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX);
2137   luaL_getmetatable(L, sqlite_ctx_meta);
2138   sqlite_ctx_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX);
2139   /* register (local) sqlite metatable */
2140   //luaL_register(L, "sqlite3", sqlitelib);
2141   luaL_requiref(L, "sqlite3", luaopen_sqlite3, 1);
2142   {
2143      int i = 0;
2144      /* add constants to global table */
2145      while (sqlite_constants[i].name) {
2146         lua_pushstring(L, sqlite_constants[i].name);
2147         lua_pushnumber(L, sqlite_constants[i].value);
2148         lua_rawset(L, -3);
2149         ++i;
2150      }
2151   }
2152   /* set sqlite's metatable to itself - set as readonly (__newindex) */
2153   lua_pushvalue(L, -1);
2154   lua_setmetatable(L, -2);
18662155
1867    /* register (local) sqlite metatable */
1868    luaL_register(L, "sqlite3", sqlitelib);
1869
1870    {
1871        int i = 0;
1872        /* add constants to global table */
1873        while (sqlite_constants[i].name) {
1874            lua_pushstring(L, sqlite_constants[i].name);
1875            lua_pushnumber(L, sqlite_constants[i].value);
1876            lua_rawset(L, -3);
1877            ++i;
1878        }
1879    }
1880
1881    /* set sqlite's metatable to itself - set as readonly (__newindex) */
1882    lua_pushvalue(L, -1);
1883    lua_setmetatable(L, -2);
1884
1885    return 1;
2156   return 1;
18862157}
trunk/src/emu/luaengine.c
r242834r242835
1010
1111#include <limits>
1212#include "lua/lua.hpp"
13#include "lua/lib/lualibs.h"
1413#include "luabridge/Source/LuaBridge/LuaBridge.h"
1514#include <signal.h>
1615#include "emu.h"
r242834r242835
4544const char *const lua_engine::tname_ioport = "lua.ioport";
4645lua_engine* lua_engine::luaThis = NULL;
4746
47extern "C" {
48   int luaopen_lsqlite3(lua_State *L);
49}
4850
4951static void lstop(lua_State *L, lua_Debug *ar)
5052{
trunk/src/emu/luaengine.h
r242834r242835
2525#endif
2626
2727#include "lua/lua.hpp"
28#include "lua/lib/lualibs.h"
2928#include "luabridge/Source/LuaBridge/LuaBridge.h"
3029
3130struct lua_State;
trunk/src/lib/lib.mak
r242834r242835
2424   $(LIBOBJ)/lib7z \
2525   $(LIBOBJ)/portmidi \
2626   $(LIBOBJ)/lua \
27   $(LIBOBJ)/lua/lib \
27   $(LIBOBJ)/lua/lsqlite3 \
2828   $(LIBOBJ)/mongoose \
2929   $(LIBOBJ)/jsoncpp \
3030   $(LIBOBJ)/sqlite3 \


Previous 199869 Revisions Next


© 1997-2024 The MAME Team