lsqlite3.c 70 KB

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