km_dbase.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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. if(! _con || !_s || !_s->s)
  157. {
  158. LM_ERR("invalid parameter value\n");
  159. return(-1);
  160. }
  161. /* this bit of nonsense in case our connection get screwed up */
  162. switch(PQstatus(CON_CONNECTION(_con)))
  163. {
  164. case CONNECTION_OK:
  165. break;
  166. case CONNECTION_BAD:
  167. LM_DBG("connection reset\n");
  168. PQreset(CON_CONNECTION(_con));
  169. break;
  170. case CONNECTION_STARTED:
  171. case CONNECTION_MADE:
  172. case CONNECTION_AWAITING_RESPONSE:
  173. case CONNECTION_AUTH_OK:
  174. case CONNECTION_SETENV:
  175. case CONNECTION_SSL_STARTUP:
  176. case CONNECTION_NEEDED:
  177. default:
  178. LM_ERR("%p PQstatus(%s) invalid: %.*s\n", _con,
  179. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  180. return -1;
  181. }
  182. if (CON_TRANSACTION(_con) == 1)
  183. retries = 0;
  184. else
  185. retries = pg_retries;
  186. s = pkg_malloc((_s->len+1)*sizeof(char));
  187. if (s==NULL)
  188. {
  189. LM_ERR("%p db_postgres_submit_query Out of Memory: Query: %.*s\n", _con, _s->len, _s->s);
  190. return -1;
  191. }
  192. memcpy( s, _s->s, _s->len );
  193. s[_s->len] = '\0';
  194. for(i = 0; i <= retries; i++) {
  195. /* free any previous query that is laying about */
  196. db_postgres_free_query(_con);
  197. /* exec the query */
  198. if (PQsendQuery(CON_CONNECTION(_con), s)) {
  199. pqresult = PQresultStatus(CON_RESULT(_con));
  200. if((pqresult!=PGRES_FATAL_ERROR)
  201. || (PQstatus(CON_CONNECTION(_con))==CONNECTION_OK))
  202. {
  203. LM_DBG("sending query ok: %p (%d) - [%.*s]\n",
  204. _con, pqresult, _s->len, _s->s);
  205. pkg_free(s);
  206. return 0;
  207. }
  208. LM_WARN("postgres result check failed with code %d (%s)\n",
  209. pqresult, PQresStatus(pqresult));
  210. }
  211. LM_WARN("postgres query command failed, connection status %d,"
  212. " error [%s]\n", PQstatus(CON_CONNECTION(_con)),
  213. PQerrorMessage(CON_CONNECTION(_con)));
  214. if(PQstatus(CON_CONNECTION(_con))!=CONNECTION_OK)
  215. {
  216. LM_DBG("reseting the connection to postgress server\n");
  217. PQreset(CON_CONNECTION(_con));
  218. }
  219. }
  220. LM_ERR("%p PQsendQuery Error: %s Query: %.*s\n", _con,
  221. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  222. pkg_free(s);
  223. return -1;
  224. }
  225. /*!
  226. * \brief Gets a partial result set, fetch rows from a result
  227. *
  228. * Gets a partial result set, fetch a number of rows from a database result.
  229. * This function initialize the given result structure on the first run, and
  230. * fetches the nrows number of rows. On subsequenting runs, it uses the
  231. * existing result and fetches more rows, until it reaches the end of the
  232. * result set. Because of this the result needs to be null in the first
  233. * invocation of the function. If the number of wanted rows is zero, the
  234. * function returns anything with a result of zero.
  235. * \param _con database connection
  236. * \param _res result set
  237. * \param nrows number of fetches rows
  238. * \return 0 on success, negative on failure
  239. */
  240. int db_postgres_fetch_result(const db1_con_t* _con, db1_res_t** _res, const int nrows)
  241. {
  242. int rows;
  243. PGresult *res = NULL;
  244. ExecStatusType pqresult;
  245. if (!_con || !_res || nrows < 0) {
  246. LM_ERR("invalid parameter value\n");
  247. return -1;
  248. }
  249. /* exit if the fetch count is zero */
  250. if (nrows == 0) {
  251. if (*_res)
  252. db_free_result(*_res);
  253. *_res = 0;
  254. return 0;
  255. }
  256. if (*_res == NULL) {
  257. /* Allocate a new result structure */
  258. *_res = db_new_result();
  259. /* Get the result of the previous query */
  260. while (1) {
  261. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  262. CON_RESULT(_con) = res;
  263. } else {
  264. break;
  265. }
  266. }
  267. pqresult = PQresultStatus(CON_RESULT(_con));
  268. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  269. PQresStatus(pqresult), CON_RESULT(_con));
  270. switch(pqresult) {
  271. case PGRES_COMMAND_OK:
  272. /* Successful completion of a command returning no data
  273. * (such as INSERT or UPDATE). */
  274. return 0;
  275. case PGRES_TUPLES_OK:
  276. /* Successful completion of a command returning data
  277. * (such as a SELECT or SHOW). */
  278. if (db_postgres_get_columns(_con, *_res) < 0) {
  279. LM_ERR("failed to get column names\n");
  280. return -2;
  281. }
  282. break;
  283. case PGRES_FATAL_ERROR:
  284. LM_ERR("%p - invalid query, execution aborted\n", _con);
  285. LM_ERR("%p - PQresultStatus(%s)\n", _con,
  286. PQresStatus(pqresult));
  287. LM_ERR("%p: %s\n", _con,
  288. PQresultErrorMessage(CON_RESULT(_con)));
  289. if (*_res)
  290. db_free_result(*_res);
  291. *_res = 0;
  292. return -3;
  293. case PGRES_EMPTY_QUERY:
  294. /* notice or warning */
  295. case PGRES_NONFATAL_ERROR:
  296. /* status for COPY command, not used */
  297. case PGRES_COPY_OUT:
  298. case PGRES_COPY_IN:
  299. /* unexpected response */
  300. case PGRES_BAD_RESPONSE:
  301. default:
  302. LM_ERR("%p - probable invalid query\n", _con);
  303. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  304. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  305. if (*_res)
  306. db_free_result(*_res);
  307. *_res = 0;
  308. return -4;
  309. }
  310. } else {
  311. if(RES_ROWS(*_res) != NULL) {
  312. db_free_rows(*_res);
  313. }
  314. RES_ROWS(*_res) = 0;
  315. RES_ROW_N(*_res) = 0;
  316. }
  317. /* Get the number of rows (tuples) in the query result. */
  318. RES_NUM_ROWS(*_res) = PQntuples(CON_RESULT(_con));
  319. /* determine the number of rows remaining to be processed */
  320. rows = RES_NUM_ROWS(*_res) - RES_LAST_ROW(*_res);
  321. /* If there aren't any more rows left to process, exit */
  322. if (rows <= 0)
  323. return 0;
  324. /* if the fetch count is less than the remaining rows to process */
  325. /* set the number of rows to process (during this call) equal to the fetch count */
  326. if (nrows < rows)
  327. rows = nrows;
  328. RES_ROW_N(*_res) = rows;
  329. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_res),
  330. RES_NUM_ROWS(*_res), RES_ROW_N(*_res));
  331. if (db_postgres_convert_rows(_con, *_res) < 0) {
  332. LM_ERR("failed to convert rows\n");
  333. if (*_res)
  334. db_free_result(*_res);
  335. *_res = 0;
  336. return -3;
  337. }
  338. /* update the total number of rows processed */
  339. RES_LAST_ROW(*_res) += rows;
  340. return 0;
  341. }
  342. /*!
  343. * \brief Free database and any old query results
  344. * \param _con database connection
  345. */
  346. static void db_postgres_free_query(const db1_con_t* _con)
  347. {
  348. if(CON_RESULT(_con))
  349. {
  350. LM_DBG("PQclear(%p) result set\n", CON_RESULT(_con));
  351. PQclear(CON_RESULT(_con));
  352. CON_RESULT(_con) = 0;
  353. }
  354. }
  355. /*!
  356. * \brief Free the query and the result memory in the core
  357. * \param _con database connection
  358. * \param _r result set
  359. * \return 0 on success, -1 on failure
  360. */
  361. int db_postgres_free_result(db1_con_t* _con, db1_res_t* _r)
  362. {
  363. if ((!_con) || (!_r)) {
  364. LM_ERR("invalid parameter value\n");
  365. return -1;
  366. }
  367. if (db_free_result(_r) < 0) {
  368. LM_ERR("unable to free result structure\n");
  369. return -1;
  370. }
  371. db_postgres_free_query(_con);
  372. return 0;
  373. }
  374. /*!
  375. * \brief Query table for specified rows
  376. * \param _h structure representing database connection
  377. * \param _k key names
  378. * \param _op operators
  379. * \param _v values of the keys that must match
  380. * \param _c column names to return
  381. * \param _n nmber of key=values pairs to compare
  382. * \param _nc number of columns to return
  383. * \param _o order by the specified column
  384. * \param _r result set
  385. * \return 0 on success, negative on failure
  386. */
  387. int db_postgres_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  388. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  389. const db_key_t _o, db1_res_t** _r)
  390. {
  391. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  392. db_postgres_submit_query, db_postgres_store_result);
  393. }
  394. /*!
  395. * \brief Query table for specified rows and lock them
  396. * \param _h structure representing database connection
  397. * \param _k key names
  398. * \param _op operators
  399. * \param _v values of the keys that must match
  400. * \param _c column names to return
  401. * \param _n nmber of key=values pairs to compare
  402. * \param _nc number of columns to return
  403. * \param _o order by the specified column
  404. * \param _r result set
  405. * \return 0 on success, negative on failure
  406. */
  407. int db_postgres_query_lock(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  408. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  409. const db_key_t _o, db1_res_t** _r)
  410. {
  411. if (CON_TRANSACTION(_h) == 0)
  412. {
  413. LM_ERR("transaction not in progress\n");
  414. return -1;
  415. }
  416. return db_do_query_lock(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  417. db_postgres_submit_query, db_postgres_store_result);
  418. }
  419. /*!
  420. * Execute a raw SQL query
  421. * \param _h database connection
  422. * \param _s raw query string
  423. * \param _r result set
  424. * \return 0 on success, negative on failure
  425. */
  426. int db_postgres_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  427. {
  428. return db_do_raw_query(_h, _s, _r, db_postgres_submit_query,
  429. db_postgres_store_result);
  430. }
  431. /*!
  432. * \brief Retrieve result set
  433. * \param _con structure representing the database connection
  434. * \param _r pointer to a structure represending the result set
  435. * \return 0 If the status of the last command produced a result set and,
  436. * If the result set contains data or the convert_result() routine
  437. * completed successfully. Negative if the status of the last command was
  438. * not handled or if the convert_result() returned an error.
  439. * \note A new result structure is allocated on every call to this routine.
  440. * If this routine returns 0, it is the callers responsbility to free the
  441. * result structure. If this routine returns < 0, then the result structure
  442. * is freed before returning to the caller.
  443. */
  444. int db_postgres_store_result(const db1_con_t* _con, db1_res_t** _r)
  445. {
  446. PGresult *res = NULL;
  447. ExecStatusType pqresult;
  448. int rc = 0;
  449. *_r = db_new_result();
  450. if (*_r==NULL) {
  451. LM_ERR("failed to init new result\n");
  452. rc = -1;
  453. goto done;
  454. }
  455. while (1) {
  456. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  457. CON_RESULT(_con) = res;
  458. } else {
  459. break;
  460. }
  461. }
  462. pqresult = PQresultStatus(CON_RESULT(_con));
  463. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  464. PQresStatus(pqresult), CON_RESULT(_con));
  465. CON_AFFECTED(_con) = 0;
  466. switch(pqresult) {
  467. case PGRES_COMMAND_OK:
  468. /* Successful completion of a command returning no data
  469. * (such as INSERT or UPDATE). */
  470. rc = 0;
  471. CON_AFFECTED(_con) = atoi(PQcmdTuples(CON_RESULT(_con)));
  472. break;
  473. case PGRES_TUPLES_OK:
  474. /* Successful completion of a command returning data
  475. * (such as a SELECT or SHOW). */
  476. if (db_postgres_convert_result(_con, *_r) < 0) {
  477. LM_ERR("error while converting result\n");
  478. LM_DBG("freeing result set at %p\n", _r);
  479. pkg_free(*_r);
  480. *_r = 0;
  481. rc = -4;
  482. break;
  483. }
  484. rc = 0;
  485. CON_AFFECTED(_con) = atoi(PQcmdTuples(CON_RESULT(_con)));
  486. break;
  487. /* query failed */
  488. case PGRES_FATAL_ERROR:
  489. LM_ERR("invalid query, execution aborted\n");
  490. LM_ERR("driver error: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  491. db_free_result(*_r);
  492. *_r = 0;
  493. rc = -3;
  494. break;
  495. case PGRES_EMPTY_QUERY:
  496. /* notice or warning */
  497. case PGRES_NONFATAL_ERROR:
  498. /* status for COPY command, not used */
  499. case PGRES_COPY_OUT:
  500. case PGRES_COPY_IN:
  501. /* unexpected response */
  502. case PGRES_BAD_RESPONSE:
  503. default:
  504. LM_ERR("probable invalid query, execution aborted\n");
  505. LM_ERR("driver message: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  506. db_free_result(*_r);
  507. *_r = 0;
  508. rc = -4;
  509. break;
  510. }
  511. done:
  512. db_postgres_free_query(_con);
  513. return (rc);
  514. }
  515. /*!
  516. * \brief Insert a row into specified table
  517. * \param _h structure representing database connection
  518. * \param _k key names
  519. * \param _v values of the keys
  520. * \param _n number of key=value pairs
  521. * \return 0 on success, negative on failure
  522. */
  523. int db_postgres_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  524. const int _n)
  525. {
  526. db1_res_t* _r = NULL;
  527. int ret = db_do_insert(_h, _k, _v, _n, db_postgres_val2str, db_postgres_submit_query);
  528. // finish the async query, otherwise the next query will not complete
  529. int tmp = db_postgres_store_result(_h, &_r);
  530. if (tmp < 0) {
  531. LM_WARN("unexpected result returned");
  532. ret = tmp;
  533. }
  534. if (_r)
  535. db_free_result(_r);
  536. return ret;
  537. }
  538. /*!
  539. * \brief Delete a row from the specified table
  540. * \param _h structure representing database connection
  541. * \param _k key names
  542. * \param _o operators
  543. * \param _v values of the keys that must match
  544. * \param _n number of key=value pairs
  545. * \return 0 on success, negative on failure
  546. */
  547. int db_postgres_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  548. const db_val_t* _v, const int _n)
  549. {
  550. db1_res_t* _r = NULL;
  551. int ret = db_do_delete(_h, _k, _o, _v, _n, db_postgres_val2str,
  552. db_postgres_submit_query);
  553. int tmp = db_postgres_store_result(_h, &_r);
  554. if (tmp < 0) {
  555. LM_WARN("unexpected result returned");
  556. ret = tmp;
  557. }
  558. if (_r)
  559. db_free_result(_r);
  560. return ret;
  561. }
  562. /*!
  563. * Update some rows in the specified table
  564. * \param _h structure representing database connection
  565. * \param _k key names
  566. * \param _o operators
  567. * \param _v values of the keys that must match
  568. * \param _uk updated columns
  569. * \param _uv updated values of the columns
  570. * \param _n number of key=value pairs
  571. * \param _un number of columns to update
  572. * \return 0 on success, negative on failure
  573. */
  574. int db_postgres_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  575. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  576. const int _un)
  577. {
  578. db1_res_t* _r = NULL;
  579. int ret = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_postgres_val2str,
  580. db_postgres_submit_query);
  581. int tmp = db_postgres_store_result(_h, &_r);
  582. if (tmp < 0) {
  583. LM_WARN("unexpected result returned");
  584. ret = tmp;
  585. }
  586. if (_r)
  587. db_free_result(_r);
  588. return ret;
  589. }
  590. /**
  591. * Returns the affected rows of the last query.
  592. * \param _h database handle
  593. * \return returns the affected rows as integer or -1 on error.
  594. */
  595. int db_postgres_affected_rows(const db1_con_t* _h)
  596. {
  597. if (!_h) {
  598. LM_ERR("invalid parameter value\n");
  599. return -1;
  600. }
  601. return CON_AFFECTED(_h);
  602. }
  603. /**
  604. * Starts a single transaction that will consist of one or more queries (SQL BEGIN)
  605. * \param _h database handle
  606. * \return 0 on success, negative on failure
  607. */
  608. int db_postgres_start_transaction(db1_con_t* _h, db_locking_t _l)
  609. {
  610. db1_res_t *res = NULL;
  611. str begin_str = str_init("BEGIN");
  612. str lock_start_str = str_init("LOCK TABLE ");
  613. str lock_write_end_str = str_init(" IN EXCLUSIVE MODE");
  614. str lock_full_end_str = str_init(" IN ACCESS EXCLUSIVE MODE");
  615. str *lock_end_str = &lock_write_end_str;
  616. str lock_str = {0, 0};
  617. if (!_h) {
  618. LM_ERR("invalid parameter value\n");
  619. return -1;
  620. }
  621. if (CON_TRANSACTION(_h) == 1) {
  622. LM_ERR("transaction already started\n");
  623. return -1;
  624. }
  625. if (db_postgres_raw_query(_h, &begin_str, &res) < 0)
  626. {
  627. LM_ERR("executing raw_query\n");
  628. return -1;
  629. }
  630. if (res) db_postgres_free_result(_h, res);
  631. CON_TRANSACTION(_h) = 1;
  632. switch(_l)
  633. {
  634. case DB_LOCKING_NONE:
  635. break;
  636. case DB_LOCKING_FULL:
  637. lock_end_str = &lock_full_end_str;
  638. /* Fall-thru */
  639. case DB_LOCKING_WRITE:
  640. if ((lock_str.s = pkg_malloc((lock_start_str.len + CON_TABLE(_h)->len + lock_end_str->len) * sizeof(char))) == NULL)
  641. {
  642. LM_ERR("allocating pkg memory\n");
  643. goto error;
  644. }
  645. memcpy(lock_str.s, lock_start_str.s, lock_start_str.len);
  646. lock_str.len += lock_start_str.len;
  647. memcpy(lock_str.s + lock_str.len, CON_TABLE(_h)->s, CON_TABLE(_h)->len);
  648. lock_str.len += CON_TABLE(_h)->len;
  649. memcpy(lock_str.s + lock_str.len, lock_end_str->s, lock_end_str->len);
  650. lock_str.len += lock_end_str->len;
  651. if (db_postgres_raw_query(_h, &lock_str, &res) < 0)
  652. {
  653. LM_ERR("executing raw_query\n");
  654. goto error;
  655. }
  656. if (res) db_postgres_free_result(_h, res);
  657. if (lock_str.s) pkg_free(lock_str.s);
  658. break;
  659. default:
  660. LM_WARN("unrecognised lock type\n");
  661. goto error;
  662. }
  663. return 0;
  664. error:
  665. if (lock_str.s) pkg_free(lock_str.s);
  666. db_postgres_abort_transaction(_h);
  667. return -1;
  668. }
  669. /**
  670. * Ends a transaction and commits the changes (SQL COMMIT)
  671. * \param _h database handle
  672. * \return 0 on success, negative on failure
  673. */
  674. int db_postgres_end_transaction(db1_con_t* _h)
  675. {
  676. db1_res_t *res = NULL;
  677. str query_str = str_init("COMMIT");
  678. if (!_h) {
  679. LM_ERR("invalid parameter value\n");
  680. return -1;
  681. }
  682. if (CON_TRANSACTION(_h) == 0) {
  683. LM_ERR("transaction not in progress\n");
  684. return -1;
  685. }
  686. if (db_postgres_raw_query(_h, &query_str, &res) < 0)
  687. {
  688. LM_ERR("executing raw_query\n");
  689. return -1;
  690. }
  691. if (res) db_postgres_free_result(_h, res);
  692. /* Only _end_ the transaction after the raw_query. That way, if the
  693. raw_query fails, and the calling module does an abort_transaction()
  694. to clean-up, a ROLLBACK will be sent to the DB. */
  695. CON_TRANSACTION(_h) = 0;
  696. return 0;
  697. }
  698. /**
  699. * Ends a transaction and rollsback the changes (SQL ROLLBACK)
  700. * \param _h database handle
  701. * \return 1 if there was something to rollback, 0 if not, negative on failure
  702. */
  703. int db_postgres_abort_transaction(db1_con_t* _h)
  704. {
  705. db1_res_t *res = NULL;
  706. str query_str = str_init("ROLLBACK");
  707. if (!_h) {
  708. LM_ERR("invalid parameter value\n");
  709. return -1;
  710. }
  711. if (CON_TRANSACTION(_h) == 0) {
  712. LM_DBG("nothing to rollback\n");
  713. return 0;
  714. }
  715. /* Whether the rollback succeeds or not we need to _end_ the
  716. transaction now or all future starts will fail */
  717. CON_TRANSACTION(_h) = 0;
  718. if (db_postgres_raw_query(_h, &query_str, &res) < 0)
  719. {
  720. LM_ERR("executing raw_query\n");
  721. return -1;
  722. }
  723. if (res) db_postgres_free_result(_h, res);
  724. return 1;
  725. }
  726. /*!
  727. * Store name of table that will be used by subsequent database functions
  728. * \param _con database connection
  729. * \param _t table name
  730. * \return 0 on success, negative on error
  731. */
  732. int db_postgres_use_table(db1_con_t* _con, const str* _t)
  733. {
  734. return db_use_table(_con, _t);
  735. }
  736. /*!
  737. * \brief SQL REPLACE implementation
  738. * \param _h structure representing database connection
  739. * \param _k key names
  740. * \param _v values of the keys
  741. * \param _n number of key=value pairs
  742. * \param _un number of keys to build the unique key, starting from first
  743. * \param _m mode - first update, then insert, or first insert, then update
  744. * \return 0 on success, negative on failure
  745. */
  746. int db_postgres_replace(const db1_con_t* _h, const db_key_t* _k,
  747. const db_val_t* _v, const int _n, const int _un, const int _m)
  748. {
  749. unsigned int pos = 0;
  750. int i;
  751. if(_un > _n)
  752. {
  753. LM_ERR("number of columns for unique key is too high\n");
  754. return -1;
  755. }
  756. if(_un > 0)
  757. {
  758. for(i=0; i<_un; i++)
  759. {
  760. if(!VAL_NULL(&_v[i]))
  761. {
  762. switch(VAL_TYPE(&_v[i]))
  763. {
  764. case DB1_INT:
  765. pos += VAL_UINT(&_v[i]);
  766. break;
  767. case DB1_STR:
  768. pos += get_hash1_raw((VAL_STR(&_v[i])).s,
  769. (VAL_STR(&_v[i])).len);
  770. break;
  771. case DB1_STRING:
  772. pos += get_hash1_raw(VAL_STRING(&_v[i]),
  773. strlen(VAL_STRING(&_v[i])));
  774. break;
  775. default:
  776. break;
  777. }
  778. }
  779. }
  780. pos &= (_pg_lock_size-1);
  781. lock_set_get(_pg_lock_set, pos);
  782. if(db_postgres_update(_h, _k, 0, _v, _k + _un,
  783. _v + _un, _un, _n -_un)< 0)
  784. {
  785. LM_ERR("update failed\n");
  786. lock_set_release(_pg_lock_set, pos);
  787. return -1;
  788. }
  789. if (db_postgres_affected_rows(_h) <= 0)
  790. {
  791. if(db_postgres_insert(_h, _k, _v, _n)< 0)
  792. {
  793. LM_ERR("insert failed\n");
  794. lock_set_release(_pg_lock_set, pos);
  795. return -1;
  796. }
  797. LM_DBG("inserted new record in database table\n");
  798. } else {
  799. LM_DBG("updated record in database table\n");
  800. }
  801. lock_set_release(_pg_lock_set, pos);
  802. } else {
  803. if(db_postgres_insert(_h, _k, _v, _n)< 0)
  804. {
  805. LM_ERR("direct insert failed\n");
  806. return -1;
  807. }
  808. LM_DBG("directly inserted new record in database table\n");
  809. }
  810. return 0;
  811. }