km_dbase.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /*
  2. * $Id$
  3. *
  4. * POSTGRES module, portions of this code were templated using
  5. * the mysql module, thus it's similarity.
  6. *
  7. * Copyright (C) 2003 August.Net Services, LLC
  8. * Copyright (C) 2006 Norman Brandinger
  9. * Copyright (C) 2008 1&1 Internet AG
  10. *
  11. * This file is part of openser, a free SIP server.
  12. *
  13. * openser is free software; you can redistribute it and/or modify
  14. * it under the terms of the GNU General Public License as published by
  15. * the Free Software Foundation; either version 2 of the License, or
  16. * (at your option) any later version
  17. *
  18. * openser is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program; if not, write to the Free Software
  25. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  26. *
  27. * ---
  28. *
  29. * History
  30. * -------
  31. * 2003-04-06 initial code written (Greg Fausak/Andy Fullford)
  32. * 2006-07-28 within pg_get_result(): added check to immediatly return of no
  33. * result set was returned added check to only execute
  34. * convert_result() if PGRES_TUPLES_OK added safety check to avoid
  35. * double pg_free_result() (norm)
  36. * 2006-08-07 Rewrote pg_get_result().
  37. * Additional debugging lines have been placed through out the code.
  38. * Added Asynchronous Command Processing (PQsendQuery/PQgetResult)
  39. * instead of PQexec. this was done in preparation of adding FETCH
  40. * support. Note that PQexec returns a result pointer while
  41. * PQsendQuery does not. The result set pointer is obtained from
  42. * a call (or multiple calls) to PQgetResult.
  43. * Removed transaction processing calls (BEGIN/COMMIT/ROLLBACK) as
  44. * they added uneeded overhead. Klaus' testing showed in excess of
  45. * 1ms gain by removing each command. In addition, OpenSER only
  46. * issues single queries and is not, at this time transaction aware.
  47. * The transaction processing routines have been left in place
  48. * should this support be needed in the future.
  49. * Updated logic in pg_query / pg_raw_query to accept a (0) result
  50. * set (_r) parameter. In this case, control is returned
  51. * immediately after submitting the query and no call to
  52. * pg_get_results() is performed. This is a requirement for
  53. * FETCH support. (norm)
  54. * 2006-10-27 Added fetch support (norm)
  55. * Removed dependency on aug_* memory routines (norm)
  56. * Added connection pooling support (norm)
  57. * Standardized API routines to pg_* names (norm)
  58. * 2006-11-01 Updated pg_insert(), pg_delete(), pg_update() and
  59. * pg_get_result() to handle failed queries. Detailed warnings
  60. * along with the text of the failed query is now displayed in the
  61. * log. Callers of these routines can now assume that a non-zero
  62. * rc indicates the query failed and that remedial action may need
  63. * to be taken. (norm)
  64. */
  65. #define MAXCOLUMNS 512
  66. #include <string.h>
  67. #include <stdio.h>
  68. #include "../../dprint.h"
  69. #include "../../mem/mem.h"
  70. #include "../../db/db.h"
  71. #include "../../db/db_ut.h"
  72. #include "../../db/db_query.h"
  73. #include "dbase.h"
  74. #include "pg_con.h"
  75. #include "val.h"
  76. #include "res.h"
  77. static int free_query(const db_con_t* _con);
  78. /*
  79. ** pg_init initialize database for future queries
  80. **
  81. ** Arguments :
  82. ** char *_url; sql database to open
  83. **
  84. ** Returns :
  85. ** db_con_t * NULL upon error
  86. ** db_con_t * if successful
  87. **
  88. ** Notes :
  89. ** pg_init must be called prior to any database functions.
  90. */
  91. db_con_t *db_postgres_init(const str* _url)
  92. {
  93. return db_do_init(_url, (void*) db_postgres_new_connection);
  94. }
  95. /*
  96. ** pg_close last function to call when db is no longer needed
  97. **
  98. ** Arguments :
  99. ** db_con_t * the connection to shut down, as supplied by pg_init()
  100. **
  101. ** Returns :
  102. ** (void)
  103. **
  104. ** Notes :
  105. ** All memory and resources are freed.
  106. */
  107. void db_postgres_close(db_con_t* _h)
  108. {
  109. db_do_close(_h, db_postgres_free_connection);
  110. }
  111. /*
  112. ** submit_query run a query
  113. **
  114. ** Arguments :
  115. ** db_con_t * as previously supplied by pg_init()
  116. ** char *_s the text query to run
  117. **
  118. ** Returns :
  119. ** 0 upon success
  120. ** negative number upon failure
  121. */
  122. static int db_postgres_submit_query(const db_con_t* _con, const str* _s)
  123. {
  124. if(! _con || !_s || !_s->s)
  125. {
  126. LM_ERR("invalid parameter value\n");
  127. return(-1);
  128. }
  129. /* this bit of nonsense in case our connection get screwed up */
  130. switch(PQstatus(CON_CONNECTION(_con)))
  131. {
  132. case CONNECTION_OK:
  133. break;
  134. case CONNECTION_BAD:
  135. LM_DBG("connection reset\n");
  136. PQreset(CON_CONNECTION(_con));
  137. break;
  138. case CONNECTION_STARTED:
  139. case CONNECTION_MADE:
  140. case CONNECTION_AWAITING_RESPONSE:
  141. case CONNECTION_AUTH_OK:
  142. case CONNECTION_SETENV:
  143. case CONNECTION_SSL_STARTUP:
  144. case CONNECTION_NEEDED:
  145. default:
  146. LM_ERR("%p PQstatus(%s) invalid: %.*s\n", _con,
  147. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  148. return -1;
  149. }
  150. /* free any previous query that is laying about */
  151. if(CON_RESULT(_con))
  152. {
  153. free_query(_con);
  154. }
  155. /* exec the query */
  156. if (PQsendQuery(CON_CONNECTION(_con), _s->s)) {
  157. LM_DBG("%p PQsendQuery(%.*s)\n", _con, _s->len, _s->s);
  158. } else {
  159. LM_ERR("%p PQsendQuery Error: %s Query: %.*s\n", _con,
  160. PQerrorMessage(CON_CONNECTION(_con)), _s->len, _s->s);
  161. return -1;
  162. }
  163. return 0;
  164. }
  165. /*
  166. *
  167. * pg_fetch_result: Gets a partial result set.
  168. *
  169. */
  170. int db_postgres_fetch_result(const db_con_t* _con, db_res_t** _res, const int nrows)
  171. {
  172. int rows;
  173. PGresult *res = NULL;
  174. ExecStatusType pqresult;
  175. if (!_con || !_res || nrows < 0) {
  176. LM_ERR("invalid parameter value\n");
  177. return -1;
  178. }
  179. /* exit if the fetch count is zero */
  180. if (nrows == 0) {
  181. if (*_res)
  182. db_free_result(*_res);
  183. *_res = 0;
  184. return 0;
  185. }
  186. if (*_res == NULL) {
  187. /* Allocate a new result structure */
  188. *_res = db_new_result();
  189. /* Get the result of the previous query */
  190. while (1) {
  191. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  192. CON_RESULT(_con) = res;
  193. } else {
  194. break;
  195. }
  196. }
  197. pqresult = PQresultStatus(CON_RESULT(_con));
  198. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  199. PQresStatus(pqresult), CON_RESULT(_con));
  200. switch(pqresult) {
  201. case PGRES_COMMAND_OK:
  202. /* Successful completion of a command returning no data (such as INSERT or UPDATE). */
  203. return 0;
  204. case PGRES_TUPLES_OK:
  205. /* Successful completion of a command returning data (such as a SELECT or SHOW). */
  206. if (db_postgres_get_columns(_con, *_res) < 0) {
  207. LM_ERR("failed to get column names\n");
  208. return -2;
  209. }
  210. break;
  211. case PGRES_FATAL_ERROR:
  212. LM_ERR("%p - invalid query, execution aborted\n", _con);
  213. LM_ERR("%p - PQresultStatus(%s)\n", _con, PQresStatus(pqresult));
  214. if (*_res)
  215. db_free_result(*_res);
  216. *_res = 0;
  217. return -3;
  218. case PGRES_EMPTY_QUERY:
  219. case PGRES_COPY_OUT:
  220. case PGRES_COPY_IN:
  221. case PGRES_BAD_RESPONSE:
  222. case PGRES_NONFATAL_ERROR:
  223. LM_WARN("%p - probable invalid query\n", _con);
  224. default:
  225. LM_WARN("%p - PQresultStatus(%s)\n",
  226. _con, PQresStatus(pqresult));
  227. if (*_res)
  228. db_free_result(*_res);
  229. *_res = 0;
  230. return 0;
  231. }
  232. } else {
  233. if(RES_ROWS(*_res) != NULL) {
  234. db_free_rows(*_res);
  235. }
  236. RES_ROWS(*_res) = 0;
  237. RES_ROW_N(*_res) = 0;
  238. }
  239. /* Get the number of rows (tuples) in the query result. */
  240. RES_NUM_ROWS(*_res) = PQntuples(CON_RESULT(_con));
  241. /* determine the number of rows remaining to be processed */
  242. rows = RES_NUM_ROWS(*_res) - RES_LAST_ROW(*_res);
  243. /* If there aren't any more rows left to process, exit */
  244. if (rows <= 0)
  245. return 0;
  246. /* if the fetch count is less than the remaining rows to process */
  247. /* set the number of rows to process (during this call) equal to the fetch count */
  248. if (nrows < rows)
  249. rows = nrows;
  250. RES_ROW_N(*_res) = rows;
  251. LM_DBG("converting row %d of %d count %d\n", RES_LAST_ROW(*_res),
  252. RES_NUM_ROWS(*_res), RES_ROW_N(*_res));
  253. if (db_postgres_convert_rows(_con, *_res) < 0) {
  254. LM_ERR("failed to convert rows\n");
  255. if (*_res)
  256. db_free_result(*_res);
  257. *_res = 0;
  258. return -3;
  259. }
  260. /* update the total number of rows processed */
  261. RES_LAST_ROW(*_res) += rows;
  262. return 0;
  263. }
  264. /*
  265. ** free_query clear the db channel and clear any old query result status
  266. **
  267. ** Arguments :
  268. ** db_con_t * as previously supplied by pg_init()
  269. **
  270. ** Returns :
  271. ** 0 upon success
  272. ** negative number upon failure
  273. */
  274. static int free_query(const db_con_t* _con)
  275. {
  276. if(CON_RESULT(_con))
  277. {
  278. LM_DBG("PQclear(%p) result set\n", CON_RESULT(_con));
  279. PQclear(CON_RESULT(_con));
  280. CON_RESULT(_con) = 0;
  281. }
  282. return 0;
  283. }
  284. /*
  285. ** db_free_result free the query and free the result memory
  286. **
  287. ** Arguments :
  288. ** db_con_t * as previously supplied by pg_init()
  289. ** db_res_t * the result of a query
  290. **
  291. ** Returns :
  292. ** 0 upon success
  293. ** negative number upon failure
  294. */
  295. int db_postgres_free_result(db_con_t* _con, db_res_t* _r)
  296. {
  297. free_query(_con);
  298. if (_r) db_free_result(_r);
  299. _r = 0;
  300. return 0;
  301. }
  302. /*
  303. * Query table for specified rows
  304. * _con: structure representing database connection
  305. * _k: key names
  306. * _op: operators
  307. * _v: values of the keys that must match
  308. * _c: column names to return
  309. * _n: nmber of key=values pairs to compare
  310. * _nc: number of columns to return
  311. * _o: order by the specified column
  312. */
  313. int db_postgres_query(const db_con_t* _h, const db_key_t* _k, const db_op_t* _op,
  314. const db_val_t* _v, const db_key_t* _c, const int _n, const int _nc,
  315. const db_key_t _o, db_res_t** _r)
  316. {
  317. return db_do_query(_h, _k, _op, _v, _c, _n, _nc, _o, _r, db_postgres_val2str,
  318. db_postgres_submit_query, db_postgres_store_result);
  319. }
  320. /*
  321. * Execute a raw SQL query
  322. */
  323. int db_postgres_raw_query(const db_con_t* _h, const str* _s, db_res_t** _r)
  324. {
  325. return db_do_raw_query(_h, _s, _r, db_postgres_submit_query,
  326. db_postgres_store_result);
  327. }
  328. /*
  329. * Retrieve result set
  330. *
  331. * Input:
  332. * db_con_t* _con Structure representing the database connection
  333. * db_res_t** _r pointer to a structure represending the result set
  334. *
  335. * Output:
  336. * return 0: If the status of the last command produced a result set and,
  337. * If the result set contains data or the convert_result() routine
  338. * completed successfully.
  339. *
  340. * return < 0: If the status of the last command was not handled or if the
  341. * convert_result() returned an error.
  342. *
  343. * Notes:
  344. * A new result structure is allocated on every call to this routine.
  345. *
  346. * If this routine returns 0, it is the callers responsbility to free the
  347. * result structure. If this routine returns < 0, then the result structure
  348. * is freed before returning to the caller.
  349. *
  350. */
  351. int db_postgres_store_result(const db_con_t* _con, db_res_t** _r)
  352. {
  353. PGresult *res = NULL;
  354. ExecStatusType pqresult;
  355. int rc = 0;
  356. *_r = db_new_result();
  357. while (1) {
  358. if ((res = PQgetResult(CON_CONNECTION(_con)))) {
  359. CON_RESULT(_con) = res;
  360. } else {
  361. break;
  362. }
  363. }
  364. pqresult = PQresultStatus(CON_RESULT(_con));
  365. LM_DBG("%p PQresultStatus(%s) PQgetResult(%p)\n", _con,
  366. PQresStatus(pqresult), CON_RESULT(_con));
  367. switch(pqresult) {
  368. case PGRES_COMMAND_OK:
  369. /* Successful completion of a command returning no data (such as INSERT or UPDATE). */
  370. rc = 0;
  371. break;
  372. case PGRES_TUPLES_OK:
  373. /* Successful completion of a command returning data (such as a SELECT or SHOW). */
  374. if (db_postgres_convert_result(_con, *_r) < 0) {
  375. LM_ERR("%p Error returned from convert_result()\n", _con);
  376. if (*_r) db_free_result(*_r);
  377. *_r = 0;
  378. rc = -4;
  379. }
  380. rc = 0;
  381. break;
  382. case PGRES_FATAL_ERROR:
  383. LM_ERR("%p - invalid query, execution aborted\n", _con);
  384. LM_ERR("%p: %s\n", _con, PQresStatus(pqresult));
  385. LM_ERR("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  386. if (*_r) db_free_result(*_r);
  387. *_r = 0;
  388. rc = -3;
  389. break;
  390. case PGRES_EMPTY_QUERY:
  391. case PGRES_COPY_OUT:
  392. case PGRES_COPY_IN:
  393. case PGRES_BAD_RESPONSE:
  394. case PGRES_NONFATAL_ERROR:
  395. LM_WARN("%p Probable invalid query\n", _con);
  396. default:
  397. LM_WARN("%p: %s\n", _con, PQresStatus(pqresult));
  398. LM_WARN("%p: %s\n", _con, PQresultErrorMessage(CON_RESULT(_con)));
  399. if (*_r) db_free_result(*_r);
  400. *_r = 0;
  401. rc = (int)pqresult;
  402. break;
  403. }
  404. free_query(_con);
  405. return (rc);
  406. }
  407. /*
  408. * Insert a row into specified table
  409. * _con: structure representing database connection
  410. * _k: key names
  411. * _v: values of the keys
  412. * _n: number of key=value pairs
  413. */
  414. int db_postgres_insert(const db_con_t* _h, const db_key_t* _k, const db_val_t* _v,
  415. const int _n)
  416. {
  417. db_res_t* _r = NULL;
  418. int tmp = db_do_insert(_h, _k, _v, _n, db_postgres_val2str, db_postgres_submit_query);
  419. // finish the async query, otherwise the next query will not complete
  420. if (db_postgres_store_result(_h, &_r) != 0)
  421. LM_WARN("unexpected result returned");
  422. if (_r)
  423. db_free_result(_r);
  424. return tmp;
  425. }
  426. /*
  427. * Delete a row from the specified table
  428. * _con: structure representing database connection
  429. * _k: key names
  430. * _o: operators
  431. * _v: values of the keys that must match
  432. * _n: number of key=value pairs
  433. */
  434. int db_postgres_delete(const db_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  435. const db_val_t* _v, const int _n)
  436. {
  437. db_res_t* _r = NULL;
  438. int tmp = db_do_delete(_h, _k, _o, _v, _n, db_postgres_val2str,
  439. db_postgres_submit_query);
  440. if (db_postgres_store_result(_h, &_r) != 0)
  441. LM_WARN("unexpected result returned");
  442. if (_r)
  443. db_free_result(_r);
  444. return tmp;
  445. }
  446. /*
  447. * Update some rows in the specified table
  448. * _con: structure representing database connection
  449. * _k: key names
  450. * _o: operators
  451. * _v: values of the keys that must match
  452. * _uk: updated columns
  453. * _uv: updated values of the columns
  454. * _n: number of key=value pairs
  455. * _un: number of columns to update
  456. */
  457. int db_postgres_update(const db_con_t* _h, const db_key_t* _k, const db_op_t* _o,
  458. const db_val_t* _v, const db_key_t* _uk, const db_val_t* _uv, const int _n,
  459. const int _un)
  460. {
  461. db_res_t* _r = NULL;
  462. int tmp = db_do_update(_h, _k, _o, _v, _uk, _uv, _n, _un, db_postgres_val2str,
  463. db_postgres_submit_query);
  464. if (db_postgres_store_result(_h, &_r) != 0)
  465. LM_WARN("unexpected result returned");
  466. if (_r)
  467. db_free_result(_r);
  468. return tmp;
  469. }
  470. /*
  471. * Store name of table that will be used by
  472. * subsequent database functions
  473. */
  474. int db_postgres_use_table(db_con_t* _con, const str* _t)
  475. {
  476. return db_use_table(_con, _t);
  477. }