You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lua_sqlite3.c 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /*
  2. * Copyright 2024 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "lua_common.h"
  17. #include "sqlite_utils.h"
  18. /***
  19. * @module rspamd_sqlite3
  20. * This module provides routines to query sqlite3 databases
  21. @example
  22. local sqlite3 = require "rspamd_sqlite3"
  23. local db = sqlite3.open("/tmp/db.sqlite")
  24. if db then
  25. db:exec([[ CREATE TABLE x (id INT, value TEXT); ]])
  26. db:exec([[ INSERT INTO x VALUES (?1, ?2); ]], 1, 'test')
  27. for row in db:rows([[ SELECT * FROM x ]]) do
  28. print(string.format('%d -> %s', row.id, row.value))
  29. end
  30. end
  31. */
  32. LUA_FUNCTION_DEF(sqlite3, open);
  33. LUA_FUNCTION_DEF(sqlite3, sql);
  34. LUA_FUNCTION_DEF(sqlite3, rows);
  35. LUA_FUNCTION_DEF(sqlite3, close);
  36. LUA_FUNCTION_DEF(sqlite3_stmt, close);
  37. static const struct luaL_reg sqlitelib_f[] = {
  38. LUA_INTERFACE_DEF(sqlite3, open),
  39. {NULL, NULL}};
  40. static const struct luaL_reg sqlitelib_m[] = {
  41. LUA_INTERFACE_DEF(sqlite3, sql),
  42. {"query", lua_sqlite3_sql},
  43. {"exec", lua_sqlite3_sql},
  44. LUA_INTERFACE_DEF(sqlite3, rows),
  45. {"__tostring", rspamd_lua_class_tostring},
  46. {"__gc", lua_sqlite3_close},
  47. {NULL, NULL}};
  48. static const struct luaL_reg sqlitestmtlib_m[] = {
  49. {"__tostring", rspamd_lua_class_tostring},
  50. {"__gc", lua_sqlite3_stmt_close},
  51. {NULL, NULL}};
  52. static void lua_sqlite3_push_row(lua_State *L, sqlite3_stmt *stmt);
  53. static sqlite3 *
  54. lua_check_sqlite3(lua_State *L, int pos)
  55. {
  56. void *ud = rspamd_lua_check_udata(L, pos, rspamd_sqlite3_classname);
  57. luaL_argcheck(L, ud != NULL, pos, "'sqlite3' expected");
  58. return ud ? *((sqlite3 **) ud) : NULL;
  59. }
  60. static sqlite3_stmt *
  61. lua_check_sqlite3_stmt(lua_State *L, int pos)
  62. {
  63. void *ud = rspamd_lua_check_udata(L, pos, rspamd_sqlite3_stmt_classname);
  64. luaL_argcheck(L, ud != NULL, pos, "'sqlite3_stmt' expected");
  65. return ud ? *((sqlite3_stmt **) ud) : NULL;
  66. }
  67. /***
  68. * @function rspamd_sqlite3.open(path)
  69. * Opens sqlite3 database at the specified path. DB is created if not exists.
  70. * @param {string} path path to db
  71. * @return {sqlite3} sqlite3 handle
  72. */
  73. static int
  74. lua_sqlite3_open(lua_State *L)
  75. {
  76. const char *path = luaL_checkstring(L, 1);
  77. sqlite3 *db, **pdb;
  78. GError *err = NULL;
  79. if (path == NULL) {
  80. lua_pushnil(L);
  81. return 1;
  82. }
  83. db = rspamd_sqlite3_open_or_create(NULL, path, NULL, 0, &err);
  84. if (db == NULL) {
  85. if (err) {
  86. msg_err("cannot open db: %e", err);
  87. g_error_free(err);
  88. }
  89. lua_pushnil(L);
  90. return 1;
  91. }
  92. pdb = lua_newuserdata(L, sizeof(db));
  93. *pdb = db;
  94. rspamd_lua_setclass(L, rspamd_sqlite3_classname, -1);
  95. return 1;
  96. }
  97. static void
  98. lua_sqlite3_bind_statements(lua_State *L, int start, int end,
  99. sqlite3_stmt *stmt)
  100. {
  101. int i, type, num = 1;
  102. const char *str;
  103. gsize slen;
  104. double n;
  105. g_assert(start <= end && start > 0 && end > 0);
  106. for (i = start; i <= end; i++) {
  107. type = lua_type(L, i);
  108. switch (type) {
  109. case LUA_TNUMBER:
  110. n = lua_tonumber(L, i);
  111. if (n == (double) ((int64_t) n)) {
  112. sqlite3_bind_int64(stmt, num, n);
  113. }
  114. else {
  115. sqlite3_bind_double(stmt, num, n);
  116. }
  117. num++;
  118. break;
  119. case LUA_TSTRING:
  120. str = lua_tolstring(L, i, &slen);
  121. sqlite3_bind_text(stmt, num, str, slen, SQLITE_TRANSIENT);
  122. num++;
  123. break;
  124. default:
  125. msg_err("invalid type at position %d: %s", i, lua_typename(L, type));
  126. break;
  127. }
  128. }
  129. }
  130. /***
  131. * @function rspamd_sqlite3:sql(query[, args..])
  132. * Performs sqlite3 query replacing '?1', '?2' and so on with the subsequent args
  133. * of the function
  134. *
  135. * @param {string} query SQL query
  136. * @param {string|number} args... variable number of arguments
  137. * @return {boolean} `true` if a statement has been successfully executed
  138. */
  139. static int
  140. lua_sqlite3_sql(lua_State *L)
  141. {
  142. LUA_TRACE_POINT;
  143. sqlite3 *db = lua_check_sqlite3(L, 1);
  144. const char *query = luaL_checkstring(L, 2);
  145. sqlite3_stmt *stmt;
  146. gboolean ret = FALSE;
  147. int top = 1, rc;
  148. if (db && query) {
  149. if (sqlite3_prepare_v2(db, query, -1, &stmt, NULL) != SQLITE_OK) {
  150. msg_err("cannot prepare query %s: %s", query, sqlite3_errmsg(db));
  151. return luaL_error(L, sqlite3_errmsg(db));
  152. }
  153. else {
  154. top = lua_gettop(L);
  155. if (top > 2) {
  156. /* Push additional arguments to sqlite3 */
  157. lua_sqlite3_bind_statements(L, 3, top, stmt);
  158. }
  159. rc = sqlite3_step(stmt);
  160. top = 1;
  161. if (rc == SQLITE_ROW || rc == SQLITE_OK || rc == SQLITE_DONE) {
  162. ret = TRUE;
  163. if (rc == SQLITE_ROW) {
  164. lua_sqlite3_push_row(L, stmt);
  165. top = 2;
  166. }
  167. }
  168. else {
  169. msg_warn("sqlite3 error: %s", sqlite3_errmsg(db));
  170. }
  171. sqlite3_finalize(stmt);
  172. }
  173. }
  174. lua_pushboolean(L, ret);
  175. return top;
  176. }
  177. static void
  178. lua_sqlite3_push_row(lua_State *L, sqlite3_stmt *stmt)
  179. {
  180. const char *str;
  181. gsize slen;
  182. int64_t num;
  183. char numbuf[32];
  184. int nresults, i, type;
  185. nresults = sqlite3_column_count(stmt);
  186. lua_createtable(L, 0, nresults);
  187. for (i = 0; i < nresults; i++) {
  188. lua_pushstring(L, sqlite3_column_name(stmt, i));
  189. type = sqlite3_column_type(stmt, i);
  190. switch (type) {
  191. case SQLITE_INTEGER:
  192. /*
  193. * XXX: we represent int64 as strings, as we can nothing else to do
  194. * about it portably
  195. */
  196. num = sqlite3_column_int64(stmt, i);
  197. rspamd_snprintf(numbuf, sizeof(numbuf), "%uL", num);
  198. lua_pushstring(L, numbuf);
  199. break;
  200. case SQLITE_FLOAT:
  201. lua_pushnumber(L, sqlite3_column_double(stmt, i));
  202. break;
  203. case SQLITE_TEXT:
  204. slen = sqlite3_column_bytes(stmt, i);
  205. str = sqlite3_column_text(stmt, i);
  206. lua_pushlstring(L, str, slen);
  207. break;
  208. case SQLITE_BLOB:
  209. slen = sqlite3_column_bytes(stmt, i);
  210. str = sqlite3_column_blob(stmt, i);
  211. lua_pushlstring(L, str, slen);
  212. break;
  213. default:
  214. lua_pushboolean(L, 0);
  215. break;
  216. }
  217. lua_settable(L, -3);
  218. }
  219. }
  220. static int
  221. lua_sqlite3_next_row(lua_State *L)
  222. {
  223. LUA_TRACE_POINT;
  224. sqlite3_stmt *stmt = *(sqlite3_stmt **) lua_touserdata(L, lua_upvalueindex(1));
  225. int rc;
  226. if (stmt != NULL) {
  227. rc = sqlite3_step(stmt);
  228. if (rc == SQLITE_ROW) {
  229. lua_sqlite3_push_row(L, stmt);
  230. return 1;
  231. }
  232. }
  233. lua_pushnil(L);
  234. return 1;
  235. }
  236. /***
  237. * @function rspamd_sqlite3:rows(query[, args..])
  238. * Performs sqlite3 query replacing '?1', '?2' and so on with the subsequent args
  239. * of the function. This function returns iterator suitable for loop construction:
  240. *
  241. * @param {string} query SQL query
  242. * @param {string|number} args... variable number of arguments
  243. * @return {function} iterator to get all rows
  244. @example
  245. for row in db:rows([[ SELECT * FROM x ]]) do
  246. print(string.format('%d -> %s', row.id, row.value))
  247. end
  248. */
  249. static int
  250. lua_sqlite3_rows(lua_State *L)
  251. {
  252. LUA_TRACE_POINT;
  253. sqlite3 *db = lua_check_sqlite3(L, 1);
  254. const char *query = luaL_checkstring(L, 2);
  255. sqlite3_stmt *stmt, **pstmt;
  256. int top;
  257. if (db && query) {
  258. if (sqlite3_prepare_v2(db, query, -1, &stmt, NULL) != SQLITE_OK) {
  259. msg_err("cannot prepare query %s: %s", query, sqlite3_errmsg(db));
  260. lua_pushstring(L, sqlite3_errmsg(db));
  261. return lua_error(L);
  262. }
  263. else {
  264. top = lua_gettop(L);
  265. if (top > 2) {
  266. /* Push additional arguments to sqlite3 */
  267. lua_sqlite3_bind_statements(L, 3, top, stmt);
  268. }
  269. /* Create C closure */
  270. pstmt = lua_newuserdata(L, sizeof(stmt));
  271. *pstmt = stmt;
  272. rspamd_lua_setclass(L, rspamd_sqlite3_stmt_classname, -1);
  273. lua_pushcclosure(L, lua_sqlite3_next_row, 1);
  274. }
  275. }
  276. else {
  277. lua_pushnil(L);
  278. }
  279. return 1;
  280. }
  281. static int
  282. lua_sqlite3_close(lua_State *L)
  283. {
  284. LUA_TRACE_POINT;
  285. sqlite3 *db = lua_check_sqlite3(L, 1);
  286. if (db) {
  287. sqlite3_close(db);
  288. }
  289. return 0;
  290. }
  291. static int
  292. lua_sqlite3_stmt_close(lua_State *L)
  293. {
  294. sqlite3_stmt *stmt = lua_check_sqlite3_stmt(L, 1);
  295. if (stmt) {
  296. sqlite3_finalize(stmt);
  297. }
  298. return 0;
  299. }
  300. static int
  301. lua_load_sqlite3(lua_State *L)
  302. {
  303. lua_newtable(L);
  304. luaL_register(L, NULL, sqlitelib_f);
  305. return 1;
  306. }
  307. /**
  308. * Open redis library
  309. * @param L lua stack
  310. * @return
  311. */
  312. void luaopen_sqlite3(lua_State *L)
  313. {
  314. rspamd_lua_new_class(L, rspamd_sqlite3_classname, sqlitelib_m);
  315. lua_pop(L, 1);
  316. rspamd_lua_new_class(L, rspamd_sqlite3_stmt_classname, sqlitestmtlib_m);
  317. lua_pop(L, 1);
  318. rspamd_lua_add_preload(L, "rspamd_sqlite3", lua_load_sqlite3);
  319. }