km_dbase.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 "../../lib/srdb1/db_query.h"
  42. #include "../../lib/srdb1/db_ut.h"
  43. #include "mysql_mod.h"
  44. #include "km_val.h"
  45. #include "km_my_con.h"
  46. #include "km_res.h"
  47. #include "km_row.h"
  48. #include "km_db_mysql.h"
  49. #include "km_dbase.h"
  50. static char *mysql_sql_buf;
  51. /**
  52. * \brief Send a SQL query to the server.
  53. *
  54. * Send a SQL query to the database server. This methods tries to reconnect
  55. * to the server if the connection is gone and the auto_reconnect parameter is
  56. * enabled. It also issues a mysql_ping before the query to connect again after
  57. * a long waiting period because for some older mysql versions the auto reconnect
  58. * don't work sufficient. If auto_reconnect is enabled and the server supports it,
  59. * then the mysql_ping is probably not necessary, but its safer to do it in this
  60. * cases too.
  61. *
  62. * \param _h handle for the db
  63. * \param _s executed query
  64. * \return zero on success, negative value on failure
  65. */
  66. static int db_mysql_submit_query(const db1_con_t* _h, const str* _s)
  67. {
  68. time_t t;
  69. int i, code;
  70. if (!_h || !_s || !_s->s) {
  71. LM_ERR("invalid parameter value\n");
  72. return -1;
  73. }
  74. if (my_ping_interval) {
  75. t = time(0);
  76. if ((t - CON_TIMESTAMP(_h)) > my_ping_interval) {
  77. if (mysql_ping(CON_CONNECTION(_h))) {
  78. LM_WARN("driver error on ping: %s\n", mysql_error(CON_CONNECTION(_h)));
  79. counter_inc(mysql_cnts_h.driver_err);
  80. }
  81. }
  82. /*
  83. * We're doing later a query anyway that will reset the timout of the server,
  84. * so it makes sense to set the timestamp value to the actual time in order
  85. * to prevent unnecessary pings.
  86. */
  87. CON_TIMESTAMP(_h) = t;
  88. }
  89. /* screws up the terminal when the query contains a BLOB :-( (by bogdan)
  90. * LM_DBG("submit_query(): %.*s\n", _s->len, _s->s);
  91. */
  92. /* When a server connection is lost and a query is attempted, most of
  93. * the time the query will return a CR_SERVER_LOST, then at the second
  94. * attempt to execute it, the mysql lib will reconnect and succeed.
  95. * However is a few cases, the first attempt returns CR_SERVER_GONE_ERROR
  96. * the second CR_SERVER_LOST and only the third succeeds.
  97. * Thus the 3 in the loop count. Increasing the loop count over this
  98. * value shouldn't be needed, but it doesn't hurt either, since the loop
  99. * will most of the time stop at the second or sometimes at the third
  100. * iteration. In the case of CR_SERVER_GONE_ERROR and CR_SERVER_LOST the
  101. * driver error counter is increased
  102. */
  103. for (i=0; i < (db_mysql_auto_reconnect ? 3 : 1); i++) {
  104. if (mysql_real_query(CON_CONNECTION(_h), _s->s, _s->len) == 0) {
  105. return 0;
  106. }
  107. code = mysql_errno(CON_CONNECTION(_h));
  108. if (code != CR_SERVER_GONE_ERROR && code != CR_SERVER_LOST) {
  109. break;
  110. }
  111. counter_inc(mysql_cnts_h.driver_err);
  112. }
  113. LM_ERR("driver error on query: %s\n", mysql_error(CON_CONNECTION(_h)));
  114. return -2;
  115. }
  116. /**
  117. * Initialize the database module.
  118. * No function should be called before this
  119. * \param _url URL used for initialization
  120. * \return zero on success, negative value on failure
  121. */
  122. db1_con_t* db_mysql_init(const str* _url)
  123. {
  124. return db_do_init(_url, (void *)db_mysql_new_connection);
  125. }
  126. /**
  127. * Shut down the database module.
  128. * No function should be called after this
  129. * \param _h handle to the closed connection
  130. * \return zero on success, negative value on failure
  131. */
  132. void db_mysql_close(db1_con_t* _h)
  133. {
  134. db_do_close(_h, db_mysql_free_connection);
  135. }
  136. /**
  137. * Retrieve a result set
  138. * \param _h handle to the database
  139. * \param _r result set that should be retrieved
  140. * \return zero on success, negative value on failure
  141. */
  142. static int db_mysql_store_result(const db1_con_t* _h, db1_res_t** _r)
  143. {
  144. int code;
  145. if ((!_h) || (!_r)) {
  146. LM_ERR("invalid parameter value\n");
  147. return -1;
  148. }
  149. *_r = db_mysql_new_result();
  150. if (*_r == 0) {
  151. LM_ERR("no memory left\n");
  152. return -2;
  153. }
  154. RES_RESULT(*_r) = mysql_store_result(CON_CONNECTION(_h));
  155. if (!RES_RESULT(*_r)) {
  156. if (mysql_field_count(CON_CONNECTION(_h)) == 0) {
  157. (*_r)->col.n = 0;
  158. (*_r)->n = 0;
  159. goto done;
  160. } else {
  161. LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
  162. code = mysql_errno(CON_CONNECTION(_h));
  163. if (code == CR_SERVER_GONE_ERROR || code == CR_SERVER_LOST) {
  164. counter_inc(mysql_cnts_h.driver_err);
  165. }
  166. db_mysql_free_result(_h, *_r);
  167. *_r = 0;
  168. return -3;
  169. }
  170. }
  171. if (db_mysql_convert_result(_h, *_r) < 0) {
  172. LM_ERR("error while converting result\n");
  173. LM_DBG("freeing result set at %p\n", _r);
  174. pkg_free(*_r);
  175. *_r = 0;
  176. /* all mem on Kamailio API side is already freed by
  177. * db_mysql_convert_result in case of error, but we also need
  178. * to free the mem from the mysql lib side */
  179. mysql_free_result(RES_RESULT(*_r));
  180. #if (MYSQL_VERSION_ID >= 40100)
  181. while( mysql_more_results(CON_CONNECTION(_h)) && mysql_next_result(CON_CONNECTION(_h)) > 0 ) {
  182. MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) );
  183. mysql_free_result(res);
  184. }
  185. #endif
  186. RES_RESULT(*_r) = 0;
  187. return -4;
  188. }
  189. done:
  190. #if (MYSQL_VERSION_ID >= 40100)
  191. while( mysql_more_results(CON_CONNECTION(_h)) && mysql_next_result(CON_CONNECTION(_h)) > 0 ) {
  192. MYSQL_RES *res = mysql_store_result( CON_CONNECTION(_h) );
  193. mysql_free_result(res);
  194. }
  195. #endif
  196. return 0;
  197. }
  198. /**
  199. * Release a result set from memory.
  200. * \param _h handle to the database
  201. * \param _r result set that should be freed
  202. * \return zero on success, negative value on failure
  203. */
  204. int db_mysql_free_result(const db1_con_t* _h, db1_res_t* _r)
  205. {
  206. if ((!_h) || (!_r)) {
  207. LM_ERR("invalid parameter value\n");
  208. return -1;
  209. }
  210. mysql_free_result(RES_RESULT(_r));
  211. RES_RESULT(_r) = 0;
  212. pkg_free(RES_PTR(_r));
  213. if (db_free_result(_r) < 0) {
  214. LM_ERR("unable to free result structure\n");
  215. return -1;
  216. }
  217. return 0;
  218. }
  219. /**
  220. * Query a table for specified rows.
  221. * \param _h structure representing database connection
  222. * \param _k key names
  223. * \param _op operators
  224. *\param _v values of the keys that must match
  225. * \param _c column names to return
  226. * \param _n number of key=values pairs to compare
  227. * \param _nc number of columns to return
  228. * \param _o order by the specified column
  229. * \param _r pointer to a structure representing the result
  230. * \return zero on success, negative value on failure
  231. */
  232. int db_mysql_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  233. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  234. const db_key_t _o, db1_res_t** _r)
  235. {
  236. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r,
  237. db_mysql_val2str, db_mysql_submit_query, db_mysql_store_result);
  238. }
  239. /**
  240. * \brief Gets a partial result set, fetch rows from a result
  241. *
  242. * Gets a partial result set, fetch a number of rows from a database result.
  243. * This function initialize the given result structure on the first run, and
  244. * fetches the nrows number of rows. On subsequenting runs, it uses the
  245. * existing result and fetches more rows, until it reaches the end of the
  246. * result set. Because of this the result needs to be null in the first
  247. * invocation of the function. If the number of wanted rows is zero, the
  248. * function returns anything with a result of zero.
  249. * \param _h structure representing the database connection
  250. * \param _r pointer to a structure representing the result
  251. * \param nrows number of fetched rows
  252. * \return zero on success, negative value on failure
  253. */
  254. int db_mysql_fetch_result(const db1_con_t* _h, db1_res_t** _r, const int nrows)
  255. {
  256. int rows, i, code;
  257. if (!_h || !_r || nrows < 0) {
  258. LM_ERR("Invalid parameter value\n");
  259. return -1;
  260. }
  261. /* exit if the fetch count is zero */
  262. if (nrows == 0) {
  263. db_mysql_free_result(_h, *_r);
  264. *_r = 0;
  265. return 0;
  266. }
  267. if(*_r==0) {
  268. /* Allocate a new result structure */
  269. *_r = db_mysql_new_result();
  270. if (*_r == 0) {
  271. LM_ERR("no memory left\n");
  272. return -2;
  273. }
  274. RES_RESULT(*_r) = mysql_store_result(CON_CONNECTION(_h));
  275. if (!RES_RESULT(*_r)) {
  276. if (mysql_field_count(CON_CONNECTION(_h)) == 0) {
  277. (*_r)->col.n = 0;
  278. (*_r)->n = 0;
  279. return 0;
  280. } else {
  281. LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
  282. code = mysql_errno(CON_CONNECTION(_h));
  283. if (code == CR_SERVER_GONE_ERROR || code == CR_SERVER_LOST) {
  284. counter_inc(mysql_cnts_h.driver_err);
  285. }
  286. db_mysql_free_result(_h, *_r);
  287. *_r = 0;
  288. return -3;
  289. }
  290. }
  291. if (db_mysql_get_columns(_h, *_r) < 0) {
  292. LM_ERR("error while getting column names\n");
  293. return -4;
  294. }
  295. RES_NUM_ROWS(*_r) = mysql_num_rows(RES_RESULT(*_r));
  296. if (!RES_NUM_ROWS(*_r)) {
  297. LM_DBG("no rows returned from the query\n");
  298. RES_ROWS(*_r) = 0;
  299. return 0;
  300. }
  301. } else {
  302. /* free old rows */
  303. if(RES_ROWS(*_r)!=0)
  304. db_free_rows(*_r);
  305. RES_ROWS(*_r) = 0;
  306. RES_ROW_N(*_r) = 0;
  307. }
  308. /* determine the number of rows remaining to be processed */
  309. rows = RES_NUM_ROWS(*_r) - RES_LAST_ROW(*_r);
  310. /* If there aren't any more rows left to process, exit */
  311. if(rows<=0)
  312. return 0;
  313. /* if the fetch count is less than the remaining rows to process */
  314. /* set the number of rows to process (during this call) equal to the fetch count */
  315. if(nrows < rows)
  316. rows = nrows;
  317. RES_ROW_N(*_r) = rows;
  318. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_r),
  319. RES_NUM_ROWS(*_r), RES_ROW_N(*_r));
  320. RES_ROWS(*_r) = (struct db_row*)pkg_malloc(sizeof(db_row_t) * rows);
  321. if (!RES_ROWS(*_r)) {
  322. LM_ERR("no memory left\n");
  323. return -5;
  324. }
  325. for(i = 0; i < rows; i++) {
  326. RES_ROW(*_r) = mysql_fetch_row(RES_RESULT(*_r));
  327. if (!RES_ROW(*_r)) {
  328. LM_ERR("driver error: %s\n", mysql_error(CON_CONNECTION(_h)));
  329. RES_ROW_N(*_r) = i;
  330. db_free_rows(*_r);
  331. return -6;
  332. }
  333. if (db_mysql_convert_row(_h, *_r, &(RES_ROWS(*_r)[i])) < 0) {
  334. LM_ERR("error while converting row #%d\n", i);
  335. RES_ROW_N(*_r) = i;
  336. db_free_rows(*_r);
  337. return -7;
  338. }
  339. }
  340. /* update the total number of rows processed */
  341. RES_LAST_ROW(*_r) += rows;
  342. return 0;
  343. }
  344. /**
  345. * Execute a raw SQL query.
  346. * \param _h handle for the database
  347. * \param _s raw query string
  348. * \param _r result set for storage
  349. * \return zero on success, negative value on failure
  350. */
  351. int db_mysql_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  352. {
  353. return db_do_raw_query(_h, _s, _r, db_mysql_submit_query,
  354. db_mysql_store_result);
  355. }
  356. /**
  357. * Insert a row into a specified table.
  358. * \param _h structure representing database connection
  359. * \param _k key names
  360. * \param _v values of the keys
  361. * \param _n number of key=value pairs
  362. * \return zero on success, negative value on failure
  363. */
  364. int db_mysql_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v, const int _n)
  365. {
  366. return db_do_insert(_h, _k, _v, _n, db_mysql_val2str,
  367. db_mysql_submit_query);
  368. }
  369. /**
  370. * Delete a row from the specified table
  371. * \param _h structure representing database connection
  372. * \param _k key names
  373. * \param _o operators
  374. * \param _v values of the keys that must match
  375. * \param _n number of key=value pairs
  376. * \return zero on success, negative value on failure
  377. */
  378. int db_mysql_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  379. const db_val_t* _v, const int _n)
  380. {
  381. return db_do_delete(_h, _k, _o, _v, _n, db_mysql_val2str,
  382. db_mysql_submit_query);
  383. }
  384. /**
  385. * Update some rows in the specified table
  386. * \param _h structure representing database connection
  387. * \param _k key names
  388. * \param _o operators
  389. * \param _v values of the keys that must match
  390. * \param _uk updated columns
  391. * \param _uv updated values of the columns
  392. * \param _n number of key=value pairs
  393. * \param _un number of columns to update
  394. * \return zero on success, negative value on failure
  395. */
  396. int db_mysql_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  397. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  398. const int _un)
  399. {
  400. return db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_mysql_val2str,
  401. db_mysql_submit_query);
  402. }
  403. /**
  404. * Just like insert, but replace the row if it exists.
  405. * \param _h database handle
  406. * \param _k key names
  407. * \param _v values of the keys that must match
  408. * \param _n number of key=value pairs
  409. * \return zero on success, negative value on failure
  410. */
  411. int db_mysql_replace(const db1_con_t* _h, const db_key_t* _k,
  412. const db_val_t* _v, const int _n, const int _un, const int _m)
  413. {
  414. return db_do_replace(_h, _k, _v, _n, db_mysql_val2str,
  415. db_mysql_submit_query);
  416. }
  417. /**
  418. * Returns the last inserted ID.
  419. * \param _h database handle
  420. * \return returns the ID as integer or returns 0 if the previous statement
  421. * does not use an AUTO_INCREMENT value.
  422. */
  423. int db_mysql_last_inserted_id(const db1_con_t* _h)
  424. {
  425. if (!_h) {
  426. LM_ERR("invalid parameter value\n");
  427. return -1;
  428. }
  429. return mysql_insert_id(CON_CONNECTION(_h));
  430. }
  431. /**
  432. * Returns the affected rows of the last query.
  433. * \param _h database handle
  434. * \return returns the affected rows as integer or -1 on error.
  435. */
  436. int db_mysql_affected_rows(const db1_con_t* _h)
  437. {
  438. if (!_h) {
  439. LM_ERR("invalid parameter value\n");
  440. return -1;
  441. }
  442. return (int)mysql_affected_rows(CON_CONNECTION(_h));
  443. }
  444. /**
  445. * Insert a row into a specified table, update on duplicate key.
  446. * \param _h structure representing database connection
  447. * \param _k key names
  448. * \param _v values of the keys
  449. * \param _n number of key=value pairs
  450. */
  451. int db_mysql_insert_update(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  452. const int _n)
  453. {
  454. int off, ret;
  455. static str sql_str;
  456. if ((!_h) || (!_k) || (!_v) || (!_n)) {
  457. LM_ERR("invalid parameter value\n");
  458. return -1;
  459. }
  460. ret = snprintf(mysql_sql_buf, sql_buffer_size, "insert into %.*s (", CON_TABLE(_h)->len, CON_TABLE(_h)->s);
  461. if (ret < 0 || ret >= sql_buffer_size) goto error;
  462. off = ret;
  463. ret = db_print_columns(mysql_sql_buf + off, sql_buffer_size - off, _k, _n);
  464. if (ret < 0) return -1;
  465. off += ret;
  466. ret = snprintf(mysql_sql_buf + off, sql_buffer_size - off, ") values (");
  467. if (ret < 0 || ret >= (sql_buffer_size - off)) goto error;
  468. off += ret;
  469. ret = db_print_values(_h, mysql_sql_buf + off, sql_buffer_size - off, _v, _n, db_mysql_val2str);
  470. if (ret < 0) return -1;
  471. off += ret;
  472. *(mysql_sql_buf + off++) = ')';
  473. ret = snprintf(mysql_sql_buf + off, sql_buffer_size - off, " on duplicate key update ");
  474. if (ret < 0 || ret >= (sql_buffer_size - off)) goto error;
  475. off += ret;
  476. ret = db_print_set(_h, mysql_sql_buf + off, sql_buffer_size - off, _k, _v, _n, db_mysql_val2str);
  477. if (ret < 0) return -1;
  478. off += ret;
  479. sql_str.s = mysql_sql_buf;
  480. sql_str.len = off;
  481. if (db_mysql_submit_query(_h, &sql_str) < 0) {
  482. LM_ERR("error while submitting query\n");
  483. return -2;
  484. }
  485. return 0;
  486. error:
  487. LM_ERR("error while preparing insert_update operation\n");
  488. return -1;
  489. }
  490. /**
  491. * Insert delayed a row into a specified table.
  492. * \param _h structure representing database connection
  493. * \param _k key names
  494. * \param _v values of the keys
  495. * \param _n number of key=value pairs
  496. * \return zero on success, negative value on failure
  497. */
  498. int db_mysql_insert_delayed(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v, const int _n)
  499. {
  500. return db_do_insert_delayed(_h, _k, _v, _n, db_mysql_val2str,
  501. db_mysql_submit_query);
  502. }
  503. /**
  504. * Store the name of table that will be used by subsequent database functions
  505. * \param _h database handle
  506. * \param _t table name
  507. * \return zero on success, negative value on failure
  508. */
  509. int db_mysql_use_table(db1_con_t* _h, const str* _t)
  510. {
  511. return db_use_table(_h, _t);
  512. }
  513. /**
  514. * Allocate a buffer for database module
  515. * No function should be called before this
  516. * \return zero on success, negative value on failure
  517. */
  518. int db_mysql_alloc_buffer(void)
  519. {
  520. if (db_api_init())
  521. {
  522. LM_ERR("Failed to initialise db api\n");
  523. return -1;
  524. }
  525. mysql_sql_buf = (char*)malloc(sql_buffer_size);
  526. if (mysql_sql_buf == NULL)
  527. return -1;
  528. else
  529. return 0;
  530. }