dbase.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. /*
  2. * $Id$
  3. *
  4. * SQlite module core functions
  5. *
  6. * Copyright (C) 2010 Timo Teräs
  7. *
  8. * This file is part of Kamailio, a free SIP server.
  9. *
  10. * Kamailio is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 2 of the License, or
  13. * (at your option) any later version
  14. *
  15. * Kamailio is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. */
  24. #include "../../mem/mem.h"
  25. #include "../../dprint.h"
  26. #include "../../lib/srdb1/db_pool.h"
  27. #include "../../lib/srdb1/db_ut.h"
  28. #include "../../lib/srdb1/db_res.h"
  29. #include "../../lib/srdb1/db_query.h"
  30. #include "dbase.h"
  31. static time_t sqlite_to_timet(double rT)
  32. {
  33. return 86400.0*(rT - 2440587.5) + 0.5;
  34. }
  35. static double timet_to_sqlite(time_t t)
  36. {
  37. return ((((double) t) - 0.5) / 86400.0) + 2440587.5;
  38. }
  39. /*
  40. * Initialize database module
  41. * No function should be called before this
  42. */
  43. static struct sqlite_connection * db_sqlite_new_connection(const struct db_id* id)
  44. {
  45. struct sqlite_connection *con;
  46. int rc;
  47. con = pkg_malloc(sizeof(*con));
  48. if (!con) {
  49. LM_ERR("failed to allocate driver connection\n");
  50. return NULL;
  51. }
  52. memset(con, 0, sizeof(*con));
  53. con->hdr.ref = 1;
  54. con->hdr.id = (struct db_id*) id; /* set here - freed on error */
  55. rc = sqlite3_open_v2(id->database, &con->conn,
  56. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
  57. if (rc != SQLITE_OK) {
  58. pkg_free(con);
  59. LM_ERR("failed to open sqlite database '%s'\n", id->database);
  60. return NULL;
  61. }
  62. return con;
  63. }
  64. db1_con_t* db_sqlite_init(const str* _url)
  65. {
  66. return db_do_init(_url, (void *) db_sqlite_new_connection);
  67. }
  68. /*
  69. * Shut down database module
  70. * No function should be called after this
  71. */
  72. static void db_sqlite_free_connection(struct sqlite_connection* con)
  73. {
  74. if (!con) return;
  75. sqlite3_close(con->conn);
  76. free_db_id(con->hdr.id);
  77. pkg_free(con);
  78. }
  79. void db_sqlite_close(db1_con_t* _h)
  80. {
  81. db_do_close(_h, db_sqlite_free_connection);
  82. }
  83. /*
  84. * Release a result set from memory
  85. */
  86. int db_sqlite_free_result(db1_con_t* _h, db1_res_t* _r)
  87. {
  88. if (!_h || !_r) {
  89. LM_ERR("invalid parameter value\n");
  90. return -1;
  91. }
  92. if (db_free_result(_r) < 0)
  93. {
  94. LM_ERR("failed to free result structure\n");
  95. return -1;
  96. }
  97. return 0;
  98. }
  99. /*
  100. * Store name of table that will be used by
  101. * subsequent database functions
  102. */
  103. int db_sqlite_use_table(db1_con_t* _h, const str* _t)
  104. {
  105. return db_use_table(_h, _t);
  106. }
  107. /*
  108. * Reset query context
  109. */
  110. static void db_sqlite_cleanup_query(const db1_con_t* _c)
  111. {
  112. struct sqlite_connection *conn = CON_SQLITE(_c);
  113. int rc;
  114. if (conn->stmt != NULL) {
  115. rc = sqlite3_finalize(conn->stmt);
  116. if (rc != SQLITE_OK)
  117. LM_ERR("finalize failed: %s\n",
  118. sqlite3_errmsg(conn->conn));
  119. }
  120. conn->stmt = NULL;
  121. conn->bindpos = 0;
  122. }
  123. /*
  124. * Convert value to sql-string as db bind index
  125. */
  126. static int db_sqlite_val2str(const db1_con_t* _c, const db_val_t* _v, char* _s, int* _len)
  127. {
  128. struct sqlite_connection *conn;
  129. int ret;
  130. if (!_c || !_v || !_s || !_len || *_len <= 0) {
  131. LM_ERR("invalid parameter value\n");
  132. return -1;
  133. }
  134. conn = CON_SQLITE(_c);
  135. if (conn->bindpos >= DB_SQLITE_MAX_BINDS) {
  136. LM_ERR("too many bindings, recompile with larger DB_SQLITE_MAX_BINDS\n");
  137. return -2;
  138. }
  139. conn->bindarg[conn->bindpos] = _v;
  140. ret = snprintf(_s, *_len, "?%u", ++conn->bindpos);
  141. if ((unsigned)ret >= (unsigned) *_len)
  142. return -11;
  143. *_len = ret;
  144. return 0;
  145. }
  146. /*
  147. * Send an SQL query to the server
  148. */
  149. static int db_sqlite_submit_query(const db1_con_t* _h, const str* _s)
  150. {
  151. struct sqlite_connection *conn = CON_SQLITE(_h);
  152. sqlite3_stmt *stmt;
  153. const db_val_t *val;
  154. int rc, i;
  155. LM_DBG("submit_query: %.*s\n", _s->len, _s->s);
  156. rc = sqlite3_prepare_v2(conn->conn, _s->s, _s->len, &stmt, NULL);
  157. if (rc != SQLITE_OK) {
  158. LM_ERR("failed to prepare statement: %s\n",
  159. sqlite3_errmsg(conn->conn));
  160. return -1;
  161. }
  162. conn->stmt = stmt;
  163. for (i = 1; i <= conn->bindpos; i++) {
  164. val = conn->bindarg[i-1];
  165. if (VAL_NULL(val)) {
  166. rc = sqlite3_bind_null(stmt, i);
  167. } else switch (VAL_TYPE(val)) {
  168. case DB1_INT:
  169. rc = sqlite3_bind_int(stmt, i, VAL_INT(val));
  170. break;
  171. case DB1_BIGINT:
  172. rc = sqlite3_bind_int64(stmt, i, VAL_BIGINT(val));
  173. break;
  174. case DB1_DOUBLE:
  175. rc = sqlite3_bind_double(stmt, i, VAL_DOUBLE(val));
  176. break;
  177. case DB1_STRING:
  178. rc = sqlite3_bind_text(stmt, i,
  179. VAL_STRING(val), -1, NULL);
  180. break;
  181. case DB1_STR:
  182. rc = sqlite3_bind_text(stmt, i,
  183. VAL_STR(val).s, VAL_STR(val).len, NULL);
  184. break;
  185. case DB1_DATETIME:
  186. rc = sqlite3_bind_double(stmt, i, timet_to_sqlite(VAL_TIME(val)));
  187. break;
  188. case DB1_BLOB:
  189. rc = sqlite3_bind_blob(stmt, i,
  190. VAL_BLOB(val).s, VAL_BLOB(val).len,
  191. NULL);
  192. break;
  193. case DB1_BITMAP:
  194. rc = sqlite3_bind_int(stmt, i, VAL_BITMAP(val));
  195. break;
  196. default:
  197. LM_ERR("unknown bind value type %d\n", VAL_TYPE(val));
  198. return -1;
  199. }
  200. if (rc != SQLITE_OK) {
  201. LM_ERR("Parameter bind failed: %s\n",
  202. sqlite3_errmsg(conn->conn));
  203. return -1;
  204. }
  205. }
  206. return 0;
  207. }
  208. #define H3(a,b,c) ((a<<16) + (b<<8) + c)
  209. #define H4(a,b,c,d) ((a<<24) + (b<<16) + (c<<8) + d)
  210. static int decltype_to_dbtype(const char *decltype)
  211. {
  212. /* SQlite3 has dynamic typing. It does not store the actual
  213. * exact type, instead it uses 'affinity' depending on the
  214. * value. We have to go through the declaration type to see
  215. * what to return.
  216. * The loose string matching (4 letter substring match) is what
  217. * SQlite does internally, but our return values differ as we want
  218. * the more exact srdb type instead of the affinity. */
  219. uint32_t h = 0;
  220. for (; *decltype; decltype++) {
  221. h <<= 8;
  222. h += toupper(*decltype);
  223. switch (h & 0x00ffffff) {
  224. case H3('I','N','T'):
  225. return DB1_INT;
  226. }
  227. switch (h) {
  228. case H4('S','E','R','I'): /* SERIAL */
  229. return DB1_INT;
  230. case H4('B','I','G','I'): /* BIGINT */
  231. return DB1_BIGINT;
  232. case H4('C','H','A','R'):
  233. case H4('C','L','O','B'):
  234. return DB1_STRING;
  235. case H4('T','E','X','T'):
  236. return DB1_STR;
  237. case H4('R','E','A','L'):
  238. case H4('F','L','O','A'): /* FLOAT */
  239. case H4('D','O','U','B'): /* DOUBLE */
  240. return DB1_DOUBLE;
  241. case H4('B','L','O','B'):
  242. return DB1_BLOB;
  243. case H4('T','I','M','E'):
  244. case H4('D','A','T','E'):
  245. return DB1_DATETIME;
  246. }
  247. }
  248. LM_ERR("sqlite decltype '%s' not recognized, defaulting to int",
  249. decltype);
  250. return DB1_INT;
  251. }
  252. static int type_to_dbtype(int type)
  253. {
  254. switch (type) {
  255. case SQLITE_INTEGER:
  256. return DB1_INT;
  257. case SQLITE_FLOAT:
  258. return DB1_DOUBLE;
  259. case SQLITE_TEXT:
  260. return DB1_STR;
  261. case SQLITE_BLOB:
  262. return DB1_BLOB;
  263. default:
  264. /* Unknown, or NULL column value. Assume this is a
  265. * string. */
  266. return DB1_STR;
  267. }
  268. }
  269. static str* str_dup(const char *_s)
  270. {
  271. str *s;
  272. int len = strlen(_s);
  273. s = (str*) pkg_malloc(sizeof(str)+len+1);
  274. if (!s)
  275. return NULL;
  276. s->len = len;
  277. s->s = ((char*)s) + sizeof(str);
  278. memcpy(s->s, _s, len);
  279. s->s[len] = '\0';
  280. return s;
  281. }
  282. static void str_assign(str* s, const char *_s, int len)
  283. {
  284. s->s = (char *) pkg_malloc(len + 1);
  285. if (s->s) {
  286. s->len = len;
  287. memcpy(s->s, _s, len);
  288. s->s[len] = 0;
  289. }
  290. }
  291. /*
  292. * Read database answer and fill the structure
  293. */
  294. int db_sqlite_store_result(const db1_con_t* _h, db1_res_t** _r)
  295. {
  296. struct sqlite_connection *conn = CON_SQLITE(_h);
  297. db1_res_t *res;
  298. int i, rc, num_rows = 0, num_alloc = 0;
  299. db_row_t *rows = NULL, *row;
  300. db_val_t *val;
  301. res = db_new_result();
  302. if (res == NULL)
  303. goto no_mem;
  304. while (1) {
  305. rc = sqlite3_step(conn->stmt);
  306. if (rc == SQLITE_DONE) {
  307. *_r = res;
  308. return 0;
  309. }
  310. if (rc != SQLITE_ROW) {
  311. LM_INFO("sqlite3_step failed: %s\n", sqlite3_errmsg(conn->conn));
  312. goto err;
  313. }
  314. if (num_rows == 0) {
  315. /* get column types */
  316. rc = sqlite3_column_count(conn->stmt);
  317. if (db_allocate_columns(res, rc) != 0)
  318. goto err;
  319. RES_COL_N(res) = rc;
  320. for (i = 0; i < RES_COL_N(res); i++) {
  321. const char *decltype;
  322. int dbtype;
  323. RES_NAMES(res)[i] = str_dup(sqlite3_column_name(conn->stmt, i));
  324. if (RES_NAMES(res)[i] == NULL)
  325. goto no_mem;
  326. decltype = sqlite3_column_decltype(conn->stmt, i);
  327. if (decltype != NULL)
  328. dbtype = decltype_to_dbtype(decltype);
  329. else
  330. dbtype = type_to_dbtype(sqlite3_column_type(conn->stmt, i));
  331. RES_TYPES(res)[i] = dbtype;
  332. }
  333. }
  334. if (num_rows >= num_alloc) {
  335. if (num_alloc)
  336. num_alloc *= 2;
  337. else
  338. num_alloc = 8;
  339. rows = pkg_realloc(rows, sizeof(db_row_t) * num_alloc);
  340. if (rows == NULL)
  341. goto no_mem;
  342. RES_ROWS(res) = rows;
  343. }
  344. row = &RES_ROWS(res)[num_rows];
  345. num_rows++;
  346. RES_ROW_N(res) = num_rows; /* rows in this result set */
  347. RES_NUM_ROWS(res) = num_rows; /* rows in total */
  348. if (db_allocate_row(res, row) != 0)
  349. goto no_mem;
  350. for (i = 0, val = ROW_VALUES(row); i < RES_COL_N(res); i++, val++) {
  351. VAL_TYPE(val) = RES_TYPES(res)[i];
  352. VAL_NULL(val) = 0;
  353. VAL_FREE(val) = 0;
  354. if (sqlite3_column_type(conn->stmt, i) == SQLITE_NULL) {
  355. VAL_NULL(val) = 1;
  356. } else switch (VAL_TYPE(val)) {
  357. case DB1_INT:
  358. VAL_INT(val) = sqlite3_column_int(conn->stmt, i);
  359. break;
  360. case DB1_BIGINT:
  361. VAL_BIGINT(val) = sqlite3_column_int64(conn->stmt, i);
  362. break;
  363. case DB1_STRING:
  364. /* first field of struct str* is the char* so we can just
  365. * do whatever DB1_STR case does */
  366. case DB1_STR:
  367. str_assign(&VAL_STR(val),
  368. (const char*) sqlite3_column_text(conn->stmt, i),
  369. sqlite3_column_bytes(conn->stmt, i));
  370. if (!VAL_STR(val).s)
  371. goto no_mem;
  372. VAL_FREE(val) = 1;
  373. break;
  374. case DB1_DOUBLE:
  375. VAL_DOUBLE(val) = sqlite3_column_double(conn->stmt, i);
  376. break;
  377. case DB1_DATETIME:
  378. VAL_TIME(val) = sqlite_to_timet(sqlite3_column_double(conn->stmt, i));
  379. break;
  380. case DB1_BLOB:
  381. str_assign(&VAL_BLOB(val),
  382. (const char*) sqlite3_column_blob(conn->stmt, i),
  383. sqlite3_column_bytes(conn->stmt, i));
  384. if (!VAL_STR(val).s)
  385. goto no_mem;
  386. VAL_FREE(val) = 1;
  387. break;
  388. default:
  389. LM_ERR("unhandled db-type\n");
  390. goto err;
  391. }
  392. }
  393. }
  394. no_mem:
  395. LM_ERR("no private memory left\n");
  396. err:
  397. if (res)
  398. db_free_result(res);
  399. return -1;
  400. }
  401. /*
  402. * Query table for specified rows
  403. * _h: structure representing database connection
  404. * _k: key names
  405. * _op: operators
  406. * _v: values of the keys that must match
  407. * _c: column names to return
  408. * _n: number of key=values pairs to compare
  409. * _nc: number of columns to return
  410. * _o: order by the specified column
  411. */
  412. int db_sqlite_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  413. const db_val_t* _v, const db_key_t* _c, int _n, int _nc,
  414. const db_key_t _o, db1_res_t** _r)
  415. {
  416. int rc;
  417. rc = db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r,
  418. db_sqlite_val2str,
  419. db_sqlite_submit_query,
  420. db_sqlite_store_result);
  421. db_sqlite_cleanup_query(_h);
  422. return rc;
  423. }
  424. static int db_sqlite_commit(const db1_con_t* _h)
  425. {
  426. struct sqlite_connection *conn = CON_SQLITE(_h);
  427. int rc;
  428. rc = sqlite3_step(conn->stmt);
  429. if (rc != SQLITE_DONE && rc != SQLITE_OK) {
  430. LM_ERR("sqlite commit failed: %s\n",
  431. sqlite3_errmsg(conn->conn));
  432. return -1;
  433. }
  434. return 0;
  435. }
  436. /*
  437. * Insert a row into specified table
  438. * _h: structure representing database connection
  439. * _k: key names
  440. * _v: values of the keys
  441. * _n: number of key=value pairs
  442. */
  443. int db_sqlite_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  444. int _n)
  445. {
  446. int rc = -1;
  447. rc = db_do_insert(_h, _k, _v, _n,
  448. db_sqlite_val2str,
  449. db_sqlite_submit_query);
  450. if (rc == 0)
  451. rc = db_sqlite_commit(_h);
  452. db_sqlite_cleanup_query(_h);
  453. return rc;
  454. }
  455. /*
  456. * Delete a row from the specified table
  457. * _h: structure representing database connection
  458. * _k: key names
  459. * _o: operators
  460. * _v: values of the keys that must match
  461. * _n: number of key=value pairs
  462. */
  463. int db_sqlite_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  464. const db_val_t* _v, int _n)
  465. {
  466. int rc;
  467. rc = db_do_delete(_h, _k, _o, _v, _n,
  468. db_sqlite_val2str,
  469. db_sqlite_submit_query);
  470. if (rc == 0)
  471. rc = db_sqlite_commit(_h);
  472. db_sqlite_cleanup_query(_h);
  473. return rc;
  474. }
  475. /*
  476. * Update some rows in the specified table
  477. * _h: structure representing database connection
  478. * _k: key names
  479. * _o: operators
  480. * _v: values of the keys that must match
  481. * _uk: updated columns
  482. * _uv: updated values of the columns
  483. * _n: number of key=value pairs
  484. * _un: number of columns to update
  485. */
  486. int db_sqlite_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  487. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv,
  488. int _n, int _un)
  489. {
  490. int rc;
  491. rc = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un,
  492. db_sqlite_val2str,
  493. db_sqlite_submit_query);
  494. if (rc == 0)
  495. rc = db_sqlite_commit(_h);
  496. db_sqlite_cleanup_query(_h);
  497. return rc;
  498. }
  499. int db_sqlite_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  500. {
  501. int rc;
  502. rc = db_do_raw_query(_h, _s, _r,
  503. db_sqlite_submit_query,
  504. db_sqlite_store_result);
  505. db_sqlite_cleanup_query(_h);
  506. return rc;
  507. }