dbase.c 22 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. /*
  2. * $Id$
  3. *
  4. * Postgres module core functions
  5. *
  6. * Portions Copyright (C) 2001-2003 FhG FOKUS
  7. * Copyright (C) 2003 August.Net Services, LLC
  8. * Portions Copyright (C) 2005 iptelorg GmbH
  9. *
  10. * This file is part of ser, a free SIP server.
  11. *
  12. * ser is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 2 of the License, or
  15. * (at your option) any later version
  16. *
  17. * For a license to use the ser software under conditions
  18. * other than those described here, or to purchase support for this
  19. * software, please contact iptel.org by e-mail at the following addresses:
  20. * [email protected]
  21. *
  22. * ser is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program; if not, write to the Free Software
  29. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  30. */
  31. #include <stdio.h>
  32. #include <string.h>
  33. #include <stdlib.h>
  34. #include <time.h>
  35. #include <libpq-fe.h>
  36. #include <netinet/in.h>
  37. #include "../../mem/mem.h"
  38. #include "../../dprint.h"
  39. #include "../../db/db_pool.h"
  40. #include "../../ut.h"
  41. #include "pg_con.h"
  42. #include "pg_type.h"
  43. #include "db_mod.h"
  44. #include "res.h"
  45. #include "dbase.h"
  46. #define SELECTALL "select * "
  47. #define SELECT "select "
  48. #define FROM "from "
  49. #define ORDER "order by "
  50. #define WHERE "where "
  51. #define AND " and "
  52. #define INSERT "insert into "
  53. #define VALUES ") values ("
  54. #define DELETE "delete from "
  55. #define UPDATE "update "
  56. #define SET "set "
  57. #define MAX_OPERATOR_LEN (sizeof(" is NULL") - 1)
  58. struct pg_params {
  59. int n;
  60. int cur;
  61. const char** data;
  62. int* len;
  63. int* formats;
  64. };
  65. static void free_pg_params(struct pg_params* ptr)
  66. {
  67. if (!ptr) return;
  68. if (ptr->data) pkg_free(ptr->data);
  69. if (ptr->len) pkg_free(ptr->len);
  70. if (ptr->formats) pkg_free(ptr->formats);
  71. pkg_free(ptr);
  72. }
  73. static struct pg_params* new_pg_params(int n)
  74. {
  75. struct pg_params* ptr;
  76. ptr = (struct pg_params*)pkg_malloc(sizeof(struct pg_params));
  77. if (!ptr) goto error;
  78. ptr->formats = (int*)pkg_malloc(sizeof(int) * n);
  79. if (!ptr->formats) goto error;
  80. ptr->data = (const char**)pkg_malloc(sizeof(const char*) * n);
  81. if (!ptr->data) goto error;
  82. ptr->len = (int*)pkg_malloc(sizeof(int) * n);
  83. if (!ptr->len) goto error;
  84. memset((char*)ptr->data, 0, sizeof(const char*) * n);
  85. memset(ptr->len, 0, sizeof(int) * n);
  86. ptr->n = n;
  87. ptr->cur = 0;
  88. return ptr;
  89. error:
  90. ERR("No memory left\n");
  91. free_pg_params(ptr);
  92. return 0;
  93. }
  94. static inline int params_add(struct pg_params* p, db_con_t* con, db_val_t* vals, int n)
  95. {
  96. int i, i1, i2;
  97. db_val_t* val;
  98. if (!p) {
  99. ERR("Invalid parameter value\n");
  100. return -1;
  101. }
  102. if (p->cur + n > p->n) {
  103. ERR("Arrays too short (bug in postgres module)\n");
  104. return -1;
  105. }
  106. for(i = 0; i < n; i++) {
  107. val = &vals[i];
  108. p->formats[p->cur] = 1;
  109. if (val->nul) continue;
  110. switch(val->type) {
  111. case DB_INT:
  112. val->val.int_val = ntohl(val->val.int_val);
  113. p->data[p->cur] = (const char*)&val->val.int_val;
  114. p->len[p->cur] = 4;
  115. break;
  116. case DB_DOUBLE:
  117. /* Change the byte order of 8-byte value to network
  118. * byte order if necessary
  119. */
  120. i1 = htonl(val->val.int8_val >> 32);
  121. i2 = htonl(val->val.int8_val & 0xffffffff);
  122. val->val.int_val = i1;
  123. (&val->val.int_val)[1] = i2;
  124. p->data[p->cur] = (const char*)&val->val.int_val;
  125. p->len[p->cur] = 8;
  126. break;
  127. case DB_STRING:
  128. p->formats[p->cur] = 0;
  129. p->data[p->cur] = val->val.string_val;
  130. break;
  131. case DB_STR:
  132. p->data[p->cur] = val->val.str_val.s;
  133. p->len[p->cur] = val->val.str_val.len;
  134. break;
  135. case DB_DATETIME:
  136. if (CON_FLAGS(con) & PG_INT8_TIMESTAMP) {
  137. val->val.int8_val = ((long long)val->val.time_val - PG_EPOCH_TIME) * 1000000;
  138. } else {
  139. val->val.double_val = (double)val->val.time_val - (double)PG_EPOCH_TIME;
  140. }
  141. i1 = htonl(val->val.int8_val >> 32);
  142. i2 = htonl(val->val.int8_val & 0xffffffff);
  143. val->val.int_val = i1;
  144. (&val->val.int_val)[1] = i2;
  145. p->data[p->cur] = (const char*)&val->val.int_val;
  146. p->len[p->cur] = 8;
  147. break;
  148. case DB_BLOB:
  149. p->data[p->cur] = val->val.blob_val.s;
  150. p->len[p->cur] = val->val.blob_val.len;
  151. break;
  152. case DB_BITMAP:
  153. (&val->val.int_val)[1] = htonl(val->val.int_val);
  154. val->val.int_val = htonl(32);
  155. p->data[p->cur] = (const char*)&val->val.int_val;
  156. p->len[p->cur] = 8;
  157. break;
  158. }
  159. p->cur++;
  160. }
  161. return 0;
  162. }
  163. static inline void free_params(struct pg_params* p)
  164. {
  165. if (p->data) pkg_free(p->data);
  166. if (p->len) pkg_free(p->len);
  167. if (p->formats) pkg_free(p->formats);
  168. }
  169. /*
  170. * Initialize database module
  171. * No function should be called before this
  172. */
  173. db_con_t* pg_init(const char* url)
  174. {
  175. struct db_id* id;
  176. struct pg_con* con;
  177. db_con_t* res;
  178. id = 0;
  179. res = 0;
  180. if (!url) {
  181. ERR("Invalid parameter value\n");
  182. return 0;
  183. }
  184. res = pkg_malloc(sizeof(db_con_t) + sizeof(struct pg_con*));
  185. if (!res) {
  186. ERR("No memory left\n");
  187. return 0;
  188. }
  189. memset(res, 0, sizeof(db_con_t) + sizeof(struct pg_con*));
  190. id = new_db_id(url);
  191. if (!id) {
  192. ERR("Cannot parse URL '%s'\n", url);
  193. goto err;
  194. }
  195. /* Find the connection in the pool */
  196. con = (struct pg_con*)pool_get(id);
  197. if (!con) {
  198. DBG("Connection '%s' not found in pool\n", url);
  199. /* Not in the pool yet */
  200. con = pg_new_connection(id);
  201. if (!con) {
  202. goto err;
  203. }
  204. pool_insert((struct pool_con*)con);
  205. } else {
  206. DBG("Connection '%s' found in pool\n", url);
  207. }
  208. res->tail = (unsigned long)con;
  209. return res;
  210. err:
  211. if (id) free_db_id(id);
  212. if (res) pkg_free(res);
  213. return 0;
  214. }
  215. /*
  216. * Shut down database module
  217. * No function should be called after this
  218. */
  219. void pg_close(db_con_t* handle)
  220. {
  221. struct pool_con* con;
  222. if (!handle) {
  223. ERR("Invalid parameter value\n");
  224. return;
  225. }
  226. con = (struct pool_con*)handle->tail;
  227. if (pool_remove(con) != 0) {
  228. pg_free_connection((struct pg_con*)con);
  229. }
  230. pkg_free(handle);
  231. }
  232. static int calc_param_len(start, num)
  233. {
  234. int max, len, order;
  235. if (!num) return 0;
  236. max = start + num - 1;
  237. len = num; /* $ */
  238. order = 0;
  239. while(max) {
  240. order++;
  241. max /= 10;
  242. }
  243. return len + order * num;
  244. }
  245. /*
  246. * Append a constant string, uses sizeof to figure the length
  247. * of the string
  248. */
  249. #define append(buf, ptr) \
  250. do { \
  251. if ((buf).len < (sizeof(ptr) - 1)) goto shortbuf; \
  252. memcpy((buf).s, (ptr), sizeof(ptr) - 1); \
  253. (buf).s += sizeof(ptr) - 1; \
  254. (buf).len -= sizeof(ptr) - 1; \
  255. } while(0);
  256. /*
  257. * Append zero terminated string, uses strlen to obtain the
  258. * length of the string
  259. */
  260. #define append_str(buf, op) \
  261. do { \
  262. int len; \
  263. len = strlen(op); \
  264. if ((buf).len < len) goto shortbuf; \
  265. memcpy((buf).s, (op), len); \
  266. (buf).s += len; \
  267. (buf).len -= len; \
  268. } while(0);
  269. /*
  270. * Append a parameter, accepts the number of the
  271. * parameter to be appended
  272. */
  273. #define append_param(buf, num) \
  274. do { \
  275. const char* c; \
  276. int len; \
  277. c = int2str((num), &len); \
  278. if ((buf).len < len + 1) goto shortbuf; \
  279. *(buf).s='$'; (buf).s++; (buf).len--; \
  280. memcpy((buf).s, c, len); \
  281. (buf).s += len; (buf).len -= len; \
  282. } while(0);
  283. /*
  284. * Calculate the length of buffer needed to hold the insert query
  285. */
  286. static unsigned int calc_insert_len(db_con_t* con, db_key_t* keys, int n)
  287. {
  288. int i;
  289. unsigned int len;
  290. if (!n) return 0;
  291. len = sizeof(INSERT) - 1;
  292. len += strlen(CON_TABLE(con)); /* Table name */
  293. len += 2; /* _( */
  294. for(i = 0; i < n; i++) {
  295. len += strlen(keys[i]); /* Key names */
  296. }
  297. len += n - 1; /* , */
  298. len += sizeof(VALUES);
  299. len += calc_param_len(1, n);
  300. len += n - 1;
  301. len += 1; /* ) */
  302. return len;
  303. }
  304. /*
  305. * Calculate the length of buffer needed to hold the delete query
  306. */
  307. static unsigned int calc_delete_len(db_con_t* con, db_key_t* keys, int n)
  308. {
  309. int i;
  310. unsigned int len;
  311. len = sizeof(DELETE) - 1;
  312. len += strlen(CON_TABLE(con));
  313. if (n) {
  314. len += 1; /* _ */
  315. len += sizeof(WHERE) - 1;
  316. len += n * MAX_OPERATOR_LEN;
  317. len += (sizeof(AND) - 1) * (n - 1);
  318. for(i = 0; i < n; i++) {
  319. len += strlen(keys[i]);
  320. }
  321. len += calc_param_len(1, n);
  322. }
  323. return len;
  324. }
  325. static unsigned int calc_select_len(db_con_t* con, db_key_t* cols, db_key_t* keys, int n, int ncol, db_key_t order)
  326. {
  327. int i;
  328. unsigned int len;
  329. if (!cols) {
  330. len = sizeof(SELECTALL) - 1;
  331. } else {
  332. len = sizeof(SELECT);
  333. for(i = 0; i < ncol; i++) {
  334. len += strlen(cols[i]);
  335. }
  336. len += ncol - 1; /* , */
  337. len++; /* space */
  338. }
  339. len += sizeof(FROM) - 1;
  340. len += strlen(CON_TABLE(con));
  341. len += 1; /* _ */
  342. if (n) {
  343. len += sizeof(WHERE) - 1;
  344. len += n * MAX_OPERATOR_LEN;
  345. len += (sizeof(AND) - 1) * (n - 1);
  346. for(i = 0; i < n; i++) {
  347. len += strlen(keys[i]);
  348. }
  349. len += calc_param_len(1, n);
  350. len++; /* space */
  351. }
  352. if (order) {
  353. len += sizeof(ORDER);
  354. len += strlen(order);
  355. }
  356. return len;
  357. }
  358. static unsigned int calc_update_len(db_con_t* con, db_key_t* ukeys, db_key_t* keys, int un, int n)
  359. {
  360. int i;
  361. unsigned int len;
  362. if (!un) return 0;
  363. len = sizeof(UPDATE) - 1;
  364. len += strlen(CON_TABLE(con));
  365. len += 1; /* _ */
  366. len += sizeof(SET) - 1;
  367. len += un; /* = */
  368. for (i = 0; i < un; i++) {
  369. len += strlen(ukeys[i]);
  370. }
  371. len += calc_param_len(1, un);
  372. len += un; /* , and last space */
  373. if (n) {
  374. len += sizeof(WHERE) - 1;
  375. len += n * MAX_OPERATOR_LEN;
  376. len += (sizeof(AND) - 1) * (n - 1);
  377. for(i = 0; i < n; i++) {
  378. len += strlen(keys[i]);
  379. }
  380. len += calc_param_len(1 + un, n);
  381. }
  382. return len;
  383. }
  384. static char* print_insert(db_con_t* con, db_key_t* keys, int n)
  385. {
  386. unsigned int len;
  387. int i;
  388. char* s;
  389. str p;
  390. if (!n || !keys) {
  391. ERR("Nothing to insert\n");
  392. return 0;
  393. }
  394. len = calc_insert_len(con, keys, n);
  395. s = (char*)pkg_malloc(len + 1);
  396. if (!s) {
  397. ERR("Unable to allocate %d of memory\n", len);
  398. return 0;
  399. }
  400. p.s = s;
  401. p.len = len;
  402. append(p, INSERT);
  403. append_str(p, CON_TABLE(con));
  404. append(p, " (");
  405. append_str(p, keys[0]);
  406. for(i = 1; i < n; i++) {
  407. append(p, ",");
  408. append_str(p, keys[i]);
  409. }
  410. append(p, VALUES);
  411. append_param(p, 1);
  412. for(i = 1; i < n; i++) {
  413. append(p, ",");
  414. append_param(p, i + 1);
  415. }
  416. append(p, ")");
  417. *p.s = '\0';
  418. return s;
  419. shortbuf:
  420. ERR("Buffer too short (bug in postgres module)\n");
  421. pkg_free(s);
  422. return 0;
  423. }
  424. static char* print_select(db_con_t* con, db_key_t* cols, db_key_t* keys, db_val_t* vals,
  425. int n, int ncol, db_op_t* ops, db_key_t order)
  426. {
  427. unsigned int len;
  428. int i;
  429. char* s;
  430. str p;
  431. len = calc_select_len(con, cols, keys, n, ncol, order);
  432. s = (char*)pkg_malloc(len + 1);
  433. if (!s) {
  434. ERR("Unable to allocate %d of memory\n", len);
  435. return 0;
  436. }
  437. p.s = s;
  438. p.len = len;
  439. if (!cols || !ncol) {
  440. append(p, SELECTALL);
  441. } else {
  442. append(p, SELECT);
  443. append_str(p, cols[0]);
  444. for(i = 1; i < ncol; i++) {
  445. append(p, ",");
  446. append_str(p, cols[i]);
  447. }
  448. append(p, " ");
  449. }
  450. append(p, FROM);
  451. append_str(p, CON_TABLE(con));
  452. append(p, " ");
  453. if (n) {
  454. append(p, WHERE);
  455. append_str(p, keys[0]);
  456. if (vals[0].nul) {
  457. append(p, " is NULL");
  458. } else {
  459. if (ops) {
  460. append_str(p, *ops);
  461. ops++;
  462. } else {
  463. append(p, "=");
  464. }
  465. append_param(p, 1);
  466. }
  467. for(i = 1; i < n; i++) {
  468. append(p, AND);
  469. append_str(p, keys[i]);
  470. if (vals[i].nul) {
  471. append(p, " is NULL");
  472. } else {
  473. if (ops) {
  474. append_str(p, *ops);
  475. ops++;
  476. } else {
  477. append(p, "=");
  478. }
  479. append_param(p, i + 1);
  480. }
  481. }
  482. append(p, " ");
  483. }
  484. if (order) {
  485. append(p, ORDER);
  486. append_str(p, order);
  487. }
  488. *p.s = '\0'; /* Zero termination */
  489. return s;
  490. shortbuf:
  491. ERR("Buffer too short (bug in postgres module)\n");
  492. pkg_free(s);
  493. return 0;
  494. }
  495. static char* print_delete(db_con_t* con, db_key_t* keys, db_op_t* ops, db_val_t* vals, int n)
  496. {
  497. unsigned int len;
  498. int i;
  499. char* s;
  500. str p;
  501. len = calc_delete_len(con, keys, n);
  502. s = (char*)pkg_malloc(len + 1);
  503. if (!s) {
  504. ERR("Unable to allocate %d of memory\n", len);
  505. return 0;
  506. }
  507. p.s = s;
  508. p.len = len;
  509. append(p, DELETE);
  510. append_str(p, CON_TABLE(con));
  511. append(p, " ");
  512. if (n) {
  513. append(p, WHERE);
  514. append_str(p, keys[0]);
  515. if (vals[0].nul) {
  516. append(p, " is NULL");
  517. } else {
  518. if (ops) {
  519. append_str(p, *ops);
  520. ops++;
  521. } else {
  522. append(p, "=");
  523. }
  524. append_param(p, 1);
  525. }
  526. for(i = 1; i < n; i++) {
  527. append(p, AND);
  528. append_str(p, keys[i]);
  529. if (vals[i].nul) {
  530. append(p, " is NULL");
  531. } else {
  532. if (ops) {
  533. append_str(p, *ops);
  534. ops++;
  535. } else {
  536. append(p, "=");
  537. }
  538. append_param(p, i + 1);
  539. }
  540. }
  541. }
  542. *p.s = '\0';
  543. return s;
  544. shortbuf:
  545. ERR("Buffer too short (bug in postgres module)\n");
  546. pkg_free(s);
  547. return 0;
  548. }
  549. static char* print_update(db_con_t* con, db_key_t* ukeys, db_key_t* keys, db_op_t* ops,
  550. db_val_t* vals, int un, int n)
  551. {
  552. unsigned int len, param_no;
  553. char* s;
  554. int i;
  555. str p;
  556. if (!un) {
  557. ERR("Nothing to update\n");
  558. return 0;
  559. }
  560. param_no = 1;
  561. len = calc_update_len(con, ukeys, keys, un, n);
  562. s = (char*)pkg_malloc(len + 1);
  563. if (!s) {
  564. ERR("Unable to allocate %d of memory\n", len);
  565. return 0;
  566. }
  567. p.s = s;
  568. p.len = len;
  569. append(p, UPDATE);
  570. append_str(p, CON_TABLE(con));
  571. append(p, " " SET);
  572. append_str(p, ukeys[0]);
  573. append(p, "=");
  574. append_param(p, param_no++);
  575. for(i = 1; i < un; i++) {
  576. append(p, ",");
  577. append_str(p, ukeys[i]);
  578. append(p, "=");
  579. append_param(p, param_no++);
  580. }
  581. append(p, " ");
  582. if (n) {
  583. append(p, WHERE);
  584. append_str(p, keys[0]);
  585. if (vals[0].nul) {
  586. append(p, " is NULL");
  587. } else {
  588. if (ops) {
  589. append_str(p, *ops);
  590. ops++;
  591. } else {
  592. append(p, "=");
  593. }
  594. append_param(p, param_no++);
  595. }
  596. for(i = 1; i < n; i++) {
  597. append(p, AND);
  598. append_str(p, keys[i]);
  599. if (vals[i].nul) {
  600. append(p, " is NULL");
  601. } else {
  602. if (ops) {
  603. append_str(p, *ops);
  604. ops++;
  605. } else {
  606. append(p, "=");
  607. }
  608. append_param(p, param_no++);
  609. }
  610. }
  611. }
  612. *p.s = '\0';
  613. return s;
  614. shortbuf:
  615. ERR("Buffer too short (bug in postgres module)\n");
  616. pkg_free(s);
  617. return 0;
  618. }
  619. /*
  620. * Return values: 1 Query failed, bad connection
  621. * 0 Query succeeded
  622. * -1 Query failed due to some other reason
  623. */
  624. static int submit_query(db_res_t** res, db_con_t* con, const char* query, struct pg_params* params)
  625. {
  626. PGresult* pgres;
  627. DBG("Executing '%s'\n", query);
  628. if (params && params->cur) {
  629. pgres = PQexecParams(CON_CONNECTION(con), query,
  630. params->cur, 0,
  631. params->data, params->len,
  632. params->formats, 1);
  633. } else {
  634. pgres = PQexecParams(CON_CONNECTION(con), query, 0, 0, 0, 0, 0, 1);
  635. }
  636. switch(PQresultStatus(pgres)) {
  637. case PGRES_EMPTY_QUERY:
  638. ERR("BUG: db_raw_query received an empty query\n");
  639. goto error;
  640. case PGRES_COMMAND_OK:
  641. case PGRES_NONFATAL_ERROR:
  642. case PGRES_TUPLES_OK:
  643. /* Success */
  644. break;
  645. case PGRES_COPY_OUT:
  646. case PGRES_COPY_IN:
  647. ERR("Unsupported transfer mode\n");
  648. goto error;
  649. case PGRES_BAD_RESPONSE:
  650. case PGRES_FATAL_ERROR:
  651. ERR("Error: %s", PQresultErrorMessage(pgres));
  652. if (PQstatus(CON_CONNECTION(con)) != CONNECTION_BAD) {
  653. goto error;
  654. }
  655. ERR("Bad connection\n");
  656. PQclear(pgres);
  657. return 1;
  658. }
  659. if (res) {
  660. *res = pg_new_result(pgres);
  661. if (!(*res)) goto error;
  662. } else {
  663. PQclear(pgres);
  664. }
  665. return 0;
  666. error:
  667. PQclear(pgres);
  668. return -1;
  669. }
  670. static int reconnect(db_con_t* con)
  671. {
  672. int attempts_left = reconnect_attempts;
  673. while(attempts_left) {
  674. ERR("Trying to recover the connection\n");
  675. PQreset(CON_CONNECTION(con));
  676. if (PQstatus(CON_CONNECTION(con)) == CONNECTION_OK) {
  677. ERR("Successfuly reconnected\n");
  678. return 0;
  679. }
  680. ERR("Reconnect attempt failed\n");
  681. attempts_left--;
  682. }
  683. ERR("No more reconnect attempts left, giving up\n");
  684. return -1;
  685. }
  686. /*
  687. * Query table for specified rows
  688. * con: structure representing database connection
  689. * keys: key names
  690. * ops: operators
  691. * vals: values of the keys that must match
  692. * cols: column names to return
  693. * n: number of key=values pairs to compare
  694. * ncol: number of columns to return
  695. * order: order by the specified column
  696. * res: query result
  697. */
  698. int pg_query(db_con_t* con, db_key_t* keys, db_op_t* ops,
  699. db_val_t* vals, db_key_t* cols, int n, int ncols,
  700. db_key_t order, db_res_t** res)
  701. {
  702. int ret;
  703. char* select;
  704. struct pg_params* params;
  705. params = 0;
  706. select = 0;
  707. if (res) *res = 0;
  708. if (!con) {
  709. ERR("Invalid parameter value\n");
  710. return -1;
  711. }
  712. select = print_select(con, cols, keys, vals, n, ncols, ops, order);
  713. if (!select) goto err;
  714. params = new_pg_params(n);
  715. if (!params) goto err;
  716. if (params_add(params, con, vals, n) < 0) goto err;
  717. do {
  718. ret = submit_query(res, con, select, params);
  719. if (ret < 0) goto err; /* Unknown error, bail out */
  720. if (ret > 0) { /* Disconnected, try to reconnect */
  721. if (reconnect(con) < 0) goto err; /* Failed to reconnect */
  722. else continue; /* Try one more time (ret is > 0) */
  723. }
  724. } while(ret != 0);
  725. if (res && pg_convert_result(*res, con) < 0) {
  726. pg_free_result(*res);
  727. goto err;
  728. }
  729. free_pg_params(params);
  730. pkg_free(select);
  731. return 0;
  732. err:
  733. if (params) free_pg_params(params);
  734. if (select) pkg_free(select);
  735. return -1;
  736. }
  737. /*
  738. * Execute a raw SQL query
  739. */
  740. int pg_raw_query(db_con_t* con, char* query, db_res_t** res)
  741. {
  742. int ret;
  743. if (!con || !query) {
  744. ERR("Invalid parameter value\n");
  745. return -1;
  746. }
  747. do {
  748. ret = submit_query(res, con, query, 0);
  749. if (ret < 0) return -1; /* Unknown error, bail out */
  750. if (ret > 0) { /* Disconnected, try to reconnect */
  751. if (reconnect(con) < 0) return -1; /* Failed to reconnect */
  752. else continue; /* Try one more time (ret is > 0) */
  753. }
  754. } while(ret != 0);
  755. if (res && (pg_convert_result(*res, con) < 0)) {
  756. pg_free_result(*res);
  757. return -1;
  758. }
  759. return 0;
  760. }
  761. /*
  762. * Insert a row into specified table
  763. * con: structure representing database connection
  764. * keys: key names
  765. * vals: values of the keys
  766. * n: number of key=value pairs
  767. */
  768. int pg_insert(db_con_t* con, db_key_t* keys, db_val_t* vals, int n)
  769. {
  770. int ret;
  771. char* insert;
  772. struct pg_params* params;
  773. if (!con || !keys || !vals || !n) {
  774. ERR("Invalid parameter value\n");
  775. return -1;
  776. }
  777. params = 0;
  778. insert = 0;
  779. insert = print_insert(con, keys, n);
  780. if (!insert) goto err;
  781. params = new_pg_params(n);
  782. if (!params) goto err;
  783. if (params_add(params, con, vals, n) < 0) goto err;
  784. do {
  785. ret = submit_query(0, con, insert, params);
  786. if (ret < 0) goto err; /* Unknown error, bail out */
  787. if (ret > 0) { /* Disconnected, try to reconnect */
  788. if (reconnect(con) < 0) goto err; /* Failed to reconnect */
  789. else continue; /* Try one more time (ret is > 0) */
  790. }
  791. } while(ret != 0);
  792. free_pg_params(params);
  793. pkg_free(insert);
  794. return 0;
  795. err:
  796. if (params) free_pg_params(params);
  797. if (insert) pkg_free(insert);
  798. return -1;
  799. }
  800. /*
  801. * Delete a row from the specified table
  802. * con : structure representing database connection
  803. * keys: key names
  804. * ops : operators
  805. * vals: values of the keys that must match
  806. * n : number of key=value pairs
  807. */
  808. int pg_delete(db_con_t* con, db_key_t* keys, db_op_t* ops, db_val_t* vals, int n)
  809. {
  810. int ret;
  811. char* delete;
  812. struct pg_params* params;
  813. if (!con) {
  814. ERR("Invalid parameter value\n");
  815. return -1;
  816. }
  817. params = 0;
  818. delete = 0;
  819. delete = print_delete(con, keys, ops, vals, n);
  820. if (!delete) goto err;
  821. params = new_pg_params(n);
  822. if (!params) goto err;
  823. if (params_add(params, con, vals, n) < 0) goto err;
  824. do {
  825. ret = submit_query(0, con, delete, params);
  826. if (ret < 0) goto err; /* Unknown error, bail out */
  827. if (ret > 0) { /* Disconnected, try to reconnect */
  828. if (reconnect(con) < 0) goto err; /* Failed to reconnect */
  829. else continue; /* Try one more time (ret is > 0) */
  830. }
  831. } while(ret != 0);
  832. free_pg_params(params);
  833. pkg_free(delete);
  834. return 0;
  835. err:
  836. if (params) free_pg_params(params);
  837. if (delete) pkg_free(delete);
  838. return -1;
  839. }
  840. /*
  841. * Update some rows in the specified table
  842. * con : structure representing database connection
  843. * keys : key names
  844. * ops : operators
  845. * vals : values of the keys that must match
  846. * ucols: updated columns
  847. * uvals: updated values of the columns
  848. * n : number of key=value pairs
  849. * un : number of columns to update
  850. */
  851. int pg_update(db_con_t* con, db_key_t* keys, db_op_t* ops, db_val_t* vals,
  852. db_key_t* ucols, db_val_t* uvals, int n, int un)
  853. {
  854. int ret;
  855. char* update;
  856. struct pg_params* params;
  857. if (!con || !ucols || !uvals || !un) {
  858. ERR("Invalid parameter value\n");
  859. return -1;
  860. }
  861. params = 0;
  862. update = 0;
  863. update = print_update(con, ucols, keys, ops, vals, un, n);
  864. if (!update) goto err;
  865. params = new_pg_params(n + un);
  866. if (!params) goto err;
  867. if (params_add(params, con, uvals, un) < 0) goto err;
  868. if (params_add(params, con, vals, n) < 0) goto err;
  869. do {
  870. ret = submit_query(0, con, update, params);
  871. if (ret < 0) goto err; /* Unknown error, bail out */
  872. if (ret > 0) { /* Disconnected, try to reconnect */
  873. if (reconnect(con) < 0) goto err; /* Failed to reconnect */
  874. else continue; /* Try one more time (ret is > 0) */
  875. }
  876. } while(ret != 0);
  877. free_pg_params(params);
  878. pkg_free(update);
  879. return 0;
  880. err:
  881. if (params) free_pg_params(params);
  882. if (update) pkg_free(update);
  883. return -1;
  884. }
  885. /*
  886. * Release a result set from memory
  887. */
  888. int pg_db_free_result(db_con_t* con, db_res_t* res)
  889. {
  890. pg_free_result(res);
  891. return 0;
  892. }