km_dbase.c 20 KB

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