2
0

km_dbase.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 "../../dprint.h"
  70. #include "../../mem/mem.h"
  71. #include "../../db/db.h"
  72. #include "../../db/db_ut.h"
  73. #include "../../db/db_query.h"
  74. #include "dbase.h"
  75. #include "pg_con.h"
  76. #include "val.h"
  77. #include "res.h"
  78. static void free_query(const db_con_t* _con);
  79. /*!
  80. * \brief Initialize database for future queries
  81. * \param _url URL of the database that should be opened
  82. * \return database connection on success, NULL on error
  83. * \note this function must be called prior to any database functions
  84. */
  85. db_con_t *db_postgres_init(const str* _url)
  86. {
  87. return db_do_init(_url, (void*) db_postgres_new_connection);
  88. }
  89. /*!
  90. * \brief Close database when the database is no longer needed
  91. * \param _h closed connection, as returned from db_postgres_init
  92. * \note free all memory and resources
  93. */
  94. void db_postgres_close(db_con_t* _h)
  95. {
  96. db_do_close(_h, db_postgres_free_connection);
  97. }
  98. /*!
  99. * \brief Submit_query, run a query
  100. * \param _h database connection
  101. * \param _s query string
  102. * \return 0 on success, negative on failure
  103. */
  104. static int db_postgres_submit_query(const db_con_t* _con, const str* _s)
  105. {
  106. if(! _con || !_s || !_s->s)
  107. {
  108. LM_ERR("invalid parameter value\n");
  109. return(-1);
  110. }
  111. /* this bit of nonsense in case our connection get screwed up */
  112. switch(PQstatus(CON_CONNECTION(_con)))
  113. {
  114. case CONNECTION_OK:
  115. break;
  116. case CONNECTION_BAD:
  117. LM_DBG("connection reset\n");
  118. PQreset(CON_CONNECTION(_con));
  119. break;
  120. case CONNECTION_STARTED:
  121. case CONNECTION_MADE:
  122. case CONNECTION_AWAITING_RESPONSE:
  123. case CONNECTION_AUTH_OK:
  124. case CONNECTION_SETENV:
  125. case CONNECTION_SSL_STARTUP:
  126. case CONNECTION_NEEDED:
  127. default:
  128. LM_ERR("%p PQstatus(%s) invalid: %.*s\n", _con,
  129. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  130. return -1;
  131. }
  132. /* free any previous query that is laying about */
  133. if(CON_RESULT(_con))
  134. {
  135. free_query(_con);
  136. }
  137. /* exec the query */
  138. if (PQsendQuery(CON_CONNECTION(_con), _s->s)) {
  139. LM_DBG("%p PQsendQuery(%.*s)\n", _con, _s->len, _s->s);
  140. } else {
  141. LM_ERR("%p PQsendQuery Error: %s Query: %.*s\n", _con,
  142. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  143. return -1;
  144. }
  145. return 0;
  146. }
  147. /*!
  148. * \brief Gets a partial result set
  149. * \param _con database connection
  150. * \param _res result set
  151. * \param nrows number of fetches rows
  152. * \return 0 on success, negative on failure
  153. */
  154. int db_postgres_fetch_result(const db_con_t* _con, db_res_t** _res, const int nrows)
  155. {
  156. int rows;
  157. PGresult *res = NULL;
  158. ExecStatusType pqresult;
  159. if (!_con || !_res || nrows < 0) {
  160. LM_ERR("invalid parameter value\n");
  161. return -1;
  162. }
  163. /* exit if the fetch count is zero */
  164. if (nrows == 0) {
  165. if (*_res)
  166. db_free_result(*_res);
  167. *_res = 0;
  168. return 0;
  169. }
  170. if (*_res == NULL) {
  171. /* Allocate a new result structure */
  172. *_res = db_new_result();
  173. /* Get the result of the previous query */
  174. while (1) {
  175. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  176. CON_RESULT(_con) = res;
  177. } else {
  178. break;
  179. }
  180. }
  181. pqresult = PQresultStatus(CON_RESULT(_con));
  182. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  183. PQresStatus(pqresult), CON_RESULT(_con));
  184. switch(pqresult) {
  185. case PGRES_COMMAND_OK:
  186. /* Successful completion of a command returning no data (such as INSERT or UPDATE). */
  187. return 0;
  188. case PGRES_TUPLES_OK:
  189. /* Successful completion of a command returning data (such as a SELECT or SHOW). */
  190. if (db_postgres_get_columns(_con, *_res) < 0) {
  191. LM_ERR("failed to get column names\n");
  192. return -2;
  193. }
  194. break;
  195. case PGRES_FATAL_ERROR:
  196. LM_ERR("%p - invalid query, execution aborted\n", _con);
  197. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  198. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  199. if (*_res)
  200. db_free_result(*_res);
  201. *_res = 0;
  202. return -3;
  203. case PGRES_EMPTY_QUERY:
  204. /* notice or warning */
  205. case PGRES_NONFATAL_ERROR:
  206. /* status for COPY command, not used */
  207. case PGRES_COPY_OUT:
  208. case PGRES_COPY_IN:
  209. /* unexpected response */
  210. case PGRES_BAD_RESPONSE:
  211. default:
  212. LM_ERR("%p - probable invalid query\n", _con);
  213. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  214. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  215. if (*_res)
  216. db_free_result(*_res);
  217. *_res = 0;
  218. return -4;
  219. }
  220. } else {
  221. if(RES_ROWS(*_res) != NULL) {
  222. db_free_rows(*_res);
  223. }
  224. RES_ROWS(*_res) = 0;
  225. RES_ROW_N(*_res) = 0;
  226. }
  227. /* Get the number of rows (tuples) in the query result. */
  228. RES_NUM_ROWS(*_res) = PQntuples(CON_RESULT(_con));
  229. /* determine the number of rows remaining to be processed */
  230. rows = RES_NUM_ROWS(*_res) - RES_LAST_ROW(*_res);
  231. /* If there aren't any more rows left to process, exit */
  232. if (rows <= 0)
  233. return 0;
  234. /* if the fetch count is less than the remaining rows to process */
  235. /* set the number of rows to process (during this call) equal to the fetch count */
  236. if (nrows < rows)
  237. rows = nrows;
  238. RES_ROW_N(*_res) = rows;
  239. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_res),
  240. RES_NUM_ROWS(*_res), RES_ROW_N(*_res));
  241. if (db_postgres_convert_rows(_con, *_res) < 0) {
  242. LM_ERR("failed to convert rows\n");
  243. if (*_res)
  244. db_free_result(*_res);
  245. *_res = 0;
  246. return -3;
  247. }
  248. /* update the total number of rows processed */
  249. RES_LAST_ROW(*_res) += rows;
  250. return 0;
  251. }
  252. /*!
  253. * \brief Free database and any old query results
  254. * \param _h database connection
  255. */
  256. static void free_query(const db_con_t* _con)
  257. {
  258. if(CON_RESULT(_con))
  259. {
  260. LM_DBG("PQclear(%p) result set\n", CON_RESULT(_con));
  261. PQclear(CON_RESULT(_con));
  262. CON_RESULT(_con) = 0;
  263. }
  264. }
  265. /*!
  266. * \brief Free the query and the result memory in the core
  267. * \param _con database connection
  268. * \param _r result set
  269. * \return 0 on success, -1 on failure
  270. */
  271. int db_postgres_free_result(db_con_t* _con, db_res_t* _r)
  272. {
  273. if ((!_con) || (!_r)) {
  274. LM_ERR("invalid parameter value\n");
  275. return -1;
  276. }
  277. if (db_free_result(_r) < 0) {
  278. LM_ERR("unable to free result structure\n");
  279. return -1;
  280. }
  281. free_query(_con);
  282. return 0;
  283. }
  284. /*!
  285. * \brief Query table for specified rows
  286. * \param _con structure representing database connection
  287. * \param _k key names
  288. * \param _op operators
  289. * \param _v values of the keys that must match
  290. * \param _c column names to return
  291. * \param _n nmber of key=values pairs to compare
  292. * \param _nc number of columns to return
  293. * \param _o order by the specified column
  294. * \return 0 on success, negative on failure
  295. */
  296. int db_postgres_query(const db_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  297. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  298. const db_key_t _o, db_res_t** _r)
  299. {
  300. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  301. db_postgres_submit_query, db_postgres_store_result);
  302. }
  303. /*!
  304. * Execute a raw SQL query
  305. * \param _h database connection
  306. * \param _s raw query string
  307. * \param _r result set
  308. * \return 0 on success, negative on failure
  309. */
  310. int db_postgres_raw_query(const db_con_t* _h, const str* _s, db_res_t** _r)
  311. {
  312. return db_do_raw_query(_h, _s, _r, db_postgres_submit_query,
  313. db_postgres_store_result);
  314. }
  315. /*!
  316. * \brief Retrieve result set
  317. * \param _con structure representing the database connection
  318. * \param _r pointer to a structure represending the result set
  319. * \return 0 If the status of the last command produced a result set and,
  320. * If the result set contains data or the convert_result() routine
  321. * completed successfully. Negative if the status of the last command was
  322. * not handled or if the convert_result() returned an error.
  323. * \note A new result structure is allocated on every call to this routine.
  324. * If this routine returns 0, it is the callers responsbility to free the
  325. * result structure. If this routine returns < 0, then the result structure
  326. * is freed before returning to the caller.
  327. */
  328. int db_postgres_store_result(const db_con_t* _con, db_res_t** _r)
  329. {
  330. PGresult *res = NULL;
  331. ExecStatusType pqresult;
  332. int rc = 0;
  333. *_r = db_new_result();
  334. if (*_r==NULL) {
  335. LM_ERR("failed to init new result\n");
  336. rc = -1;
  337. goto done;
  338. }
  339. while (1) {
  340. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  341. CON_RESULT(_con) = res;
  342. } else {
  343. break;
  344. }
  345. }
  346. pqresult = PQresultStatus(CON_RESULT(_con));
  347. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  348. PQresStatus(pqresult), CON_RESULT(_con));
  349. switch(pqresult) {
  350. case PGRES_COMMAND_OK:
  351. /* Successful completion of a command returning no data
  352. * (such as INSERT or UPDATE). */
  353. rc = 0;
  354. break;
  355. case PGRES_TUPLES_OK:
  356. /* Successful completion of a command returning data
  357. * (such as a SELECT or SHOW). */
  358. if (db_postgres_convert_result(_con, *_r) < 0) {
  359. LM_ERR("%p Error returned from convert_result()\n", _con);
  360. db_free_result(*_r);
  361. *_r = 0;
  362. rc = -4;
  363. break;
  364. }
  365. rc = 0;
  366. break;
  367. /* query failed */
  368. case PGRES_FATAL_ERROR:
  369. LM_ERR("%p - invalid query, execution aborted\n", _con);
  370. LM_ERR("%p: %s\n", _con, PQresStatus(pqresult));
  371. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  372. db_free_result(*_r);
  373. *_r = 0;
  374. rc = -3;
  375. break;
  376. case PGRES_EMPTY_QUERY:
  377. /* notice or warning */
  378. case PGRES_NONFATAL_ERROR:
  379. /* status for COPY command, not used */
  380. case PGRES_COPY_OUT:
  381. case PGRES_COPY_IN:
  382. /* unexpected response */
  383. case PGRES_BAD_RESPONSE:
  384. default:
  385. LM_ERR("%p Probable invalid query\n", _con);
  386. LM_ERR("%p: %s\n", _con, PQresStatus(pqresult));
  387. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  388. db_free_result(*_r);
  389. *_r = 0;
  390. rc = -4;
  391. break;
  392. }
  393. done:
  394. free_query(_con);
  395. return (rc);
  396. }
  397. /*!
  398. * \brief Insert a row into specified table
  399. * \param _h structure representing database connection
  400. * \param _k key names
  401. * \param _v values of the keys
  402. * \param _n number of key=value pairs
  403. * \return 0 on success, negative on failure
  404. */
  405. int db_postgres_insert(const db_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  406. const int _n)
  407. {
  408. db_res_t* _r = NULL;
  409. int tmp = db_do_insert(_h, _k, _v, _n, db_postgres_val2str, db_postgres_submit_query);
  410. // finish the async query, otherwise the next query will not complete
  411. if (db_postgres_store_result(_h, &_r) != 0)
  412. LM_WARN("unexpected result returned");
  413. if (_r)
  414. db_free_result(_r);
  415. return tmp;
  416. }
  417. /*!
  418. * \brief Delete a row from the specified table
  419. * \param _h structure representing database connection
  420. * \param _k key names
  421. * \param _o operators
  422. * \param _v values of the keys that must match
  423. * \param _n number of key=value pairs
  424. * \return 0 on success, negative on failure
  425. */
  426. int db_postgres_delete(const db_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  427. const db_val_t* _v, const int _n)
  428. {
  429. db_res_t* _r = NULL;
  430. int tmp = db_do_delete(_h, _k, _o, _v, _n, db_postgres_val2str,
  431. db_postgres_submit_query);
  432. if (db_postgres_store_result(_h, &_r) != 0)
  433. LM_WARN("unexpected result returned");
  434. if (_r)
  435. db_free_result(_r);
  436. return tmp;
  437. }
  438. /*!
  439. * Update some rows in the specified table
  440. * \param _h structure representing database connection
  441. * \param _k key names
  442. * \param _o operators
  443. * \param _v values of the keys that must match
  444. * \param _uk updated columns
  445. * \param _uv updated values of the columns
  446. * \param _n number of key=value pairs
  447. * \param _un number of columns to update
  448. * \return 0 on success, negative on failure
  449. */
  450. int db_postgres_update(const db_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  451. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  452. const int _un)
  453. {
  454. db_res_t* _r = NULL;
  455. int tmp = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_postgres_val2str,
  456. db_postgres_submit_query);
  457. if (db_postgres_store_result(_h, &_r) != 0)
  458. LM_WARN("unexpected result returned");
  459. if (_r)
  460. db_free_result(_r);
  461. return tmp;
  462. }
  463. /*!
  464. * Store name of table that will be used by subsequent database functions
  465. * \param _con database connection
  466. * \param _t table name
  467. * \return 0 on success, negative on error
  468. */
  469. int db_postgres_use_table(db_con_t* _con, const str* _t)
  470. {
  471. return db_use_table(_con, _t);
  472. }