km_dbase.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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, 0);
  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_init_nopool(const str* _url)
  133. {
  134. return db_do_init(_url, (void*) db_postgres_new_connection, 1);
  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. int i;
  154. ExecStatusType pqresult;
  155. if(! _con || !_s || !_s->s)
  156. {
  157. LM_ERR("invalid parameter value\n");
  158. return(-1);
  159. }
  160. /* this bit of nonsense in case our connection get screwed up */
  161. switch(PQstatus(CON_CONNECTION(_con)))
  162. {
  163. case CONNECTION_OK:
  164. break;
  165. case CONNECTION_BAD:
  166. LM_DBG("connection reset\n");
  167. PQreset(CON_CONNECTION(_con));
  168. break;
  169. case CONNECTION_STARTED:
  170. case CONNECTION_MADE:
  171. case CONNECTION_AWAITING_RESPONSE:
  172. case CONNECTION_AUTH_OK:
  173. case CONNECTION_SETENV:
  174. case CONNECTION_SSL_STARTUP:
  175. case CONNECTION_NEEDED:
  176. default:
  177. LM_ERR("%p PQstatus(%s) invalid: %.*s\n", _con,
  178. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  179. return -1;
  180. }
  181. for(i = 0; i <= pg_retries; i++) {
  182. /* free any previous query that is laying about */
  183. db_postgres_free_query(_con);
  184. /* exec the query */
  185. if (PQsendQuery(CON_CONNECTION(_con), _s->s)) {
  186. pqresult = PQresultStatus(CON_RESULT(_con));
  187. if((pqresult!=PGRES_FATAL_ERROR)
  188. || (PQstatus(CON_CONNECTION(_con))==CONNECTION_OK))
  189. {
  190. LM_DBG("sending query ok: %p (%d) - [%.*s]\n",
  191. _con, pqresult, _s->len, _s->s);
  192. return 0;
  193. }
  194. LM_WARN("postgres result check failed with code %d (%s)\n",
  195. pqresult, PQresStatus(pqresult));
  196. }
  197. LM_WARN("postgres query command failed, connection status %d,"
  198. " error [%s]\n", PQstatus(CON_CONNECTION(_con)),
  199. PQerrorMessage(CON_CONNECTION(_con)));
  200. if(PQstatus(CON_CONNECTION(_con))!=CONNECTION_OK)
  201. {
  202. LM_DBG("reseting the connection to postgress server\n");
  203. PQreset(CON_CONNECTION(_con));
  204. }
  205. }
  206. LM_ERR("%p PQsendQuery Error: %s Query: %.*s\n", _con,
  207. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  208. return -1;
  209. }
  210. /*!
  211. * \brief Gets a partial result set, fetch rows from a result
  212. *
  213. * Gets a partial result set, fetch a number of rows from a database result.
  214. * This function initialize the given result structure on the first run, and
  215. * fetches the nrows number of rows. On subsequenting runs, it uses the
  216. * existing result and fetches more rows, until it reaches the end of the
  217. * result set. Because of this the result needs to be null in the first
  218. * invocation of the function. If the number of wanted rows is zero, the
  219. * function returns anything with a result of zero.
  220. * \param _con database connection
  221. * \param _res result set
  222. * \param nrows number of fetches rows
  223. * \return 0 on success, negative on failure
  224. */
  225. int db_postgres_fetch_result(const db1_con_t* _con, db1_res_t** _res, const int nrows)
  226. {
  227. int rows;
  228. PGresult *res = NULL;
  229. ExecStatusType pqresult;
  230. if (!_con || !_res || nrows < 0) {
  231. LM_ERR("invalid parameter value\n");
  232. return -1;
  233. }
  234. /* exit if the fetch count is zero */
  235. if (nrows == 0) {
  236. if (*_res)
  237. db_free_result(*_res);
  238. *_res = 0;
  239. return 0;
  240. }
  241. if (*_res == NULL) {
  242. /* Allocate a new result structure */
  243. *_res = db_new_result();
  244. /* Get the result of the previous query */
  245. while (1) {
  246. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  247. CON_RESULT(_con) = res;
  248. } else {
  249. break;
  250. }
  251. }
  252. pqresult = PQresultStatus(CON_RESULT(_con));
  253. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  254. PQresStatus(pqresult), CON_RESULT(_con));
  255. switch(pqresult) {
  256. case PGRES_COMMAND_OK:
  257. /* Successful completion of a command returning no data
  258. * (such as INSERT or UPDATE). */
  259. return 0;
  260. case PGRES_TUPLES_OK:
  261. /* Successful completion of a command returning data
  262. * (such as a SELECT or SHOW). */
  263. if (db_postgres_get_columns(_con, *_res) < 0) {
  264. LM_ERR("failed to get column names\n");
  265. return -2;
  266. }
  267. break;
  268. case PGRES_FATAL_ERROR:
  269. LM_ERR("%p - invalid query, execution aborted\n", _con);
  270. LM_ERR("%p - PQresultStatus(%s)\n", _con,
  271. PQresStatus(pqresult));
  272. LM_ERR("%p: %s\n", _con,
  273. PQresultErrorMessage(CON_RESULT(_con)));
  274. if (*_res)
  275. db_free_result(*_res);
  276. *_res = 0;
  277. return -3;
  278. case PGRES_EMPTY_QUERY:
  279. /* notice or warning */
  280. case PGRES_NONFATAL_ERROR:
  281. /* status for COPY command, not used */
  282. case PGRES_COPY_OUT:
  283. case PGRES_COPY_IN:
  284. /* unexpected response */
  285. case PGRES_BAD_RESPONSE:
  286. default:
  287. LM_ERR("%p - probable invalid query\n", _con);
  288. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  289. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  290. if (*_res)
  291. db_free_result(*_res);
  292. *_res = 0;
  293. return -4;
  294. }
  295. } else {
  296. if(RES_ROWS(*_res) != NULL) {
  297. db_free_rows(*_res);
  298. }
  299. RES_ROWS(*_res) = 0;
  300. RES_ROW_N(*_res) = 0;
  301. }
  302. /* Get the number of rows (tuples) in the query result. */
  303. RES_NUM_ROWS(*_res) = PQntuples(CON_RESULT(_con));
  304. /* determine the number of rows remaining to be processed */
  305. rows = RES_NUM_ROWS(*_res) - RES_LAST_ROW(*_res);
  306. /* If there aren't any more rows left to process, exit */
  307. if (rows <= 0)
  308. return 0;
  309. /* if the fetch count is less than the remaining rows to process */
  310. /* set the number of rows to process (during this call) equal to the fetch count */
  311. if (nrows < rows)
  312. rows = nrows;
  313. RES_ROW_N(*_res) = rows;
  314. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_res),
  315. RES_NUM_ROWS(*_res), RES_ROW_N(*_res));
  316. if (db_postgres_convert_rows(_con, *_res) < 0) {
  317. LM_ERR("failed to convert rows\n");
  318. if (*_res)
  319. db_free_result(*_res);
  320. *_res = 0;
  321. return -3;
  322. }
  323. /* update the total number of rows processed */
  324. RES_LAST_ROW(*_res) += rows;
  325. return 0;
  326. }
  327. /*!
  328. * \brief Free database and any old query results
  329. * \param _con database connection
  330. */
  331. static void db_postgres_free_query(const db1_con_t* _con)
  332. {
  333. if(CON_RESULT(_con))
  334. {
  335. LM_DBG("PQclear(%p) result set\n", CON_RESULT(_con));
  336. PQclear(CON_RESULT(_con));
  337. CON_RESULT(_con) = 0;
  338. }
  339. }
  340. /*!
  341. * \brief Free the query and the result memory in the core
  342. * \param _con database connection
  343. * \param _r result set
  344. * \return 0 on success, -1 on failure
  345. */
  346. int db_postgres_free_result(db1_con_t* _con, db1_res_t* _r)
  347. {
  348. if ((!_con) || (!_r)) {
  349. LM_ERR("invalid parameter value\n");
  350. return -1;
  351. }
  352. if (db_free_result(_r) < 0) {
  353. LM_ERR("unable to free result structure\n");
  354. return -1;
  355. }
  356. db_postgres_free_query(_con);
  357. return 0;
  358. }
  359. /*!
  360. * \brief Query table for specified rows
  361. * \param _h structure representing database connection
  362. * \param _k key names
  363. * \param _op operators
  364. * \param _v values of the keys that must match
  365. * \param _c column names to return
  366. * \param _n nmber of key=values pairs to compare
  367. * \param _nc number of columns to return
  368. * \param _o order by the specified column
  369. * \param _r result set
  370. * \return 0 on success, negative on failure
  371. */
  372. int db_postgres_query(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  373. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  374. const db_key_t _o, db1_res_t** _r)
  375. {
  376. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  377. db_postgres_submit_query, db_postgres_store_result);
  378. }
  379. /*!
  380. * Execute a raw SQL query
  381. * \param _h database connection
  382. * \param _s raw query string
  383. * \param _r result set
  384. * \return 0 on success, negative on failure
  385. */
  386. int db_postgres_raw_query(const db1_con_t* _h, const str* _s, db1_res_t** _r)
  387. {
  388. return db_do_raw_query(_h, _s, _r, db_postgres_submit_query,
  389. db_postgres_store_result);
  390. }
  391. /*!
  392. * \brief Retrieve result set
  393. * \param _con structure representing the database connection
  394. * \param _r pointer to a structure represending the result set
  395. * \return 0 If the status of the last command produced a result set and,
  396. * If the result set contains data or the convert_result() routine
  397. * completed successfully. Negative if the status of the last command was
  398. * not handled or if the convert_result() returned an error.
  399. * \note A new result structure is allocated on every call to this routine.
  400. * If this routine returns 0, it is the callers responsbility to free the
  401. * result structure. If this routine returns < 0, then the result structure
  402. * is freed before returning to the caller.
  403. */
  404. int db_postgres_store_result(const db1_con_t* _con, db1_res_t** _r)
  405. {
  406. PGresult *res = NULL;
  407. ExecStatusType pqresult;
  408. int rc = 0;
  409. *_r = db_new_result();
  410. if (*_r==NULL) {
  411. LM_ERR("failed to init new result\n");
  412. rc = -1;
  413. goto done;
  414. }
  415. while (1) {
  416. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  417. CON_RESULT(_con) = res;
  418. } else {
  419. break;
  420. }
  421. }
  422. pqresult = PQresultStatus(CON_RESULT(_con));
  423. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  424. PQresStatus(pqresult), CON_RESULT(_con));
  425. CON_AFFECTED(_con) = 0;
  426. switch(pqresult) {
  427. case PGRES_COMMAND_OK:
  428. /* Successful completion of a command returning no data
  429. * (such as INSERT or UPDATE). */
  430. rc = 0;
  431. CON_AFFECTED(_con) = atoi(PQcmdTuples(CON_RESULT(_con)));
  432. break;
  433. case PGRES_TUPLES_OK:
  434. /* Successful completion of a command returning data
  435. * (such as a SELECT or SHOW). */
  436. if (db_postgres_convert_result(_con, *_r) < 0) {
  437. LM_ERR("error while converting result\n");
  438. LM_DBG("freeing result set at %p\n", _r);
  439. pkg_free(*_r);
  440. *_r = 0;
  441. rc = -4;
  442. break;
  443. }
  444. rc = 0;
  445. CON_AFFECTED(_con) = atoi(PQcmdTuples(CON_RESULT(_con)));
  446. break;
  447. /* query failed */
  448. case PGRES_FATAL_ERROR:
  449. LM_ERR("invalid query, execution aborted\n");
  450. LM_ERR("driver error: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  451. db_free_result(*_r);
  452. *_r = 0;
  453. rc = -3;
  454. break;
  455. case PGRES_EMPTY_QUERY:
  456. /* notice or warning */
  457. case PGRES_NONFATAL_ERROR:
  458. /* status for COPY command, not used */
  459. case PGRES_COPY_OUT:
  460. case PGRES_COPY_IN:
  461. /* unexpected response */
  462. case PGRES_BAD_RESPONSE:
  463. default:
  464. LM_ERR("probable invalid query, execution aborted\n");
  465. LM_ERR("driver message: %s, %s\n", PQresStatus(pqresult), PQresultErrorMessage(CON_RESULT(_con)));
  466. db_free_result(*_r);
  467. *_r = 0;
  468. rc = -4;
  469. break;
  470. }
  471. done:
  472. db_postgres_free_query(_con);
  473. return (rc);
  474. }
  475. /*!
  476. * \brief Insert a row into specified table
  477. * \param _h structure representing database connection
  478. * \param _k key names
  479. * \param _v values of the keys
  480. * \param _n number of key=value pairs
  481. * \return 0 on success, negative on failure
  482. */
  483. int db_postgres_insert(const db1_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  484. const int _n)
  485. {
  486. db1_res_t* _r = NULL;
  487. int tmp = db_do_insert(_h, _k, _v, _n, db_postgres_val2str, db_postgres_submit_query);
  488. // finish the async query, otherwise the next query will not complete
  489. if (db_postgres_store_result(_h, &_r) != 0)
  490. LM_WARN("unexpected result returned");
  491. if (_r)
  492. db_free_result(_r);
  493. return tmp;
  494. }
  495. /*!
  496. * \brief Delete a row from the specified table
  497. * \param _h structure representing database connection
  498. * \param _k key names
  499. * \param _o operators
  500. * \param _v values of the keys that must match
  501. * \param _n number of key=value pairs
  502. * \return 0 on success, negative on failure
  503. */
  504. int db_postgres_delete(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  505. const db_val_t* _v, const int _n)
  506. {
  507. db1_res_t* _r = NULL;
  508. int tmp = db_do_delete(_h, _k, _o, _v, _n, db_postgres_val2str,
  509. db_postgres_submit_query);
  510. if (db_postgres_store_result(_h, &_r) != 0)
  511. LM_WARN("unexpected result returned");
  512. if (_r)
  513. db_free_result(_r);
  514. return tmp;
  515. }
  516. /*!
  517. * Update some rows in the specified table
  518. * \param _h structure representing database connection
  519. * \param _k key names
  520. * \param _o operators
  521. * \param _v values of the keys that must match
  522. * \param _uk updated columns
  523. * \param _uv updated values of the columns
  524. * \param _n number of key=value pairs
  525. * \param _un number of columns to update
  526. * \return 0 on success, negative on failure
  527. */
  528. int db_postgres_update(const db1_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  529. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  530. const int _un)
  531. {
  532. db1_res_t* _r = NULL;
  533. int tmp = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_postgres_val2str,
  534. db_postgres_submit_query);
  535. if (db_postgres_store_result(_h, &_r) != 0)
  536. LM_WARN("unexpected result returned");
  537. if (_r)
  538. db_free_result(_r);
  539. return tmp;
  540. }
  541. /**
  542. * Returns the affected rows of the last query.
  543. * \param _h database handle
  544. * \return returns the affected rows as integer or -1 on error.
  545. */
  546. int db_postgres_affected_rows(const db1_con_t* _h)
  547. {
  548. if (!_h) {
  549. LM_ERR("invalid parameter value\n");
  550. return -1;
  551. }
  552. return CON_AFFECTED(_h);
  553. }
  554. /*!
  555. * Store name of table that will be used by subsequent database functions
  556. * \param _con database connection
  557. * \param _t table name
  558. * \return 0 on success, negative on error
  559. */
  560. int db_postgres_use_table(db1_con_t* _con, const str* _t)
  561. {
  562. return db_use_table(_con, _t);
  563. }
  564. /*!
  565. * \brief SQL REPLACE implementation
  566. * \param _h structure representing database connection
  567. * \param _k key names
  568. * \param _v values of the keys
  569. * \param _n number of key=value pairs
  570. * \param _un number of keys to build the unique key, starting from first
  571. * \param _m mode - first update, then insert, or first insert, then update
  572. * \return 0 on success, negative on failure
  573. */
  574. int db_postgres_replace(const db1_con_t* _h, const db_key_t* _k,
  575. const db_val_t* _v, const int _n, const int _un, const int _m)
  576. {
  577. unsigned int pos = 0;
  578. int i;
  579. if(_un > _n)
  580. {
  581. LM_ERR("number of columns for unique key is too high\n");
  582. return -1;
  583. }
  584. if(_un > 0)
  585. {
  586. for(i=0; i<_un; i++)
  587. {
  588. if(!VAL_NULL(&_v[i]))
  589. {
  590. switch(VAL_TYPE(&_v[i]))
  591. {
  592. case DB1_INT:
  593. pos += VAL_UINT(&_v[i]);
  594. break;
  595. case DB1_STR:
  596. pos += get_hash1_raw((VAL_STR(&_v[i])).s,
  597. (VAL_STR(&_v[i])).len);
  598. break;
  599. case DB1_STRING:
  600. pos += get_hash1_raw(VAL_STRING(&_v[i]),
  601. strlen(VAL_STRING(&_v[i])));
  602. break;
  603. default:
  604. break;
  605. }
  606. }
  607. }
  608. pos &= (_pg_lock_size-1);
  609. lock_set_get(_pg_lock_set, pos);
  610. if(db_postgres_update(_h, _k, 0, _v, _k + _un,
  611. _v + _un, _un, _n -_un)< 0)
  612. {
  613. LM_ERR("update failed\n");
  614. lock_set_release(_pg_lock_set, pos);
  615. return -1;
  616. }
  617. if (db_postgres_affected_rows(_h) <= 0)
  618. {
  619. if(db_postgres_insert(_h, _k, _v, _n)< 0)
  620. {
  621. LM_ERR("insert failed\n");
  622. lock_set_release(_pg_lock_set, pos);
  623. return -1;
  624. }
  625. LM_DBG("inserted new record in database table\n");
  626. } else {
  627. LM_DBG("updated record in database table\n");
  628. }
  629. lock_set_release(_pg_lock_set, pos);
  630. } else {
  631. if(db_postgres_insert(_h, _k, _v, _n)< 0)
  632. {
  633. LM_ERR("direct insert failed\n");
  634. return -1;
  635. }
  636. LM_DBG("directly inserted new record in database table\n");
  637. }
  638. return 0;
  639. }