lsqlite3.c 70 KB

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