km_dbase.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. /*
  2. * $Id$
  3. *
  4. * MySQL module core functions
  5. *
  6. * Copyright (C) 2001-2003 FhG Fokus
  7. * Copyright (C) 2007-2008 1&1 Internet AG
  8. *
  9. * This file is part of Kamailio, a free SIP server.
  10. *
  11. * Kamailio is free software; you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation; either version 2 of the License, or
  14. * (at your option) any later version
  15. *
  16. * Kamailio is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. */
  25. /*!
  26. * \file
  27. * \brief Implementation of core functions for the MySQL driver.
  28. *
  29. * This file contains the implementation of core functions for the MySQL
  30. * database driver, for example to submit a query or fetch a result.
  31. * \ingroup db_mysql
  32. * Module: \ref db_mysql
  33. */
  34. #include <stdio.h>
  35. #include <string.h>
  36. #include <mysql/mysql.h>
  37. #include <mysql/errmsg.h>
  38. #include <mysql/mysql_version.h>
  39. #include "../../mem/mem.h"
  40. #include "../../dprint.h"
  41. #include "../../async_task.h"
  42. #include "../../lib/srdb1/db_query.h"
  43. #include "../../lib/srdb1/db_ut.h"
  44. #include "mysql_mod.h"
  45. #include "km_val.h"
  46. #include "km_my_con.h"
  47. #include "km_res.h"
  48. #include "km_row.h"
  49. #include "km_db_mysql.h"
  50. #include "km_dbase.h"
  51. static char *mysql_sql_buf;
  52. /**
  53. * \brief Send a SQL query to the server.
  54. *
  55. * Send a SQL query to the database server. This methods tries to reconnect
  56. * to the server if the connection is gone and the auto_reconnect parameter is
  57. * enabled. It also issues a mysql_ping before the query to connect again after
  58. * a long waiting period because for some older mysql versions the auto reconnect
  59. * don't work sufficient. If auto_reconnect is enabled and the server supports it,
  60. * then the mysql_ping is probably not necessary, but its safer to do it in this
  61. * cases too.
  62. *
  63. * \param _h handle for the db
  64. * \param _s executed query
  65. * \return zero on success, negative value on failure
  66. */
  67. static int db_mysql_submit_query(const db1_con_t* _h, const str* _s)
  68. {
  69. time_t t;
  70. int i, code;
  71. if (!_h || !_s || !_s->s) {
  72. LM_ERR("invalid parameter value\n");
  73. return -1;
  74. }
  75. if (my_ping_interval) {
  76. t = time(0);
  77. if ((t - CON_TIMESTAMP(_h)) > my_ping_interval) {
  78. if (mysql_ping(CON_CONNECTION(_h))) {
  79. LM_WARN("driver error on ping: %s\n", mysql_error(CON_CONNECTION(_h)));
  80. counter_inc(mysql_cnts_h.driver_err);
  81. }
  82. }
  83. /*
  84. * We're doing later a query anyway that will reset the timout of the server,
  85. * so it makes sense to set the timestamp value to the actual time in order
  86. * to prevent unnecessary pings.
  87. */
  88. CON_TIMESTAMP(_h) = t;
  89. }
  90. /* screws up the terminal when the query contains a BLOB :-( (by bogdan)
  91. * LM_DBG("submit_query(): %.*s\n", _s->len, _s->s);
  92. */
  93. /* When a server connection is lost and a query is attempted, most of
  94. * the time the query will return a CR_SERVER_LOST, then at the second
  95. * attempt to execute it, the mysql lib will reconnect and succeed.
  96. * However is a few cases, the first attempt returns CR_SERVER_GONE_ERROR
  97. * the second CR_SERVER_LOST and only the third succeeds.
  98. * Thus the 3 in the loop count. Increasing the loop count over this
  99. * value shouldn't be needed, but it doesn't hurt either, since the loop
  100. * will most of the time stop at the second or sometimes at the third
  101. * iteration. In the case of CR_SERVER_GONE_ERROR and CR_SERVER_LOST the
  102. * driver error counter is increased
  103. */
  104. for (i=0; i < (db_mysql_auto_reconnect ? 3 : 1); i++) {
  105. if (mysql_real_query(CON_CONNECTION(_h), _s->s, _s->len) == 0) {
  106. return 0;
  107. }
  108. code = mysql_errno(CON_CONNECTION(_h));
  109. if (code != CR_SERVER_GONE_ERROR && code != CR_SERVER_LOST) {
  110. break;
  111. }
  112. counter_inc(mysql_cnts_h.driver_err);
  113. }
  114. LM_ERR("driver error on query: %s\n", mysql_error(CON_CONNECTION(_h)));
  115. return -2;
  116. }
  117. /**
  118. *
  119. */
  120. void db_mysql_async_exec_task(void *param)
  121. {
  122. str *p;
  123. db1_con_t* dbc;
  124. p = (str*)param;
  125. dbc = db_mysql_init(&p[0]);
  126. if(dbc==NULL) {
  127. LM_ERR("failed to open connection for [%.*s]\n", p[0].len, p[0].s);
  128. return;
  129. }
  130. if(db_mysql_submit_query(dbc, &p[1])<0) {
  131. LM_ERR("failed to execute query on async worker\n");
  132. }
  133. db_mysql_close(dbc);
  134. }
  135. /**
  136. * Execute a raw SQL query via core async framework.
  137. * \param _h handle for the database
  138. * \param _s raw query string
  139. * \return zero on success, negative value on failure
  140. */
  141. int db_mysql_submit_query_async(const db1_con_t* _h, const str* _s)
  142. {
  143. struct db_id* di;
  144. async_task_t *atask;
  145. int asize;
  146. str *p;
  147. di = ((struct pool_con*)_h->tail)->id;
  148. asize = sizeof(async_task_t) + 2*sizeof(str) + di->url.len + _s->len + 2;
  149. atask = shm_malloc(asize);
  150. if(atask==NULL) {
  151. LM_ERR("no more shared memory to allocate %d\n", asize);
  152. return -1;
  153. }
  154. atask->exec = db_mysql_async_exec_task;
  155. atask->param = (char*)atask + sizeof(async_task_t);
  156. p = (str*)((char*)atask + sizeof(async_task_t));
  157. p[0].s = (char*)p + 2*sizeof(str);
  158. p[0].len = di->url.len;
  159. strncpy(p[0].s, di->url.s, di->url.len);
  160. p[1].s = p[0].s + p[0].len + 1;
  161. p[1].len = _s->len;
  162. strncpy(p[1].s, _s->s, _s->len);
  163. async_task_push(atask);
  164. return 0;
  165. }
  166. /**
  167. * Initialize the database module.
  168. * No function should be called before this
  169. * \param _url URL used for initialization
  170. * \return zero on success, negative value on failure
  171. */
  172. db1_con_t* db_mysql_init(const str* _url)
  173. {
  174. return db_do_init(_url, (void *)db_mysql_new_connection);
  175. }
  176. /**
  177. * Shut down the database module.
  178. * No function should be called after this
  179. * \param _h handle to the closed connection
  180. * \return zero on success, negative value on failure
  181. */
  182. void db_mysql_close(db1_con_t* _h)
  183. {
  184. db_do_close(_h, db_mysql_free_connection);
  185. }
  186. /**
  187. * Retrieve a result set
  188. * \param _h handle to the database
  189. * \param _r result set that should be retrieved
  190. * \return zero on success, negative value on failure
  191. */
  192. static int db_mysql_store_result(const db1_con_t* _h, db1_res_t** _r)
  193. {
  194. int code;
  195. if ((!_h) || (!_r)) {
  196. LM_ERR("invalid parameter value\n");
  197. return -1;
  198. }
  199. *_r = db_mysql_new_result();
  200. if (*_r == 0) {
  201. LM_ERR("no memory left\n");
  202. return -2;
  203. }
  204. RES_RESULT(*_r) = mysql_store_result(CON_CONNECTION(_h));
  205. if (!RES_RESULT(*_r)) {
  206. if (mysql_field_count(CON_CONNECTION(_h)) == 0) {
  207. (*_r)->col.n = 0;
  208. (*_r)->n = 0;
  209. goto done;
  210. } else {
  211. LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
  212. code = mysql_errno(CON_CONNECTION(_h));
  213. if (code == CR_SERVER_GONE_ERROR || code == CR_SERVER_LOST) {
  214. counter_inc(mysql_cnts_h.driver_err);
  215. }
  216. db_mysql_free_result(_h, *_r);
  217. *_r = 0;
  218. return -3;
  219. }
  220. }
  221. if (db_mysql_convert_result(_h, *_r) < 0) {
  222. LM_ERR("error while converting result\n");
  223. LM_DBG("freeing result set at %p\n", _r);
  224. /* all mem on Kamailio API side is already freed by
  225. * db_mysql_convert_result in case of error, but we also need
  226. * to free the mem from the mysql lib side, internal pkg for it
  227. * and *_r */
  228. db_mysql_free_result(_h, *_r);
  229. *_r = 0;
  230. #if (MYSQL_VERSION_ID >= 40100)
  231. while( mysql_more_results(CON_CONNECTION(_h)) && mysql_next_result(CON_CONNECTION(_h)) == 0 ) {
  232. MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) );
  233. mysql_free_result(res);
  234. }
  235. #endif
  236. return -4;
  237. }
  238. done:
  239. #if (MYSQL_VERSION_ID >= 40100)
  240. while( mysql_more_results(CON_CONNECTION(_h)) && mysql_next_result(CON_CONNECTION(_h)) == 0 ) {
  241. MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) );
  242. mysql_free_result(res);
  243. }
  244. #endif
  245. return 0;
  246. }
  247. /**
  248. * Release a result set from memory.
  249. * \param _h handle to the database
  250. * \param _r result set that should be freed
  251. * \return zero on success, negative value on failure
  252. */
  253. int db_mysql_free_result(const db1_con_t* _h, db1_res_t* _r)
  254. {
  255. if ((!_h) || (!_r)) {
  256. LM_ERR("invalid parameter value\n");
  257. return -1;
  258. }
  259. mysql_free_result(RES_RESULT(_r));
  260. RES_RESULT(_r) = 0;
  261. pkg_free(RES_PTR(_r));
  262. if (db_free_result(_r) < 0) {
  263. LM_ERR("unable to free result structure\n");
  264. return -1;
  265. }
  266. return 0;
  267. }
  268. /**
  269. * Query a table for specified rows.
  270. * \param _h structure representing database connection
  271. * \param _k key names
  272. * \param _op operators
  273. *\param _v values of the keys that must match
  274. * \param _c column names to return
  275. * \param _n number of key=values pairs to compare
  276. * \param _nc number of columns to return
  277. * \param _o order by the specified column
  278. * \param _r pointer to a structure representing the result
  279. * \return zero on success, negative value on failure
  280. */
  281. int db_mysql_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  282. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  283. const db_key_t _o, db1_res_t** _r)
  284. {
  285. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r,
  286. db_mysql_val2str, db_mysql_submit_query, db_mysql_store_result);
  287. }
  288. /**
  289. * \brief Gets a partial result set, fetch rows from a result
  290. *
  291. * Gets a partial result set, fetch a number of rows from a database result.
  292. * This function initialize the given result structure on the first run, and
  293. * fetches the nrows number of rows. On subsequenting runs, it uses the
  294. * existing result and fetches more rows, until it reaches the end of the
  295. * result set. Because of this the result needs to be null in the first
  296. * invocation of the function. If the number of wanted rows is zero, the
  297. * function returns anything with a result of zero.
  298. * \param _h structure representing the database connection
  299. * \param _r pointer to a structure representing the result
  300. * \param nrows number of fetched rows
  301. * \return zero on success, negative value on failure
  302. */
  303. int db_mysql_fetch_result(const db1_con_t* _h, db1_res_t** _r, const int nrows)
  304. {
  305. int rows, i, code;
  306. if (!_h || !_r || nrows < 0) {
  307. LM_ERR("Invalid parameter value\n");
  308. return -1;
  309. }
  310. /* exit if the fetch count is zero */
  311. if (nrows == 0) {
  312. db_mysql_free_result(_h, *_r);
  313. *_r = 0;
  314. return 0;
  315. }
  316. if(*_r==0) {
  317. /* Allocate a new result structure */
  318. *_r = db_mysql_new_result();
  319. if (*_r == 0) {
  320. LM_ERR("no memory left\n");
  321. return -2;
  322. }
  323. RES_RESULT(*_r) = mysql_store_result(CON_CONNECTION(_h));
  324. if (!RES_RESULT(*_r)) {
  325. if (mysql_field_count(CON_CONNECTION(_h)) == 0) {
  326. (*_r)->col.n = 0;
  327. (*_r)->n = 0;
  328. return 0;
  329. } else {
  330. LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
  331. code = mysql_errno(CON_CONNECTION(_h));
  332. if (code == CR_SERVER_GONE_ERROR || code == CR_SERVER_LOST) {
  333. counter_inc(mysql_cnts_h.driver_err);
  334. }
  335. db_mysql_free_result(_h, *_r);
  336. *_r = 0;
  337. return -3;
  338. }
  339. }
  340. if (db_mysql_get_columns(_h, *_r) < 0) {
  341. LM_ERR("error while getting column names\n");
  342. return -4;
  343. }
  344. RES_NUM_ROWS(*_r) = mysql_num_rows(RES_RESULT(*_r));
  345. if (!RES_NUM_ROWS(*_r)) {
  346. LM_DBG("no rows returned from the query\n");
  347. RES_ROWS(*_r) = 0;
  348. return 0;
  349. }
  350. } else {
  351. /* free old rows */
  352. if(RES_ROWS(*_r)!=0)
  353. db_free_rows(*_r);
  354. RES_ROWS(*_r) = 0;
  355. RES_ROW_N(*_r) = 0;
  356. }
  357. /* determine the number of rows remaining to be processed */
  358. rows = RES_NUM_ROWS(*_r) - RES_LAST_ROW(*_r);
  359. /* If there aren't any more rows left to process, exit */
  360. if(rows<=0)
  361. return 0;
  362. /* if the fetch count is less than the remaining rows to process */
  363. /* set the number of rows to process (during this call) equal to the fetch count */
  364. if(nrows < rows)
  365. rows = nrows;
  366. RES_ROW_N(*_r) = rows;
  367. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_r),
  368. RES_NUM_ROWS(*_r), RES_ROW_N(*_r));
  369. RES_ROWS(*_r) = (struct db_row*)pkg_malloc(sizeof(db_row_t) * rows);
  370. if (!RES_ROWS(*_r)) {
  371. LM_ERR("no memory left\n");
  372. return -5;
  373. }
  374. for(i = 0; i < rows; i++) {
  375. RES_ROW(*_r) = mysql_fetch_row(RES_RESULT(*_r));
  376. if (!RES_ROW(*_r)) {
  377. LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
  378. RES_ROW_N(*_r) = i;
  379. db_free_rows(*_r);
  380. return -6;
  381. }
  382. if (db_mysql_convert_row(_h, *_r, &(RES_ROWS(*_r)[i])) < 0) {
  383. LM_ERR("error while converting row #%d\n", i);
  384. RES_ROW_N(*_r) = i;
  385. db_free_rows(*_r);
  386. return -7;
  387. }
  388. }
  389. /* update the total number of rows processed */
  390. RES_LAST_ROW(*_r) += rows;
  391. return 0;
  392. }
  393. /**
  394. * Execute a raw SQL query.
  395. * \param _h handle for the database
  396. * \param _s raw query string
  397. * \param _r result set for storage
  398. * \return zero on success, negative value on failure
  399. */
  400. int db_mysql_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  401. {
  402. return db_do_raw_query(_h, _s, _r, db_mysql_submit_query,
  403. db_mysql_store_result);
  404. }
  405. /**
  406. * Execute a raw SQL query via core async framework.
  407. * \param _h handle for the database
  408. * \param _s raw query string
  409. * \return zero on success, negative value on failure
  410. */
  411. int db_mysql_raw_query_async(const db1_con_t* _h, const str* _s)
  412. {
  413. return db_mysql_submit_query_async(_h, _s);
  414. }
  415. /**
  416. * Insert a row into a specified table.
  417. * \param _h structure representing database connection
  418. * \param _k key names
  419. * \param _v values of the keys
  420. * \param _n number of key=value pairs
  421. * \return zero on success, negative value on failure
  422. */
  423. int db_mysql_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  424. const int _n)
  425. {
  426. if(unlikely(db_mysql_insert_all_delayed==1))
  427. return db_do_insert_delayed(_h, _k, _v, _n, db_mysql_val2str,
  428. db_mysql_submit_query);
  429. else
  430. return db_do_insert(_h, _k, _v, _n, db_mysql_val2str,
  431. db_mysql_submit_query);
  432. }
  433. /**
  434. * Delete a row from the specified table
  435. * \param _h structure representing database connection
  436. * \param _k key names
  437. * \param _o operators
  438. * \param _v values of the keys that must match
  439. * \param _n number of key=value pairs
  440. * \return zero on success, negative value on failure
  441. */
  442. int db_mysql_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  443. const db_val_t* _v, const int _n)
  444. {
  445. return db_do_delete(_h, _k, _o, _v, _n, db_mysql_val2str,
  446. db_mysql_submit_query);
  447. }
  448. /**
  449. * Update some rows in the specified table
  450. * \param _h structure representing database connection
  451. * \param _k key names
  452. * \param _o operators
  453. * \param _v values of the keys that must match
  454. * \param _uk updated columns
  455. * \param _uv updated values of the columns
  456. * \param _n number of key=value pairs
  457. * \param _un number of columns to update
  458. * \return zero on success, negative value on failure
  459. */
  460. int db_mysql_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  461. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  462. const int _un)
  463. {
  464. return db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_mysql_val2str,
  465. db_mysql_submit_query);
  466. }
  467. /**
  468. * Just like insert, but replace the row if it exists.
  469. * \param _h database handle
  470. * \param _k key names
  471. * \param _v values of the keys that must match
  472. * \param _n number of key=value pairs
  473. * \return zero on success, negative value on failure
  474. */
  475. int db_mysql_replace(const db1_con_t* _h, const db_key_t* _k,
  476. const db_val_t* _v, const int _n, const int _un, const int _m)
  477. {
  478. return db_do_replace(_h, _k, _v, _n, db_mysql_val2str,
  479. db_mysql_submit_query);
  480. }
  481. /**
  482. * Returns the last inserted ID.
  483. * \param _h database handle
  484. * \return returns the ID as integer or returns 0 if the previous statement
  485. * does not use an AUTO_INCREMENT value.
  486. */
  487. int db_mysql_last_inserted_id(const db1_con_t* _h)
  488. {
  489. if (!_h) {
  490. LM_ERR("invalid parameter value\n");
  491. return -1;
  492. }
  493. return mysql_insert_id(CON_CONNECTION(_h));
  494. }
  495. /**
  496. * Returns the affected rows of the last query.
  497. * \param _h database handle
  498. * \return returns the affected rows as integer or -1 on error.
  499. */
  500. int db_mysql_affected_rows(const db1_con_t* _h)
  501. {
  502. if (!_h) {
  503. LM_ERR("invalid parameter value\n");
  504. return -1;
  505. }
  506. return (int)mysql_affected_rows(CON_CONNECTION(_h));
  507. }
  508. /**
  509. * Starts a single transaction that will consist of one or more queries (SQL BEGIN)
  510. * \param _h database handle
  511. * \return 0 on success, negative on failure
  512. */
  513. int db_mysql_start_transaction(db1_con_t* _h, db_locking_t _l)
  514. {
  515. str begin_str = str_init("SET autocommit=0");
  516. str lock_start_str = str_init("LOCK TABLES ");
  517. str lock_end_str = str_init(" WRITE");
  518. str lock_str = {0, 0};
  519. if (!_h) {
  520. LM_ERR("invalid parameter value\n");
  521. return -1;
  522. }
  523. if (CON_TRANSACTION(_h) == 1) {
  524. LM_ERR("transaction already started\n");
  525. return -1;
  526. }
  527. if (db_mysql_raw_query(_h, &begin_str, NULL) < 0)
  528. {
  529. LM_ERR("executing raw_query\n");
  530. return -1;
  531. }
  532. CON_TRANSACTION(_h) = 1;
  533. switch(_l)
  534. {
  535. case DB_LOCKING_NONE:
  536. break;
  537. case DB_LOCKING_FULL:
  538. /* Fall-thru */
  539. case DB_LOCKING_WRITE:
  540. if ((lock_str.s = pkg_malloc((lock_start_str.len + CON_TABLE(_h)->len + lock_end_str.len) * sizeof(char))) == NULL)
  541. {
  542. LM_ERR("allocating pkg memory\n");
  543. goto error;
  544. }
  545. memcpy(lock_str.s, lock_start_str.s, lock_start_str.len);
  546. lock_str.len += lock_start_str.len;
  547. memcpy(lock_str.s + lock_str.len, CON_TABLE(_h)->s, CON_TABLE(_h)->len);
  548. lock_str.len += CON_TABLE(_h)->len;
  549. memcpy(lock_str.s + lock_str.len, lock_end_str.s, lock_end_str.len);
  550. lock_str.len += lock_end_str.len;
  551. if (db_mysql_raw_query(_h, &lock_str, NULL) < 0)
  552. {
  553. LM_ERR("executing raw_query\n");
  554. goto error;
  555. }
  556. if (lock_str.s) pkg_free(lock_str.s);
  557. CON_LOCKEDTABLES(_h) = 1;
  558. break;
  559. default:
  560. LM_WARN("unrecognised lock type\n");
  561. goto error;
  562. }
  563. return 0;
  564. error:
  565. if (lock_str.s) pkg_free(lock_str.s);
  566. db_mysql_abort_transaction(_h);
  567. return -1;
  568. }
  569. /**
  570. * Unlock tables in the session
  571. * \param _h database handle
  572. * \return 0 on success, negative on failure
  573. */
  574. int db_mysql_unlock_tables(db1_con_t* _h)
  575. {
  576. str query_str = str_init("UNLOCK TABLES");
  577. if (!_h) {
  578. LM_ERR("invalid parameter value\n");
  579. return -1;
  580. }
  581. if (CON_LOCKEDTABLES(_h) == 0) {
  582. LM_DBG("no active locked tables\n");
  583. return 0;
  584. }
  585. if (db_mysql_raw_query(_h, &query_str, NULL) < 0)
  586. {
  587. LM_ERR("executing raw_query\n");
  588. return -1;
  589. }
  590. CON_LOCKEDTABLES(_h) = 0;
  591. return 0;
  592. }
  593. /**
  594. * Ends a transaction and commits the changes (SQL COMMIT)
  595. * \param _h database handle
  596. * \return 0 on success, negative on failure
  597. */
  598. int db_mysql_end_transaction(db1_con_t* _h)
  599. {
  600. str commit_query_str = str_init("COMMIT");
  601. str set_query_str = str_init("SET autocommit=1");
  602. if (!_h) {
  603. LM_ERR("invalid parameter value\n");
  604. return -1;
  605. }
  606. if (CON_TRANSACTION(_h) == 0) {
  607. LM_ERR("transaction not in progress\n");
  608. return -1;
  609. }
  610. if (db_mysql_raw_query(_h, &commit_query_str, NULL) < 0)
  611. {
  612. LM_ERR("executing raw_query\n");
  613. return -1;
  614. }
  615. if (db_mysql_raw_query(_h, &set_query_str, NULL) < 0)
  616. {
  617. LM_ERR("executing raw_query\n");
  618. return -1;
  619. }
  620. /* Only _end_ the transaction after the raw_query. That way, if the
  621. raw_query fails, and the calling module does an abort_transaction()
  622. to clean-up, a ROLLBACK will be sent to the DB. */
  623. CON_TRANSACTION(_h) = 0;
  624. if(db_mysql_unlock_tables(_h)<0)
  625. return -1;
  626. return 0;
  627. }
  628. /**
  629. * Ends a transaction and rollsback the changes (SQL ROLLBACK)
  630. * \param _h database handle
  631. * \return 1 if there was something to rollback, 0 if not, negative on failure
  632. */
  633. int db_mysql_abort_transaction(db1_con_t* _h)
  634. {
  635. str rollback_query_str = str_init("ROLLBACK");
  636. str set_query_str = str_init("SET autocommit=1");
  637. int ret;
  638. if (!_h) {
  639. LM_ERR("invalid parameter value\n");
  640. return -1;
  641. }
  642. if (CON_TRANSACTION(_h) == 0) {
  643. LM_DBG("nothing to rollback\n");
  644. ret = 0;
  645. goto done;
  646. }
  647. /* Whether the rollback succeeds or not we need to _end_ the
  648. transaction now or all future starts will fail */
  649. CON_TRANSACTION(_h) = 0;
  650. if (db_mysql_raw_query(_h, &rollback_query_str, NULL) < 0)
  651. {
  652. LM_ERR("executing raw_query\n");
  653. ret = -1;
  654. goto done;
  655. }
  656. if (db_mysql_raw_query(_h, &set_query_str, NULL) < 0)
  657. {
  658. LM_ERR("executing raw_query\n");
  659. ret = -1;
  660. goto done;
  661. }
  662. ret = 1;
  663. done:
  664. db_mysql_unlock_tables(_h);
  665. return ret;
  666. }
  667. /**
  668. * Insert a row into a specified table, update on duplicate key.
  669. * \param _h structure representing database connection
  670. * \param _k key names
  671. * \param _v values of the keys
  672. * \param _n number of key=value pairs
  673. */
  674. int db_mysql_insert_update(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  675. const int _n)
  676. {
  677. int off, ret;
  678. static str sql_str;
  679. if ((!_h) || (!_k) || (!_v) || (!_n)) {
  680. LM_ERR("invalid parameter value\n");
  681. return -1;
  682. }
  683. ret = snprintf(mysql_sql_buf, sql_buffer_size, "insert into %.*s (", CON_TABLE(_h)->len, CON_TABLE(_h)->s);
  684. if (ret < 0 || ret >= sql_buffer_size) goto error;
  685. off = ret;
  686. ret = db_print_columns(mysql_sql_buf + off, sql_buffer_size - off, _k, _n);
  687. if (ret < 0) return -1;
  688. off += ret;
  689. ret = snprintf(mysql_sql_buf + off, sql_buffer_size - off, ") values (");
  690. if (ret < 0 || ret >= (sql_buffer_size - off)) goto error;
  691. off += ret;
  692. ret = db_print_values(_h, mysql_sql_buf + off, sql_buffer_size - off, _v, _n, db_mysql_val2str);
  693. if (ret < 0) return -1;
  694. off += ret;
  695. *(mysql_sql_buf + off++) = ')';
  696. ret = snprintf(mysql_sql_buf + off, sql_buffer_size - off, " on duplicate key update ");
  697. if (ret < 0 || ret >= (sql_buffer_size - off)) goto error;
  698. off += ret;
  699. ret = db_print_set(_h, mysql_sql_buf + off, sql_buffer_size - off, _k, _v, _n, db_mysql_val2str);
  700. if (ret < 0) return -1;
  701. off += ret;
  702. sql_str.s = mysql_sql_buf;
  703. sql_str.len = off;
  704. if (db_mysql_submit_query(_h, &sql_str) < 0) {
  705. LM_ERR("error while submitting query\n");
  706. return -2;
  707. }
  708. return 0;
  709. error:
  710. LM_ERR("error while preparing insert_update operation\n");
  711. return -1;
  712. }
  713. /**
  714. * Insert delayed a row into a specified table.
  715. * \param _h structure representing database connection
  716. * \param _k key names
  717. * \param _v values of the keys
  718. * \param _n number of key=value pairs
  719. * \return zero on success, negative value on failure
  720. */
  721. int db_mysql_insert_delayed(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v, const int _n)
  722. {
  723. return db_do_insert_delayed(_h, _k, _v, _n, db_mysql_val2str,
  724. db_mysql_submit_query);
  725. }
  726. /**
  727. * Insert a row into a specified table via core async framework.
  728. * \param _h structure representing database connection
  729. * \param _k key names
  730. * \param _v values of the keys
  731. * \param _n number of key=value pairs
  732. * \return zero on success, negative value on failure
  733. */
  734. int db_mysql_insert_async(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v, const int _n)
  735. {
  736. return db_do_insert(_h, _k, _v, _n, db_mysql_val2str,
  737. db_mysql_submit_query_async);
  738. }
  739. /**
  740. * Store the name of table that will be used by subsequent database functions
  741. * \param _h database handle
  742. * \param _t table name
  743. * \return zero on success, negative value on failure
  744. */
  745. int db_mysql_use_table(db1_con_t* _h, const str* _t)
  746. {
  747. return db_use_table(_h, _t);
  748. }
  749. /**
  750. * Allocate a buffer for database module
  751. * No function should be called before this
  752. * \return zero on success, negative value on failure
  753. */
  754. int db_mysql_alloc_buffer(void)
  755. {
  756. if (db_api_init())
  757. {
  758. LM_ERR("Failed to initialise db api\n");
  759. return -1;
  760. }
  761. mysql_sql_buf = (char*)malloc(sql_buffer_size);
  762. if (mysql_sql_buf == NULL)
  763. return -1;
  764. else
  765. return 0;
  766. }