km_dbase.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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.h>
  37. #include <errmsg.h>
  38. #include <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. && code!=CR_SSL_CONNECTION_ERROR && code!=CR_CONNECTION_ERROR
  111. && code!=CR_CONN_HOST_ERROR && code!=CR_SERVER_LOST_EXTENDED) {
  112. break;
  113. }
  114. counter_inc(mysql_cnts_h.driver_err);
  115. }
  116. LM_ERR("driver error on query: %s (%d)\n", mysql_error(CON_CONNECTION(_h)),
  117. mysql_errno(CON_CONNECTION(_h)));
  118. return -2;
  119. }
  120. /**
  121. *
  122. */
  123. void db_mysql_async_exec_task(void *param)
  124. {
  125. str *p;
  126. db1_con_t* dbc;
  127. p = (str*)param;
  128. dbc = db_mysql_init(&p[0]);
  129. if(dbc==NULL) {
  130. LM_ERR("failed to open connection for [%.*s]\n", p[0].len, p[0].s);
  131. return;
  132. }
  133. if(db_mysql_submit_query(dbc, &p[1])<0) {
  134. LM_ERR("failed to execute query [%.*s] on async worker\n",
  135. (p[1].len>100)?100:p[1].len, p[1].s);
  136. }
  137. db_mysql_close(dbc);
  138. }
  139. /**
  140. * Execute a raw SQL query via core async framework.
  141. * \param _h handle for the database
  142. * \param _s raw query string
  143. * \return zero on success, negative value on failure
  144. */
  145. int db_mysql_submit_query_async(const db1_con_t* _h, const str* _s)
  146. {
  147. struct db_id* di;
  148. async_task_t *atask;
  149. int asize;
  150. str *p;
  151. di = ((struct pool_con*)_h->tail)->id;
  152. asize = sizeof(async_task_t) + 2*sizeof(str) + di->url.len + _s->len + 2;
  153. atask = shm_malloc(asize);
  154. if(atask==NULL) {
  155. LM_ERR("no more shared memory to allocate %d\n", asize);
  156. return -1;
  157. }
  158. atask->exec = db_mysql_async_exec_task;
  159. atask->param = (char*)atask + sizeof(async_task_t);
  160. p = (str*)((char*)atask + sizeof(async_task_t));
  161. p[0].s = (char*)p + 2*sizeof(str);
  162. p[0].len = di->url.len;
  163. strncpy(p[0].s, di->url.s, di->url.len);
  164. p[1].s = p[0].s + p[0].len + 1;
  165. p[1].len = _s->len;
  166. strncpy(p[1].s, _s->s, _s->len);
  167. async_task_push(atask);
  168. return 0;
  169. }
  170. /**
  171. * Initialize the database module.
  172. * No function should be called before this
  173. * \param _url URL used for initialization
  174. * \return zero on success, negative value on failure
  175. */
  176. db1_con_t* db_mysql_init(const str* _url)
  177. {
  178. return db_do_init(_url, (void *)db_mysql_new_connection);
  179. }
  180. /**
  181. * Shut down the database module.
  182. * No function should be called after this
  183. * \param _h handle to the closed connection
  184. * \return zero on success, negative value on failure
  185. */
  186. void db_mysql_close(db1_con_t* _h)
  187. {
  188. db_do_close(_h, db_mysql_free_connection);
  189. }
  190. /**
  191. * Retrieve a result set
  192. * \param _h handle to the database
  193. * \param _r result set that should be retrieved
  194. * \return zero on success, negative value on failure
  195. */
  196. static int db_mysql_store_result(const db1_con_t* _h, db1_res_t** _r)
  197. {
  198. int code;
  199. if ((!_h) || (!_r)) {
  200. LM_ERR("invalid parameter value\n");
  201. return -1;
  202. }
  203. *_r = db_mysql_new_result();
  204. if (*_r == 0) {
  205. LM_ERR("no memory left\n");
  206. return -2;
  207. }
  208. RES_RESULT(*_r) = mysql_store_result(CON_CONNECTION(_h));
  209. if (!RES_RESULT(*_r)) {
  210. if (mysql_field_count(CON_CONNECTION(_h)) == 0) {
  211. (*_r)->col.n = 0;
  212. (*_r)->n = 0;
  213. goto done;
  214. } else {
  215. LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
  216. code = mysql_errno(CON_CONNECTION(_h));
  217. if (code == CR_SERVER_GONE_ERROR || code == CR_SERVER_LOST) {
  218. counter_inc(mysql_cnts_h.driver_err);
  219. }
  220. db_mysql_free_result(_h, *_r);
  221. *_r = 0;
  222. return -3;
  223. }
  224. }
  225. if (db_mysql_convert_result(_h, *_r) < 0) {
  226. LM_ERR("error while converting result\n");
  227. LM_DBG("freeing result set at %p\n", _r);
  228. /* all mem on Kamailio API side is already freed by
  229. * db_mysql_convert_result in case of error, but we also need
  230. * to free the mem from the mysql lib side, internal pkg for it
  231. * and *_r */
  232. db_mysql_free_result(_h, *_r);
  233. *_r = 0;
  234. #if (MYSQL_VERSION_ID >= 40100)
  235. while( mysql_more_results(CON_CONNECTION(_h)) && mysql_next_result(CON_CONNECTION(_h)) == 0 ) {
  236. MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) );
  237. mysql_free_result(res);
  238. }
  239. #endif
  240. return -4;
  241. }
  242. done:
  243. #if (MYSQL_VERSION_ID >= 40100)
  244. while( mysql_more_results(CON_CONNECTION(_h)) && mysql_next_result(CON_CONNECTION(_h)) == 0 ) {
  245. MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) );
  246. mysql_free_result(res);
  247. }
  248. #endif
  249. return 0;
  250. }
  251. /**
  252. * Release a result set from memory.
  253. * \param _h handle to the database
  254. * \param _r result set that should be freed
  255. * \return zero on success, negative value on failure
  256. */
  257. int db_mysql_free_result(const db1_con_t* _h, db1_res_t* _r)
  258. {
  259. if ((!_h) || (!_r)) {
  260. LM_ERR("invalid parameter value\n");
  261. return -1;
  262. }
  263. mysql_free_result(RES_RESULT(_r));
  264. RES_RESULT(_r) = 0;
  265. pkg_free(RES_PTR(_r));
  266. if (db_free_result(_r) < 0) {
  267. LM_ERR("unable to free result structure\n");
  268. return -1;
  269. }
  270. return 0;
  271. }
  272. /**
  273. * Query a table for specified rows.
  274. * \param _h structure representing database connection
  275. * \param _k key names
  276. * \param _op operators
  277. *\param _v values of the keys that must match
  278. * \param _c column names to return
  279. * \param _n number of key=values pairs to compare
  280. * \param _nc number of columns to return
  281. * \param _o order by the specified column
  282. * \param _r pointer to a structure representing the result
  283. * \return zero on success, negative value on failure
  284. */
  285. int db_mysql_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  286. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  287. const db_key_t _o, db1_res_t** _r)
  288. {
  289. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r,
  290. db_mysql_val2str, db_mysql_submit_query, db_mysql_store_result);
  291. }
  292. /**
  293. * \brief Gets a partial result set, fetch rows from a result
  294. *
  295. * Gets a partial result set, fetch a number of rows from a database result.
  296. * This function initialize the given result structure on the first run, and
  297. * fetches the nrows number of rows. On subsequenting runs, it uses the
  298. * existing result and fetches more rows, until it reaches the end of the
  299. * result set. Because of this the result needs to be null in the first
  300. * invocation of the function. If the number of wanted rows is zero, the
  301. * function returns anything with a result of zero.
  302. * \param _h structure representing the database connection
  303. * \param _r pointer to a structure representing the result
  304. * \param nrows number of fetched rows
  305. * \return zero on success, negative value on failure
  306. */
  307. int db_mysql_fetch_result(const db1_con_t* _h, db1_res_t** _r, const int nrows)
  308. {
  309. int rows, i, code;
  310. if (!_h || !_r || nrows < 0) {
  311. LM_ERR("Invalid parameter value\n");
  312. return -1;
  313. }
  314. /* exit if the fetch count is zero */
  315. if (nrows == 0) {
  316. db_mysql_free_result(_h, *_r);
  317. *_r = 0;
  318. return 0;
  319. }
  320. if(*_r==0) {
  321. /* Allocate a new result structure */
  322. *_r = db_mysql_new_result();
  323. if (*_r == 0) {
  324. LM_ERR("no memory left\n");
  325. return -2;
  326. }
  327. RES_RESULT(*_r) = mysql_store_result(CON_CONNECTION(_h));
  328. if (!RES_RESULT(*_r)) {
  329. if (mysql_field_count(CON_CONNECTION(_h)) == 0) {
  330. (*_r)->col.n = 0;
  331. (*_r)->n = 0;
  332. return 0;
  333. } else {
  334. LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
  335. code = mysql_errno(CON_CONNECTION(_h));
  336. if (code == CR_SERVER_GONE_ERROR || code == CR_SERVER_LOST) {
  337. counter_inc(mysql_cnts_h.driver_err);
  338. }
  339. db_mysql_free_result(_h, *_r);
  340. *_r = 0;
  341. return -3;
  342. }
  343. }
  344. if (db_mysql_get_columns(_h, *_r) < 0) {
  345. LM_ERR("error while getting column names\n");
  346. return -4;
  347. }
  348. RES_NUM_ROWS(*_r) = mysql_num_rows(RES_RESULT(*_r));
  349. if (!RES_NUM_ROWS(*_r)) {
  350. LM_DBG("no rows returned from the query\n");
  351. RES_ROWS(*_r) = 0;
  352. return 0;
  353. }
  354. } else {
  355. /* free old rows */
  356. if(RES_ROWS(*_r)!=0)
  357. db_free_rows(*_r);
  358. RES_ROWS(*_r) = 0;
  359. RES_ROW_N(*_r) = 0;
  360. }
  361. /* determine the number of rows remaining to be processed */
  362. rows = RES_NUM_ROWS(*_r) - RES_LAST_ROW(*_r);
  363. /* If there aren't any more rows left to process, exit */
  364. if(rows<=0)
  365. return 0;
  366. /* if the fetch count is less than the remaining rows to process */
  367. /* set the number of rows to process (during this call) equal to the fetch count */
  368. if(nrows < rows)
  369. rows = nrows;
  370. RES_ROW_N(*_r) = rows;
  371. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_r),
  372. RES_NUM_ROWS(*_r), RES_ROW_N(*_r));
  373. RES_ROWS(*_r) = (struct db_row*)pkg_malloc(sizeof(db_row_t) * rows);
  374. if (!RES_ROWS(*_r)) {
  375. LM_ERR("no memory left\n");
  376. return -5;
  377. }
  378. for(i = 0; i < rows; i++) {
  379. RES_ROW(*_r) = mysql_fetch_row(RES_RESULT(*_r));
  380. if (!RES_ROW(*_r)) {
  381. LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
  382. RES_ROW_N(*_r) = i;
  383. db_free_rows(*_r);
  384. return -6;
  385. }
  386. if (db_mysql_convert_row(_h, *_r, &(RES_ROWS(*_r)[i])) < 0) {
  387. LM_ERR("error while converting row #%d\n", i);
  388. RES_ROW_N(*_r) = i;
  389. db_free_rows(*_r);
  390. return -7;
  391. }
  392. }
  393. /* update the total number of rows processed */
  394. RES_LAST_ROW(*_r) += rows;
  395. return 0;
  396. }
  397. /**
  398. * Execute a raw SQL query.
  399. * \param _h handle for the database
  400. * \param _s raw query string
  401. * \param _r result set for storage
  402. * \return zero on success, negative value on failure
  403. */
  404. int db_mysql_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  405. {
  406. return db_do_raw_query(_h, _s, _r, db_mysql_submit_query,
  407. db_mysql_store_result);
  408. }
  409. /**
  410. * Execute a raw SQL query via core async framework.
  411. * \param _h handle for the database
  412. * \param _s raw query string
  413. * \return zero on success, negative value on failure
  414. */
  415. int db_mysql_raw_query_async(const db1_con_t* _h, const str* _s)
  416. {
  417. return db_mysql_submit_query_async(_h, _s);
  418. }
  419. /**
  420. * Insert a row into a specified table.
  421. * \param _h structure representing database connection
  422. * \param _k key names
  423. * \param _v values of the keys
  424. * \param _n number of key=value pairs
  425. * \return zero on success, negative value on failure
  426. */
  427. int db_mysql_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  428. const int _n)
  429. {
  430. if(unlikely(db_mysql_insert_all_delayed==1))
  431. return db_do_insert_delayed(_h, _k, _v, _n, db_mysql_val2str,
  432. db_mysql_submit_query);
  433. else
  434. return db_do_insert(_h, _k, _v, _n, db_mysql_val2str,
  435. db_mysql_submit_query);
  436. }
  437. /**
  438. * Delete a row from the specified table
  439. * \param _h structure representing database connection
  440. * \param _k key names
  441. * \param _o operators
  442. * \param _v values of the keys that must match
  443. * \param _n number of key=value pairs
  444. * \return zero on success, negative value on failure
  445. */
  446. int db_mysql_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  447. const db_val_t* _v, const int _n)
  448. {
  449. return db_do_delete(_h, _k, _o, _v, _n, db_mysql_val2str,
  450. db_mysql_submit_query);
  451. }
  452. /**
  453. * Update some rows in the specified table
  454. * \param _h structure representing database connection
  455. * \param _k key names
  456. * \param _o operators
  457. * \param _v values of the keys that must match
  458. * \param _uk updated columns
  459. * \param _uv updated values of the columns
  460. * \param _n number of key=value pairs
  461. * \param _un number of columns to update
  462. * \return zero on success, negative value on failure
  463. */
  464. int db_mysql_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  465. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  466. const int _un)
  467. {
  468. return db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_mysql_val2str,
  469. db_mysql_submit_query);
  470. }
  471. /**
  472. * Just like insert, but replace the row if it exists.
  473. * \param _h database handle
  474. * \param _k key names
  475. * \param _v values of the keys that must match
  476. * \param _n number of key=value pairs
  477. * \return zero on success, negative value on failure
  478. */
  479. int db_mysql_replace(const db1_con_t* _h, const db_key_t* _k,
  480. const db_val_t* _v, const int _n, const int _un, const int _m)
  481. {
  482. return db_do_replace(_h, _k, _v, _n, db_mysql_val2str,
  483. db_mysql_submit_query);
  484. }
  485. /**
  486. * Returns the last inserted ID.
  487. * \param _h database handle
  488. * \return returns the ID as integer or returns 0 if the previous statement
  489. * does not use an AUTO_INCREMENT value.
  490. */
  491. int db_mysql_last_inserted_id(const db1_con_t* _h)
  492. {
  493. if (!_h) {
  494. LM_ERR("invalid parameter value\n");
  495. return -1;
  496. }
  497. return mysql_insert_id(CON_CONNECTION(_h));
  498. }
  499. /**
  500. * Returns the affected rows of the last query.
  501. * \param _h database handle
  502. * \return returns the affected rows as integer or -1 on error.
  503. */
  504. int db_mysql_affected_rows(const db1_con_t* _h)
  505. {
  506. if (!_h) {
  507. LM_ERR("invalid parameter value\n");
  508. return -1;
  509. }
  510. return (int)mysql_affected_rows(CON_CONNECTION(_h));
  511. }
  512. /**
  513. * Starts a single transaction that will consist of one or more queries (SQL BEGIN)
  514. * \param _h database handle
  515. * \return 0 on success, negative on failure
  516. */
  517. int db_mysql_start_transaction(db1_con_t* _h, db_locking_t _l)
  518. {
  519. str begin_str = str_init("SET autocommit=0");
  520. str lock_start_str = str_init("LOCK TABLES ");
  521. str lock_end_str = str_init(" WRITE");
  522. str lock_str = {0, 0};
  523. if (!_h) {
  524. LM_ERR("invalid parameter value\n");
  525. return -1;
  526. }
  527. if (CON_TRANSACTION(_h) == 1) {
  528. LM_ERR("transaction already started\n");
  529. return -1;
  530. }
  531. if (db_mysql_raw_query(_h, &begin_str, NULL) < 0)
  532. {
  533. LM_ERR("executing raw_query\n");
  534. return -1;
  535. }
  536. CON_TRANSACTION(_h) = 1;
  537. switch(_l)
  538. {
  539. case DB_LOCKING_NONE:
  540. break;
  541. case DB_LOCKING_FULL:
  542. /* Fall-thru */
  543. case DB_LOCKING_WRITE:
  544. if ((lock_str.s = pkg_malloc((lock_start_str.len + CON_TABLE(_h)->len + lock_end_str.len) * sizeof(char))) == NULL)
  545. {
  546. LM_ERR("allocating pkg memory\n");
  547. goto error;
  548. }
  549. memcpy(lock_str.s, lock_start_str.s, lock_start_str.len);
  550. lock_str.len += lock_start_str.len;
  551. memcpy(lock_str.s + lock_str.len, CON_TABLE(_h)->s, CON_TABLE(_h)->len);
  552. lock_str.len += CON_TABLE(_h)->len;
  553. memcpy(lock_str.s + lock_str.len, lock_end_str.s, lock_end_str.len);
  554. lock_str.len += lock_end_str.len;
  555. if (db_mysql_raw_query(_h, &lock_str, NULL) < 0)
  556. {
  557. LM_ERR("executing raw_query\n");
  558. goto error;
  559. }
  560. if (lock_str.s) pkg_free(lock_str.s);
  561. CON_LOCKEDTABLES(_h) = 1;
  562. break;
  563. default:
  564. LM_WARN("unrecognised lock type\n");
  565. goto error;
  566. }
  567. return 0;
  568. error:
  569. if (lock_str.s) pkg_free(lock_str.s);
  570. db_mysql_abort_transaction(_h);
  571. return -1;
  572. }
  573. /**
  574. * Unlock tables in the session
  575. * \param _h database handle
  576. * \return 0 on success, negative on failure
  577. */
  578. int db_mysql_unlock_tables(db1_con_t* _h)
  579. {
  580. str query_str = str_init("UNLOCK TABLES");
  581. if (!_h) {
  582. LM_ERR("invalid parameter value\n");
  583. return -1;
  584. }
  585. if (CON_LOCKEDTABLES(_h) == 0) {
  586. LM_DBG("no active locked tables\n");
  587. return 0;
  588. }
  589. if (db_mysql_raw_query(_h, &query_str, NULL) < 0)
  590. {
  591. LM_ERR("executing raw_query\n");
  592. return -1;
  593. }
  594. CON_LOCKEDTABLES(_h) = 0;
  595. return 0;
  596. }
  597. /**
  598. * Ends a transaction and commits the changes (SQL COMMIT)
  599. * \param _h database handle
  600. * \return 0 on success, negative on failure
  601. */
  602. int db_mysql_end_transaction(db1_con_t* _h)
  603. {
  604. str commit_query_str = str_init("COMMIT");
  605. str set_query_str = str_init("SET autocommit=1");
  606. if (!_h) {
  607. LM_ERR("invalid parameter value\n");
  608. return -1;
  609. }
  610. if (CON_TRANSACTION(_h) == 0) {
  611. LM_ERR("transaction not in progress\n");
  612. return -1;
  613. }
  614. if (db_mysql_raw_query(_h, &commit_query_str, NULL) < 0)
  615. {
  616. LM_ERR("executing raw_query\n");
  617. return -1;
  618. }
  619. if (db_mysql_raw_query(_h, &set_query_str, NULL) < 0)
  620. {
  621. LM_ERR("executing raw_query\n");
  622. return -1;
  623. }
  624. /* Only _end_ the transaction after the raw_query. That way, if the
  625. raw_query fails, and the calling module does an abort_transaction()
  626. to clean-up, a ROLLBACK will be sent to the DB. */
  627. CON_TRANSACTION(_h) = 0;
  628. if(db_mysql_unlock_tables(_h)<0)
  629. return -1;
  630. return 0;
  631. }
  632. /**
  633. * Ends a transaction and rollsback the changes (SQL ROLLBACK)
  634. * \param _h database handle
  635. * \return 1 if there was something to rollback, 0 if not, negative on failure
  636. */
  637. int db_mysql_abort_transaction(db1_con_t* _h)
  638. {
  639. str rollback_query_str = str_init("ROLLBACK");
  640. str set_query_str = str_init("SET autocommit=1");
  641. int ret;
  642. if (!_h) {
  643. LM_ERR("invalid parameter value\n");
  644. return -1;
  645. }
  646. if (CON_TRANSACTION(_h) == 0) {
  647. LM_DBG("nothing to rollback\n");
  648. ret = 0;
  649. goto done;
  650. }
  651. /* Whether the rollback succeeds or not we need to _end_ the
  652. transaction now or all future starts will fail */
  653. CON_TRANSACTION(_h) = 0;
  654. if (db_mysql_raw_query(_h, &rollback_query_str, NULL) < 0)
  655. {
  656. LM_ERR("executing raw_query\n");
  657. ret = -1;
  658. goto done;
  659. }
  660. if (db_mysql_raw_query(_h, &set_query_str, NULL) < 0)
  661. {
  662. LM_ERR("executing raw_query\n");
  663. ret = -1;
  664. goto done;
  665. }
  666. ret = 1;
  667. done:
  668. db_mysql_unlock_tables(_h);
  669. return ret;
  670. }
  671. /**
  672. * Insert a row into a specified table, update on duplicate key.
  673. * \param _h structure representing database connection
  674. * \param _k key names
  675. * \param _v values of the keys
  676. * \param _n number of key=value pairs
  677. */
  678. int db_mysql_insert_update(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  679. const int _n)
  680. {
  681. int off, ret;
  682. static str sql_str;
  683. if ((!_h) || (!_k) || (!_v) || (!_n)) {
  684. LM_ERR("invalid parameter value\n");
  685. return -1;
  686. }
  687. ret = snprintf(mysql_sql_buf, sql_buffer_size, "insert into %.*s (", CON_TABLE(_h)->len, CON_TABLE(_h)->s);
  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);
  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. }