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