km_dbase.c 23 KB

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