km_dbase.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. /*
  2. * $Id$
  3. *
  4. * Copyright (C) 2003 August.Net Services, LLC
  5. * Copyright (C) 2006 Norman Brandinger
  6. * Copyright (C) 2008 1&1 Internet AG
  7. *
  8. * This file is part of Kamailio, a free SIP server.
  9. *
  10. * Kamailio is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 2 of the License, or
  13. * (at your option) any later version
  14. *
  15. * Kamailio is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. *
  24. * History
  25. * -------
  26. * 2003-04-06 initial code written (Greg Fausak/Andy Fullford)
  27. * 2006-07-28 within pg_get_result(): added check to immediatly return of no
  28. * result set was returned added check to only execute
  29. * convert_result() if PGRES_TUPLES_OK added safety check to avoid
  30. * double pg_free_result() (norm)
  31. * 2006-08-07 Rewrote pg_get_result().
  32. * Additional debugging lines have been placed through out the code.
  33. * Added Asynchronous Command Processing (PQsendQuery/PQgetResult)
  34. * instead of PQexec. this was done in preparation of adding FETCH
  35. * support. Note that PQexec returns a result pointer while
  36. * PQsendQuery does not. The result set pointer is obtained from
  37. * a call (or multiple calls) to PQgetResult.
  38. * Removed transaction processing calls (BEGIN/COMMIT/ROLLBACK) as
  39. * they added uneeded overhead. Klaus' testing showed in excess of
  40. * 1ms gain by removing each command. In addition, Kamailio only
  41. * issues single queries and is not, at this time transaction aware.
  42. * The transaction processing routines have been left in place
  43. * should this support be needed in the future.
  44. * Updated logic in pg_query / pg_raw_query to accept a (0) result
  45. * set (_r) parameter. In this case, control is returned
  46. * immediately after submitting the query and no call to
  47. * pg_get_results() is performed. This is a requirement for
  48. * FETCH support. (norm)
  49. * 2006-10-27 Added fetch support (norm)
  50. * Removed dependency on aug_* memory routines (norm)
  51. * Added connection pooling support (norm)
  52. * Standardized API routines to pg_* names (norm)
  53. * 2006-11-01 Updated pg_insert(), pg_delete(), pg_update() and
  54. * pg_get_result() to handle failed queries. Detailed warnings
  55. * along with the text of the failed query is now displayed in the
  56. * log. Callers of these routines can now assume that a non-zero
  57. * rc indicates the query failed and that remedial action may need
  58. * to be taken. (norm)
  59. */
  60. /*! \file
  61. * \brief DB_POSTGRES :: Core
  62. * \ingroup db_postgres
  63. * Module: \ref db_postgres
  64. */
  65. /*! maximum number of columns */
  66. #define MAXCOLUMNS 512
  67. #include <string.h>
  68. #include <stdio.h>
  69. #include <stdlib.h>
  70. #include "../../dprint.h"
  71. #include "../../mem/mem.h"
  72. #include "../../lib/srdb1/db.h"
  73. #include "../../lib/srdb1/db_ut.h"
  74. #include "../../lib/srdb1/db_query.h"
  75. #include "../../locking.h"
  76. #include "../../hashes.h"
  77. #include "km_dbase.h"
  78. #include "km_pg_con.h"
  79. #include "km_val.h"
  80. #include "km_res.h"
  81. #include "pg_mod.h"
  82. static gen_lock_set_t *_pg_lock_set = NULL;
  83. static unsigned int _pg_lock_size = 0;
  84. /*!
  85. * \brief init lock set used to implement SQL REPLACE via UPDATE/INSERT
  86. * \param sz power of two to compute the lock set size
  87. * \return 0 on success, -1 on error
  88. */
  89. int pg_init_lock_set(int sz)
  90. {
  91. if(sz>0 && sz<=10)
  92. {
  93. _pg_lock_size = 1<<sz;
  94. } else {
  95. _pg_lock_size = 1<<4;
  96. }
  97. _pg_lock_set = lock_set_alloc(_pg_lock_size);
  98. if(_pg_lock_set==NULL || lock_set_init(_pg_lock_set)==NULL)
  99. {
  100. LM_ERR("cannot initiate lock set\n");
  101. return -1;
  102. }
  103. return 0;
  104. }
  105. void pg_destroy_lock_set(void)
  106. {
  107. if(_pg_lock_set!=NULL)
  108. {
  109. lock_set_destroy(_pg_lock_set);
  110. lock_set_dealloc(_pg_lock_set);
  111. _pg_lock_set = NULL;
  112. _pg_lock_size = 0;
  113. }
  114. }
  115. static void db_postgres_free_query(const db1_con_t* _con);
  116. /*!
  117. * \brief Initialize database for future queries
  118. * \param _url URL of the database that should be opened
  119. * \return database connection on success, NULL on error
  120. * \note this function must be called prior to any database functions
  121. */
  122. db1_con_t *db_postgres_init(const str* _url)
  123. {
  124. return db_do_init(_url, (void*) db_postgres_new_connection);
  125. }
  126. /*!
  127. * \brief Initialize database for future queries - no pooling
  128. * \param _url URL of the database that should be opened
  129. * \return database connection on success, NULL on error
  130. * \note this function must be called prior to any database functions
  131. */
  132. db1_con_t *db_postgres_init2(const str* _url, db_pooling_t pooling)
  133. {
  134. return db_do_init2(_url, (void*) db_postgres_new_connection, pooling);
  135. }
  136. /*!
  137. * \brief Close database when the database is no longer needed
  138. * \param _h closed connection, as returned from db_postgres_init
  139. * \note free all memory and resources
  140. */
  141. void db_postgres_close(db1_con_t* _h)
  142. {
  143. db_do_close(_h, db_postgres_free_connection);
  144. }
  145. /*!
  146. * \brief Submit_query, run a query
  147. * \param _con database connection
  148. * \param _s query string
  149. * \return 0 on success, negative on failure
  150. */
  151. static int db_postgres_submit_query(const db1_con_t* _con, const str* _s)
  152. {
  153. char *s=NULL;
  154. int i, retries;
  155. ExecStatusType pqresult;
  156. PGresult *res = NULL;
  157. if(! _con || !_s || !_s->s)
  158. {
  159. LM_ERR("invalid parameter value\n");
  160. return(-1);
  161. }
  162. /* this bit of nonsense in case our connection get screwed up */
  163. switch(PQstatus(CON_CONNECTION(_con)))
  164. {
  165. case CONNECTION_OK:
  166. break;
  167. case CONNECTION_BAD:
  168. LM_DBG("connection reset\n");
  169. PQreset(CON_CONNECTION(_con));
  170. break;
  171. case CONNECTION_STARTED:
  172. case CONNECTION_MADE:
  173. case CONNECTION_AWAITING_RESPONSE:
  174. case CONNECTION_AUTH_OK:
  175. case CONNECTION_SETENV:
  176. case CONNECTION_SSL_STARTUP:
  177. case CONNECTION_NEEDED:
  178. default:
  179. LM_ERR("%p PQstatus(%s) invalid: %.*s\n", _con,
  180. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  181. return -1;
  182. }
  183. if (CON_TRANSACTION(_con) == 1)
  184. retries = 0;
  185. else
  186. retries = pg_retries;
  187. s = pkg_malloc((_s->len+1)*sizeof(char));
  188. if (s==NULL)
  189. {
  190. LM_ERR("%p db_postgres_submit_query Out of Memory: Query: %.*s\n", _con, _s->len, _s->s);
  191. return -1;
  192. }
  193. memcpy( s, _s->s, _s->len );
  194. s[_s->len] = '\0';
  195. for(i = 0; i <= retries; i++) {
  196. /* free any previous query that is laying about */
  197. db_postgres_free_query(_con);
  198. /* exec the query */
  199. if (PQsendQuery(CON_CONNECTION(_con), s)) {
  200. /* Get the result of the query */
  201. while ((res = PQgetResult(CON_CONNECTION(_con))) != NULL) {
  202. db_postgres_free_query(_con);
  203. CON_RESULT(_con) = res;
  204. }
  205. pqresult = PQresultStatus(CON_RESULT(_con));
  206. if((pqresult!=PGRES_FATAL_ERROR)
  207. && (PQstatus(CON_CONNECTION(_con))==CONNECTION_OK))
  208. {
  209. LM_DBG("sending query ok: %p (%d) - [%.*s]\n",
  210. _con, pqresult, _s->len, _s->s);
  211. pkg_free(s);
  212. return 0;
  213. }
  214. LM_WARN("postgres result check failed with code %d (%s)\n",
  215. pqresult, PQresStatus(pqresult));
  216. }
  217. LM_WARN("postgres query command failed, connection status %d,"
  218. " error [%s]\n", PQstatus(CON_CONNECTION(_con)),
  219. PQerrorMessage(CON_CONNECTION(_con)));
  220. if(PQstatus(CON_CONNECTION(_con))!=CONNECTION_OK)
  221. {
  222. LM_DBG("reseting the connection to postgress server\n");
  223. PQreset(CON_CONNECTION(_con));
  224. }
  225. }
  226. LM_ERR("%p PQsendQuery Error: %s Query: %.*s\n", _con,
  227. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  228. pkg_free(s);
  229. return -1;
  230. }
  231. /*!
  232. * \brief Gets a partial result set, fetch rows from a result
  233. *
  234. * Gets a partial result set, fetch a number of rows from a database result.
  235. * This function initialize the given result structure on the first run, and
  236. * fetches the nrows number of rows. On subsequenting runs, it uses the
  237. * existing result and fetches more rows, until it reaches the end of the
  238. * result set. Because of this the result needs to be null in the first
  239. * invocation of the function. If the number of wanted rows is zero, the
  240. * function returns anything with a result of zero.
  241. * \param _con database connection
  242. * \param _res result set
  243. * \param nrows number of fetches rows
  244. * \return 0 on success, negative on failure
  245. */
  246. int db_postgres_fetch_result(const db1_con_t* _con, db1_res_t** _res, const int nrows)
  247. {
  248. int rows;
  249. ExecStatusType pqresult;
  250. if (!_con || !_res || nrows < 0) {
  251. LM_ERR("invalid parameter value\n");
  252. return -1;
  253. }
  254. /* exit if the fetch count is zero */
  255. if (nrows == 0) {
  256. if (*_res)
  257. db_free_result(*_res);
  258. *_res = 0;
  259. return 0;
  260. }
  261. if (*_res == NULL) {
  262. /* Allocate a new result structure */
  263. *_res = db_new_result();
  264. pqresult = PQresultStatus(CON_RESULT(_con));
  265. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  266. PQresStatus(pqresult), CON_RESULT(_con));
  267. switch(pqresult) {
  268. case PGRES_COMMAND_OK:
  269. /* Successful completion of a command returning no data
  270. * (such as INSERT or UPDATE). */
  271. return 0;
  272. case PGRES_TUPLES_OK:
  273. /* Successful completion of a command returning data
  274. * (such as a SELECT or SHOW). */
  275. if (db_postgres_get_columns(_con, *_res) < 0) {
  276. LM_ERR("failed to get column names\n");
  277. return -2;
  278. }
  279. break;
  280. case PGRES_FATAL_ERROR:
  281. LM_ERR("%p - invalid query, execution aborted\n", _con);
  282. LM_ERR("%p - PQresultStatus(%s)\n", _con,
  283. PQresStatus(pqresult));
  284. LM_ERR("%p: %s\n", _con,
  285. PQresultErrorMessage(CON_RESULT(_con)));
  286. if (*_res)
  287. db_free_result(*_res);
  288. *_res = 0;
  289. return -3;
  290. case PGRES_EMPTY_QUERY:
  291. /* notice or warning */
  292. case PGRES_NONFATAL_ERROR:
  293. /* status for COPY command, not used */
  294. case PGRES_COPY_OUT:
  295. case PGRES_COPY_IN:
  296. /* unexpected response */
  297. case PGRES_BAD_RESPONSE:
  298. default:
  299. LM_ERR("%p - probable invalid query\n", _con);
  300. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  301. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  302. if (*_res)
  303. db_free_result(*_res);
  304. *_res = 0;
  305. return -4;
  306. }
  307. } else {
  308. if(RES_ROWS(*_res) != NULL) {
  309. db_free_rows(*_res);
  310. }
  311. RES_ROWS(*_res) = 0;
  312. RES_ROW_N(*_res) = 0;
  313. }
  314. /* Get the number of rows (tuples) in the query result. */
  315. RES_NUM_ROWS(*_res) = PQntuples(CON_RESULT(_con));
  316. /* determine the number of rows remaining to be processed */
  317. rows = RES_NUM_ROWS(*_res) - RES_LAST_ROW(*_res);
  318. /* If there aren't any more rows left to process, exit */
  319. if (rows <= 0)
  320. return 0;
  321. /* if the fetch count is less than the remaining rows to process */
  322. /* set the number of rows to process (during this call) equal to the fetch count */
  323. if (nrows < rows)
  324. rows = nrows;
  325. RES_ROW_N(*_res) = rows;
  326. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_res),
  327. RES_NUM_ROWS(*_res), RES_ROW_N(*_res));
  328. if (db_postgres_convert_rows(_con, *_res) < 0) {
  329. LM_ERR("failed to convert rows\n");
  330. if (*_res)
  331. db_free_result(*_res);
  332. *_res = 0;
  333. return -3;
  334. }
  335. /* update the total number of rows processed */
  336. RES_LAST_ROW(*_res) += rows;
  337. return 0;
  338. }
  339. /*!
  340. * \brief Free database and any old query results
  341. * \param _con database connection
  342. */
  343. static void db_postgres_free_query(const db1_con_t* _con)
  344. {
  345. if(CON_RESULT(_con))
  346. {
  347. LM_DBG("PQclear(%p) result set\n", CON_RESULT(_con));
  348. PQclear(CON_RESULT(_con));
  349. CON_RESULT(_con) = 0;
  350. }
  351. }
  352. /*!
  353. * \brief Free the query and the result memory in the core
  354. * \param _con database connection
  355. * \param _r result set
  356. * \return 0 on success, -1 on failure
  357. */
  358. int db_postgres_free_result(db1_con_t* _con, db1_res_t* _r)
  359. {
  360. if ((!_con) || (!_r)) {
  361. LM_ERR("invalid parameter value\n");
  362. return -1;
  363. }
  364. if (db_free_result(_r) < 0) {
  365. LM_ERR("unable to free result structure\n");
  366. return -1;
  367. }
  368. db_postgres_free_query(_con);
  369. return 0;
  370. }
  371. /*!
  372. * \brief Query table for specified rows
  373. * \param _h structure representing database connection
  374. * \param _k key names
  375. * \param _op operators
  376. * \param _v values of the keys that must match
  377. * \param _c column names to return
  378. * \param _n nmber of key=values pairs to compare
  379. * \param _nc number of columns to return
  380. * \param _o order by the specified column
  381. * \param _r result set
  382. * \return 0 on success, negative on failure
  383. */
  384. int db_postgres_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  385. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  386. const db_key_t _o, db1_res_t** _r)
  387. {
  388. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  389. db_postgres_submit_query, db_postgres_store_result);
  390. }
  391. /*!
  392. * \brief Query table for specified rows and lock them
  393. * \param _h structure representing database connection
  394. * \param _k key names
  395. * \param _op operators
  396. * \param _v values of the keys that must match
  397. * \param _c column names to return
  398. * \param _n nmber of key=values pairs to compare
  399. * \param _nc number of columns to return
  400. * \param _o order by the specified column
  401. * \param _r result set
  402. * \return 0 on success, negative on failure
  403. */
  404. int db_postgres_query_lock(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  405. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  406. const db_key_t _o, db1_res_t** _r)
  407. {
  408. if (CON_TRANSACTION(_h) == 0)
  409. {
  410. LM_ERR("transaction not in progress\n");
  411. return -1;
  412. }
  413. return db_do_query_lock(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  414. db_postgres_submit_query, db_postgres_store_result);
  415. }
  416. /*!
  417. * Execute a raw SQL query
  418. * \param _h database connection
  419. * \param _s raw query string
  420. * \param _r result set
  421. * \return 0 on success, negative on failure
  422. */
  423. int db_postgres_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  424. {
  425. return db_do_raw_query(_h, _s, _r, db_postgres_submit_query,
  426. db_postgres_store_result);
  427. }
  428. /*!
  429. * \brief Retrieve result set
  430. * \param _con structure representing the database connection
  431. * \param _r pointer to a structure represending the result set
  432. * \return 0 If the status of the last command produced a result set and,
  433. * If the result set contains data or the convert_result() routine
  434. * completed successfully. Negative if the status of the last command was
  435. * not handled or if the convert_result() returned an error.
  436. * \note A new result structure is allocated on every call to this routine.
  437. * If this routine returns 0, it is the callers responsbility to free the
  438. * result structure. If this routine returns < 0, then the result structure
  439. * is freed before returning to the caller.
  440. */
  441. int db_postgres_store_result(const db1_con_t* _con, db1_res_t** _r)
  442. {
  443. ExecStatusType pqresult;
  444. int rc = 0;
  445. *_r = db_new_result();
  446. if (*_r==NULL) {
  447. LM_ERR("failed to init new result\n");
  448. rc = -1;
  449. goto done;
  450. }
  451. pqresult = PQresultStatus(CON_RESULT(_con));
  452. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  453. PQresStatus(pqresult), CON_RESULT(_con));
  454. CON_AFFECTED(_con) = 0;
  455. switch(pqresult) {
  456. case PGRES_COMMAND_OK:
  457. /* Successful completion of a command returning no data
  458. * (such as INSERT or UPDATE). */
  459. rc = 0;
  460. CON_AFFECTED(_con) = atoi(PQcmdTuples(CON_RESULT(_con)));
  461. break;
  462. case PGRES_TUPLES_OK:
  463. /* Successful completion of a command returning data
  464. * (such as a SELECT or SHOW). */
  465. if (db_postgres_convert_result(_con, *_r) < 0) {
  466. LM_ERR("error while converting result\n");
  467. LM_DBG("freeing result set at %p\n", _r);
  468. pkg_free(*_r);
  469. *_r = 0;
  470. rc = -4;
  471. break;
  472. }
  473. rc = 0;
  474. CON_AFFECTED(_con) = atoi(PQcmdTuples(CON_RESULT(_con)));
  475. break;
  476. /* query failed */
  477. case PGRES_FATAL_ERROR:
  478. LM_ERR("invalid query, execution aborted\n");
  479. LM_ERR("driver error: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  480. db_free_result(*_r);
  481. *_r = 0;
  482. rc = -3;
  483. break;
  484. case PGRES_EMPTY_QUERY:
  485. /* notice or warning */
  486. case PGRES_NONFATAL_ERROR:
  487. /* status for COPY command, not used */
  488. case PGRES_COPY_OUT:
  489. case PGRES_COPY_IN:
  490. /* unexpected response */
  491. case PGRES_BAD_RESPONSE:
  492. default:
  493. LM_ERR("probable invalid query, execution aborted\n");
  494. LM_ERR("driver message: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  495. db_free_result(*_r);
  496. *_r = 0;
  497. rc = -4;
  498. break;
  499. }
  500. done:
  501. db_postgres_free_query(_con);
  502. return (rc);
  503. }
  504. /*!
  505. * \brief Insert a row into specified table
  506. * \param _h structure representing database connection
  507. * \param _k key names
  508. * \param _v values of the keys
  509. * \param _n number of key=value pairs
  510. * \return 0 on success, negative on failure
  511. */
  512. int db_postgres_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  513. const int _n)
  514. {
  515. db1_res_t* _r = NULL;
  516. int ret = db_do_insert(_h, _k, _v, _n, db_postgres_val2str, db_postgres_submit_query);
  517. // finish the async query, otherwise the next query will not complete
  518. int tmp = db_postgres_store_result(_h, &_r);
  519. if (tmp < 0) {
  520. LM_WARN("unexpected result returned");
  521. ret = tmp;
  522. }
  523. if (_r)
  524. db_free_result(_r);
  525. return ret;
  526. }
  527. /*!
  528. * \brief Delete a row from the specified table
  529. * \param _h structure representing database connection
  530. * \param _k key names
  531. * \param _o operators
  532. * \param _v values of the keys that must match
  533. * \param _n number of key=value pairs
  534. * \return 0 on success, negative on failure
  535. */
  536. int db_postgres_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  537. const db_val_t* _v, const int _n)
  538. {
  539. db1_res_t* _r = NULL;
  540. int ret = db_do_delete(_h, _k, _o, _v, _n, db_postgres_val2str,
  541. db_postgres_submit_query);
  542. int tmp = db_postgres_store_result(_h, &_r);
  543. if (tmp < 0) {
  544. LM_WARN("unexpected result returned");
  545. ret = tmp;
  546. }
  547. if (_r)
  548. db_free_result(_r);
  549. return ret;
  550. }
  551. /*!
  552. * Update some rows in the specified table
  553. * \param _h structure representing database connection
  554. * \param _k key names
  555. * \param _o operators
  556. * \param _v values of the keys that must match
  557. * \param _uk updated columns
  558. * \param _uv updated values of the columns
  559. * \param _n number of key=value pairs
  560. * \param _un number of columns to update
  561. * \return 0 on success, negative on failure
  562. */
  563. int db_postgres_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  564. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  565. const int _un)
  566. {
  567. db1_res_t* _r = NULL;
  568. int ret = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_postgres_val2str,
  569. db_postgres_submit_query);
  570. int tmp = db_postgres_store_result(_h, &_r);
  571. if (tmp < 0) {
  572. LM_WARN("unexpected result returned");
  573. ret = tmp;
  574. }
  575. if (_r)
  576. db_free_result(_r);
  577. return ret;
  578. }
  579. /**
  580. * Returns the affected rows of the last query.
  581. * \param _h database handle
  582. * \return returns the affected rows as integer or -1 on error.
  583. */
  584. int db_postgres_affected_rows(const db1_con_t* _h)
  585. {
  586. if (!_h) {
  587. LM_ERR("invalid parameter value\n");
  588. return -1;
  589. }
  590. return CON_AFFECTED(_h);
  591. }
  592. /**
  593. * Starts a single transaction that will consist of one or more queries (SQL BEGIN)
  594. * \param _h database handle
  595. * \return 0 on success, negative on failure
  596. */
  597. int db_postgres_start_transaction(db1_con_t* _h, db_locking_t _l)
  598. {
  599. db1_res_t *res = NULL;
  600. str begin_str = str_init("BEGIN");
  601. str lock_start_str = str_init("LOCK TABLE ");
  602. str lock_write_end_str = str_init(" IN EXCLUSIVE MODE");
  603. str lock_full_end_str = str_init(" IN ACCESS EXCLUSIVE MODE");
  604. str *lock_end_str = &lock_write_end_str;
  605. str lock_str = {0, 0};
  606. if (!_h) {
  607. LM_ERR("invalid parameter value\n");
  608. return -1;
  609. }
  610. if (CON_TRANSACTION(_h) == 1) {
  611. LM_ERR("transaction already started\n");
  612. return -1;
  613. }
  614. if (db_postgres_raw_query(_h, &begin_str, &res) < 0)
  615. {
  616. LM_ERR("executing raw_query\n");
  617. return -1;
  618. }
  619. if (res) db_postgres_free_result(_h, res);
  620. CON_TRANSACTION(_h) = 1;
  621. switch(_l)
  622. {
  623. case DB_LOCKING_NONE:
  624. break;
  625. case DB_LOCKING_FULL:
  626. lock_end_str = &lock_full_end_str;
  627. /* Fall-thru */
  628. case DB_LOCKING_WRITE:
  629. if ((lock_str.s = pkg_malloc((lock_start_str.len + CON_TABLE(_h)->len + lock_end_str->len) * sizeof(char))) == NULL)
  630. {
  631. LM_ERR("allocating pkg memory\n");
  632. goto error;
  633. }
  634. memcpy(lock_str.s, lock_start_str.s, lock_start_str.len);
  635. lock_str.len += lock_start_str.len;
  636. memcpy(lock_str.s + lock_str.len, CON_TABLE(_h)->s, CON_TABLE(_h)->len);
  637. lock_str.len += CON_TABLE(_h)->len;
  638. memcpy(lock_str.s + lock_str.len, lock_end_str->s, lock_end_str->len);
  639. lock_str.len += lock_end_str->len;
  640. if (db_postgres_raw_query(_h, &lock_str, &res) < 0)
  641. {
  642. LM_ERR("executing raw_query\n");
  643. goto error;
  644. }
  645. if (res) db_postgres_free_result(_h, res);
  646. if (lock_str.s) pkg_free(lock_str.s);
  647. break;
  648. default:
  649. LM_WARN("unrecognised lock type\n");
  650. goto error;
  651. }
  652. return 0;
  653. error:
  654. if (lock_str.s) pkg_free(lock_str.s);
  655. db_postgres_abort_transaction(_h);
  656. return -1;
  657. }
  658. /**
  659. * Ends a transaction and commits the changes (SQL COMMIT)
  660. * \param _h database handle
  661. * \return 0 on success, negative on failure
  662. */
  663. int db_postgres_end_transaction(db1_con_t* _h)
  664. {
  665. db1_res_t *res = NULL;
  666. str query_str = str_init("COMMIT");
  667. if (!_h) {
  668. LM_ERR("invalid parameter value\n");
  669. return -1;
  670. }
  671. if (CON_TRANSACTION(_h) == 0) {
  672. LM_ERR("transaction not in progress\n");
  673. return -1;
  674. }
  675. if (db_postgres_raw_query(_h, &query_str, &res) < 0)
  676. {
  677. LM_ERR("executing raw_query\n");
  678. return -1;
  679. }
  680. if (res) db_postgres_free_result(_h, res);
  681. /* Only _end_ the transaction after the raw_query. That way, if the
  682. raw_query fails, and the calling module does an abort_transaction()
  683. to clean-up, a ROLLBACK will be sent to the DB. */
  684. CON_TRANSACTION(_h) = 0;
  685. return 0;
  686. }
  687. /**
  688. * Ends a transaction and rollsback the changes (SQL ROLLBACK)
  689. * \param _h database handle
  690. * \return 1 if there was something to rollback, 0 if not, negative on failure
  691. */
  692. int db_postgres_abort_transaction(db1_con_t* _h)
  693. {
  694. db1_res_t *res = NULL;
  695. str query_str = str_init("ROLLBACK");
  696. if (!_h) {
  697. LM_ERR("invalid parameter value\n");
  698. return -1;
  699. }
  700. if (CON_TRANSACTION(_h) == 0) {
  701. LM_DBG("nothing to rollback\n");
  702. return 0;
  703. }
  704. /* Whether the rollback succeeds or not we need to _end_ the
  705. transaction now or all future starts will fail */
  706. CON_TRANSACTION(_h) = 0;
  707. if (db_postgres_raw_query(_h, &query_str, &res) < 0)
  708. {
  709. LM_ERR("executing raw_query\n");
  710. return -1;
  711. }
  712. if (res) db_postgres_free_result(_h, res);
  713. return 1;
  714. }
  715. /*!
  716. * Store name of table that will be used by subsequent database functions
  717. * \param _con database connection
  718. * \param _t table name
  719. * \return 0 on success, negative on error
  720. */
  721. int db_postgres_use_table(db1_con_t* _con, const str* _t)
  722. {
  723. return db_use_table(_con, _t);
  724. }
  725. /*!
  726. * \brief SQL REPLACE implementation
  727. * \param _h structure representing database connection
  728. * \param _k key names
  729. * \param _v values of the keys
  730. * \param _n number of key=value pairs
  731. * \param _un number of keys to build the unique key, starting from first
  732. * \param _m mode - first update, then insert, or first insert, then update
  733. * \return 0 on success, negative on failure
  734. */
  735. int db_postgres_replace(const db1_con_t* _h, const db_key_t* _k,
  736. const db_val_t* _v, const int _n, const int _un, const int _m)
  737. {
  738. unsigned int pos = 0;
  739. int i;
  740. if(_un > _n)
  741. {
  742. LM_ERR("number of columns for unique key is too high\n");
  743. return -1;
  744. }
  745. if(_un > 0)
  746. {
  747. for(i=0; i<_un; i++)
  748. {
  749. if(!VAL_NULL(&_v[i]))
  750. {
  751. switch(VAL_TYPE(&_v[i]))
  752. {
  753. case DB1_INT:
  754. pos += VAL_UINT(&_v[i]);
  755. break;
  756. case DB1_STR:
  757. pos += get_hash1_raw((VAL_STR(&_v[i])).s,
  758. (VAL_STR(&_v[i])).len);
  759. break;
  760. case DB1_STRING:
  761. pos += get_hash1_raw(VAL_STRING(&_v[i]),
  762. strlen(VAL_STRING(&_v[i])));
  763. break;
  764. default:
  765. break;
  766. }
  767. }
  768. }
  769. pos &= (_pg_lock_size-1);
  770. lock_set_get(_pg_lock_set, pos);
  771. if(db_postgres_update(_h, _k, 0, _v, _k + _un,
  772. _v + _un, _un, _n -_un)< 0)
  773. {
  774. LM_ERR("update failed\n");
  775. lock_set_release(_pg_lock_set, pos);
  776. return -1;
  777. }
  778. if (db_postgres_affected_rows(_h) <= 0)
  779. {
  780. if(db_postgres_insert(_h, _k, _v, _n)< 0)
  781. {
  782. LM_ERR("insert failed\n");
  783. lock_set_release(_pg_lock_set, pos);
  784. return -1;
  785. }
  786. LM_DBG("inserted new record in database table\n");
  787. } else {
  788. LM_DBG("updated record in database table\n");
  789. }
  790. lock_set_release(_pg_lock_set, pos);
  791. } else {
  792. if(db_postgres_insert(_h, _k, _v, _n)< 0)
  793. {
  794. LM_ERR("direct insert failed\n");
  795. return -1;
  796. }
  797. LM_DBG("directly inserted new record in database table\n");
  798. }
  799. return 0;
  800. }