lsqlite3.c 62 KB

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