You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5710 lines
156 KiB

21 years ago
27 years ago
27 years ago
24 years ago
24 years ago
24 years ago
25 years ago
25 years ago
25 years ago
23 years ago
23 years ago
23 years ago
23 years ago
24 years ago
25 years ago
24 years ago
26 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
25 years ago
21 years ago
24 years ago
22 years ago
25 years ago
21 years ago
21 years ago
21 years ago
23 years ago
26 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
24 years ago
23 years ago
23 years ago
23 years ago
22 years ago
22 years ago
23 years ago
24 years ago
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2005 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 3.0 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available through the world-wide-web at the following url: |
  10. | http://www.php.net/license/3_0.txt. |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | license@php.net so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Authors: Zeev Suraski <zeev@zend.com> |
  16. | Jouni Ahto <jouni.ahto@exdec.fi> |
  17. | Yasuo Ohgaki <yohgaki@php.net> |
  18. | Youichi Iwakiri <yiwakiri@st.rim.or.jp> (pg_copy_*) |
  19. | Chris Kings-Lynne <chriskl@php.net> (v3 protocol) |
  20. +----------------------------------------------------------------------+
  21. */
  22. /* $Id$ */
  23. #include <stdlib.h>
  24. #define PHP_PGSQL_PRIVATE 1
  25. #ifdef HAVE_CONFIG_H
  26. #include "config.h"
  27. #endif
  28. #define SMART_STR_PREALLOC 512
  29. #include "php.h"
  30. #include "php_ini.h"
  31. #include "ext/standard/php_standard.h"
  32. #include "ext/standard/php_smart_str.h"
  33. #include "php_pgsql.h"
  34. #include "php_globals.h"
  35. #include "zend_exceptions.h"
  36. #if HAVE_PGSQL
  37. #ifndef InvalidOid
  38. #define InvalidOid ((Oid) 0)
  39. #endif
  40. #define PGSQL_ASSOC 1<<0
  41. #define PGSQL_NUM 1<<1
  42. #define PGSQL_BOTH (PGSQL_ASSOC|PGSQL_NUM)
  43. #define PGSQL_STATUS_LONG 1
  44. #define PGSQL_STATUS_STRING 2
  45. #define PGSQL_MAX_LENGTH_OF_LONG 30
  46. #define PGSQL_MAX_LENGTH_OF_DOUBLE 60
  47. #define PGSQL_RETURN_OID(oid) do { \
  48. if (oid > LONG_MAX) { \
  49. smart_str s = {0}; \
  50. smart_str_append_unsigned(&s, oid); \
  51. smart_str_0(&s); \
  52. RETURN_STRINGL(s.c, s.len, 0); \
  53. } \
  54. RETURN_LONG((long)oid); \
  55. } while(0)
  56. #if HAVE_PQSETNONBLOCKING
  57. #define PQ_SETNONBLOCKING(pg_link, flag) PQsetnonblocking(pg_link, flag)
  58. #else
  59. #define PQ_SETNONBLOCKING(pg_link, flag) 0
  60. #endif
  61. #define CHECK_DEFAULT_LINK(x) if ((x) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No PostgreSQL link opened yet"); }
  62. /* {{{ pgsql_functions[]
  63. */
  64. function_entry pgsql_functions[] = {
  65. /* connection functions */
  66. PHP_FE(pg_connect, NULL)
  67. PHP_FE(pg_pconnect, NULL)
  68. PHP_FE(pg_close, NULL)
  69. PHP_FE(pg_connection_status, NULL)
  70. PHP_FE(pg_connection_busy, NULL)
  71. PHP_FE(pg_connection_reset, NULL)
  72. PHP_FE(pg_host, NULL)
  73. PHP_FE(pg_dbname, NULL)
  74. PHP_FE(pg_port, NULL)
  75. PHP_FE(pg_tty, NULL)
  76. PHP_FE(pg_options, NULL)
  77. PHP_FE(pg_version, NULL)
  78. PHP_FE(pg_ping, NULL)
  79. #if HAVE_PQPARAMETERSTATUS
  80. PHP_FE(pg_parameter_status, NULL)
  81. #endif
  82. #if HAVE_PGTRANSACTIONSTATUS
  83. PHP_FE(pg_transaction_status, NULL)
  84. #endif
  85. /* query functions */
  86. PHP_FE(pg_query, NULL)
  87. #if HAVE_PQEXECPARAMS
  88. PHP_FE(pg_query_params, NULL)
  89. #endif
  90. #if HAVE_PQPREPARE
  91. PHP_FE(pg_prepare, NULL)
  92. #endif
  93. #if HAVE_PQEXECPREPARED
  94. PHP_FE(pg_execute, NULL)
  95. #endif
  96. PHP_FE(pg_send_query, NULL)
  97. #if HAVE_PQSENDQUERYPARAMS
  98. PHP_FE(pg_send_query_params, NULL)
  99. #endif
  100. #if HAVE_PQSENDPREPARE
  101. PHP_FE(pg_send_prepare, NULL)
  102. #endif
  103. #if HAVE_PQSENDQUERYPREPARED
  104. PHP_FE(pg_send_execute, NULL)
  105. #endif
  106. PHP_FE(pg_cancel_query, NULL)
  107. /* result functions */
  108. PHP_FE(pg_fetch_result, NULL)
  109. PHP_FE(pg_fetch_row, NULL)
  110. PHP_FE(pg_fetch_assoc, NULL)
  111. PHP_FE(pg_fetch_array, NULL)
  112. PHP_FE(pg_fetch_object, NULL)
  113. PHP_FE(pg_fetch_all, NULL)
  114. PHP_FE(pg_fetch_all_columns, NULL)
  115. #if HAVE_PQCMDTUPLES
  116. PHP_FE(pg_affected_rows,NULL)
  117. #endif
  118. PHP_FE(pg_get_result, NULL)
  119. PHP_FE(pg_result_seek, NULL)
  120. PHP_FE(pg_result_status,NULL)
  121. PHP_FE(pg_free_result, NULL)
  122. PHP_FE(pg_last_oid, NULL)
  123. PHP_FE(pg_num_rows, NULL)
  124. PHP_FE(pg_num_fields, NULL)
  125. PHP_FE(pg_field_name, NULL)
  126. PHP_FE(pg_field_num, NULL)
  127. PHP_FE(pg_field_size, NULL)
  128. PHP_FE(pg_field_type, NULL)
  129. PHP_FE(pg_field_type_oid, NULL)
  130. PHP_FE(pg_field_prtlen, NULL)
  131. PHP_FE(pg_field_is_null,NULL)
  132. /* async message function */
  133. PHP_FE(pg_get_notify, NULL)
  134. PHP_FE(pg_get_pid, NULL)
  135. /* error message functions */
  136. PHP_FE(pg_result_error, NULL)
  137. #if HAVE_PQRESULTERRORFIELD
  138. PHP_FE(pg_result_error_field, NULL)
  139. #endif
  140. PHP_FE(pg_last_error, NULL)
  141. PHP_FE(pg_last_notice, NULL)
  142. /* copy functions */
  143. PHP_FE(pg_put_line, NULL)
  144. PHP_FE(pg_end_copy, NULL)
  145. PHP_FE(pg_copy_to, NULL)
  146. PHP_FE(pg_copy_from, NULL)
  147. /* debug functions */
  148. PHP_FE(pg_trace, NULL)
  149. PHP_FE(pg_untrace, NULL)
  150. /* large object functions */
  151. PHP_FE(pg_lo_create, NULL)
  152. PHP_FE(pg_lo_unlink, NULL)
  153. PHP_FE(pg_lo_open, NULL)
  154. PHP_FE(pg_lo_close, NULL)
  155. PHP_FE(pg_lo_read, NULL)
  156. PHP_FE(pg_lo_write, NULL)
  157. PHP_FE(pg_lo_read_all, NULL)
  158. PHP_FE(pg_lo_import, NULL)
  159. PHP_FE(pg_lo_export, NULL)
  160. PHP_FE(pg_lo_seek, NULL)
  161. PHP_FE(pg_lo_tell, NULL)
  162. /* utility functions */
  163. #if HAVE_PQESCAPE
  164. PHP_FE(pg_escape_string,NULL)
  165. PHP_FE(pg_escape_bytea, NULL)
  166. PHP_FE(pg_unescape_bytea, NULL)
  167. #endif
  168. #if HAVE_PQSETERRORVERBOSITY
  169. PHP_FE(pg_set_error_verbosity, NULL)
  170. #endif
  171. #if HAVE_PQCLIENTENCODING
  172. PHP_FE(pg_client_encoding, NULL)
  173. PHP_FE(pg_set_client_encoding, NULL)
  174. #endif
  175. /* misc function */
  176. PHP_FE(pg_meta_data, NULL)
  177. PHP_FE(pg_convert, NULL)
  178. PHP_FE(pg_insert, NULL)
  179. PHP_FE(pg_update, NULL)
  180. PHP_FE(pg_delete, NULL)
  181. PHP_FE(pg_select, NULL)
  182. /* aliases for downwards compatibility */
  183. PHP_FALIAS(pg_exec, pg_query, NULL)
  184. PHP_FALIAS(pg_getlastoid, pg_last_oid, NULL)
  185. #if HAVE_PQCMDTUPLES
  186. PHP_FALIAS(pg_cmdtuples, pg_affected_rows, NULL)
  187. #endif
  188. PHP_FALIAS(pg_errormessage, pg_last_error, NULL)
  189. PHP_FALIAS(pg_numrows, pg_num_rows, NULL)
  190. PHP_FALIAS(pg_numfields, pg_num_fields, NULL)
  191. PHP_FALIAS(pg_fieldname, pg_field_name, NULL)
  192. PHP_FALIAS(pg_fieldsize, pg_field_size, NULL)
  193. PHP_FALIAS(pg_fieldtype, pg_field_type, NULL)
  194. PHP_FALIAS(pg_fieldnum, pg_field_num, NULL)
  195. PHP_FALIAS(pg_fieldprtlen, pg_field_prtlen, NULL)
  196. PHP_FALIAS(pg_fieldisnull, pg_field_is_null, NULL)
  197. PHP_FALIAS(pg_freeresult, pg_free_result, NULL)
  198. PHP_FALIAS(pg_result, pg_fetch_result, NULL)
  199. PHP_FALIAS(pg_loreadall, pg_lo_read_all, NULL)
  200. PHP_FALIAS(pg_locreate, pg_lo_create, NULL)
  201. PHP_FALIAS(pg_lounlink, pg_lo_unlink, NULL)
  202. PHP_FALIAS(pg_loopen, pg_lo_open, NULL)
  203. PHP_FALIAS(pg_loclose, pg_lo_close, NULL)
  204. PHP_FALIAS(pg_loread, pg_lo_read, NULL)
  205. PHP_FALIAS(pg_lowrite, pg_lo_write, NULL)
  206. PHP_FALIAS(pg_loimport, pg_lo_import, NULL)
  207. PHP_FALIAS(pg_loexport, pg_lo_export, NULL)
  208. #if HAVE_PQCLIENTENCODING
  209. PHP_FALIAS(pg_clientencoding, pg_client_encoding, NULL)
  210. PHP_FALIAS(pg_setclientencoding, pg_set_client_encoding, NULL)
  211. #endif
  212. {NULL, NULL, NULL}
  213. };
  214. /* }}} */
  215. /* {{{ pgsql_module_entry
  216. */
  217. zend_module_entry pgsql_module_entry = {
  218. STANDARD_MODULE_HEADER,
  219. "pgsql",
  220. pgsql_functions,
  221. PHP_MINIT(pgsql),
  222. PHP_MSHUTDOWN(pgsql),
  223. PHP_RINIT(pgsql),
  224. PHP_RSHUTDOWN(pgsql),
  225. PHP_MINFO(pgsql),
  226. NO_VERSION_YET,
  227. STANDARD_MODULE_PROPERTIES
  228. };
  229. /* }}} */
  230. #ifdef COMPILE_DL_PGSQL
  231. ZEND_GET_MODULE(pgsql)
  232. #endif
  233. static int le_link, le_plink, le_result, le_lofp, le_string;
  234. ZEND_DECLARE_MODULE_GLOBALS(pgsql);
  235. /* {{{ _php_pgsql_trim_message */
  236. static char * _php_pgsql_trim_message(const char *message, int *len)
  237. {
  238. register int i = strlen(message)-1;
  239. if (i>1 && (message[i-1] == '\r' || message[i-1] == '\n') && message[i] == '.') {
  240. --i;
  241. }
  242. while (i>0 && (message[i] == '\r' || message[i] == '\n')) {
  243. --i;
  244. }
  245. ++i;
  246. if (len) {
  247. *len = i;
  248. }
  249. return estrndup(message, i);
  250. }
  251. /* }}} */
  252. /* {{{ _php_pgsql_trim_result */
  253. static inline char * _php_pgsql_trim_result(PGconn * pgsql, char **buf)
  254. {
  255. return *buf = _php_pgsql_trim_message(PQerrorMessage(pgsql), NULL);
  256. }
  257. /* }}} */
  258. #define PQErrorMessageTrim(pgsql, buf) _php_pgsql_trim_result(pgsql, buf)
  259. #define PHP_PQ_ERROR(text, pgsql) { \
  260. char *msgbuf = _php_pgsql_trim_message(PQerrorMessage(pgsql), NULL); \
  261. php_error_docref(NULL TSRMLS_CC, E_WARNING, text, msgbuf); \
  262. efree(msgbuf); \
  263. } \
  264. /* {{{ php_pgsql_set_default_link
  265. */
  266. static void php_pgsql_set_default_link(int id TSRMLS_DC)
  267. {
  268. zend_list_addref(id);
  269. if (PGG(default_link) != -1) {
  270. zend_list_delete(PGG(default_link));
  271. }
  272. PGG(default_link) = id;
  273. }
  274. /* }}} */
  275. /* {{{ _close_pgsql_link
  276. */
  277. static void _close_pgsql_link(zend_rsrc_list_entry *rsrc TSRMLS_DC)
  278. {
  279. PGconn *link = (PGconn *)rsrc->ptr;
  280. PGresult *res;
  281. while ((res = PQgetResult(link))) {
  282. PQclear(res);
  283. }
  284. PQfinish(link);
  285. PGG(num_links)--;
  286. }
  287. /* }}} */
  288. /* {{{ _close_pgsql_plink
  289. */
  290. static void _close_pgsql_plink(zend_rsrc_list_entry *rsrc TSRMLS_DC)
  291. {
  292. PGconn *link = (PGconn *)rsrc->ptr;
  293. PGresult *res;
  294. while ((res = PQgetResult(link))) {
  295. PQclear(res);
  296. }
  297. PQfinish(link);
  298. PGG(num_persistent)--;
  299. PGG(num_links)--;
  300. }
  301. /* }}} */
  302. /* {{{ _php_pgsql_notice_handler
  303. */
  304. static void _php_pgsql_notice_handler(void *resource_id, const char *message)
  305. {
  306. php_pgsql_notice *notice;
  307. TSRMLS_FETCH();
  308. if (! PGG(ignore_notices)) {
  309. notice = (php_pgsql_notice *)emalloc(sizeof(php_pgsql_notice));
  310. notice->message = _php_pgsql_trim_message(message, &notice->len);
  311. if (PGG(log_notices)) {
  312. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "%s", notice->message);
  313. }
  314. zend_hash_index_update(&PGG(notices), *(int *)resource_id, (void **)&notice, sizeof(php_pgsql_notice *), NULL);
  315. }
  316. }
  317. /* }}} */
  318. #define PHP_PGSQL_NOTICE_PTR_DTOR (void (*)(void *))_php_pgsql_notice_ptr_dtor
  319. /* {{{ _php_pgsql_notice_dtor
  320. */
  321. static void _php_pgsql_notice_ptr_dtor(void **ptr)
  322. {
  323. php_pgsql_notice *notice = (php_pgsql_notice *)*ptr;
  324. if (notice) {
  325. efree(notice->message);
  326. efree(notice);
  327. notice = NULL;
  328. }
  329. }
  330. /* }}} */
  331. /* {{{ _rollback_transactions
  332. */
  333. static int _rollback_transactions(zend_rsrc_list_entry *rsrc TSRMLS_DC)
  334. {
  335. PGconn *link;
  336. PGresult *res;
  337. int orig;
  338. if (Z_TYPE_P(rsrc) != le_plink)
  339. return 0;
  340. link = (PGconn *) rsrc->ptr;
  341. if (PQ_SETNONBLOCKING(link, 0)) {
  342. php_error_docref("ref.pgsql" TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
  343. return -1;
  344. }
  345. while ((res = PQgetResult(link))) {
  346. PQclear(res);
  347. }
  348. #if HAVE_PGTRANSACTIONSTATUS && HAVE_PQPROTOCOLVERSION
  349. if ((PQprotocolVersion(link) >= 3 && PQtransactionStatus(link) != PQTRANS_IDLE) || PQprotocolVersion(link) < 3)
  350. #endif
  351. {
  352. orig = PGG(ignore_notices);
  353. PGG(ignore_notices) = 1;
  354. #if HAVE_PGTRANSACTIONSTATUS && HAVE_PQPROTOCOLVERSION
  355. res = PQexec(link,"ROLLBACK;");
  356. #else
  357. res = PQexec(link,"BEGIN;");
  358. PQclear(res);
  359. res = PQexec(link,"ROLLBACK;");
  360. #endif
  361. PQclear(res);
  362. PGG(ignore_notices) = orig;
  363. }
  364. return 0;
  365. }
  366. /* }}} */
  367. /* {{{ _free_ptr
  368. */
  369. static void _free_ptr(zend_rsrc_list_entry *rsrc TSRMLS_DC)
  370. {
  371. pgLofp *lofp = (pgLofp *)rsrc->ptr;
  372. efree(lofp);
  373. }
  374. /* }}} */
  375. /* {{{ _free_result
  376. */
  377. static void _free_result(zend_rsrc_list_entry *rsrc TSRMLS_DC)
  378. {
  379. pgsql_result_handle *pg_result = (pgsql_result_handle *)rsrc->ptr;
  380. PQclear(pg_result->result);
  381. efree(pg_result);
  382. }
  383. /* }}} */
  384. /* {{{ PHP_INI
  385. */
  386. PHP_INI_BEGIN()
  387. STD_PHP_INI_BOOLEAN( "pgsql.allow_persistent", "1", PHP_INI_SYSTEM, OnUpdateBool, allow_persistent, zend_pgsql_globals, pgsql_globals)
  388. STD_PHP_INI_ENTRY_EX("pgsql.max_persistent", "-1", PHP_INI_SYSTEM, OnUpdateLong, max_persistent, zend_pgsql_globals, pgsql_globals, display_link_numbers)
  389. STD_PHP_INI_ENTRY_EX("pgsql.max_links", "-1", PHP_INI_SYSTEM, OnUpdateLong, max_links, zend_pgsql_globals, pgsql_globals, display_link_numbers)
  390. STD_PHP_INI_BOOLEAN( "pgsql.auto_reset_persistent", "0", PHP_INI_SYSTEM, OnUpdateBool, auto_reset_persistent, zend_pgsql_globals, pgsql_globals)
  391. STD_PHP_INI_BOOLEAN( "pgsql.ignore_notice", "0", PHP_INI_ALL, OnUpdateBool, ignore_notices, zend_pgsql_globals, pgsql_globals)
  392. STD_PHP_INI_BOOLEAN( "pgsql.log_notice", "0", PHP_INI_ALL, OnUpdateBool, log_notices, zend_pgsql_globals, pgsql_globals)
  393. PHP_INI_END()
  394. /* }}} */
  395. /* {{{ php_pgsql_init_globals
  396. */
  397. static void php_pgsql_init_globals(zend_pgsql_globals *pgsql_globals)
  398. {
  399. memset(pgsql_globals, 0, sizeof(zend_pgsql_globals));
  400. /* Initilize notice message hash at MINIT only */
  401. zend_hash_init_ex(&pgsql_globals->notices, 0, NULL, PHP_PGSQL_NOTICE_PTR_DTOR, 1, 0);
  402. }
  403. /* }}} */
  404. /* {{{ PHP_MINIT_FUNCTION
  405. */
  406. PHP_MINIT_FUNCTION(pgsql)
  407. {
  408. ZEND_INIT_MODULE_GLOBALS(pgsql, php_pgsql_init_globals, NULL);
  409. REGISTER_INI_ENTRIES();
  410. le_link = zend_register_list_destructors_ex(_close_pgsql_link, NULL, "pgsql link", module_number);
  411. le_plink = zend_register_list_destructors_ex(NULL, _close_pgsql_plink, "pgsql link persistent", module_number);
  412. le_result = zend_register_list_destructors_ex(_free_result, NULL, "pgsql result", module_number);
  413. le_lofp = zend_register_list_destructors_ex(_free_ptr, NULL, "pgsql large object", module_number);
  414. le_string = zend_register_list_destructors_ex(_free_ptr, NULL, "pgsql string", module_number);
  415. /* For connection option */
  416. REGISTER_LONG_CONSTANT("PGSQL_CONNECT_FORCE_NEW", PGSQL_CONNECT_FORCE_NEW, CONST_CS | CONST_PERSISTENT);
  417. /* For pg_fetch_array() */
  418. REGISTER_LONG_CONSTANT("PGSQL_ASSOC", PGSQL_ASSOC, CONST_CS | CONST_PERSISTENT);
  419. REGISTER_LONG_CONSTANT("PGSQL_NUM", PGSQL_NUM, CONST_CS | CONST_PERSISTENT);
  420. REGISTER_LONG_CONSTANT("PGSQL_BOTH", PGSQL_BOTH, CONST_CS | CONST_PERSISTENT);
  421. /* For pg_connection_status() */
  422. REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_BAD", CONNECTION_BAD, CONST_CS | CONST_PERSISTENT);
  423. REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_OK", CONNECTION_OK, CONST_CS | CONST_PERSISTENT);
  424. #if HAVE_PGTRANSACTIONSTATUS
  425. /* For pg_transaction_status() */
  426. REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_IDLE", PQTRANS_IDLE, CONST_CS | CONST_PERSISTENT);
  427. REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_ACTIVE", PQTRANS_ACTIVE, CONST_CS | CONST_PERSISTENT);
  428. REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_INTRANS", PQTRANS_INTRANS, CONST_CS | CONST_PERSISTENT);
  429. REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_INERROR", PQTRANS_INERROR, CONST_CS | CONST_PERSISTENT);
  430. REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_UNKNOWN", PQTRANS_UNKNOWN, CONST_CS | CONST_PERSISTENT);
  431. #endif
  432. #if HAVE_PQSETERRORVERBOSITY
  433. /* For pg_set_error_verbosity() */
  434. REGISTER_LONG_CONSTANT("PGSQL_ERRORS_TERSE", PQERRORS_TERSE, CONST_CS | CONST_PERSISTENT);
  435. REGISTER_LONG_CONSTANT("PGSQL_ERRORS_DEFAULT", PQERRORS_DEFAULT, CONST_CS | CONST_PERSISTENT);
  436. REGISTER_LONG_CONSTANT("PGSQL_ERRORS_VERBOSE", PQERRORS_VERBOSE, CONST_CS | CONST_PERSISTENT);
  437. #endif
  438. /* For lo_seek() */
  439. REGISTER_LONG_CONSTANT("PGSQL_SEEK_SET", SEEK_SET, CONST_CS | CONST_PERSISTENT);
  440. REGISTER_LONG_CONSTANT("PGSQL_SEEK_CUR", SEEK_CUR, CONST_CS | CONST_PERSISTENT);
  441. REGISTER_LONG_CONSTANT("PGSQL_SEEK_END", SEEK_END, CONST_CS | CONST_PERSISTENT);
  442. /* For pg_result_status() return value type */
  443. REGISTER_LONG_CONSTANT("PGSQL_STATUS_LONG", PGSQL_STATUS_LONG, CONST_CS | CONST_PERSISTENT);
  444. REGISTER_LONG_CONSTANT("PGSQL_STATUS_STRING", PGSQL_STATUS_STRING, CONST_CS | CONST_PERSISTENT);
  445. /* For pg_result_status() return value */
  446. REGISTER_LONG_CONSTANT("PGSQL_EMPTY_QUERY", PGRES_EMPTY_QUERY, CONST_CS | CONST_PERSISTENT);
  447. REGISTER_LONG_CONSTANT("PGSQL_COMMAND_OK", PGRES_COMMAND_OK, CONST_CS | CONST_PERSISTENT);
  448. REGISTER_LONG_CONSTANT("PGSQL_TUPLES_OK", PGRES_TUPLES_OK, CONST_CS | CONST_PERSISTENT);
  449. REGISTER_LONG_CONSTANT("PGSQL_COPY_OUT", PGRES_COPY_OUT, CONST_CS | CONST_PERSISTENT);
  450. REGISTER_LONG_CONSTANT("PGSQL_COPY_IN", PGRES_COPY_IN, CONST_CS | CONST_PERSISTENT);
  451. REGISTER_LONG_CONSTANT("PGSQL_BAD_RESPONSE", PGRES_BAD_RESPONSE, CONST_CS | CONST_PERSISTENT);
  452. REGISTER_LONG_CONSTANT("PGSQL_NONFATAL_ERROR", PGRES_NONFATAL_ERROR, CONST_CS | CONST_PERSISTENT);
  453. REGISTER_LONG_CONSTANT("PGSQL_FATAL_ERROR", PGRES_FATAL_ERROR, CONST_CS | CONST_PERSISTENT);
  454. #if HAVE_PQRESULTERRORFIELD
  455. /* For pg_result_error_field() field codes */
  456. REGISTER_LONG_CONSTANT("PGSQL_DIAG_SEVERITY", PG_DIAG_SEVERITY, CONST_CS | CONST_PERSISTENT);
  457. REGISTER_LONG_CONSTANT("PGSQL_DIAG_SQLSTATE", PG_DIAG_SQLSTATE, CONST_CS | CONST_PERSISTENT);
  458. REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_PRIMARY", PG_DIAG_MESSAGE_PRIMARY, CONST_CS | CONST_PERSISTENT);
  459. REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_DETAIL", PG_DIAG_MESSAGE_DETAIL, CONST_CS | CONST_PERSISTENT);
  460. REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_HINT", PG_DIAG_MESSAGE_HINT, CONST_CS | CONST_PERSISTENT);
  461. REGISTER_LONG_CONSTANT("PGSQL_DIAG_STATEMENT_POSITION", PG_DIAG_STATEMENT_POSITION, CONST_CS | CONST_PERSISTENT);
  462. #ifdef PG_DIAG_INTERNAL_POSITION
  463. REGISTER_LONG_CONSTANT("PGSQL_DIAG_INTERNAL_POSITION", PG_DIAG_INTERNAL_POSITION, CONST_CS | CONST_PERSISTENT);
  464. #endif
  465. #ifdef PG_DIAG_INTERNAL_QUERY
  466. REGISTER_LONG_CONSTANT("PGSQL_DIAG_INTERNAL_QUERY", PG_DIAG_INTERNAL_QUERY, CONST_CS | CONST_PERSISTENT);
  467. #endif
  468. REGISTER_LONG_CONSTANT("PGSQL_DIAG_CONTEXT", PG_DIAG_CONTEXT, CONST_CS | CONST_PERSISTENT);
  469. REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_FILE", PG_DIAG_SOURCE_FILE, CONST_CS | CONST_PERSISTENT);
  470. REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_LINE", PG_DIAG_SOURCE_LINE, CONST_CS | CONST_PERSISTENT);
  471. REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_FUNCTION", PG_DIAG_SOURCE_FUNCTION, CONST_CS | CONST_PERSISTENT);
  472. #endif
  473. /* pg_convert options */
  474. REGISTER_LONG_CONSTANT("PGSQL_CONV_IGNORE_DEFAULT", PGSQL_CONV_IGNORE_DEFAULT, CONST_CS | CONST_PERSISTENT);
  475. REGISTER_LONG_CONSTANT("PGSQL_CONV_FORCE_NULL", PGSQL_CONV_FORCE_NULL, CONST_CS | CONST_PERSISTENT);
  476. REGISTER_LONG_CONSTANT("PGSQL_CONV_IGNORE_NOT_NULL", PGSQL_CONV_IGNORE_NOT_NULL, CONST_CS | CONST_PERSISTENT);
  477. /* pg_insert/update/delete/select options */
  478. REGISTER_LONG_CONSTANT("PGSQL_DML_NO_CONV", PGSQL_DML_NO_CONV, CONST_CS | CONST_PERSISTENT);
  479. REGISTER_LONG_CONSTANT("PGSQL_DML_EXEC", PGSQL_DML_EXEC, CONST_CS | CONST_PERSISTENT);
  480. REGISTER_LONG_CONSTANT("PGSQL_DML_ASYNC", PGSQL_DML_ASYNC, CONST_CS | CONST_PERSISTENT);
  481. REGISTER_LONG_CONSTANT("PGSQL_DML_STRING", PGSQL_DML_STRING, CONST_CS | CONST_PERSISTENT);
  482. return SUCCESS;
  483. }
  484. /* }}} */
  485. /* {{{ PHP_MSHUTDOWN_FUNCTION
  486. */
  487. PHP_MSHUTDOWN_FUNCTION(pgsql)
  488. {
  489. UNREGISTER_INI_ENTRIES();
  490. zend_hash_destroy(&PGG(notices));
  491. return SUCCESS;
  492. }
  493. /* }}} */
  494. /* {{{ PHP_RINIT_FUNCTION
  495. */
  496. PHP_RINIT_FUNCTION(pgsql)
  497. {
  498. PGG(default_link)=-1;
  499. PGG(num_links) = PGG(num_persistent);
  500. return SUCCESS;
  501. }
  502. /* }}} */
  503. /* {{{ PHP_RSHUTDOWN_FUNCTION
  504. */
  505. PHP_RSHUTDOWN_FUNCTION(pgsql)
  506. {
  507. /* clean up notice messages */
  508. zend_hash_clean(&PGG(notices));
  509. /* clean up persistent connection */
  510. zend_hash_apply(&EG(persistent_list), (apply_func_t) _rollback_transactions TSRMLS_CC);
  511. return SUCCESS;
  512. }
  513. /* }}} */
  514. /* {{{ PHP_MINFO_FUNCTION
  515. */
  516. PHP_MINFO_FUNCTION(pgsql)
  517. {
  518. char buf[256];
  519. php_info_print_table_start();
  520. php_info_print_table_header(2, "PostgreSQL Support", "enabled");
  521. #if HAVE_PG_CONFIG_H
  522. php_info_print_table_row(2, "PostgreSQL(libpq) Version", PG_VERSION);
  523. #ifdef HAVE_PGSQL_WITH_MULTIBYTE_SUPPORT
  524. php_info_print_table_row(2, "Multibyte character support", "enabled");
  525. #else
  526. php_info_print_table_row(2, "Multibyte character support", "disabled");
  527. #endif
  528. #ifdef USE_SSL
  529. php_info_print_table_row(2, "SSL support", "enabled");
  530. #else
  531. php_info_print_table_row(2, "SSL support", "disabled");
  532. #endif
  533. #endif /* HAVE_PG_CONFIG_H */
  534. sprintf(buf, "%ld", PGG(num_persistent));
  535. php_info_print_table_row(2, "Active Persistent Links", buf);
  536. sprintf(buf, "%ld", PGG(num_links));
  537. php_info_print_table_row(2, "Active Links", buf);
  538. php_info_print_table_end();
  539. DISPLAY_INI_ENTRIES();
  540. }
  541. /* }}} */
  542. /* {{{ php_pgsql_do_connect
  543. */
  544. static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent)
  545. {
  546. char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL;
  547. PGconn *pgsql;
  548. smart_str str = {0};
  549. zval **args[5];
  550. int i, connect_type = 0;
  551. PGresult *pg_result;
  552. if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5
  553. || zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) {
  554. WRONG_PARAM_COUNT;
  555. }
  556. smart_str_appends(&str, "pgsql");
  557. for (i = 0; i < ZEND_NUM_ARGS(); i++) {
  558. convert_to_string_ex(args[i]);
  559. smart_str_appendc(&str, '_');
  560. smart_str_appendl(&str, Z_STRVAL_PP(args[i]), Z_STRLEN_PP(args[i]));
  561. }
  562. smart_str_0(&str);
  563. if (ZEND_NUM_ARGS() == 1) { /* new style, using connection string */
  564. connstring = Z_STRVAL_PP(args[0]);
  565. } else if (ZEND_NUM_ARGS() == 2 ) { /* Safe to add conntype_option, since 2 args was illegal */
  566. connstring = Z_STRVAL_PP(args[0]);
  567. convert_to_long_ex(args[1]);
  568. connect_type = Z_LVAL_PP(args[1]);
  569. } else {
  570. host = Z_STRVAL_PP(args[0]);
  571. port = Z_STRVAL_PP(args[1]);
  572. dbname = Z_STRVAL_PP(args[ZEND_NUM_ARGS()-1]);
  573. switch (ZEND_NUM_ARGS()) {
  574. case 5:
  575. tty = Z_STRVAL_PP(args[3]);
  576. /* fall through */
  577. case 4:
  578. options = Z_STRVAL_PP(args[2]);
  579. break;
  580. }
  581. }
  582. if (persistent && PGG(allow_persistent)) {
  583. list_entry *le;
  584. /* try to find if we already have this link in our persistent list */
  585. if (zend_hash_find(&EG(persistent_list), str.c, str.len+1, (void **) &le)==FAILURE) { /* we don't */
  586. list_entry new_le;
  587. if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
  588. php_error_docref(NULL TSRMLS_CC, E_WARNING,
  589. "Cannot create new link. Too many open links (%ld)", PGG(num_links));
  590. goto err;
  591. }
  592. if (PGG(max_persistent)!=-1 && PGG(num_persistent)>=PGG(max_persistent)) {
  593. php_error_docref(NULL TSRMLS_CC, E_WARNING,
  594. "Cannot create new link. Too many open persistent links (%ld)", PGG(num_persistent));
  595. goto err;
  596. }
  597. /* create the link */
  598. if (connstring) {
  599. pgsql=PQconnectdb(connstring);
  600. } else {
  601. pgsql=PQsetdb(host,port,options,tty,dbname);
  602. }
  603. if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
  604. PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql)
  605. if (pgsql) {
  606. PQfinish(pgsql);
  607. }
  608. goto err;
  609. }
  610. /* hash it up */
  611. Z_TYPE(new_le) = le_plink;
  612. new_le.ptr = pgsql;
  613. if (zend_hash_update(&EG(persistent_list), str.c, str.len+1, (void *) &new_le, sizeof(list_entry), NULL)==FAILURE) {
  614. goto err;
  615. }
  616. PGG(num_links)++;
  617. PGG(num_persistent)++;
  618. } else { /* we do */
  619. if (Z_TYPE_P(le) != le_plink) {
  620. RETURN_FALSE;
  621. }
  622. /* ensure that the link did not die */
  623. if (PGG(auto_reset_persistent) & 1) {
  624. /* need to send & get something from backend to
  625. make sure we catch CONNECTION_BAD everytime */
  626. PGresult *pg_result;
  627. pg_result = PQexec(le->ptr, "select 1");
  628. PQclear(pg_result);
  629. }
  630. if (PQstatus(le->ptr)==CONNECTION_BAD) { /* the link died */
  631. if (le->ptr == NULL) {
  632. if (connstring) {
  633. le->ptr=PQconnectdb(connstring);
  634. } else {
  635. le->ptr=PQsetdb(host,port,options,tty,dbname);
  636. }
  637. }
  638. else {
  639. PQreset(le->ptr);
  640. }
  641. if (le->ptr==NULL || PQstatus(le->ptr)==CONNECTION_BAD) {
  642. php_error_docref(NULL TSRMLS_CC, E_WARNING,"PostgreSQL link lost, unable to reconnect");
  643. zend_hash_del(&EG(persistent_list),str.c,str.len+1);
  644. goto err;
  645. }
  646. }
  647. pgsql = (PGconn *) le->ptr;
  648. #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS
  649. if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 7.2) {
  650. #else
  651. if (atof(PG_VERSION) >= 7.2) {
  652. #endif
  653. pg_result = PQexec(pgsql, "RESET ALL;");
  654. PQclear(pg_result);
  655. }
  656. }
  657. ZEND_REGISTER_RESOURCE(return_value, pgsql, le_plink);
  658. } else { /* Non persistent connection */
  659. list_entry *index_ptr,new_index_ptr;
  660. /* first we check the hash for the hashed_details key. if it exists,
  661. * it should point us to the right offset where the actual pgsql link sits.
  662. * if it doesn't, open a new pgsql link, add it to the resource list,
  663. * and add a pointer to it with hashed_details as the key.
  664. */
  665. if (!(connect_type & PGSQL_CONNECT_FORCE_NEW)
  666. && zend_hash_find(&EG(regular_list),str.c,str.len+1,(void **) &index_ptr)==SUCCESS) {
  667. int type,link;
  668. void *ptr;
  669. if (Z_TYPE_P(index_ptr) != le_index_ptr) {
  670. RETURN_FALSE;
  671. }
  672. link = (int) index_ptr->ptr;
  673. ptr = zend_list_find(link,&type); /* check if the link is still there */
  674. if (ptr && (type==le_link || type==le_plink)) {
  675. Z_LVAL_P(return_value) = link;
  676. zend_list_addref(link);
  677. php_pgsql_set_default_link(link TSRMLS_CC);
  678. Z_TYPE_P(return_value) = IS_RESOURCE;
  679. goto cleanup;
  680. } else {
  681. zend_hash_del(&EG(regular_list),str.c,str.len+1);
  682. }
  683. }
  684. if (PGG(max_links)!=-1 && PGG(num_links)>=PGG(max_links)) {
  685. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create new link. Too many open links (%ld)", PGG(num_links));
  686. goto err;
  687. }
  688. if (connstring) {
  689. pgsql = PQconnectdb(connstring);
  690. } else {
  691. pgsql = PQsetdb(host,port,options,tty,dbname);
  692. }
  693. if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) {
  694. PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql);
  695. if (pgsql) {
  696. PQfinish(pgsql);
  697. }
  698. goto err;
  699. }
  700. /* add it to the list */
  701. ZEND_REGISTER_RESOURCE(return_value, pgsql, le_link);
  702. /* add it to the hash */
  703. new_index_ptr.ptr = (void *) Z_LVAL_P(return_value);
  704. Z_TYPE(new_index_ptr) = le_index_ptr;
  705. if (zend_hash_update(&EG(regular_list),str.c,str.len+1,(void *) &new_index_ptr, sizeof(list_entry), NULL)==FAILURE) {
  706. goto err;
  707. }
  708. PGG(num_links)++;
  709. }
  710. /* set notice processer */
  711. if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) {
  712. PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void *)&Z_RESVAL_P(return_value));
  713. }
  714. php_pgsql_set_default_link(Z_LVAL_P(return_value) TSRMLS_CC);
  715. cleanup:
  716. smart_str_free(&str);
  717. return;
  718. err:
  719. smart_str_free(&str);
  720. RETURN_FALSE;
  721. }
  722. /* }}} */
  723. #if 0
  724. /* {{{ php_pgsql_get_default_link
  725. */
  726. static int php_pgsql_get_default_link(INTERNAL_FUNCTION_PARAMETERS)
  727. {
  728. if (PGG(default_link)==-1) { /* no link opened yet, implicitly open one */
  729. ht = 0;
  730. php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
  731. }
  732. return PGG(default_link);
  733. }
  734. /* }}} */
  735. #endif
  736. /* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database)
  737. Open a PostgreSQL connection */
  738. PHP_FUNCTION(pg_connect)
  739. {
  740. php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0);
  741. }
  742. /* }}} */
  743. /* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database)
  744. Open a persistent PostgreSQL connection */
  745. PHP_FUNCTION(pg_pconnect)
  746. {
  747. php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1);
  748. }
  749. /* }}} */
  750. /* {{{ proto bool pg_close([resource connection])
  751. Close a PostgreSQL connection */
  752. PHP_FUNCTION(pg_close)
  753. {
  754. zval **pgsql_link = NULL;
  755. int id;
  756. PGconn *pgsql;
  757. switch (ZEND_NUM_ARGS()) {
  758. case 0:
  759. id = PGG(default_link);
  760. CHECK_DEFAULT_LINK(id);
  761. break;
  762. case 1:
  763. if (zend_get_parameters_ex(1, &pgsql_link)==FAILURE) {
  764. RETURN_FALSE;
  765. }
  766. id = -1;
  767. break;
  768. default:
  769. WRONG_PARAM_COUNT;
  770. break;
  771. }
  772. if (pgsql_link == NULL && id == -1) {
  773. RETURN_FALSE;
  774. }
  775. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  776. if (id==-1) { /* explicit resource number */
  777. zend_list_delete(Z_RESVAL_PP(pgsql_link));
  778. }
  779. if (id!=-1
  780. || (pgsql_link && Z_RESVAL_PP(pgsql_link)==PGG(default_link))) {
  781. zend_list_delete(PGG(default_link));
  782. PGG(default_link) = -1;
  783. }
  784. RETURN_TRUE;
  785. }
  786. /* }}} */
  787. #define PHP_PG_DBNAME 1
  788. #define PHP_PG_ERROR_MESSAGE 2
  789. #define PHP_PG_OPTIONS 3
  790. #define PHP_PG_PORT 4
  791. #define PHP_PG_TTY 5
  792. #define PHP_PG_HOST 6
  793. #define PHP_PG_VERSION 7
  794. /* {{{ php_pgsql_get_link_info
  795. */
  796. static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
  797. {
  798. zval **pgsql_link = NULL;
  799. int id = -1;
  800. PGconn *pgsql;
  801. char *msgbuf;
  802. switch(ZEND_NUM_ARGS()) {
  803. case 0:
  804. id = PGG(default_link);
  805. CHECK_DEFAULT_LINK(id);
  806. break;
  807. case 1:
  808. if (zend_get_parameters_ex(1, &pgsql_link)==FAILURE) {
  809. RETURN_FALSE;
  810. }
  811. break;
  812. default:
  813. WRONG_PARAM_COUNT;
  814. break;
  815. }
  816. if (pgsql_link == NULL && id == -1) {
  817. RETURN_FALSE;
  818. }
  819. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  820. switch(entry_type) {
  821. case PHP_PG_DBNAME:
  822. Z_STRVAL_P(return_value) = PQdb(pgsql);
  823. break;
  824. case PHP_PG_ERROR_MESSAGE:
  825. RETURN_STRING(PQErrorMessageTrim(pgsql, &msgbuf), 0);
  826. return;
  827. case PHP_PG_OPTIONS:
  828. Z_STRVAL_P(return_value) = PQoptions(pgsql);
  829. break;
  830. case PHP_PG_PORT:
  831. Z_STRVAL_P(return_value) = PQport(pgsql);
  832. break;
  833. case PHP_PG_TTY:
  834. Z_STRVAL_P(return_value) = PQtty(pgsql);
  835. break;
  836. case PHP_PG_HOST:
  837. Z_STRVAL_P(return_value) = PQhost(pgsql);
  838. break;
  839. case PHP_PG_VERSION:
  840. array_init(return_value);
  841. add_assoc_string(return_value, "client", PG_VERSION, 1);
  842. #if HAVE_PQPROTOCOLVERSION
  843. add_assoc_long(return_value, "protocol", PQprotocolVersion(pgsql));
  844. #if HAVE_PQPARAMETERSTATUS
  845. if (PQprotocolVersion(pgsql) >= 3) {
  846. add_assoc_string(return_value, "server", (char*)PQparameterStatus(pgsql, "server_version"), 1);
  847. }
  848. #endif
  849. #endif
  850. return;
  851. default:
  852. RETURN_FALSE;
  853. }
  854. if (Z_STRVAL_P(return_value)) {
  855. Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
  856. Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
  857. } else {
  858. Z_STRLEN_P(return_value) = 0;
  859. Z_STRVAL_P(return_value) = (char *) estrdup("");
  860. }
  861. Z_TYPE_P(return_value) = IS_STRING;
  862. }
  863. /* }}} */
  864. /* {{{ proto string pg_dbname([resource connection])
  865. Get the database name */
  866. PHP_FUNCTION(pg_dbname)
  867. {
  868. php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME);
  869. }
  870. /* }}} */
  871. /* {{{ proto string pg_last_error([resource connection])
  872. Get the error message string */
  873. PHP_FUNCTION(pg_last_error)
  874. {
  875. php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE);
  876. }
  877. /* }}} */
  878. /* {{{ proto string pg_options([resource connection])
  879. Get the options associated with the connection */
  880. PHP_FUNCTION(pg_options)
  881. {
  882. php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS);
  883. }
  884. /* }}} */
  885. /* {{{ proto int pg_port([resource connection])
  886. Return the port number associated with the connection */
  887. PHP_FUNCTION(pg_port)
  888. {
  889. php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT);
  890. }
  891. /* }}} */
  892. /* {{{ proto string pg_tty([resource connection])
  893. Return the tty name associated with the connection */
  894. PHP_FUNCTION(pg_tty)
  895. {
  896. php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY);
  897. }
  898. /* }}} */
  899. /* {{{ proto string pg_host([resource connection])
  900. Returns the host name associated with the connection */
  901. PHP_FUNCTION(pg_host)
  902. {
  903. php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST);
  904. }
  905. /* }}} */
  906. /* {{{ proto array pg_version([resource connection])
  907. Returns an array with client, protocol and server version (when available) */
  908. PHP_FUNCTION(pg_version)
  909. {
  910. php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION);
  911. }
  912. /* }}} */
  913. #if HAVE_PQPARAMETERSTATUS
  914. /* {{{ proto string|false pg_parameter_status([resource connection,] string param_name)
  915. Returns the value of a server parameter */
  916. PHP_FUNCTION(pg_parameter_status)
  917. {
  918. zval *pgsql_link;
  919. int id;
  920. PGconn *pgsql;
  921. char *param;
  922. int len;
  923. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rs", &pgsql_link, &param, &len) == SUCCESS) {
  924. id = -1;
  925. } else if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &param, &len) == SUCCESS) {
  926. pgsql_link = NULL;
  927. id = PGG(default_link);
  928. } else {
  929. RETURN_FALSE;
  930. }
  931. if (pgsql_link == NULL && id == -1) {
  932. RETURN_FALSE;
  933. }
  934. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  935. param = (char*)PQparameterStatus(pgsql, param);
  936. if (param) {
  937. RETURN_STRING(param, 1);
  938. } else {
  939. RETURN_FALSE;
  940. }
  941. }
  942. /* }}} */
  943. #endif
  944. /* {{{ proto bool pg_ping([resource connection])
  945. Ping database. If connection is bad, try to reconnect. */
  946. PHP_FUNCTION(pg_ping)
  947. {
  948. zval *pgsql_link;
  949. int id;
  950. PGconn *pgsql;
  951. PGresult *res;
  952. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r", &pgsql_link) == SUCCESS) {
  953. id = -1;
  954. } else {
  955. pgsql_link = NULL;
  956. id = PGG(default_link);
  957. }
  958. if (pgsql_link == NULL && id == -1) {
  959. RETURN_FALSE;
  960. }
  961. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  962. /* ping connection */
  963. res = PQexec(pgsql, "SELECT 1;");
  964. PQclear(res);
  965. /* check status. */
  966. if (PQstatus(pgsql) == CONNECTION_OK)
  967. RETURN_TRUE;
  968. /* reset connection if it's broken */
  969. PQreset(pgsql);
  970. if (PQstatus(pgsql) == CONNECTION_OK) {
  971. RETURN_TRUE;
  972. }
  973. RETURN_FALSE;
  974. }
  975. /* }}} */
  976. /* {{{ proto resource pg_query([resource connection,] string query)
  977. Execute a query */
  978. PHP_FUNCTION(pg_query)
  979. {
  980. zval **query, **pgsql_link = NULL;
  981. int id = -1;
  982. int leftover = 0;
  983. PGconn *pgsql;
  984. PGresult *pgsql_result;
  985. ExecStatusType status;
  986. pgsql_result_handle *pg_result;
  987. switch(ZEND_NUM_ARGS()) {
  988. case 1:
  989. if (zend_get_parameters_ex(1, &query)==FAILURE) {
  990. RETURN_FALSE;
  991. }
  992. id = PGG(default_link);
  993. CHECK_DEFAULT_LINK(id);
  994. break;
  995. case 2:
  996. if (zend_get_parameters_ex(2, &pgsql_link, &query)==FAILURE) {
  997. RETURN_FALSE;
  998. }
  999. break;
  1000. default:
  1001. WRONG_PARAM_COUNT;
  1002. break;
  1003. }
  1004. if (pgsql_link == NULL && id == -1) {
  1005. RETURN_FALSE;
  1006. }
  1007. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  1008. convert_to_string_ex(query);
  1009. if (PQ_SETNONBLOCKING(pgsql, 0)) {
  1010. php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
  1011. RETURN_FALSE;
  1012. }
  1013. while ((pgsql_result = PQgetResult(pgsql))) {
  1014. PQclear(pgsql_result);
  1015. leftover = 1;
  1016. }
  1017. if (leftover) {
  1018. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
  1019. }
  1020. pgsql_result = PQexec(pgsql, Z_STRVAL_PP(query));
  1021. if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
  1022. PQclear(pgsql_result);
  1023. PQreset(pgsql);
  1024. pgsql_result = PQexec(pgsql, Z_STRVAL_PP(query));
  1025. }
  1026. if (pgsql_result) {
  1027. status = PQresultStatus(pgsql_result);
  1028. } else {
  1029. status = (ExecStatusType) PQstatus(pgsql);
  1030. }
  1031. switch (status) {
  1032. case PGRES_EMPTY_QUERY:
  1033. case PGRES_BAD_RESPONSE:
  1034. case PGRES_NONFATAL_ERROR:
  1035. case PGRES_FATAL_ERROR:
  1036. PHP_PQ_ERROR("Query failed: %s", pgsql);
  1037. PQclear(pgsql_result);
  1038. RETURN_FALSE;
  1039. break;
  1040. case PGRES_COMMAND_OK: /* successful command that did not return rows */
  1041. default:
  1042. if (pgsql_result) {
  1043. pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
  1044. pg_result->conn = pgsql;
  1045. pg_result->result = pgsql_result;
  1046. pg_result->row = 0;
  1047. ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
  1048. } else {
  1049. PQclear(pgsql_result);
  1050. RETURN_FALSE;
  1051. }
  1052. break;
  1053. }
  1054. }
  1055. /* }}} */
  1056. #if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED
  1057. /* {{{ _php_pgsql_free_params */
  1058. static void _php_pgsql_free_params(char **params, int num_params)
  1059. {
  1060. if (num_params > 0) {
  1061. efree(params);
  1062. }
  1063. }
  1064. /* }}} */
  1065. #endif
  1066. #if HAVE_PQEXECPARAMS
  1067. /* {{{ proto resource pg_query_params([resource connection,] string query, array params)
  1068. Execute a query */
  1069. PHP_FUNCTION(pg_query_params)
  1070. {
  1071. zval **query, **pgsql_link = NULL;
  1072. zval **pv_param_arr, **tmp;
  1073. int id = -1;
  1074. int leftover = 0;
  1075. int num_params = 0;
  1076. char **params = NULL;
  1077. unsigned char otype;
  1078. PGconn *pgsql;
  1079. PGresult *pgsql_result;
  1080. ExecStatusType status;
  1081. pgsql_result_handle *pg_result;
  1082. switch(ZEND_NUM_ARGS()) {
  1083. case 2:
  1084. if (zend_get_parameters_ex(2, &query, &pv_param_arr)==FAILURE) {
  1085. RETURN_FALSE;
  1086. }
  1087. id = PGG(default_link);
  1088. CHECK_DEFAULT_LINK(id);
  1089. break;
  1090. case 3:
  1091. if (zend_get_parameters_ex(3, &pgsql_link, &query, &pv_param_arr)==FAILURE) {
  1092. RETURN_FALSE;
  1093. }
  1094. break;
  1095. default:
  1096. WRONG_PARAM_COUNT;
  1097. break;
  1098. }
  1099. if (pgsql_link == NULL && id == -1) {
  1100. RETURN_FALSE;
  1101. }
  1102. if (Z_TYPE_PP(pv_param_arr) != IS_ARRAY) {
  1103. php_error_docref(NULL TSRMLS_CC, E_WARNING, "No array passed");
  1104. RETURN_FALSE;
  1105. }
  1106. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  1107. convert_to_string_ex(query);
  1108. if (PQ_SETNONBLOCKING(pgsql, 0)) {
  1109. php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
  1110. RETURN_FALSE;
  1111. }
  1112. while ((pgsql_result = PQgetResult(pgsql))) {
  1113. PQclear(pgsql_result);
  1114. leftover = 1;
  1115. }
  1116. if (leftover) {
  1117. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
  1118. }
  1119. zend_hash_internal_pointer_reset(Z_ARRVAL_PP(pv_param_arr));
  1120. num_params = zend_hash_num_elements(Z_ARRVAL_PP(pv_param_arr));
  1121. if (num_params > 0) {
  1122. int i = 0;
  1123. params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
  1124. for(i = 0; i < num_params; i++) {
  1125. if (zend_hash_get_current_data(Z_ARRVAL_PP(pv_param_arr), (void **) &tmp) == FAILURE) {
  1126. php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
  1127. _php_pgsql_free_params(params, num_params);
  1128. RETURN_FALSE;
  1129. }
  1130. otype = (*tmp)->type;
  1131. convert_to_string(*tmp);
  1132. if (Z_TYPE_PP(tmp) != IS_STRING) {
  1133. php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
  1134. _php_pgsql_free_params(params, num_params);
  1135. RETURN_FALSE;
  1136. }
  1137. if (otype == IS_NULL) {
  1138. params[i] = NULL;
  1139. }
  1140. else {
  1141. params[i] = Z_STRVAL_PP(tmp);
  1142. }
  1143. zend_hash_move_forward(Z_ARRVAL_PP(pv_param_arr));
  1144. }
  1145. }
  1146. pgsql_result = PQexecParams(pgsql, Z_STRVAL_PP(query), num_params,
  1147. NULL, (const char * const *)params, NULL, NULL, 0);
  1148. if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
  1149. PQclear(pgsql_result);
  1150. PQreset(pgsql);
  1151. pgsql_result = PQexecParams(pgsql, Z_STRVAL_PP(query), num_params,
  1152. NULL, (const char * const *)params, NULL, NULL, 0);
  1153. }
  1154. if (pgsql_result) {
  1155. status = PQresultStatus(pgsql_result);
  1156. } else {
  1157. status = (ExecStatusType) PQstatus(pgsql);
  1158. }
  1159. _php_pgsql_free_params(params, num_params);
  1160. switch (status) {
  1161. case PGRES_EMPTY_QUERY:
  1162. case PGRES_BAD_RESPONSE:
  1163. case PGRES_NONFATAL_ERROR:
  1164. case PGRES_FATAL_ERROR:
  1165. PHP_PQ_ERROR("Query failed: %s", pgsql);
  1166. PQclear(pgsql_result);
  1167. RETURN_FALSE;
  1168. break;
  1169. case PGRES_COMMAND_OK: /* successful command that did not return rows */
  1170. default:
  1171. if (pgsql_result) {
  1172. pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
  1173. pg_result->conn = pgsql;
  1174. pg_result->result = pgsql_result;
  1175. pg_result->row = 0;
  1176. ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
  1177. } else {
  1178. PQclear(pgsql_result);
  1179. RETURN_FALSE;
  1180. }
  1181. break;
  1182. }
  1183. }
  1184. /* }}} */
  1185. #endif
  1186. #if HAVE_PQPREPARE
  1187. /* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query)
  1188. Prepare a query for future execution */
  1189. PHP_FUNCTION(pg_prepare)
  1190. {
  1191. zval **query, **stmtname, **pgsql_link = NULL;
  1192. int id = -1;
  1193. int leftover = 0;
  1194. PGconn *pgsql;
  1195. PGresult *pgsql_result;
  1196. ExecStatusType status;
  1197. pgsql_result_handle *pg_result;
  1198. switch(ZEND_NUM_ARGS()) {
  1199. case 2:
  1200. if (zend_get_parameters_ex(2, &stmtname, &query)==FAILURE) {
  1201. RETURN_FALSE;
  1202. }
  1203. id = PGG(default_link);
  1204. CHECK_DEFAULT_LINK(id);
  1205. break;
  1206. case 3:
  1207. if (zend_get_parameters_ex(3, &pgsql_link, &stmtname, &query)==FAILURE) {
  1208. RETURN_FALSE;
  1209. }
  1210. break;
  1211. default:
  1212. WRONG_PARAM_COUNT;
  1213. break;
  1214. }
  1215. if (pgsql_link == NULL && id == -1) {
  1216. RETURN_FALSE;
  1217. }
  1218. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  1219. convert_to_string_ex(stmtname);
  1220. convert_to_string_ex(query);
  1221. if (PQ_SETNONBLOCKING(pgsql, 0)) {
  1222. php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
  1223. RETURN_FALSE;
  1224. }
  1225. while ((pgsql_result = PQgetResult(pgsql))) {
  1226. PQclear(pgsql_result);
  1227. leftover = 1;
  1228. }
  1229. if (leftover) {
  1230. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
  1231. }
  1232. pgsql_result = PQprepare(pgsql, Z_STRVAL_PP(stmtname), Z_STRVAL_PP(query), 0, NULL);
  1233. if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
  1234. PQclear(pgsql_result);
  1235. PQreset(pgsql);
  1236. pgsql_result = PQprepare(pgsql, Z_STRVAL_PP(stmtname), Z_STRVAL_PP(query), 0, NULL);
  1237. }
  1238. if (pgsql_result) {
  1239. status = PQresultStatus(pgsql_result);
  1240. } else {
  1241. status = (ExecStatusType) PQstatus(pgsql);
  1242. }
  1243. switch (status) {
  1244. case PGRES_EMPTY_QUERY:
  1245. case PGRES_BAD_RESPONSE:
  1246. case PGRES_NONFATAL_ERROR:
  1247. case PGRES_FATAL_ERROR:
  1248. PHP_PQ_ERROR("Query failed: %s", pgsql);
  1249. PQclear(pgsql_result);
  1250. RETURN_FALSE;
  1251. break;
  1252. case PGRES_COMMAND_OK: /* successful command that did not return rows */
  1253. default:
  1254. if (pgsql_result) {
  1255. pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
  1256. pg_result->conn = pgsql;
  1257. pg_result->result = pgsql_result;
  1258. pg_result->row = 0;
  1259. ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
  1260. } else {
  1261. PQclear(pgsql_result);
  1262. RETURN_FALSE;
  1263. }
  1264. break;
  1265. }
  1266. }
  1267. /* }}} */
  1268. #endif
  1269. #if HAVE_PQEXECPREPARED
  1270. /* {{{ proto resource pg_execute([resource connection,] string stmtname, array params)
  1271. Execute a prepared query */
  1272. PHP_FUNCTION(pg_execute)
  1273. {
  1274. zval **stmtname, **pgsql_link = NULL;
  1275. zval **pv_param_arr, **tmp;
  1276. int id = -1;
  1277. int leftover = 0;
  1278. int num_params = 0;
  1279. char **params = NULL;
  1280. unsigned char otype;
  1281. PGconn *pgsql;
  1282. PGresult *pgsql_result;
  1283. ExecStatusType status;
  1284. pgsql_result_handle *pg_result;
  1285. switch(ZEND_NUM_ARGS()) {
  1286. case 2:
  1287. if (zend_get_parameters_ex(2, &stmtname, &pv_param_arr)==FAILURE) {
  1288. RETURN_FALSE;
  1289. }
  1290. id = PGG(default_link);
  1291. CHECK_DEFAULT_LINK(id);
  1292. break;
  1293. case 3:
  1294. if (zend_get_parameters_ex(3, &pgsql_link, &stmtname, &pv_param_arr)==FAILURE) {
  1295. RETURN_FALSE;
  1296. }
  1297. break;
  1298. default:
  1299. WRONG_PARAM_COUNT;
  1300. break;
  1301. }
  1302. if (pgsql_link == NULL && id == -1) {
  1303. RETURN_FALSE;
  1304. }
  1305. if (Z_TYPE_PP(pv_param_arr) != IS_ARRAY) {
  1306. php_error_docref(NULL TSRMLS_CC, E_WARNING, "No array passed");
  1307. RETURN_FALSE;
  1308. }
  1309. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  1310. convert_to_string_ex(stmtname);
  1311. if (PQ_SETNONBLOCKING(pgsql, 0)) {
  1312. php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to blocking mode");
  1313. RETURN_FALSE;
  1314. }
  1315. while ((pgsql_result = PQgetResult(pgsql))) {
  1316. PQclear(pgsql_result);
  1317. leftover = 1;
  1318. }
  1319. if (leftover) {
  1320. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first");
  1321. }
  1322. zend_hash_internal_pointer_reset(Z_ARRVAL_PP(pv_param_arr));
  1323. num_params = zend_hash_num_elements(Z_ARRVAL_PP(pv_param_arr));
  1324. if (num_params > 0) {
  1325. int i = 0;
  1326. params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
  1327. for(i = 0; i < num_params; i++) {
  1328. if (zend_hash_get_current_data(Z_ARRVAL_PP(pv_param_arr), (void **) &tmp) == FAILURE) {
  1329. php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
  1330. _php_pgsql_free_params(params, num_params);
  1331. RETURN_FALSE;
  1332. }
  1333. otype = (*tmp)->type;
  1334. convert_to_string(*tmp);
  1335. if (Z_TYPE_PP(tmp) != IS_STRING) {
  1336. php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
  1337. _php_pgsql_free_params(params, num_params);
  1338. RETURN_FALSE;
  1339. }
  1340. if (otype == IS_NULL) {
  1341. params[i] = NULL;
  1342. }
  1343. else {
  1344. params[i] = Z_STRVAL_PP(tmp);
  1345. }
  1346. zend_hash_move_forward(Z_ARRVAL_PP(pv_param_arr));
  1347. }
  1348. }
  1349. pgsql_result = PQexecPrepared(pgsql, Z_STRVAL_PP(stmtname), num_params,
  1350. (const char * const *)params, NULL, NULL, 0);
  1351. if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
  1352. PQclear(pgsql_result);
  1353. PQreset(pgsql);
  1354. pgsql_result = PQexecPrepared(pgsql, Z_STRVAL_PP(stmtname), num_params,
  1355. (const char * const *)params, NULL, NULL, 0);
  1356. }
  1357. if (pgsql_result) {
  1358. status = PQresultStatus(pgsql_result);
  1359. } else {
  1360. status = (ExecStatusType) PQstatus(pgsql);
  1361. }
  1362. _php_pgsql_free_params(params, num_params);
  1363. switch (status) {
  1364. case PGRES_EMPTY_QUERY:
  1365. case PGRES_BAD_RESPONSE:
  1366. case PGRES_NONFATAL_ERROR:
  1367. case PGRES_FATAL_ERROR:
  1368. PHP_PQ_ERROR("Query failed: %s", pgsql);
  1369. PQclear(pgsql_result);
  1370. RETURN_FALSE;
  1371. break;
  1372. case PGRES_COMMAND_OK: /* successful command that did not return rows */
  1373. default:
  1374. if (pgsql_result) {
  1375. pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
  1376. pg_result->conn = pgsql;
  1377. pg_result->result = pgsql_result;
  1378. pg_result->row = 0;
  1379. ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
  1380. } else {
  1381. PQclear(pgsql_result);
  1382. RETURN_FALSE;
  1383. }
  1384. break;
  1385. }
  1386. }
  1387. /* }}} */
  1388. #endif
  1389. #define PHP_PG_NUM_ROWS 1
  1390. #define PHP_PG_NUM_FIELDS 2
  1391. #define PHP_PG_CMD_TUPLES 3
  1392. /* {{{ php_pgsql_get_result_info
  1393. */
  1394. static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
  1395. {
  1396. zval **result;
  1397. PGresult *pgsql_result;
  1398. pgsql_result_handle *pg_result;
  1399. if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &result)==FAILURE) {
  1400. WRONG_PARAM_COUNT;
  1401. }
  1402. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
  1403. pgsql_result = pg_result->result;
  1404. switch (entry_type) {
  1405. case PHP_PG_NUM_ROWS:
  1406. Z_LVAL_P(return_value) = PQntuples(pgsql_result);
  1407. break;
  1408. case PHP_PG_NUM_FIELDS:
  1409. Z_LVAL_P(return_value) = PQnfields(pgsql_result);
  1410. break;
  1411. case PHP_PG_CMD_TUPLES:
  1412. #if HAVE_PQCMDTUPLES
  1413. Z_LVAL_P(return_value) = atoi(PQcmdTuples(pgsql_result));
  1414. #else
  1415. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Not supported under this build");
  1416. Z_LVAL_P(return_value) = 0;
  1417. #endif
  1418. break;
  1419. default:
  1420. RETURN_FALSE;
  1421. }
  1422. Z_TYPE_P(return_value) = IS_LONG;
  1423. }
  1424. /* }}} */
  1425. /* {{{ proto int pg_num_rows(resource result)
  1426. Return the number of rows in the result */
  1427. PHP_FUNCTION(pg_num_rows)
  1428. {
  1429. php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS);
  1430. }
  1431. /* }}} */
  1432. /* {{{ proto int pg_num_fields(resource result)
  1433. Return the number of fields in the result */
  1434. PHP_FUNCTION(pg_num_fields)
  1435. {
  1436. php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS);
  1437. }
  1438. /* }}} */
  1439. #if HAVE_PQCMDTUPLES
  1440. /* {{{ proto int pg_affected_rows(resource result)
  1441. Returns the number of affected tuples */
  1442. PHP_FUNCTION(pg_affected_rows)
  1443. {
  1444. php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES);
  1445. }
  1446. /* }}} */
  1447. #endif
  1448. /* {{{ proto string pg_last_notice(resource connection)
  1449. Returns the last notice set by the backend */
  1450. PHP_FUNCTION(pg_last_notice)
  1451. {
  1452. zval *pgsql_link;
  1453. PGconn *pg_link;
  1454. int id = -1;
  1455. php_pgsql_notice **notice;
  1456. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r",
  1457. &pgsql_link) == FAILURE) {
  1458. return;
  1459. }
  1460. /* Just to check if user passed valid resoruce */
  1461. ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  1462. if (zend_hash_index_find(&PGG(notices), Z_RESVAL_P(pgsql_link), (void **)&notice) == FAILURE) {
  1463. RETURN_FALSE;
  1464. }
  1465. RETURN_STRINGL((*notice)->message, (*notice)->len, 1);
  1466. }
  1467. /* }}} */
  1468. /* {{{ get_field_name
  1469. */
  1470. static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list TSRMLS_DC)
  1471. {
  1472. PGresult *result;
  1473. smart_str str = {0};
  1474. list_entry *field_type;
  1475. char *ret=NULL;
  1476. /* try to lookup the type in the resource list */
  1477. smart_str_appends(&str, "pgsql_oid_");
  1478. smart_str_append_unsigned(&str, oid);
  1479. smart_str_0(&str);
  1480. if (zend_hash_find(list,str.c,str.len+1,(void **) &field_type)==SUCCESS) {
  1481. ret = estrdup((char *)field_type->ptr);
  1482. } else { /* hash all oid's */
  1483. int i,num_rows;
  1484. int oid_offset,name_offset;
  1485. char *tmp_oid, *end_ptr, *tmp_name;
  1486. list_entry new_oid_entry;
  1487. if ((result = PQexec(pgsql,"select oid,typname from pg_type")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) {
  1488. if (result) {
  1489. PQclear(result);
  1490. }
  1491. smart_str_free(&str);
  1492. return STR_EMPTY_ALLOC();
  1493. }
  1494. num_rows = PQntuples(result);
  1495. oid_offset = PQfnumber(result,"oid");
  1496. name_offset = PQfnumber(result,"typname");
  1497. for (i=0; i<num_rows; i++) {
  1498. if ((tmp_oid = PQgetvalue(result,i,oid_offset))==NULL) {
  1499. continue;
  1500. }
  1501. str.len = 0;
  1502. smart_str_appends(&str, "pgsql_oid_");
  1503. smart_str_appends(&str, tmp_oid);
  1504. smart_str_0(&str);
  1505. if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) {
  1506. continue;
  1507. }
  1508. Z_TYPE(new_oid_entry) = le_string;
  1509. new_oid_entry.ptr = estrdup(tmp_name);
  1510. zend_hash_update(list,str.c,str.len+1,(void *) &new_oid_entry, sizeof(list_entry), NULL);
  1511. if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) {
  1512. ret = estrdup(tmp_name);
  1513. }
  1514. }
  1515. PQclear(result);
  1516. }
  1517. smart_str_free(&str);
  1518. return ret;
  1519. }
  1520. /* }}} */
  1521. #define PHP_PG_FIELD_NAME 1
  1522. #define PHP_PG_FIELD_SIZE 2
  1523. #define PHP_PG_FIELD_TYPE 3
  1524. #define PHP_PG_FIELD_TYPE_OID 4
  1525. /* {{{ php_pgsql_get_field_info
  1526. */
  1527. static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
  1528. {
  1529. zval **result, **field;
  1530. PGresult *pgsql_result;
  1531. pgsql_result_handle *pg_result;
  1532. Oid oid;
  1533. if (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(2, &result, &field)==FAILURE) {
  1534. WRONG_PARAM_COUNT;
  1535. }
  1536. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
  1537. pgsql_result = pg_result->result;
  1538. convert_to_long_ex(field);
  1539. if (Z_LVAL_PP(field) < 0 || Z_LVAL_PP(field) >= PQnfields(pgsql_result)) {
  1540. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad field offset specified");
  1541. RETURN_FALSE;
  1542. }
  1543. switch (entry_type) {
  1544. case PHP_PG_FIELD_NAME:
  1545. Z_STRVAL_P(return_value) = PQfname(pgsql_result, Z_LVAL_PP(field));
  1546. Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
  1547. Z_STRVAL_P(return_value) = estrndup(Z_STRVAL_P(return_value),Z_STRLEN_P(return_value));
  1548. Z_TYPE_P(return_value) = IS_STRING;
  1549. break;
  1550. case PHP_PG_FIELD_SIZE:
  1551. Z_LVAL_P(return_value) = PQfsize(pgsql_result, Z_LVAL_PP(field));
  1552. Z_TYPE_P(return_value) = IS_LONG;
  1553. break;
  1554. case PHP_PG_FIELD_TYPE:
  1555. Z_STRVAL_P(return_value) = get_field_name(pg_result->conn, PQftype(pgsql_result, Z_LVAL_PP(field)), &EG(regular_list) TSRMLS_CC);
  1556. Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
  1557. Z_TYPE_P(return_value) = IS_STRING;
  1558. break;
  1559. case PHP_PG_FIELD_TYPE_OID:
  1560. oid = PQftype(pgsql_result, Z_LVAL_PP(field));
  1561. if (oid > LONG_MAX) {
  1562. smart_str s = {0};
  1563. smart_str_append_unsigned(&s, oid);
  1564. smart_str_0(&s);
  1565. Z_STRVAL_P(return_value) = s.c;
  1566. Z_STRLEN_P(return_value) = s.len;
  1567. Z_TYPE_P(return_value) = IS_STRING;
  1568. }
  1569. else
  1570. {
  1571. Z_LVAL_P(return_value) = (long)oid;
  1572. Z_TYPE_P(return_value) = IS_LONG;
  1573. }
  1574. break;
  1575. default:
  1576. RETURN_FALSE;
  1577. }
  1578. }
  1579. /* }}} */
  1580. /* {{{ proto string pg_field_name(resource result, int field_number)
  1581. Returns the name of the field */
  1582. PHP_FUNCTION(pg_field_name)
  1583. {
  1584. php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME);
  1585. }
  1586. /* }}} */
  1587. /* {{{ proto int pg_field_size(resource result, int field_number)
  1588. Returns the internal size of the field */
  1589. PHP_FUNCTION(pg_field_size)
  1590. {
  1591. php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE);
  1592. }
  1593. /* }}} */
  1594. /* {{{ proto string pg_field_type(resource result, int field_number)
  1595. Returns the type name for the given field */
  1596. PHP_FUNCTION(pg_field_type)
  1597. {
  1598. php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE);
  1599. }
  1600. /* }}} */
  1601. /* {{{ proto string pg_field_type_oid(resource result, int field_number)
  1602. Returns the type oid for the given field */
  1603. PHP_FUNCTION(pg_field_type_oid)
  1604. {
  1605. php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID);
  1606. }
  1607. /* }}} */
  1608. /* {{{ proto int pg_field_num(resource result, string field_name)
  1609. Returns the field number of the named field */
  1610. PHP_FUNCTION(pg_field_num)
  1611. {
  1612. zval **result, **field;
  1613. PGresult *pgsql_result;
  1614. pgsql_result_handle *pg_result;
  1615. if (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(2, &result, &field)==FAILURE) {
  1616. WRONG_PARAM_COUNT;
  1617. }
  1618. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
  1619. pgsql_result = pg_result->result;
  1620. convert_to_string_ex(field);
  1621. Z_LVAL_P(return_value) = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
  1622. Z_TYPE_P(return_value) = IS_LONG;
  1623. }
  1624. /* }}} */
  1625. /* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name)
  1626. Returns values from a result identifier */
  1627. PHP_FUNCTION(pg_fetch_result)
  1628. {
  1629. zval **result, **row, **field=NULL;
  1630. PGresult *pgsql_result;
  1631. pgsql_result_handle *pg_result;
  1632. int field_offset, pgsql_row;
  1633. if ((ZEND_NUM_ARGS() != 3 || zend_get_parameters_ex(3, &result, &row, &field)==FAILURE) &&
  1634. (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(2, &result, &field)==FAILURE)) {
  1635. WRONG_PARAM_COUNT;
  1636. }
  1637. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
  1638. pgsql_result = pg_result->result;
  1639. if (ZEND_NUM_ARGS() == 2) {
  1640. if (pg_result->row < 0)
  1641. pg_result->row = 0;
  1642. pgsql_row = pg_result->row;
  1643. if (pgsql_row >= PQntuples(pgsql_result)) {
  1644. RETURN_FALSE;
  1645. }
  1646. } else {
  1647. convert_to_long_ex(row);
  1648. pgsql_row = Z_LVAL_PP(row);
  1649. if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
  1650. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
  1651. Z_LVAL_PP(row), Z_LVAL_PP(result));
  1652. RETURN_FALSE;
  1653. }
  1654. }
  1655. switch(Z_TYPE_PP(field)) {
  1656. case IS_STRING:
  1657. field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
  1658. break;
  1659. default:
  1660. convert_to_long_ex(field);
  1661. field_offset = Z_LVAL_PP(field);
  1662. break;
  1663. }
  1664. if (field_offset<0 || field_offset>=PQnfields(pgsql_result)) {
  1665. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
  1666. RETURN_FALSE;
  1667. }
  1668. if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) {
  1669. Z_TYPE_P(return_value) = IS_NULL;
  1670. } else {
  1671. Z_STRVAL_P(return_value) = PQgetvalue(pgsql_result, pgsql_row, field_offset);
  1672. Z_STRLEN_P(return_value) = (Z_STRVAL_P(return_value) ? strlen(Z_STRVAL_P(return_value)) : 0);
  1673. Z_STRVAL_P(return_value) = safe_estrndup(Z_STRVAL_P(return_value),Z_STRLEN_P(return_value));
  1674. Z_TYPE_P(return_value) = IS_STRING;
  1675. }
  1676. }
  1677. /* }}} */
  1678. /* {{{ void php_pgsql_fetch_hash */
  1679. static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, long result_type, int into_object)
  1680. {
  1681. zval *result, *zrow;
  1682. PGresult *pgsql_result;
  1683. pgsql_result_handle *pg_result;
  1684. int i, num_fields, pgsql_row, use_row;
  1685. long row;
  1686. char *element, *field_name;
  1687. uint element_len;
  1688. zval *ctor_params = NULL;
  1689. zend_class_entry *ce = NULL;
  1690. if (into_object) {
  1691. char *class_name;
  1692. int class_name_len;
  1693. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|zsz", &result, &zrow, &class_name, &class_name_len, &ctor_params) == FAILURE) {
  1694. return;
  1695. }
  1696. if (ZEND_NUM_ARGS() < 3) {
  1697. ce = zend_standard_class_def;
  1698. } else {
  1699. ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
  1700. }
  1701. if (!ce) {
  1702. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find class '%s'", class_name);
  1703. return;
  1704. }
  1705. result_type = PGSQL_ASSOC;
  1706. } else {
  1707. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|zl", &result, &zrow, &result_type) == FAILURE) {
  1708. return;
  1709. }
  1710. }
  1711. use_row = ZEND_NUM_ARGS() > 1 && Z_TYPE_P(zrow) != IS_NULL;
  1712. if (use_row) {
  1713. convert_to_long_ex(&zrow);
  1714. row = Z_LVAL_P(zrow);
  1715. }
  1716. if (!(result_type & PGSQL_BOTH)) {
  1717. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
  1718. RETURN_FALSE;
  1719. }
  1720. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
  1721. pgsql_result = pg_result->result;
  1722. if (use_row) {
  1723. pgsql_row = row;
  1724. pg_result->row = pgsql_row;
  1725. if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
  1726. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
  1727. row, Z_LVAL_P(result));
  1728. RETURN_FALSE;
  1729. }
  1730. } else {
  1731. /* If 2nd param is NULL, use internal row counter to access next row */
  1732. pgsql_row = pg_result->row;
  1733. if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
  1734. RETURN_FALSE;
  1735. }
  1736. pg_result->row++;
  1737. }
  1738. array_init(return_value);
  1739. for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) {
  1740. if (PQgetisnull(pgsql_result, pgsql_row, i)) {
  1741. if (result_type & PGSQL_NUM) {
  1742. add_index_null(return_value, i);
  1743. }
  1744. if (result_type & PGSQL_ASSOC) {
  1745. field_name = PQfname(pgsql_result, i);
  1746. add_assoc_null(return_value, field_name);
  1747. }
  1748. } else {
  1749. element = PQgetvalue(pgsql_result, pgsql_row, i);
  1750. element_len = (element ? strlen(element) : 0);
  1751. if (element) {
  1752. char *data;
  1753. int data_len;
  1754. int should_copy=0;
  1755. if (PG(magic_quotes_runtime)) {
  1756. data = php_addslashes(element, element_len, &data_len, 0 TSRMLS_CC);
  1757. } else {
  1758. data = safe_estrndup(element, element_len);
  1759. data_len = element_len;
  1760. }
  1761. if (result_type & PGSQL_NUM) {
  1762. add_index_stringl(return_value, i, data, data_len, should_copy);
  1763. should_copy=1;
  1764. }
  1765. if (result_type & PGSQL_ASSOC) {
  1766. field_name = PQfname(pgsql_result, i);
  1767. add_assoc_stringl(return_value, field_name, data, data_len, should_copy);
  1768. }
  1769. }
  1770. }
  1771. }
  1772. if (into_object) {
  1773. zval dataset = *return_value;
  1774. zend_fcall_info fci;
  1775. zend_fcall_info_cache fcc;
  1776. zval *retval_ptr;
  1777. object_and_properties_init(return_value, ce, NULL);
  1778. zend_merge_properties(return_value, Z_ARRVAL(dataset), 1 TSRMLS_CC);
  1779. if (ce->constructor) {
  1780. fci.size = sizeof(fci);
  1781. fci.function_table = &ce->function_table;
  1782. fci.function_name = NULL;
  1783. fci.symbol_table = NULL;
  1784. fci.object_pp = &return_value;
  1785. fci.retval_ptr_ptr = &retval_ptr;
  1786. if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
  1787. if (Z_TYPE_P(ctor_params) == IS_ARRAY) {
  1788. HashTable *ht = Z_ARRVAL_P(ctor_params);
  1789. Bucket *p;
  1790. fci.param_count = 0;
  1791. fci.params = emalloc(sizeof(zval*) * ht->nNumOfElements);
  1792. p = ht->pListHead;
  1793. while (p != NULL) {
  1794. fci.params[fci.param_count++] = (zval**)p->pData;
  1795. p = p->pListNext;
  1796. }
  1797. } else {
  1798. /* Two problems why we throw exceptions here: PHP is typeless
  1799. * and hence passing one argument that's not an array could be
  1800. * by mistake and the other way round is possible, too. The
  1801. * single value is an array. Also we'd have to make that one
  1802. * argument passed by reference.
  1803. */
  1804. zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Parameter ctor_params must be an array", 0 TSRMLS_CC);
  1805. return;
  1806. }
  1807. } else {
  1808. fci.param_count = 0;
  1809. fci.params = NULL;
  1810. }
  1811. fci.no_separation = 1;
  1812. fcc.initialized = 1;
  1813. fcc.function_handler = ce->constructor;
  1814. fcc.calling_scope = EG(scope);
  1815. fcc.object_pp = &return_value;
  1816. if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) {
  1817. zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Could not execute %s::%s()", ce->name, ce->constructor->common.function_name);
  1818. } else {
  1819. if (retval_ptr) {
  1820. zval_ptr_dtor(&retval_ptr);
  1821. }
  1822. }
  1823. if (fci.params) {
  1824. efree(fci.params);
  1825. }
  1826. } else if (ctor_params) {
  1827. zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, "Class %s does not have a constructor hence you cannot use ctor_params", ce->name);
  1828. }
  1829. }
  1830. }
  1831. /* }}} */
  1832. /* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]])
  1833. Get a row as an enumerated array */
  1834. PHP_FUNCTION(pg_fetch_row)
  1835. {
  1836. php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0);
  1837. }
  1838. /* }}} */
  1839. /* {{{ proto array pg_fetch_assoc(resource result [, int row])
  1840. Fetch a row as an assoc array */
  1841. PHP_FUNCTION(pg_fetch_assoc)
  1842. {
  1843. /* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when
  1844. there is 3rd parameter */
  1845. if (ZEND_NUM_ARGS() > 2)
  1846. WRONG_PARAM_COUNT;
  1847. php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0);
  1848. }
  1849. /* }}} */
  1850. /* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]])
  1851. Fetch a row as an array */
  1852. PHP_FUNCTION(pg_fetch_array)
  1853. {
  1854. php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0);
  1855. }
  1856. /* }}} */
  1857. /* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]])
  1858. Fetch a row as an object */
  1859. PHP_FUNCTION(pg_fetch_object)
  1860. {
  1861. /* pg_fetch_object() allowed result_type used to be. 3rd parameter
  1862. must be allowed for compatibility */
  1863. php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1);
  1864. }
  1865. /* }}} */
  1866. /* {{{ proto array pg_fetch_all(resource result)
  1867. Fetch all rows into array */
  1868. PHP_FUNCTION(pg_fetch_all)
  1869. {
  1870. zval *result;
  1871. PGresult *pgsql_result;
  1872. pgsql_result_handle *pg_result;
  1873. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r",
  1874. &result) == FAILURE) {
  1875. return;
  1876. }
  1877. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
  1878. pgsql_result = pg_result->result;
  1879. array_init(return_value);
  1880. if (php_pgsql_result2array(pgsql_result, return_value TSRMLS_CC) == FAILURE) {
  1881. zval_dtor(return_value);
  1882. RETURN_FALSE;
  1883. }
  1884. }
  1885. /* }}} */
  1886. /* {{{ proto array pg_fetch_all_columns(resource result [, int column_number])
  1887. Fetch all rows into array */
  1888. PHP_FUNCTION(pg_fetch_all_columns)
  1889. {
  1890. zval *result;
  1891. PGresult *pgsql_result;
  1892. pgsql_result_handle *pg_result;
  1893. long colno=0;
  1894. int pg_numrows, pg_row;
  1895. size_t num_fields;
  1896. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &result, &colno) == FAILURE) {
  1897. RETURN_FALSE;
  1898. }
  1899. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
  1900. pgsql_result = pg_result->result;
  1901. num_fields = PQnfields(pgsql_result);
  1902. if (colno >= num_fields || colno < 0) {
  1903. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid column number '%ld'", colno);
  1904. RETURN_FALSE;
  1905. }
  1906. array_init(return_value);
  1907. if ((pg_numrows = PQntuples(pgsql_result)) <= 0) {
  1908. return;
  1909. }
  1910. for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
  1911. if (PQgetisnull(pgsql_result, pg_row, colno)) {
  1912. add_next_index_null(return_value);
  1913. } else {
  1914. add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, colno), 1);
  1915. }
  1916. }
  1917. }
  1918. /* }}} */
  1919. /* {{{ proto bool pg_result_seek(resource result, int offset)
  1920. Set internal row offset */
  1921. PHP_FUNCTION(pg_result_seek)
  1922. {
  1923. zval *result;
  1924. long row;
  1925. pgsql_result_handle *pg_result;
  1926. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &result, &row) == FAILURE) {
  1927. return;
  1928. }
  1929. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
  1930. if (row < 0 || row >= PQntuples(pg_result->result)) {
  1931. RETURN_FALSE;
  1932. }
  1933. /* seek to offset */
  1934. pg_result->row = row;
  1935. RETURN_TRUE;
  1936. }
  1937. /* }}} */
  1938. #define PHP_PG_DATA_LENGTH 1
  1939. #define PHP_PG_DATA_ISNULL 2
  1940. /* {{{ php_pgsql_data_info
  1941. */
  1942. static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
  1943. {
  1944. zval **result, **row, **field;
  1945. PGresult *pgsql_result;
  1946. pgsql_result_handle *pg_result;
  1947. int field_offset, pgsql_row;
  1948. if ((ZEND_NUM_ARGS() != 3 || zend_get_parameters_ex(3, &result, &row, &field)==FAILURE) &&
  1949. (ZEND_NUM_ARGS() != 2 || zend_get_parameters_ex(2, &result, &field)==FAILURE)) {
  1950. WRONG_PARAM_COUNT;
  1951. }
  1952. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
  1953. pgsql_result = pg_result->result;
  1954. if (ZEND_NUM_ARGS() == 2) {
  1955. if (pg_result->row < 0)
  1956. pg_result->row = 0;
  1957. pgsql_row = pg_result->row;
  1958. if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
  1959. RETURN_FALSE;
  1960. }
  1961. } else {
  1962. convert_to_long_ex(row);
  1963. pgsql_row = Z_LVAL_PP(row);
  1964. if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) {
  1965. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to jump to row %ld on PostgreSQL result index %ld",
  1966. Z_LVAL_PP(row), Z_LVAL_PP(result));
  1967. RETURN_FALSE;
  1968. }
  1969. }
  1970. switch(Z_TYPE_PP(field)) {
  1971. case IS_STRING:
  1972. convert_to_string_ex(field);
  1973. field_offset = PQfnumber(pgsql_result, Z_STRVAL_PP(field));
  1974. break;
  1975. default:
  1976. convert_to_long_ex(field);
  1977. field_offset = Z_LVAL_PP(field);
  1978. break;
  1979. }
  1980. if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) {
  1981. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Bad column offset specified");
  1982. RETURN_FALSE;
  1983. }
  1984. switch (entry_type) {
  1985. case PHP_PG_DATA_LENGTH:
  1986. Z_LVAL_P(return_value) = PQgetlength(pgsql_result, pgsql_row, field_offset);
  1987. break;
  1988. case PHP_PG_DATA_ISNULL:
  1989. Z_LVAL_P(return_value) = PQgetisnull(pgsql_result, pgsql_row, field_offset);
  1990. break;
  1991. }
  1992. Z_TYPE_P(return_value) = IS_LONG;
  1993. }
  1994. /* }}} */
  1995. /* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number)
  1996. Returns the printed length */
  1997. PHP_FUNCTION(pg_field_prtlen)
  1998. {
  1999. php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH);
  2000. }
  2001. /* }}} */
  2002. /* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number)
  2003. Test if a field is NULL */
  2004. PHP_FUNCTION(pg_field_is_null)
  2005. {
  2006. php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL);
  2007. }
  2008. /* }}} */
  2009. /* {{{ proto bool pg_free_result(resource result)
  2010. Free result memory */
  2011. PHP_FUNCTION(pg_free_result)
  2012. {
  2013. zval **result;
  2014. pgsql_result_handle *pg_result;
  2015. if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &result)==FAILURE) {
  2016. WRONG_PARAM_COUNT;
  2017. }
  2018. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
  2019. if (Z_LVAL_PP(result) == 0) {
  2020. RETURN_FALSE;
  2021. }
  2022. zend_list_delete(Z_LVAL_PP(result));
  2023. RETURN_TRUE;
  2024. }
  2025. /* }}} */
  2026. /* {{{ proto string pg_last_oid(resource result)
  2027. Returns the last object identifier */
  2028. PHP_FUNCTION(pg_last_oid)
  2029. {
  2030. zval **result;
  2031. PGresult *pgsql_result;
  2032. pgsql_result_handle *pg_result;
  2033. #ifdef HAVE_PQOIDVALUE
  2034. Oid oid;
  2035. #endif
  2036. if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &result)==FAILURE) {
  2037. WRONG_PARAM_COUNT;
  2038. }
  2039. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, result, -1, "PostgreSQL result", le_result);
  2040. pgsql_result = pg_result->result;
  2041. #ifdef HAVE_PQOIDVALUE
  2042. oid = PQoidValue(pgsql_result);
  2043. if (oid == InvalidOid) {
  2044. RETURN_FALSE;
  2045. }
  2046. PGSQL_RETURN_OID(oid);
  2047. #else
  2048. Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result);
  2049. if (Z_STRVAL_P(return_value)) {
  2050. RETURN_STRING(Z_STRVAL_P(return_value), 1);
  2051. }
  2052. RETURN_STRING("", 1);
  2053. #endif
  2054. }
  2055. /* }}} */
  2056. /* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]])
  2057. Enable tracing a PostgreSQL connection */
  2058. PHP_FUNCTION(pg_trace)
  2059. {
  2060. zval **z_filename, **z_mode, **pgsql_link = NULL;
  2061. int id = -1;
  2062. PGconn *pgsql;
  2063. char *mode = "w";
  2064. FILE *fp = NULL;
  2065. php_stream *stream;
  2066. id = PGG(default_link);
  2067. switch (ZEND_NUM_ARGS()) {
  2068. case 1:
  2069. if (zend_get_parameters_ex(1, &z_filename)==FAILURE) {
  2070. RETURN_FALSE;
  2071. }
  2072. CHECK_DEFAULT_LINK(id);
  2073. break;
  2074. case 2:
  2075. if (zend_get_parameters_ex(2, &z_filename, &z_mode)==FAILURE) {
  2076. RETURN_FALSE;
  2077. }
  2078. CHECK_DEFAULT_LINK(id);
  2079. convert_to_string_ex(z_mode);
  2080. mode = Z_STRVAL_PP(z_mode);
  2081. break;
  2082. case 3:
  2083. if (zend_get_parameters_ex(3, &z_filename, &z_mode, &pgsql_link)==FAILURE) {
  2084. RETURN_FALSE;
  2085. }
  2086. convert_to_string_ex(z_mode);
  2087. mode = Z_STRVAL_PP(z_mode);
  2088. break;
  2089. default:
  2090. ZEND_WRONG_PARAM_COUNT();
  2091. break;
  2092. }
  2093. if (pgsql_link == NULL && id == -1) {
  2094. RETURN_FALSE;
  2095. }
  2096. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2097. convert_to_string_ex(z_filename);
  2098. stream = php_stream_open_wrapper(Z_STRVAL_PP(z_filename), mode, ENFORCE_SAFE_MODE|REPORT_ERRORS, NULL);
  2099. if (!stream) {
  2100. RETURN_FALSE;
  2101. }
  2102. if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)fp, REPORT_ERRORS)) {
  2103. php_stream_close(stream);
  2104. RETURN_FALSE;
  2105. }
  2106. php_stream_auto_cleanup(stream);
  2107. PQtrace(pgsql, fp);
  2108. RETURN_TRUE;
  2109. }
  2110. /* }}} */
  2111. /* {{{ proto bool pg_untrace([resource connection])
  2112. Disable tracing of a PostgreSQL connection */
  2113. PHP_FUNCTION(pg_untrace)
  2114. {
  2115. zval **pgsql_link = NULL;
  2116. int id = -1;
  2117. PGconn *pgsql;
  2118. switch (ZEND_NUM_ARGS()) {
  2119. case 0:
  2120. id = PGG(default_link);
  2121. CHECK_DEFAULT_LINK(id);
  2122. break;
  2123. case 1:
  2124. if (zend_get_parameters_ex(1, &pgsql_link)==FAILURE) {
  2125. RETURN_FALSE;
  2126. }
  2127. break;
  2128. default:
  2129. ZEND_WRONG_PARAM_COUNT();
  2130. break;
  2131. }
  2132. if (pgsql_link == NULL && id == -1) {
  2133. RETURN_FALSE;
  2134. }
  2135. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2136. PQuntrace(pgsql);
  2137. RETURN_TRUE;
  2138. }
  2139. /* }}} */
  2140. /* {{{ proto int pg_lo_create([resource connection])
  2141. Create a large object */
  2142. PHP_FUNCTION(pg_lo_create)
  2143. {
  2144. zval **pgsql_link = NULL;
  2145. PGconn *pgsql;
  2146. Oid pgsql_oid;
  2147. int id = -1;
  2148. switch(ZEND_NUM_ARGS()) {
  2149. case 0:
  2150. id = PGG(default_link);
  2151. CHECK_DEFAULT_LINK(id);
  2152. break;
  2153. case 1:
  2154. if (zend_get_parameters_ex(1, &pgsql_link)==FAILURE) {
  2155. RETURN_FALSE;
  2156. }
  2157. break;
  2158. default:
  2159. WRONG_PARAM_COUNT;
  2160. break;
  2161. }
  2162. if (pgsql_link == NULL && id == -1) {
  2163. RETURN_FALSE;
  2164. }
  2165. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2166. /* NOTE: Archive modes not supported until I get some more data. Don't think anybody's
  2167. using it anyway. I believe it's also somehow related to the 'time travel' feature of
  2168. PostgreSQL, that's on the list of features to be removed... Create modes not supported.
  2169. What's the use of an object that can be only written to, but not read from, and vice
  2170. versa? Beats me... And the access type (r/w) must be specified again when opening
  2171. the object, probably (?) overrides this. (Jouni)
  2172. */
  2173. if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) {
  2174. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
  2175. RETURN_FALSE;
  2176. }
  2177. PGSQL_RETURN_OID(pgsql_oid);
  2178. }
  2179. /* }}} */
  2180. /* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid)
  2181. Delete a large object */
  2182. PHP_FUNCTION(pg_lo_unlink)
  2183. {
  2184. zval *pgsql_link = NULL;
  2185. long oid_long;
  2186. char *oid_string, *end_ptr;
  2187. int oid_strlen;
  2188. PGconn *pgsql;
  2189. Oid oid;
  2190. int id = -1;
  2191. int argc = ZEND_NUM_ARGS();
  2192. /* accept string type since Oid type is unsigned int */
  2193. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2194. "rs", &pgsql_link, &oid_string, &oid_strlen) == SUCCESS) {
  2195. oid = (Oid)strtoul(oid_string, &end_ptr, 10);
  2196. if ((oid_string+oid_strlen) != end_ptr) {
  2197. /* wrong integer format */
  2198. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
  2199. RETURN_FALSE;
  2200. }
  2201. }
  2202. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2203. "rl", &pgsql_link, &oid_long) == SUCCESS) {
  2204. if (oid_long <= InvalidOid) {
  2205. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
  2206. RETURN_FALSE;
  2207. }
  2208. oid = (Oid)oid_long;
  2209. }
  2210. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2211. "s", &oid_string, &oid_strlen) == SUCCESS) {
  2212. oid = (Oid)strtoul(oid_string, &end_ptr, 10);
  2213. if ((oid_string+oid_strlen) != end_ptr) {
  2214. /* wrong integer format */
  2215. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
  2216. RETURN_FALSE;
  2217. }
  2218. id = PGG(default_link);
  2219. CHECK_DEFAULT_LINK(id);
  2220. }
  2221. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2222. "l", &oid_long) == SUCCESS) {
  2223. if (oid_long <= InvalidOid) {
  2224. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID is specified");
  2225. RETURN_FALSE;
  2226. }
  2227. oid = (Oid)oid_long;
  2228. id = PGG(default_link);
  2229. CHECK_DEFAULT_LINK(id);
  2230. }
  2231. else {
  2232. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
  2233. RETURN_FALSE;
  2234. }
  2235. if (pgsql_link == NULL && id == -1) {
  2236. RETURN_FALSE;
  2237. }
  2238. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2239. if (lo_unlink(pgsql, oid) == -1) {
  2240. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to delete PostgreSQL large object %u", oid);
  2241. RETURN_FALSE;
  2242. }
  2243. RETURN_TRUE;
  2244. }
  2245. /* }}} */
  2246. /* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode)
  2247. Open a large object and return fd */
  2248. PHP_FUNCTION(pg_lo_open)
  2249. {
  2250. zval *pgsql_link = NULL;
  2251. long oid_long;
  2252. char *oid_string, *end_ptr, *mode_string;
  2253. int oid_strlen, mode_strlen;
  2254. PGconn *pgsql;
  2255. Oid oid;
  2256. int id = -1, pgsql_mode=0, pgsql_lofd;
  2257. int create=0;
  2258. pgLofp *pgsql_lofp;
  2259. int argc = ZEND_NUM_ARGS();
  2260. /* accept string type since Oid is unsigned int */
  2261. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2262. "rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
  2263. oid = (Oid)strtoul(oid_string, &end_ptr, 10);
  2264. if ((oid_string+oid_strlen) != end_ptr) {
  2265. /* wrong integer format */
  2266. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
  2267. RETURN_FALSE;
  2268. }
  2269. }
  2270. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2271. "rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
  2272. if (oid_long <= InvalidOid) {
  2273. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
  2274. RETURN_FALSE;
  2275. }
  2276. oid = (Oid)oid_long;
  2277. }
  2278. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2279. "ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) {
  2280. oid = (Oid)strtoul(oid_string, &end_ptr, 10);
  2281. if ((oid_string+oid_strlen) != end_ptr) {
  2282. /* wrong integer format */
  2283. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
  2284. RETURN_FALSE;
  2285. }
  2286. id = PGG(default_link);
  2287. CHECK_DEFAULT_LINK(id);
  2288. }
  2289. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2290. "ls", &oid_long, &mode_string, &mode_strlen) == SUCCESS) {
  2291. if (oid_long <= InvalidOid) {
  2292. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
  2293. RETURN_FALSE;
  2294. }
  2295. oid = (Oid)oid_long;
  2296. id = PGG(default_link);
  2297. CHECK_DEFAULT_LINK(id);
  2298. }
  2299. else {
  2300. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 1 or 2 arguments");
  2301. RETURN_FALSE;
  2302. }
  2303. if (pgsql_link == NULL && id == -1) {
  2304. RETURN_FALSE;
  2305. }
  2306. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2307. /* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of
  2308. faster to type. Unfortunately, doesn't behave the same way as fopen()...
  2309. (Jouni)
  2310. */
  2311. if (strchr(mode_string, 'r') == mode_string) {
  2312. pgsql_mode |= INV_READ;
  2313. if (strchr(mode_string, '+') == mode_string+1) {
  2314. pgsql_mode |= INV_WRITE;
  2315. }
  2316. }
  2317. if (strchr(mode_string, 'w') == mode_string) {
  2318. pgsql_mode |= INV_WRITE;
  2319. create = 1;
  2320. if (strchr(mode_string, '+') == mode_string+1) {
  2321. pgsql_mode |= INV_READ;
  2322. }
  2323. }
  2324. pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp));
  2325. if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
  2326. if (create) {
  2327. if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) {
  2328. efree(pgsql_lofp);
  2329. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to create PostgreSQL large object");
  2330. RETURN_FALSE;
  2331. } else {
  2332. if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) {
  2333. if (lo_unlink(pgsql, oid) == -1) {
  2334. efree(pgsql_lofp);
  2335. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP");
  2336. RETURN_FALSE;
  2337. }
  2338. efree(pgsql_lofp);
  2339. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
  2340. RETURN_FALSE;
  2341. } else {
  2342. pgsql_lofp->conn = pgsql;
  2343. pgsql_lofp->lofd = pgsql_lofd;
  2344. Z_LVAL_P(return_value) = zend_list_insert(pgsql_lofp, le_lofp);
  2345. Z_TYPE_P(return_value) = IS_LONG;
  2346. }
  2347. }
  2348. } else {
  2349. efree(pgsql_lofp);
  2350. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to open PostgreSQL large object");
  2351. RETURN_FALSE;
  2352. }
  2353. } else {
  2354. pgsql_lofp->conn = pgsql;
  2355. pgsql_lofp->lofd = pgsql_lofd;
  2356. ZEND_REGISTER_RESOURCE(return_value, pgsql_lofp, le_lofp);
  2357. }
  2358. }
  2359. /* }}} */
  2360. /* {{{ proto bool pg_lo_close(resource large_object)
  2361. Close a large object */
  2362. PHP_FUNCTION(pg_lo_close)
  2363. {
  2364. zval **pgsql_lofp;
  2365. pgLofp *pgsql;
  2366. switch(ZEND_NUM_ARGS()) {
  2367. case 1:
  2368. if (zend_get_parameters_ex(1, &pgsql_lofp)==FAILURE) {
  2369. RETURN_FALSE;
  2370. }
  2371. break;
  2372. default:
  2373. WRONG_PARAM_COUNT;
  2374. break;
  2375. }
  2376. ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_lofp, -1, "PostgreSQL large object", le_lofp);
  2377. if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) {
  2378. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to close PostgreSQL large object descriptor %d", pgsql->lofd);
  2379. RETVAL_FALSE;
  2380. } else {
  2381. RETVAL_TRUE;
  2382. }
  2383. zend_list_delete(Z_RESVAL_PP(pgsql_lofp));
  2384. return;
  2385. }
  2386. /* }}} */
  2387. #define PGSQL_LO_READ_BUF_SIZE 8192
  2388. /* {{{ proto string pg_lo_read(resource large_object [, int len])
  2389. Read a large object */
  2390. PHP_FUNCTION(pg_lo_read)
  2391. {
  2392. zval **pgsql_id, **len;
  2393. int buf_len = PGSQL_LO_READ_BUF_SIZE, nbytes;
  2394. char *buf;
  2395. pgLofp *pgsql;
  2396. if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 2 ||
  2397. zend_get_parameters_ex(ZEND_NUM_ARGS(), &pgsql_id, &len) == FAILURE) {
  2398. WRONG_PARAM_COUNT;
  2399. }
  2400. ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, "PostgreSQL large object", le_lofp);
  2401. if (ZEND_NUM_ARGS() > 1) {
  2402. convert_to_long_ex(len);
  2403. buf_len = Z_LVAL_PP(len);
  2404. }
  2405. buf = (char *) safe_emalloc(sizeof(char), (buf_len+1), 0);
  2406. if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, buf_len))<0) {
  2407. efree(buf);
  2408. RETURN_FALSE;
  2409. }
  2410. buf[nbytes] = '\0';
  2411. RETURN_STRINGL(buf, nbytes, 0);
  2412. }
  2413. /* }}} */
  2414. /* {{{ proto int pg_lo_write(resource large_object, string buf [, int len])
  2415. Write a large object */
  2416. PHP_FUNCTION(pg_lo_write)
  2417. {
  2418. zval **pgsql_id, **str, **z_len;
  2419. int nbytes;
  2420. int len;
  2421. pgLofp *pgsql;
  2422. int argc = ZEND_NUM_ARGS();
  2423. if (argc < 2 || argc > 3 ||
  2424. zend_get_parameters_ex(argc, &pgsql_id, &str, &z_len) == FAILURE) {
  2425. WRONG_PARAM_COUNT;
  2426. }
  2427. convert_to_string_ex(str);
  2428. if (argc > 2) {
  2429. convert_to_long_ex(z_len);
  2430. if (Z_LVAL_PP(z_len) > Z_STRLEN_PP(str)) {
  2431. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot write more than buffer size %d. Tried to write %ld",
  2432. Z_STRLEN_PP(str), Z_LVAL_PP(z_len));
  2433. RETURN_FALSE;
  2434. }
  2435. if (Z_LVAL_PP(z_len) < 0) {
  2436. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Buffer size must be larger than 0, but %ld was specified", Z_LVAL_PP(z_len));
  2437. RETURN_FALSE;
  2438. }
  2439. len = Z_LVAL_PP(z_len);
  2440. }
  2441. else {
  2442. len = Z_STRLEN_PP(str);
  2443. }
  2444. ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, "PostgreSQL large object", le_lofp);
  2445. if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, Z_STRVAL_PP(str), len)) == -1) {
  2446. RETURN_FALSE;
  2447. }
  2448. RETURN_LONG(nbytes);
  2449. }
  2450. /* }}} */
  2451. /* {{{ proto int pg_lo_read_all(resource large_object)
  2452. Read a large object and send straight to browser */
  2453. PHP_FUNCTION(pg_lo_read_all)
  2454. {
  2455. zval **pgsql_id;
  2456. int tbytes;
  2457. volatile int nbytes;
  2458. char buf[PGSQL_LO_READ_BUF_SIZE];
  2459. pgLofp *pgsql;
  2460. switch(ZEND_NUM_ARGS()) {
  2461. case 1:
  2462. if (zend_get_parameters_ex(1, &pgsql_id)==FAILURE) {
  2463. RETURN_FALSE;
  2464. }
  2465. break;
  2466. default:
  2467. WRONG_PARAM_COUNT;
  2468. break;
  2469. }
  2470. ZEND_FETCH_RESOURCE(pgsql, pgLofp *, pgsql_id, -1, "PostgreSQL large object", le_lofp);
  2471. tbytes = 0;
  2472. while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) {
  2473. php_body_write(buf, nbytes TSRMLS_CC);
  2474. tbytes += nbytes;
  2475. }
  2476. RETURN_LONG(tbytes);
  2477. }
  2478. /* }}} */
  2479. /* {{{ proto int pg_lo_import([resource connection, ] string filename)
  2480. Import large object direct from filesystem */
  2481. PHP_FUNCTION(pg_lo_import)
  2482. {
  2483. zval *pgsql_link = NULL;
  2484. char *file_in;
  2485. int id = -1, name_len;
  2486. int argc = ZEND_NUM_ARGS();
  2487. PGconn *pgsql;
  2488. Oid oid;
  2489. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2490. "rs", &pgsql_link, &file_in, &name_len) == SUCCESS) {
  2491. ;
  2492. }
  2493. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2494. "s", &file_in, &name_len) == SUCCESS) {
  2495. id = PGG(default_link);
  2496. CHECK_DEFAULT_LINK(id);
  2497. }
  2498. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2499. "sr", &file_in, &name_len, &pgsql_link ) == SUCCESS) {
  2500. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
  2501. }
  2502. else {
  2503. WRONG_PARAM_COUNT;
  2504. }
  2505. if (PG(safe_mode) &&(!php_checkuid(file_in, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
  2506. RETURN_FALSE;
  2507. }
  2508. if (php_check_open_basedir(file_in TSRMLS_CC)) {
  2509. RETURN_FALSE;
  2510. }
  2511. if (pgsql_link == NULL && id == -1) {
  2512. RETURN_FALSE;
  2513. }
  2514. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2515. oid = lo_import(pgsql, file_in);
  2516. if (oid == InvalidOid) {
  2517. RETURN_FALSE;
  2518. }
  2519. PGSQL_RETURN_OID(oid);
  2520. }
  2521. /* }}} */
  2522. /* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename)
  2523. Export large object direct to filesystem */
  2524. PHP_FUNCTION(pg_lo_export)
  2525. {
  2526. zval *pgsql_link = NULL;
  2527. char *file_out, *oid_string, *end_ptr;
  2528. int oid_strlen;
  2529. int id = -1, name_len;
  2530. long oid_long;
  2531. Oid oid;
  2532. PGconn *pgsql;
  2533. int argc = ZEND_NUM_ARGS();
  2534. /* allow string to handle large OID value correctly */
  2535. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2536. "rls", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) {
  2537. if (oid_long <= InvalidOid) {
  2538. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
  2539. RETURN_FALSE;
  2540. }
  2541. oid = (Oid)oid_long;
  2542. }
  2543. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2544. "rss", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
  2545. oid = (Oid)strtoul(oid_string, &end_ptr, 10);
  2546. if ((oid_string+oid_strlen) != end_ptr) {
  2547. /* wrong integer format */
  2548. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
  2549. RETURN_FALSE;
  2550. }
  2551. }
  2552. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2553. "ls", &oid_long, &file_out, &name_len) == SUCCESS) {
  2554. if (oid_long <= InvalidOid) {
  2555. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
  2556. RETURN_FALSE;
  2557. }
  2558. oid = (Oid)oid_long;
  2559. id = PGG(default_link);
  2560. CHECK_DEFAULT_LINK(id);
  2561. }
  2562. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2563. "ss", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) {
  2564. oid = (Oid)strtoul(oid_string, &end_ptr, 10);
  2565. if ((oid_string+oid_strlen) != end_ptr) {
  2566. /* wrong integer format */
  2567. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
  2568. RETURN_FALSE;
  2569. }
  2570. id = PGG(default_link);
  2571. CHECK_DEFAULT_LINK(id);
  2572. }
  2573. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2574. "ssr", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) {
  2575. oid = (Oid)strtoul(oid_string, &end_ptr, 10);
  2576. if ((oid_string+oid_strlen) != end_ptr) {
  2577. /* wrong integer format */
  2578. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Wrong OID value passed");
  2579. RETURN_FALSE;
  2580. }
  2581. }
  2582. else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc TSRMLS_CC,
  2583. "lsr", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) {
  2584. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Old API is used");
  2585. if (oid_long <= InvalidOid) {
  2586. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid OID specified");
  2587. RETURN_FALSE;
  2588. }
  2589. oid = (Oid)oid_long;
  2590. }
  2591. else {
  2592. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Requires 2 or 3 arguments");
  2593. RETURN_FALSE;
  2594. }
  2595. if (PG(safe_mode) &&(!php_checkuid(file_out, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
  2596. RETURN_FALSE;
  2597. }
  2598. if (php_check_open_basedir(file_out TSRMLS_CC)) {
  2599. RETURN_FALSE;
  2600. }
  2601. if (pgsql_link == NULL && id == -1) {
  2602. RETURN_FALSE;
  2603. }
  2604. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2605. if (lo_export(pgsql, oid, file_out)) {
  2606. RETURN_TRUE;
  2607. }
  2608. RETURN_FALSE;
  2609. }
  2610. /* }}} */
  2611. /* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence])
  2612. Seeks position of large object */
  2613. PHP_FUNCTION(pg_lo_seek)
  2614. {
  2615. zval *pgsql_id = NULL;
  2616. long offset = 0, whence = SEEK_CUR;
  2617. pgLofp *pgsql;
  2618. int argc = ZEND_NUM_ARGS();
  2619. if (zend_parse_parameters(argc TSRMLS_CC, "rl|l", &pgsql_id, &offset, &whence) == FAILURE) {
  2620. return;
  2621. }
  2622. if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) {
  2623. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid whence parameter");
  2624. return;
  2625. }
  2626. ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
  2627. if (lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence) > -1) {
  2628. RETURN_TRUE;
  2629. } else {
  2630. RETURN_FALSE;
  2631. }
  2632. }
  2633. /* }}} */
  2634. /* {{{ proto int pg_lo_tell(resource large_object)
  2635. Returns current position of large object */
  2636. PHP_FUNCTION(pg_lo_tell)
  2637. {
  2638. zval *pgsql_id = NULL;
  2639. int offset = 0;
  2640. pgLofp *pgsql;
  2641. int argc = ZEND_NUM_ARGS();
  2642. if (zend_parse_parameters(argc TSRMLS_CC, "r", &pgsql_id) == FAILURE) {
  2643. return;
  2644. }
  2645. ZEND_FETCH_RESOURCE(pgsql, pgLofp *, &pgsql_id, -1, "PostgreSQL large object", le_lofp);
  2646. offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd);
  2647. RETURN_LONG(offset);
  2648. }
  2649. /* }}} */
  2650. #if HAVE_PQSETERRORVERBOSITY
  2651. /* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity)
  2652. Set error verbosity */
  2653. PHP_FUNCTION(pg_set_error_verbosity)
  2654. {
  2655. zval **verbosity, **pgsql_link = NULL;
  2656. long val;
  2657. int id = -1;
  2658. PGconn *pgsql;
  2659. switch(ZEND_NUM_ARGS()) {
  2660. case 1:
  2661. if (zend_get_parameters_ex(1, &verbosity)==FAILURE) {
  2662. RETURN_FALSE;
  2663. }
  2664. id = PGG(default_link);
  2665. CHECK_DEFAULT_LINK(id);
  2666. break;
  2667. case 2:
  2668. if (zend_get_parameters_ex(2, &pgsql_link, &verbosity)==FAILURE) {
  2669. RETURN_FALSE;
  2670. }
  2671. break;
  2672. default:
  2673. WRONG_PARAM_COUNT;
  2674. break;
  2675. }
  2676. if (pgsql_link == NULL && id == -1) {
  2677. RETURN_FALSE;
  2678. }
  2679. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2680. convert_to_long_ex(verbosity);
  2681. val = Z_LVAL_PP(verbosity);
  2682. if (val & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) {
  2683. Z_LVAL_P(return_value) = PQsetErrorVerbosity(pgsql, val);
  2684. Z_TYPE_P(return_value) = IS_LONG;
  2685. } else {
  2686. RETURN_FALSE;
  2687. }
  2688. }
  2689. /* }}} */
  2690. #endif
  2691. #ifdef HAVE_PQCLIENTENCODING
  2692. /* {{{ proto int pg_set_client_encoding([resource connection,] string encoding)
  2693. Set client encoding */
  2694. PHP_FUNCTION(pg_set_client_encoding)
  2695. {
  2696. zval **encoding, **pgsql_link = NULL;
  2697. int id = -1;
  2698. PGconn *pgsql;
  2699. switch(ZEND_NUM_ARGS()) {
  2700. case 1:
  2701. if (zend_get_parameters_ex(1, &encoding)==FAILURE) {
  2702. RETURN_FALSE;
  2703. }
  2704. id = PGG(default_link);
  2705. CHECK_DEFAULT_LINK(id);
  2706. break;
  2707. case 2:
  2708. if (zend_get_parameters_ex(2, &pgsql_link, &encoding)==FAILURE) {
  2709. RETURN_FALSE;
  2710. }
  2711. break;
  2712. default:
  2713. WRONG_PARAM_COUNT;
  2714. break;
  2715. }
  2716. if (pgsql_link == NULL && id == -1) {
  2717. RETURN_FALSE;
  2718. }
  2719. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2720. convert_to_string_ex(encoding);
  2721. Z_LVAL_P(return_value) = PQsetClientEncoding(pgsql, Z_STRVAL_PP(encoding));
  2722. Z_TYPE_P(return_value) = IS_LONG;
  2723. }
  2724. /* }}} */
  2725. /* {{{ proto string pg_client_encoding([resource connection])
  2726. Get the current client encoding */
  2727. PHP_FUNCTION(pg_client_encoding)
  2728. {
  2729. zval **pgsql_link = NULL;
  2730. int id = -1;
  2731. PGconn *pgsql;
  2732. switch(ZEND_NUM_ARGS()) {
  2733. case 0:
  2734. id = PGG(default_link);
  2735. CHECK_DEFAULT_LINK(id);
  2736. break;
  2737. case 1:
  2738. if (zend_get_parameters_ex(1, &pgsql_link)==FAILURE) {
  2739. RETURN_FALSE;
  2740. }
  2741. break;
  2742. default:
  2743. WRONG_PARAM_COUNT;
  2744. break;
  2745. }
  2746. if (pgsql_link == NULL && id == -1) {
  2747. RETURN_FALSE;
  2748. }
  2749. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2750. /* Just do the same as found in PostgreSQL sources... */
  2751. #ifndef HAVE_PGSQL_WITH_MULTIBYTE_SUPPORT
  2752. #define pg_encoding_to_char(x) "SQL_ASCII"
  2753. #endif
  2754. Z_STRVAL_P(return_value)
  2755. = (char *) pg_encoding_to_char(PQclientEncoding(pgsql));
  2756. Z_STRLEN_P(return_value) = strlen(Z_STRVAL_P(return_value));
  2757. Z_STRVAL_P(return_value) = (char *) estrdup(Z_STRVAL_P(return_value));
  2758. Z_TYPE_P(return_value) = IS_STRING;
  2759. }
  2760. /* }}} */
  2761. #endif
  2762. #if !HAVE_PQGETCOPYDATA
  2763. #define COPYBUFSIZ 8192
  2764. #endif
  2765. /* {{{ proto bool pg_end_copy([resource connection])
  2766. Sync with backend. Completes the Copy command */
  2767. PHP_FUNCTION(pg_end_copy)
  2768. {
  2769. zval **pgsql_link = NULL;
  2770. int id = -1;
  2771. PGconn *pgsql;
  2772. int result = 0;
  2773. switch(ZEND_NUM_ARGS()) {
  2774. case 0:
  2775. id = PGG(default_link);
  2776. CHECK_DEFAULT_LINK(id);
  2777. break;
  2778. case 1:
  2779. if (zend_get_parameters_ex(1, &pgsql_link)==FAILURE) {
  2780. RETURN_FALSE;
  2781. }
  2782. break;
  2783. default:
  2784. WRONG_PARAM_COUNT;
  2785. break;
  2786. }
  2787. if (pgsql_link == NULL && id == -1) {
  2788. RETURN_FALSE;
  2789. }
  2790. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2791. result = PQendcopy(pgsql);
  2792. if (result!=0) {
  2793. PHP_PQ_ERROR("Query failed: %s", pgsql);
  2794. RETURN_FALSE;
  2795. }
  2796. RETURN_TRUE;
  2797. }
  2798. /* }}} */
  2799. /* {{{ proto bool pg_put_line([resource connection,] string query)
  2800. Send null-terminated string to backend server*/
  2801. PHP_FUNCTION(pg_put_line)
  2802. {
  2803. zval **query, **pgsql_link = NULL;
  2804. int id = -1;
  2805. PGconn *pgsql;
  2806. int result = 0;
  2807. switch(ZEND_NUM_ARGS()) {
  2808. case 1:
  2809. if (zend_get_parameters_ex(1, &query)==FAILURE) {
  2810. RETURN_FALSE;
  2811. }
  2812. id = PGG(default_link);
  2813. CHECK_DEFAULT_LINK(id);
  2814. break;
  2815. case 2:
  2816. if (zend_get_parameters_ex(2, &pgsql_link, &query)==FAILURE) {
  2817. RETURN_FALSE;
  2818. }
  2819. break;
  2820. default:
  2821. WRONG_PARAM_COUNT;
  2822. break;
  2823. }
  2824. if (pgsql_link == NULL && id == -1) {
  2825. RETURN_FALSE;
  2826. }
  2827. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2828. convert_to_string_ex(query);
  2829. result = PQputline(pgsql, Z_STRVAL_PP(query));
  2830. if (result==EOF) {
  2831. PHP_PQ_ERROR("Query failed: %s", pgsql);
  2832. RETURN_FALSE;
  2833. }
  2834. RETURN_TRUE;
  2835. }
  2836. /* }}} */
  2837. /* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]])
  2838. Copy table to array */
  2839. PHP_FUNCTION(pg_copy_to)
  2840. {
  2841. zval *pgsql_link;
  2842. char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
  2843. int table_name_len, pg_delim_len, pg_null_as_len;
  2844. char *query;
  2845. char *query_template = "COPY \"\" TO STDOUT DELIMITERS ':' WITH NULL AS ''";
  2846. int id = -1;
  2847. PGconn *pgsql;
  2848. PGresult *pgsql_result;
  2849. ExecStatusType status;
  2850. int copydone = 0;
  2851. #if !HAVE_PQGETCOPYDATA
  2852. char copybuf[COPYBUFSIZ];
  2853. #endif
  2854. char *csv = (char *)NULL;
  2855. int ret;
  2856. int argc = ZEND_NUM_ARGS();
  2857. if (zend_parse_parameters(argc TSRMLS_CC, "rs|ss",
  2858. &pgsql_link, &table_name, &table_name_len,
  2859. &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
  2860. return;
  2861. }
  2862. if (!pg_delim) {
  2863. pg_delim = "\t";
  2864. }
  2865. if (!pg_null_as) {
  2866. pg_null_as = safe_estrdup("\\\\N");
  2867. }
  2868. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2869. query = (char *)emalloc(strlen(query_template) + strlen(table_name) + strlen(pg_null_as) + 1);
  2870. sprintf(query, "COPY \"%s\" TO STDOUT DELIMITERS '%c' WITH NULL AS '%s'",
  2871. table_name, *pg_delim, pg_null_as);
  2872. while ((pgsql_result = PQgetResult(pgsql))) {
  2873. PQclear(pgsql_result);
  2874. }
  2875. pgsql_result = PQexec(pgsql, query);
  2876. efree(pg_null_as);
  2877. efree(query);
  2878. if (pgsql_result) {
  2879. status = PQresultStatus(pgsql_result);
  2880. } else {
  2881. status = (ExecStatusType) PQstatus(pgsql);
  2882. }
  2883. switch (status) {
  2884. case PGRES_COPY_OUT:
  2885. if (pgsql_result) {
  2886. PQclear(pgsql_result);
  2887. array_init(return_value);
  2888. #if HAVE_PQGETCOPYDATA
  2889. while (!copydone)
  2890. {
  2891. ret = PQgetCopyData(pgsql, &csv, 0);
  2892. switch (ret) {
  2893. case -1:
  2894. copydone = 1;
  2895. break;
  2896. case 0:
  2897. case -2:
  2898. PHP_PQ_ERROR("getline failed: %s", pgsql);
  2899. RETURN_FALSE;
  2900. break;
  2901. default:
  2902. add_next_index_string(return_value, csv, 1);
  2903. PQfreemem(csv);
  2904. break;
  2905. }
  2906. }
  2907. #else
  2908. while (!copydone)
  2909. {
  2910. if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) {
  2911. PHP_PQ_ERROR("getline failed: %s", pgsql);
  2912. RETURN_FALSE;
  2913. }
  2914. if (copybuf[0] == '\\' &&
  2915. copybuf[1] == '.' &&
  2916. copybuf[2] == '\0')
  2917. {
  2918. copydone = 1;
  2919. }
  2920. else
  2921. {
  2922. if (csv == (char *)NULL) {
  2923. csv = estrdup(copybuf);
  2924. } else {
  2925. csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1));
  2926. strcat(csv, copybuf);
  2927. }
  2928. switch (ret)
  2929. {
  2930. case EOF:
  2931. copydone = 1;
  2932. case 0:
  2933. add_next_index_string(return_value, csv, 1);
  2934. efree(csv);
  2935. csv = (char *)NULL;
  2936. break;
  2937. case 1:
  2938. break;
  2939. }
  2940. }
  2941. }
  2942. if (PQendcopy(pgsql)) {
  2943. PHP_PQ_ERROR("endcopy failed: %s", pgsql);
  2944. RETURN_FALSE;
  2945. }
  2946. #endif
  2947. while ((pgsql_result = PQgetResult(pgsql))) {
  2948. PQclear(pgsql_result);
  2949. }
  2950. } else {
  2951. PQclear(pgsql_result);
  2952. RETURN_FALSE;
  2953. }
  2954. break;
  2955. default:
  2956. PQclear(pgsql_result);
  2957. PHP_PQ_ERROR("Copy command failed: %s", pgsql);
  2958. RETURN_FALSE;
  2959. break;
  2960. }
  2961. }
  2962. /* }}} */
  2963. /* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]])
  2964. Copy table from array */
  2965. PHP_FUNCTION(pg_copy_from)
  2966. {
  2967. zval *pgsql_link = NULL, *pg_rows;
  2968. zval **tmp;
  2969. char *table_name, *pg_delim = NULL, *pg_null_as = NULL;
  2970. int table_name_len, pg_delim_len, pg_null_as_len;
  2971. int pg_null_as_free = 0;
  2972. char *query;
  2973. char *query_template = "COPY \"\" FROM STDIN DELIMITERS ':' WITH NULL AS ''";
  2974. HashPosition pos;
  2975. int id = -1;
  2976. PGconn *pgsql;
  2977. PGresult *pgsql_result;
  2978. ExecStatusType status;
  2979. int argc = ZEND_NUM_ARGS();
  2980. if (zend_parse_parameters(argc TSRMLS_CC, "rs/a|ss",
  2981. &pgsql_link, &table_name, &table_name_len, &pg_rows,
  2982. &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) {
  2983. return;
  2984. }
  2985. if (!pg_delim) {
  2986. pg_delim = "\t";
  2987. }
  2988. if (!pg_null_as) {
  2989. pg_null_as = safe_estrdup("\\\\N");
  2990. pg_null_as_free = 1;
  2991. }
  2992. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  2993. query = (char *)emalloc(strlen(query_template) + strlen(table_name) + strlen(pg_null_as) + 1);
  2994. sprintf(query, "COPY \"%s\" FROM STDIN DELIMITERS '%c' WITH NULL AS '%s'",
  2995. table_name, *pg_delim, pg_null_as);
  2996. while ((pgsql_result = PQgetResult(pgsql))) {
  2997. PQclear(pgsql_result);
  2998. }
  2999. pgsql_result = PQexec(pgsql, query);
  3000. if (pg_null_as_free) {
  3001. efree(pg_null_as);
  3002. }
  3003. efree(query);
  3004. if (pgsql_result) {
  3005. status = PQresultStatus(pgsql_result);
  3006. } else {
  3007. status = (ExecStatusType) PQstatus(pgsql);
  3008. }
  3009. switch (status) {
  3010. case PGRES_COPY_IN:
  3011. if (pgsql_result) {
  3012. int command_failed = 0;
  3013. PQclear(pgsql_result);
  3014. zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos);
  3015. #if HAVE_PQPUTCOPYDATA
  3016. while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
  3017. convert_to_string_ex(tmp);
  3018. query = (char *)emalloc(Z_STRLEN_PP(tmp) +2);
  3019. strcpy(query, Z_STRVAL_PP(tmp));
  3020. if(*(query+Z_STRLEN_PP(tmp)-1) != '\n')
  3021. strcat(query, "\n");
  3022. if (PQputCopyData(pgsql, query, strlen(query)) != 1) {
  3023. efree(query);
  3024. PHP_PQ_ERROR("copy failed: %s", pgsql);
  3025. RETURN_FALSE;
  3026. }
  3027. efree(query);
  3028. zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
  3029. }
  3030. if (PQputCopyEnd(pgsql, NULL) != 1) {
  3031. PHP_PQ_ERROR("putcopyend failed: %s", pgsql);
  3032. RETURN_FALSE;
  3033. }
  3034. #else
  3035. while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
  3036. convert_to_string_ex(tmp);
  3037. query = (char *)emalloc(Z_STRLEN_PP(tmp) +2);
  3038. strcpy(query, Z_STRVAL_PP(tmp));
  3039. if(*(query+Z_STRLEN_PP(tmp)-1) != '\n')
  3040. strcat(query, "\n");
  3041. if (PQputline(pgsql, query)==EOF) {
  3042. efree(query);
  3043. PHP_PQ_ERROR("copy failed: %s", pgsql);
  3044. RETURN_FALSE;
  3045. }
  3046. efree(query);
  3047. zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
  3048. }
  3049. if (PQputline(pgsql, "\\.\n") == EOF) {
  3050. PHP_PQ_ERROR("putline failed: %s", pgsql);
  3051. RETURN_FALSE;
  3052. }
  3053. if (PQendcopy(pgsql)) {
  3054. PHP_PQ_ERROR("endcopy failed: %s", pgsql);
  3055. RETURN_FALSE;
  3056. }
  3057. #endif
  3058. while ((pgsql_result = PQgetResult(pgsql))) {
  3059. if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
  3060. PHP_PQ_ERROR("Copy command failed: %s", pgsql);
  3061. command_failed = 1;
  3062. }
  3063. PQclear(pgsql_result);
  3064. }
  3065. if (command_failed) {
  3066. RETURN_FALSE;
  3067. }
  3068. } else {
  3069. PQclear(pgsql_result);
  3070. RETURN_FALSE;
  3071. }
  3072. RETURN_TRUE;
  3073. break;
  3074. default:
  3075. PQclear(pgsql_result);
  3076. PHP_PQ_ERROR("Copy command failed: %s", pgsql);
  3077. RETURN_FALSE;
  3078. break;
  3079. }
  3080. }
  3081. /* }}} */
  3082. #ifdef HAVE_PQESCAPE
  3083. /* {{{ proto string pg_escape_string(string data)
  3084. Escape string for text/char type */
  3085. PHP_FUNCTION(pg_escape_string)
  3086. {
  3087. char *from = NULL, *to = NULL;
  3088. int to_len;
  3089. int from_len;
  3090. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
  3091. &from, &from_len) == FAILURE) {
  3092. return;
  3093. }
  3094. to = (char *)safe_emalloc(from_len, 2, 1);
  3095. to_len = (int)PQescapeString(to, from, from_len);
  3096. RETURN_STRINGL(to, to_len, 0);
  3097. }
  3098. /* }}} */
  3099. /* {{{ proto string pg_escape_bytea(string data)
  3100. Escape binary for bytea type */
  3101. PHP_FUNCTION(pg_escape_bytea)
  3102. {
  3103. char *from = NULL, *to = NULL;
  3104. size_t to_len;
  3105. int from_len;
  3106. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
  3107. &from, &from_len) == FAILURE) {
  3108. return;
  3109. }
  3110. to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len);
  3111. RETVAL_STRINGL(to, to_len-1, 1); /* to_len includes addtional '\0' */
  3112. free(to);
  3113. }
  3114. /* }}} */
  3115. #if !HAVE_PQUNESCAPEBYTEA
  3116. /* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users.
  3117. Renamed to php_pgsql_unescape_bytea() */
  3118. /*
  3119. * PQunescapeBytea - converts the null terminated string representation
  3120. * of a bytea, strtext, into binary, filling a buffer. It returns a
  3121. * pointer to the buffer which is NULL on error, and the size of the
  3122. * buffer in retbuflen. The pointer may subsequently be used as an
  3123. * argument to the function free(3). It is the reverse of PQescapeBytea.
  3124. *
  3125. * The following transformations are reversed:
  3126. * '\0' == ASCII 0 == \000
  3127. * '\'' == ASCII 39 == \'
  3128. * '\\' == ASCII 92 == \\
  3129. *
  3130. * States:
  3131. * 0 normal 0->1->2->3->4
  3132. * 1 \ 1->5
  3133. * 2 \0 1->6
  3134. * 3 \00
  3135. * 4 \000
  3136. * 5 \'
  3137. * 6 \\
  3138. */
  3139. static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen)
  3140. {
  3141. size_t buflen;
  3142. unsigned char *buffer,
  3143. *sp,
  3144. *bp;
  3145. unsigned int state = 0;
  3146. if (strtext == NULL)
  3147. return NULL;
  3148. buflen = strlen(strtext); /* will shrink, also we discover if
  3149. * strtext */
  3150. buffer = (unsigned char *) emalloc(buflen); /* isn't NULL terminated */
  3151. for (bp = buffer, sp = strtext; *sp != '\0'; bp++, sp++)
  3152. {
  3153. switch (state)
  3154. {
  3155. case 0:
  3156. if (*sp == '\\')
  3157. state = 1;
  3158. *bp = *sp;
  3159. break;
  3160. case 1:
  3161. if (*sp == '\'') /* state=5 */
  3162. { /* replace \' with 39 */
  3163. bp--;
  3164. *bp = '\'';
  3165. buflen--;
  3166. state = 0;
  3167. }
  3168. else if (*sp == '\\') /* state=6 */
  3169. { /* replace \\ with 92 */
  3170. bp--;
  3171. *bp = '\\';
  3172. buflen--;
  3173. state = 0;
  3174. }
  3175. else
  3176. {
  3177. if (isdigit(*sp))
  3178. state = 2;
  3179. else
  3180. state = 0;
  3181. *bp = *sp;
  3182. }
  3183. break;
  3184. case 2:
  3185. if (isdigit(*sp))
  3186. state = 3;
  3187. else
  3188. state = 0;
  3189. *bp = *sp;
  3190. break;
  3191. case 3:
  3192. if (isdigit(*sp)) /* state=4 */
  3193. {
  3194. unsigned char *start, *end, buf[4]; /* 000 + '\0' */
  3195. bp -= 3;
  3196. memcpy(buf, sp-2, 3);
  3197. buf[3] = '\0';
  3198. start = buf;
  3199. *bp = (unsigned char)strtoul(start, (char **)&end, 8);
  3200. buflen -= 3;
  3201. state = 0;
  3202. }
  3203. else
  3204. {
  3205. *bp = *sp;
  3206. state = 0;
  3207. }
  3208. break;
  3209. }
  3210. }
  3211. buffer = erealloc(buffer, buflen+1);
  3212. buffer[buflen] = '\0';
  3213. *retbuflen = buflen;
  3214. return buffer;
  3215. }
  3216. #endif
  3217. /* {{{ proto string pg_unescape_bytea(string data)
  3218. Unescape binary for bytea type */
  3219. PHP_FUNCTION(pg_unescape_bytea)
  3220. {
  3221. char *from = NULL, *to = NULL, *tmp = NULL;
  3222. size_t to_len;
  3223. int from_len;
  3224. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
  3225. &from, &from_len) == FAILURE) {
  3226. return;
  3227. }
  3228. #if HAVE_PQUNESCAPEBYTEA
  3229. tmp = (char *)PQunescapeBytea((unsigned char*)from, &to_len);
  3230. to = estrndup(tmp, to_len);
  3231. PQfreemem(tmp);
  3232. #else
  3233. to = (char *)php_pgsql_unescape_bytea((unsigned char*)from, &to_len);
  3234. #endif
  3235. if (!to) {
  3236. RETURN_FALSE;
  3237. }
  3238. RETVAL_STRINGL(to, to_len, 0);
  3239. }
  3240. /* }}} */
  3241. #endif
  3242. /* {{{ proto string pg_result_error(resource result)
  3243. Get error message associated with result */
  3244. PHP_FUNCTION(pg_result_error)
  3245. {
  3246. zval *result;
  3247. PGresult *pgsql_result;
  3248. pgsql_result_handle *pg_result;
  3249. char *err = NULL;
  3250. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
  3251. &result) == FAILURE) {
  3252. RETURN_FALSE;
  3253. }
  3254. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
  3255. pgsql_result = pg_result->result;
  3256. if (!pgsql_result) {
  3257. RETURN_FALSE;
  3258. }
  3259. err = (char *)PQresultErrorMessage(pgsql_result);
  3260. RETURN_STRING(err,1);
  3261. }
  3262. /* }}} */
  3263. #if HAVE_PQRESULTERRORFIELD
  3264. /* {{{ proto string pg_result_error_field(resource result, int fieldcode)
  3265. Get error message field associated with result */
  3266. PHP_FUNCTION(pg_result_error_field)
  3267. {
  3268. zval *result;
  3269. long fieldcode;
  3270. PGresult *pgsql_result;
  3271. pgsql_result_handle *pg_result;
  3272. char *field = NULL;
  3273. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "rl",
  3274. &result, &fieldcode) == FAILURE) {
  3275. RETURN_FALSE;
  3276. }
  3277. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
  3278. pgsql_result = pg_result->result;
  3279. if (!pgsql_result) {
  3280. RETURN_FALSE;
  3281. }
  3282. if (fieldcode & (PG_DIAG_SEVERITY|PG_DIAG_SQLSTATE|PG_DIAG_MESSAGE_PRIMARY|PG_DIAG_MESSAGE_DETAIL
  3283. |PG_DIAG_MESSAGE_HINT|PG_DIAG_STATEMENT_POSITION
  3284. #if PG_DIAG_INTERNAL_POSITION
  3285. |PG_DIAG_INTERNAL_POSITION
  3286. #endif
  3287. #if PG_DIAG_INTERNAL_QUERY
  3288. |PG_DIAG_INTERNAL_QUERY
  3289. #endif
  3290. |PG_DIAG_CONTEXT|PG_DIAG_SOURCE_FILE|PG_DIAG_SOURCE_LINE
  3291. |PG_DIAG_SOURCE_FUNCTION)) {
  3292. field = (char *)PQresultErrorField(pgsql_result, fieldcode);
  3293. if (field == NULL) {
  3294. RETURN_NULL();
  3295. } else {
  3296. RETURN_STRING(field, 1);
  3297. }
  3298. } else {
  3299. RETURN_FALSE;
  3300. }
  3301. }
  3302. /* }}} */
  3303. #endif
  3304. /* {{{ proto int pg_connection_status(resource connnection)
  3305. Get connection status */
  3306. PHP_FUNCTION(pg_connection_status)
  3307. {
  3308. zval *pgsql_link = NULL;
  3309. int id = -1;
  3310. PGconn *pgsql;
  3311. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
  3312. &pgsql_link) == FAILURE) {
  3313. RETURN_FALSE;
  3314. }
  3315. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3316. RETURN_LONG(PQstatus(pgsql));
  3317. }
  3318. /* }}} */
  3319. #if HAVE_PGTRANSACTIONSTATUS
  3320. /* {{{ proto int pg_transaction_status(resource connnection)
  3321. Get transaction status */
  3322. PHP_FUNCTION(pg_transaction_status)
  3323. {
  3324. zval *pgsql_link = NULL;
  3325. int id = -1;
  3326. PGconn *pgsql;
  3327. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
  3328. &pgsql_link) == FAILURE) {
  3329. RETURN_FALSE;
  3330. }
  3331. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3332. RETURN_LONG(PQtransactionStatus(pgsql));
  3333. }
  3334. #endif
  3335. /* }}} */
  3336. /* {{{ proto bool pg_connection_reset(resource connection)
  3337. Reset connection (reconnect) */
  3338. PHP_FUNCTION(pg_connection_reset)
  3339. {
  3340. zval *pgsql_link;
  3341. int id = -1;
  3342. PGconn *pgsql;
  3343. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
  3344. &pgsql_link) == FAILURE) {
  3345. RETURN_FALSE;
  3346. }
  3347. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3348. PQreset(pgsql);
  3349. if (PQstatus(pgsql) == CONNECTION_BAD) {
  3350. RETURN_FALSE;
  3351. }
  3352. RETURN_TRUE;
  3353. }
  3354. /* }}} */
  3355. #define PHP_PG_ASYNC_IS_BUSY 1
  3356. #define PHP_PG_ASYNC_REQUEST_CANCEL 2
  3357. /* {{{ php_pgsql_flush_query
  3358. */
  3359. static int php_pgsql_flush_query(PGconn *pgsql TSRMLS_DC)
  3360. {
  3361. PGresult *res;
  3362. int leftover = 0;
  3363. if (PQ_SETNONBLOCKING(pgsql, 1)) {
  3364. php_error_docref(NULL TSRMLS_CC, E_NOTICE,"Cannot set connection to nonblocking mode");
  3365. return -1;
  3366. }
  3367. while ((res = PQgetResult(pgsql))) {
  3368. PQclear(res);
  3369. leftover++;
  3370. }
  3371. PQ_SETNONBLOCKING(pgsql, 0);
  3372. return leftover;
  3373. }
  3374. /* }}} */
  3375. /* {{{ php_pgsql_do_async
  3376. */
  3377. static void php_pgsql_do_async(INTERNAL_FUNCTION_PARAMETERS, int entry_type)
  3378. {
  3379. zval *pgsql_link;
  3380. int id = -1;
  3381. PGconn *pgsql;
  3382. PGresult *pgsql_result;
  3383. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
  3384. &pgsql_link) == FAILURE) {
  3385. RETURN_FALSE;
  3386. }
  3387. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3388. if (PQ_SETNONBLOCKING(pgsql, 1)) {
  3389. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
  3390. RETURN_FALSE;
  3391. }
  3392. switch(entry_type) {
  3393. case PHP_PG_ASYNC_IS_BUSY:
  3394. PQconsumeInput(pgsql);
  3395. Z_LVAL_P(return_value) = PQisBusy(pgsql);
  3396. Z_TYPE_P(return_value) = IS_LONG;
  3397. break;
  3398. case PHP_PG_ASYNC_REQUEST_CANCEL:
  3399. Z_LVAL_P(return_value) = PQrequestCancel(pgsql);
  3400. Z_TYPE_P(return_value) = IS_LONG;
  3401. while ((pgsql_result = PQgetResult(pgsql))) {
  3402. PQclear(pgsql_result);
  3403. }
  3404. break;
  3405. default:
  3406. php_error_docref(NULL TSRMLS_CC, E_ERROR, "PostgreSQL module error, please report this error");
  3407. break;
  3408. }
  3409. if (PQ_SETNONBLOCKING(pgsql, 0)) {
  3410. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
  3411. }
  3412. convert_to_boolean_ex(&return_value);
  3413. }
  3414. /* }}} */
  3415. /* {{{ proto bool pg_cancel_query(resource connection)
  3416. Cancel request */
  3417. PHP_FUNCTION(pg_cancel_query)
  3418. {
  3419. php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_REQUEST_CANCEL);
  3420. }
  3421. /* }}} */
  3422. /* {{{ proto bool pg_connection_busy(resource connection)
  3423. Get connection is busy or not */
  3424. PHP_FUNCTION(pg_connection_busy)
  3425. {
  3426. php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_IS_BUSY);
  3427. }
  3428. /* }}} */
  3429. /* {{{ proto bool pg_send_query(resource connection, string query)
  3430. Send asynchronous query */
  3431. PHP_FUNCTION(pg_send_query)
  3432. {
  3433. zval *pgsql_link;
  3434. char *query;
  3435. int len;
  3436. int id = -1;
  3437. PGconn *pgsql;
  3438. PGresult *res;
  3439. int leftover = 0;
  3440. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs",
  3441. &pgsql_link, &query, &len) == FAILURE) {
  3442. return;
  3443. }
  3444. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3445. if (PQ_SETNONBLOCKING(pgsql, 1)) {
  3446. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
  3447. RETURN_FALSE;
  3448. }
  3449. while ((res = PQgetResult(pgsql))) {
  3450. PQclear(res);
  3451. leftover = 1;
  3452. }
  3453. if (leftover) {
  3454. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "There are results on this connection. Call pg_get_result() until it returns FALSE");
  3455. }
  3456. if (!PQsendQuery(pgsql, query)) {
  3457. if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
  3458. PQreset(pgsql);
  3459. }
  3460. if (!PQsendQuery(pgsql, query)) {
  3461. RETURN_FALSE;
  3462. }
  3463. }
  3464. if (PQ_SETNONBLOCKING(pgsql, 0)) {
  3465. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
  3466. }
  3467. RETURN_TRUE;
  3468. }
  3469. /* }}} */
  3470. #if HAVE_PQSENDQUERYPARAMS
  3471. /* {{{ proto bool pg_send_query_params(resource connection, string query)
  3472. Send asynchronous parameterized query */
  3473. PHP_FUNCTION(pg_send_query_params)
  3474. {
  3475. zval **pgsql_link;
  3476. zval **pv_param_arr, **tmp;
  3477. int num_params = 0;
  3478. char **params = NULL;
  3479. unsigned char otype;
  3480. zval **query;
  3481. int id = -1;
  3482. PGconn *pgsql;
  3483. PGresult *res;
  3484. int leftover = 0;
  3485. if (zend_get_parameters_ex(3, &pgsql_link, &query, &pv_param_arr) == FAILURE) {
  3486. return;
  3487. }
  3488. if (pgsql_link == NULL && id == -1) {
  3489. RETURN_FALSE;
  3490. }
  3491. if (Z_TYPE_PP(pv_param_arr) != IS_ARRAY) {
  3492. php_error_docref(NULL TSRMLS_CC, E_WARNING, "No array passed");
  3493. RETURN_FALSE;
  3494. }
  3495. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3496. convert_to_string_ex(query);
  3497. if (PQ_SETNONBLOCKING(pgsql, 1)) {
  3498. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
  3499. RETURN_FALSE;
  3500. }
  3501. while ((res = PQgetResult(pgsql))) {
  3502. PQclear(res);
  3503. leftover = 1;
  3504. }
  3505. if (leftover) {
  3506. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "There are results on this connection. Call pg_get_result() until it returns FALSE");
  3507. }
  3508. zend_hash_internal_pointer_reset(Z_ARRVAL_PP(pv_param_arr));
  3509. num_params = zend_hash_num_elements(Z_ARRVAL_PP(pv_param_arr));
  3510. if (num_params > 0) {
  3511. int i = 0;
  3512. params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
  3513. for(i = 0; i < num_params; i++) {
  3514. if (zend_hash_get_current_data(Z_ARRVAL_PP(pv_param_arr), (void **) &tmp) == FAILURE) {
  3515. php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
  3516. _php_pgsql_free_params(params, num_params);
  3517. RETURN_FALSE;
  3518. }
  3519. otype = (*tmp)->type;
  3520. convert_to_string(*tmp);
  3521. if (Z_TYPE_PP(tmp) != IS_STRING) {
  3522. php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
  3523. _php_pgsql_free_params(params, num_params);
  3524. RETURN_FALSE;
  3525. }
  3526. if (otype == IS_NULL) {
  3527. params[i] = NULL;
  3528. }
  3529. else {
  3530. params[i] = Z_STRVAL_PP(tmp);
  3531. }
  3532. zend_hash_move_forward(Z_ARRVAL_PP(pv_param_arr));
  3533. }
  3534. }
  3535. if (!PQsendQueryParams(pgsql, Z_STRVAL_PP(query), num_params, NULL, (const char * const *)params, NULL, NULL, 0)) {
  3536. if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
  3537. PQreset(pgsql);
  3538. }
  3539. if (!PQsendQueryParams(pgsql, Z_STRVAL_PP(query), num_params, NULL, (const char * const *)params, NULL, NULL, 0)) {
  3540. _php_pgsql_free_params(params, num_params);
  3541. RETURN_FALSE;
  3542. }
  3543. }
  3544. _php_pgsql_free_params(params, num_params);
  3545. if (PQ_SETNONBLOCKING(pgsql, 0)) {
  3546. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
  3547. }
  3548. RETURN_TRUE;
  3549. }
  3550. /* }}} */
  3551. #endif
  3552. #if HAVE_PQSENDPREPARE
  3553. /* {{{ proto bool pg_send_prepare(resource connection, string stmtname, string query)
  3554. Asynchronously prepare a query for future execution */
  3555. PHP_FUNCTION(pg_send_prepare)
  3556. {
  3557. zval **pgsql_link;
  3558. zval **query, **stmtname;
  3559. int id = -1;
  3560. PGconn *pgsql;
  3561. PGresult *res;
  3562. int leftover = 0;
  3563. if (zend_get_parameters_ex(3, &pgsql_link, &stmtname, &query) == FAILURE) {
  3564. return;
  3565. }
  3566. if (pgsql_link == NULL && id == -1) {
  3567. RETURN_FALSE;
  3568. }
  3569. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3570. convert_to_string_ex(stmtname);
  3571. convert_to_string_ex(query);
  3572. if (PQ_SETNONBLOCKING(pgsql, 1)) {
  3573. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
  3574. RETURN_FALSE;
  3575. }
  3576. while ((res = PQgetResult(pgsql))) {
  3577. PQclear(res);
  3578. leftover = 1;
  3579. }
  3580. if (leftover) {
  3581. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "There are results on this connection. Call pg_get_result() until it returns FALSE");
  3582. }
  3583. if (!PQsendPrepare(pgsql, Z_STRVAL_PP(stmtname), Z_STRVAL_PP(query), 0, NULL)) {
  3584. if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
  3585. PQreset(pgsql);
  3586. }
  3587. if (!PQsendPrepare(pgsql, Z_STRVAL_PP(stmtname), Z_STRVAL_PP(query), 0, NULL)) {
  3588. RETURN_FALSE;
  3589. }
  3590. }
  3591. if (PQ_SETNONBLOCKING(pgsql, 0)) {
  3592. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
  3593. }
  3594. RETURN_TRUE;
  3595. }
  3596. /* }}} */
  3597. #endif
  3598. #if HAVE_PQSENDQUERYPREPARED
  3599. /* {{{ proto bool pg_send_execute(resource connection, string stmtname, array params)
  3600. Executes prevriously prepared stmtname asynchronously */
  3601. PHP_FUNCTION(pg_send_execute)
  3602. {
  3603. zval **pgsql_link;
  3604. zval **pv_param_arr, **tmp;
  3605. int num_params = 0;
  3606. char **params = NULL;
  3607. unsigned char otype;
  3608. zval **stmtname;
  3609. int id = -1;
  3610. PGconn *pgsql;
  3611. PGresult *res;
  3612. int leftover = 0;
  3613. if (zend_get_parameters_ex(3, &pgsql_link, &stmtname, &pv_param_arr)==FAILURE) {
  3614. return;
  3615. }
  3616. if (pgsql_link == NULL && id == -1) {
  3617. RETURN_FALSE;
  3618. }
  3619. if (Z_TYPE_PP(pv_param_arr) != IS_ARRAY) {
  3620. php_error_docref(NULL TSRMLS_CC, E_WARNING, "No array passed");
  3621. RETURN_FALSE;
  3622. }
  3623. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3624. convert_to_string_ex(stmtname);
  3625. if (PQ_SETNONBLOCKING(pgsql, 1)) {
  3626. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to nonblocking mode");
  3627. RETURN_FALSE;
  3628. }
  3629. while ((res = PQgetResult(pgsql))) {
  3630. PQclear(res);
  3631. leftover = 1;
  3632. }
  3633. if (leftover) {
  3634. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "There are results on this connection. Call pg_get_result() until it returns FALSE");
  3635. }
  3636. zend_hash_internal_pointer_reset(Z_ARRVAL_PP(pv_param_arr));
  3637. num_params = zend_hash_num_elements(Z_ARRVAL_PP(pv_param_arr));
  3638. if (num_params > 0) {
  3639. int i = 0;
  3640. params = (char **)safe_emalloc(sizeof(char *), num_params, 0);
  3641. for(i = 0; i < num_params; i++) {
  3642. if (zend_hash_get_current_data(Z_ARRVAL_PP(pv_param_arr), (void **) &tmp) == FAILURE) {
  3643. php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error getting parameter");
  3644. _php_pgsql_free_params(params, num_params);
  3645. RETURN_FALSE;
  3646. }
  3647. otype = (*tmp)->type;
  3648. convert_to_string(*tmp);
  3649. if (Z_TYPE_PP(tmp) != IS_STRING) {
  3650. php_error_docref(NULL TSRMLS_CC, E_WARNING,"Error converting parameter");
  3651. _php_pgsql_free_params(params, num_params);
  3652. RETURN_FALSE;
  3653. }
  3654. if (otype == IS_NULL) {
  3655. params[i] = NULL;
  3656. }
  3657. else {
  3658. params[i] = Z_STRVAL_PP(tmp);
  3659. }
  3660. zend_hash_move_forward(Z_ARRVAL_PP(pv_param_arr));
  3661. }
  3662. }
  3663. if (!PQsendQueryPrepared(pgsql, Z_STRVAL_PP(stmtname), num_params, (const char * const *)params, NULL, NULL, 0)) {
  3664. if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) {
  3665. PQreset(pgsql);
  3666. }
  3667. if (!PQsendQueryPrepared(pgsql, Z_STRVAL_PP(stmtname), num_params, (const char * const *)params, NULL, NULL, 0)) {
  3668. _php_pgsql_free_params(params, num_params);
  3669. RETURN_FALSE;
  3670. }
  3671. }
  3672. _php_pgsql_free_params(params, num_params);
  3673. if (PQ_SETNONBLOCKING(pgsql, 0)) {
  3674. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Cannot set connection to blocking mode");
  3675. }
  3676. RETURN_TRUE;
  3677. }
  3678. /* }}} */
  3679. #endif
  3680. /* {{{ proto resource pg_get_result(resource connection)
  3681. Get asynchronous query result */
  3682. PHP_FUNCTION(pg_get_result)
  3683. {
  3684. zval *pgsql_link;
  3685. int id = -1;
  3686. PGconn *pgsql;
  3687. PGresult *pgsql_result;
  3688. pgsql_result_handle *pg_result;
  3689. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
  3690. &pgsql_link) == FAILURE) {
  3691. RETURN_FALSE;
  3692. }
  3693. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3694. pgsql_result = PQgetResult(pgsql);
  3695. if (!pgsql_result) {
  3696. /* no result */
  3697. RETURN_FALSE;
  3698. }
  3699. pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle));
  3700. pg_result->conn = pgsql;
  3701. pg_result->result = pgsql_result;
  3702. pg_result->row = 0;
  3703. ZEND_REGISTER_RESOURCE(return_value, pg_result, le_result);
  3704. }
  3705. /* }}} */
  3706. /* {{{ proto mixed pg_result_status(resource result[, long result_type])
  3707. Get status of query result */
  3708. PHP_FUNCTION(pg_result_status)
  3709. {
  3710. zval *result;
  3711. long result_type = PGSQL_STATUS_LONG;
  3712. ExecStatusType status;
  3713. PGresult *pgsql_result;
  3714. pgsql_result_handle *pg_result;
  3715. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l",
  3716. &result, &result_type) == FAILURE) {
  3717. RETURN_FALSE;
  3718. }
  3719. ZEND_FETCH_RESOURCE(pg_result, pgsql_result_handle *, &result, -1, "PostgreSQL result", le_result);
  3720. pgsql_result = pg_result->result;
  3721. if (result_type == PGSQL_STATUS_LONG) {
  3722. status = PQresultStatus(pgsql_result);
  3723. RETURN_LONG((int)status);
  3724. }
  3725. else if (result_type == PGSQL_STATUS_STRING) {
  3726. RETURN_STRING(PQcmdStatus(pgsql_result), 1);
  3727. }
  3728. else {
  3729. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Optional 2nd parameter should be PGSQL_STATUS_LONG or PGSQL_STATUS_STRING");
  3730. RETURN_FALSE;
  3731. }
  3732. }
  3733. /* }}} */
  3734. /* {{{ proto array pg_get_notify([resource connection[, result_type]])
  3735. Get asynchronous notification */
  3736. PHP_FUNCTION(pg_get_notify)
  3737. {
  3738. zval *pgsql_link;
  3739. int id = -1;
  3740. long result_type = PGSQL_ASSOC;
  3741. PGconn *pgsql;
  3742. PGnotify *pgsql_notify;
  3743. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r|l",
  3744. &pgsql_link, &result_type) == FAILURE) {
  3745. RETURN_FALSE;
  3746. }
  3747. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3748. if (!(result_type & PGSQL_BOTH)) {
  3749. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
  3750. RETURN_FALSE;
  3751. }
  3752. PQconsumeInput(pgsql);
  3753. pgsql_notify = PQnotifies(pgsql);
  3754. if (!pgsql_notify) {
  3755. /* no notify message */
  3756. RETURN_FALSE;
  3757. }
  3758. array_init(return_value);
  3759. if (result_type & PGSQL_NUM) {
  3760. add_index_string(return_value, 0, pgsql_notify->relname, 1);
  3761. add_index_long(return_value, 1, pgsql_notify->be_pid);
  3762. }
  3763. if (result_type & PGSQL_ASSOC) {
  3764. add_assoc_string(return_value, "message", pgsql_notify->relname, 1);
  3765. add_assoc_long(return_value, "pid", pgsql_notify->be_pid);
  3766. }
  3767. }
  3768. /* }}} */
  3769. /* {{{ proto int pg_get_pid([resource connection)
  3770. Get backend(server) pid */
  3771. PHP_FUNCTION(pg_get_pid)
  3772. {
  3773. zval *pgsql_link;
  3774. int id = -1;
  3775. PGconn *pgsql;
  3776. if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "r",
  3777. &pgsql_link) == FAILURE) {
  3778. RETURN_FALSE;
  3779. }
  3780. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3781. RETURN_LONG(PQbackendPID(pgsql));
  3782. }
  3783. /* }}} */
  3784. /* {{{ php_pgsql_meta_data
  3785. * TODO: Add meta_data cache for better performance
  3786. */
  3787. PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, zval *meta TSRMLS_DC)
  3788. {
  3789. PGresult *pg_result;
  3790. char *tmp_name;
  3791. smart_str querystr = {0};
  3792. int new_len;
  3793. int i, num_rows;
  3794. zval *elem;
  3795. smart_str_appends(&querystr,
  3796. "SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotNULL, a.atthasdef, a.attndims "
  3797. "FROM pg_class as c, pg_attribute a, pg_type t "
  3798. "WHERE a.attnum > 0 AND a.attrelid = c.oid AND c.relname = '");
  3799. tmp_name = php_addslashes((char *)table_name, strlen(table_name), &new_len, 0 TSRMLS_CC);
  3800. smart_str_appendl(&querystr, tmp_name, new_len);
  3801. efree(tmp_name);
  3802. smart_str_appends(&querystr, "' AND a.atttypid = t.oid ORDER BY a.attnum;");
  3803. smart_str_0(&querystr);
  3804. pg_result = PQexec(pg_link, querystr.c);
  3805. if (PQresultStatus(pg_result) != PGRES_TUPLES_OK || (num_rows = PQntuples(pg_result)) == 0) {
  3806. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to query meta_data for '%s' table %s", table_name, querystr.c);
  3807. smart_str_free(&querystr);
  3808. PQclear(pg_result);
  3809. return FAILURE;
  3810. }
  3811. smart_str_free(&querystr);
  3812. for (i = 0; i < num_rows; i++) {
  3813. char *name;
  3814. MAKE_STD_ZVAL(elem);
  3815. array_init(elem);
  3816. add_assoc_long(elem, "num", atoi(PQgetvalue(pg_result,i,1)));
  3817. add_assoc_string(elem, "type", PQgetvalue(pg_result,i,2), 1);
  3818. add_assoc_long(elem, "len", atoi(PQgetvalue(pg_result,i,3)));
  3819. if (!strcmp(PQgetvalue(pg_result,i,4), "t")) {
  3820. add_assoc_bool(elem, "not null", 1);
  3821. }
  3822. else {
  3823. add_assoc_bool(elem, "not null", 0);
  3824. }
  3825. if (!strcmp(PQgetvalue(pg_result,i,5), "t")) {
  3826. add_assoc_bool(elem, "has default", 1);
  3827. }
  3828. else {
  3829. add_assoc_bool(elem, "has default", 0);
  3830. }
  3831. add_assoc_long(elem, "array dims", atoi(PQgetvalue(pg_result,i,6)));
  3832. name = PQgetvalue(pg_result,i,0);
  3833. add_assoc_zval(meta, name, elem);
  3834. }
  3835. PQclear(pg_result);
  3836. return SUCCESS;
  3837. }
  3838. /* }}} */
  3839. /* {{{ proto array pg_meta_data(resource db, string table)
  3840. Get meta_data */
  3841. PHP_FUNCTION(pg_meta_data)
  3842. {
  3843. zval *pgsql_link;
  3844. char *table_name;
  3845. uint table_name_len;
  3846. PGconn *pgsql;
  3847. int id = -1;
  3848. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs",
  3849. &pgsql_link, &table_name, &table_name_len) == FAILURE) {
  3850. return;
  3851. }
  3852. ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  3853. array_init(return_value);
  3854. if (php_pgsql_meta_data(pgsql, table_name, return_value TSRMLS_CC) == FAILURE) {
  3855. zval_dtor(return_value); /* destroy array */
  3856. RETURN_FALSE;
  3857. }
  3858. }
  3859. /* }}} */
  3860. /* {{{ php_pgsql_get_data_type
  3861. */
  3862. static php_pgsql_data_type php_pgsql_get_data_type(const char *type_name, size_t len)
  3863. {
  3864. /* This is stupid way to do. I'll fix it when I decied how to support
  3865. user defined types. (Yasuo) */
  3866. /* boolean */
  3867. if (!strcmp(type_name, "bool")|| !strcmp(type_name, "boolean"))
  3868. return PG_BOOL;
  3869. /* object id */
  3870. if (!strcmp(type_name, "oid"))
  3871. return PG_OID;
  3872. /* integer */
  3873. if (!strcmp(type_name, "int2") || !strcmp(type_name, "smallint"))
  3874. return PG_INT2;
  3875. if (!strcmp(type_name, "int4") || !strcmp(type_name, "integer"))
  3876. return PG_INT4;
  3877. if (!strcmp(type_name, "int8") || !strcmp(type_name, "bigint"))
  3878. return PG_INT8;
  3879. /* real and other */
  3880. if (!strcmp(type_name, "float4") || !strcmp(type_name, "real"))
  3881. return PG_FLOAT4;
  3882. if (!strcmp(type_name, "float8") || !strcmp(type_name, "double precision"))
  3883. return PG_FLOAT8;
  3884. if (!strcmp(type_name, "numeric"))
  3885. return PG_NUMERIC;
  3886. if (!strcmp(type_name, "money"))
  3887. return PG_MONEY;
  3888. /* character */
  3889. if (!strcmp(type_name, "text"))
  3890. return PG_TEXT;
  3891. if (!strcmp(type_name, "bpchar") || !strcmp(type_name, "character"))
  3892. return PG_CHAR;
  3893. if (!strcmp(type_name, "varchar") || !strcmp(type_name, "character varying"))
  3894. return PG_VARCHAR;
  3895. /* time and interval */
  3896. if (!strcmp(type_name, "abstime"))
  3897. return PG_UNIX_TIME;
  3898. if (!strcmp(type_name, "reltime"))
  3899. return PG_UNIX_TIME_INTERVAL;
  3900. if (!strcmp(type_name, "tinterval"))
  3901. return PG_UNIX_TIME_INTERVAL;
  3902. if (!strcmp(type_name, "date"))
  3903. return PG_DATE;
  3904. if (!strcmp(type_name, "time"))
  3905. return PG_TIME;
  3906. if (!strcmp(type_name, "time with time zone") || !strcmp(type_name, "timetz"))
  3907. return PG_TIME_WITH_TIMEZONE;
  3908. if (!strcmp(type_name, "timestamp without time zone") || !strcmp(type_name, "timestamp"))
  3909. return PG_TIMESTAMP;
  3910. if (!strcmp(type_name, "timestamp with time zone") || !strcmp(type_name, "timestamptz"))
  3911. return PG_TIMESTAMP_WITH_TIMEZONE;
  3912. if (!strcmp(type_name, "interval"))
  3913. return PG_INTERVAL;
  3914. /* binary */
  3915. if (!strcmp(type_name, "bytea"))
  3916. return PG_BYTEA;
  3917. /* network */
  3918. if (!strcmp(type_name, "cidr"))
  3919. return PG_CIDR;
  3920. if (!strcmp(type_name, "inet"))
  3921. return PG_INET;
  3922. if (!strcmp(type_name, "macaddr"))
  3923. return PG_MACADDR;
  3924. /* bit */
  3925. if (!strcmp(type_name, "bit"))
  3926. return PG_BIT;
  3927. if (!strcmp(type_name, "bit varying"))
  3928. return PG_VARBIT;
  3929. /* geometric */
  3930. if (!strcmp(type_name, "line"))
  3931. return PG_LINE;
  3932. if (!strcmp(type_name, "lseg"))
  3933. return PG_LSEG;
  3934. if (!strcmp(type_name, "box"))
  3935. return PG_BOX;
  3936. if (!strcmp(type_name, "path"))
  3937. return PG_PATH;
  3938. if (!strcmp(type_name, "point"))
  3939. return PG_POINT;
  3940. if (!strcmp(type_name, "polygon"))
  3941. return PG_POLYGON;
  3942. if (!strcmp(type_name, "circle"))
  3943. return PG_CIRCLE;
  3944. return PG_UNKNOWN;
  3945. }
  3946. /* }}} */
  3947. /* {{{ php_pgsql_convert_match
  3948. * test field value with regular expression specified.
  3949. */
  3950. static int php_pgsql_convert_match(const char *str, const char *regex , int icase TSRMLS_DC)
  3951. {
  3952. regex_t re;
  3953. regmatch_t *subs;
  3954. int regopt = REG_EXTENDED;
  3955. int regerr, ret = SUCCESS;
  3956. if (icase) {
  3957. regopt |= REG_ICASE;
  3958. }
  3959. regerr = regcomp(&re, regex, regopt);
  3960. if (regerr) {
  3961. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot compile regex");
  3962. regfree(&re);
  3963. return FAILURE;
  3964. }
  3965. subs = (regmatch_t *)ecalloc(sizeof(regmatch_t), re.re_nsub+1);
  3966. regerr = regexec(&re, str, re.re_nsub+1, subs, 0);
  3967. if (regerr == REG_NOMATCH) {
  3968. #ifdef PHP_DEBUG
  3969. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "'%s' does not match with '%s'", str, regex);
  3970. #endif
  3971. ret = FAILURE;
  3972. }
  3973. else if (regerr) {
  3974. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot exec regex");
  3975. ret = FAILURE;
  3976. }
  3977. regfree(&re);
  3978. efree(subs);
  3979. return ret;
  3980. }
  3981. /* }}} */
  3982. /* {{{ php_pgsql_add_quote
  3983. * add quotes around string.
  3984. */
  3985. static int php_pgsql_add_quotes(zval *src, zend_bool should_free TSRMLS_DC)
  3986. {
  3987. smart_str str = {0};
  3988. assert(Z_TYPE_P(src) == IS_STRING);
  3989. assert(should_free == 1 || should_free == 0);
  3990. smart_str_appendc(&str, '\'');
  3991. smart_str_appendl(&str, Z_STRVAL_P(src), Z_STRLEN_P(src));
  3992. smart_str_appendc(&str, '\'');
  3993. smart_str_0(&str);
  3994. if (should_free) {
  3995. efree(Z_STRVAL_P(src));
  3996. }
  3997. Z_STRVAL_P(src) = str.c;
  3998. Z_STRLEN_P(src) = str.len;
  3999. return SUCCESS;
  4000. }
  4001. /* }}} */
  4002. #define PGSQL_CONV_CHECK_IGNORE() \
  4003. if (!err && Z_TYPE_P(new_val) == IS_STRING && !strcmp(Z_STRVAL_P(new_val), "NULL")) { \
  4004. /* if new_value is string "NULL" and field has default value, remove element to use default value */ \
  4005. if (!(opt & PGSQL_CONV_IGNORE_DEFAULT) && Z_BVAL_PP(has_default)) { \
  4006. zval_dtor(new_val); \
  4007. FREE_ZVAL(new_val); \
  4008. skip_field = 1; \
  4009. } \
  4010. /* raise error if it's not null and cannot be ignored */ \
  4011. else if (!(opt & PGSQL_CONV_IGNORE_NOT_NULL) && Z_BVAL_PP(not_null)) { \
  4012. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected NULL for 'NOT NULL' field '%s'", field ); \
  4013. err = 1; \
  4014. } \
  4015. }
  4016. /* {{{ php_pgsql_convert
  4017. * check and convert array values (fieldname=>vlaue pair) for sql
  4018. */
  4019. PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, const zval *values, zval *result, ulong opt TSRMLS_DC)
  4020. {
  4021. HashPosition pos;
  4022. char *field = NULL;
  4023. uint field_len = -1;
  4024. ulong num_idx = -1;
  4025. zval *meta, **def, **type, **not_null, **has_default, **val, *new_val;
  4026. int new_len, key_type, err = 0, skip_field;
  4027. assert(pg_link != NULL);
  4028. assert(Z_TYPE_P(values) == IS_ARRAY);
  4029. assert(Z_TYPE_P(result) == IS_ARRAY);
  4030. assert(!(opt & ~PGSQL_CONV_OPTS));
  4031. if (!table_name) {
  4032. return FAILURE;
  4033. }
  4034. MAKE_STD_ZVAL(meta);
  4035. array_init(meta);
  4036. if (php_pgsql_meta_data(pg_link, table_name, meta TSRMLS_CC) == FAILURE) {
  4037. zval_dtor(meta);
  4038. FREE_ZVAL(meta);
  4039. return FAILURE;
  4040. }
  4041. for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(values), &pos);
  4042. zend_hash_get_current_data_ex(Z_ARRVAL_P(values), (void **)&val, &pos) == SUCCESS;
  4043. zend_hash_move_forward_ex(Z_ARRVAL_P(values), &pos)) {
  4044. skip_field = 0;
  4045. if ((key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(values), &field, &field_len, &num_idx, 0, &pos)) == HASH_KEY_NON_EXISTANT) {
  4046. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to get array key type");
  4047. err = 1;
  4048. }
  4049. if (!err && key_type == HASH_KEY_IS_LONG) {
  4050. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Accepts only string key for values");
  4051. err = 1;
  4052. }
  4053. if (!err && key_type == HASH_KEY_NON_EXISTANT) {
  4054. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Accepts only string key for values");
  4055. err = 1;
  4056. }
  4057. if (!err && zend_hash_find(Z_ARRVAL_P(meta), field, field_len, (void **)&def) == FAILURE) {
  4058. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Invalid field name (%s) in values", field);
  4059. err = 1;
  4060. }
  4061. if (!err && zend_hash_find(Z_ARRVAL_PP(def), "type", sizeof("type"), (void **)&type) == FAILURE) {
  4062. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected broken meta data. Missing 'type'");
  4063. err = 1;
  4064. }
  4065. if (!err && zend_hash_find(Z_ARRVAL_PP(def), "not null", sizeof("not null"), (void **)&not_null) == FAILURE) {
  4066. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected broken meta data. Missing 'not null'");
  4067. err = 1;
  4068. }
  4069. if (!err && zend_hash_find(Z_ARRVAL_PP(def), "has default", sizeof("has default"), (void **)&has_default) == FAILURE) {
  4070. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected broken meta data. Missing 'has default'");
  4071. err = 1;
  4072. }
  4073. if (!err && (Z_TYPE_PP(val) == IS_ARRAY ||
  4074. Z_TYPE_PP(val) == IS_OBJECT ||
  4075. Z_TYPE_PP(val) == IS_CONSTANT_ARRAY)) {
  4076. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects scaler values as field values");
  4077. err = 1;
  4078. }
  4079. if (err) {
  4080. break; /* break out for() */
  4081. }
  4082. MAKE_STD_ZVAL(new_val);
  4083. switch(php_pgsql_get_data_type(Z_STRVAL_PP(type), Z_STRLEN_PP(type)))
  4084. {
  4085. case PG_BOOL:
  4086. switch (Z_TYPE_PP(val)) {
  4087. case IS_STRING:
  4088. if (Z_STRLEN_PP(val) == 0) {
  4089. ZVAL_STRING(new_val, "NULL", 1);
  4090. }
  4091. else {
  4092. if (!strcmp(Z_STRVAL_PP(val), "t") || !strcmp(Z_STRVAL_PP(val), "T") ||
  4093. !strcmp(Z_STRVAL_PP(val), "y") || !strcmp(Z_STRVAL_PP(val), "Y") ||
  4094. !strcmp(Z_STRVAL_PP(val), "true") || !strcmp(Z_STRVAL_PP(val), "True") ||
  4095. !strcmp(Z_STRVAL_PP(val), "yes") || !strcmp(Z_STRVAL_PP(val), "Yes") ||
  4096. !strcmp(Z_STRVAL_PP(val), "1")) {
  4097. ZVAL_STRING(new_val, "'t'", 1);
  4098. }
  4099. else if (!strcmp(Z_STRVAL_PP(val), "f") || !strcmp(Z_STRVAL_PP(val), "F") ||
  4100. !strcmp(Z_STRVAL_PP(val), "n") || !strcmp(Z_STRVAL_PP(val), "N") ||
  4101. !strcmp(Z_STRVAL_PP(val), "false") || !strcmp(Z_STRVAL_PP(val), "False") ||
  4102. !strcmp(Z_STRVAL_PP(val), "no") || !strcmp(Z_STRVAL_PP(val), "No") ||
  4103. !strcmp(Z_STRVAL_PP(val), "0")) {
  4104. ZVAL_STRING(new_val, "'f'", 1);
  4105. }
  4106. else {
  4107. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected invalid value (%s) for PostgreSQL %s field (%s)", Z_STRVAL_PP(val), Z_STRVAL_PP(type), field);
  4108. err = 1;
  4109. }
  4110. }
  4111. break;
  4112. case IS_LONG:
  4113. case IS_BOOL:
  4114. if (Z_LVAL_PP(val)) {
  4115. ZVAL_STRING(new_val, "'t'", 1);
  4116. }
  4117. else {
  4118. ZVAL_STRING(new_val, "'f'", 1);
  4119. }
  4120. break;
  4121. case IS_NULL:
  4122. ZVAL_STRING(new_val, "NULL", 1);
  4123. break;
  4124. default:
  4125. err = 1;
  4126. }
  4127. PGSQL_CONV_CHECK_IGNORE();
  4128. if (err) {
  4129. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects string, null, long or boolelan value for PostgreSQL '%s' (%s)", Z_STRVAL_PP(type), field);
  4130. }
  4131. break;
  4132. case PG_OID:
  4133. case PG_INT2:
  4134. case PG_INT4:
  4135. case PG_INT8:
  4136. switch (Z_TYPE_PP(val)) {
  4137. case IS_STRING:
  4138. if (Z_STRLEN_PP(val) == 0) {
  4139. ZVAL_STRING(new_val, "NULL", 1);
  4140. }
  4141. else {
  4142. /* FIXME: better regex must be used */
  4143. if (php_pgsql_convert_match(Z_STRVAL_PP(val), "^([+-]{0,1}[0-9]+)$", 0 TSRMLS_CC) == FAILURE) {
  4144. err = 1;
  4145. }
  4146. else {
  4147. ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
  4148. }
  4149. }
  4150. break;
  4151. case IS_DOUBLE:
  4152. ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
  4153. convert_to_long_ex(&new_val);
  4154. break;
  4155. case IS_LONG:
  4156. ZVAL_LONG(new_val, Z_LVAL_PP(val));
  4157. break;
  4158. case IS_NULL:
  4159. ZVAL_STRING(new_val, "NULL", 1);
  4160. break;
  4161. default:
  4162. err = 1;
  4163. }
  4164. PGSQL_CONV_CHECK_IGNORE();
  4165. if (err) {
  4166. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for pgsql '%s' (%s)", Z_STRVAL_PP(type), field);
  4167. }
  4168. break;
  4169. case PG_NUMERIC:
  4170. case PG_MONEY:
  4171. case PG_FLOAT4:
  4172. case PG_FLOAT8:
  4173. switch (Z_TYPE_PP(val)) {
  4174. case IS_STRING:
  4175. if (Z_STRLEN_PP(val) == 0) {
  4176. ZVAL_STRING(new_val, "NULL", 1);
  4177. }
  4178. else {
  4179. /* FIXME: better regex must be used */
  4180. if (php_pgsql_convert_match(Z_STRVAL_PP(val), "^([+-]{0,1}[0-9]+)|([+-]{0,1}[0-9]*[\\.][0-9]+)|([+-]{0,1}[0-9]+[\\.][0-9]*)$", 0 TSRMLS_CC) == FAILURE) {
  4181. err = 1;
  4182. }
  4183. else {
  4184. ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
  4185. }
  4186. }
  4187. break;
  4188. case IS_LONG:
  4189. ZVAL_LONG(new_val, Z_LVAL_PP(val));
  4190. break;
  4191. case IS_DOUBLE:
  4192. ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
  4193. break;
  4194. case IS_NULL:
  4195. ZVAL_STRING(new_val, "NULL", 1);
  4196. break;
  4197. default:
  4198. err = 1;
  4199. }
  4200. PGSQL_CONV_CHECK_IGNORE();
  4201. if (err) {
  4202. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_PP(type), field);
  4203. }
  4204. break;
  4205. case PG_TEXT:
  4206. case PG_CHAR:
  4207. case PG_VARCHAR:
  4208. switch (Z_TYPE_PP(val)) {
  4209. case IS_STRING:
  4210. if (Z_STRLEN_PP(val) == 0) {
  4211. if (opt & PGSQL_CONV_FORCE_NULL) {
  4212. ZVAL_STRING(new_val, "NULL", 1);
  4213. } else {
  4214. ZVAL_STRING(new_val, "''", 1);
  4215. }
  4216. }
  4217. else {
  4218. Z_TYPE_P(new_val) = IS_STRING;
  4219. #if HAVE_PQESCAPE
  4220. {
  4221. char *tmp;
  4222. tmp = (char *)safe_emalloc(Z_STRLEN_PP(val), 2, 1);
  4223. Z_STRLEN_P(new_val) = (int)PQescapeString(tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val));
  4224. Z_STRVAL_P(new_val) = tmp;
  4225. }
  4226. #else
  4227. Z_STRVAL_P(new_val) = php_addslashes(Z_STRVAL_PP(val), Z_STRLEN_PP(val), &Z_STRLEN_P(new_val), 0 TSRMLS_CC);
  4228. #endif
  4229. php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
  4230. }
  4231. break;
  4232. case IS_LONG:
  4233. ZVAL_LONG(new_val, Z_LVAL_PP(val));
  4234. convert_to_string_ex(&new_val);
  4235. break;
  4236. case IS_DOUBLE:
  4237. ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
  4238. convert_to_string_ex(&new_val);
  4239. break;
  4240. case IS_NULL:
  4241. ZVAL_STRING(new_val, "NULL", 1);
  4242. break;
  4243. default:
  4244. err = 1;
  4245. }
  4246. PGSQL_CONV_CHECK_IGNORE();
  4247. if (err) {
  4248. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_PP(type), field);
  4249. }
  4250. break;
  4251. case PG_UNIX_TIME:
  4252. case PG_UNIX_TIME_INTERVAL:
  4253. /* these are the actallay a integer */
  4254. switch (Z_TYPE_PP(val)) {
  4255. case IS_STRING:
  4256. if (Z_STRLEN_PP(val) == 0) {
  4257. ZVAL_STRING(new_val, "NULL", 1);
  4258. }
  4259. else {
  4260. /* FIXME: Better regex must be used */
  4261. if (php_pgsql_convert_match(Z_STRVAL_PP(val), "^[0-9]+$", 0 TSRMLS_CC) == FAILURE) {
  4262. err = 1;
  4263. }
  4264. else {
  4265. ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
  4266. convert_to_long_ex(&new_val);
  4267. }
  4268. }
  4269. break;
  4270. case IS_DOUBLE:
  4271. ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
  4272. convert_to_long_ex(&new_val);
  4273. break;
  4274. case IS_LONG:
  4275. ZVAL_LONG(new_val, Z_LVAL_PP(val));
  4276. break;
  4277. case IS_NULL:
  4278. ZVAL_STRING(new_val, "NULL", 1);
  4279. break;
  4280. default:
  4281. err = 1;
  4282. }
  4283. PGSQL_CONV_CHECK_IGNORE();
  4284. if (err) {
  4285. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for '%s' (%s)", Z_STRVAL_PP(type), field);
  4286. }
  4287. break;
  4288. case PG_CIDR:
  4289. case PG_INET:
  4290. switch (Z_TYPE_PP(val)) {
  4291. case IS_STRING:
  4292. if (Z_STRLEN_PP(val) == 0) {
  4293. ZVAL_STRING(new_val, "NULL", 1);
  4294. }
  4295. else {
  4296. /* FIXME: Better regex must be used */
  4297. if (php_pgsql_convert_match(Z_STRVAL_PP(val), "^([0-9]{1,3}\\.){3}[0-9]{1,3}(/[0-9]{1,2}){0,1}$", 0 TSRMLS_CC) == FAILURE) {
  4298. err = 1;
  4299. }
  4300. else {
  4301. ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
  4302. php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
  4303. }
  4304. }
  4305. break;
  4306. case IS_NULL:
  4307. ZVAL_STRING(new_val, "NULL", 1);
  4308. break;
  4309. default:
  4310. err = 1;
  4311. }
  4312. PGSQL_CONV_CHECK_IGNORE();
  4313. if (err) {
  4314. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for '%s' (%s)", Z_STRVAL_PP(type), field);
  4315. }
  4316. break;
  4317. case PG_TIME_WITH_TIMEZONE:
  4318. case PG_TIMESTAMP:
  4319. case PG_TIMESTAMP_WITH_TIMEZONE:
  4320. switch(Z_TYPE_PP(val)) {
  4321. case IS_STRING:
  4322. if (Z_STRLEN_PP(val) == 0) {
  4323. ZVAL_STRING(new_val, "NULL", 1);
  4324. }
  4325. else {
  4326. /* FIXME: better regex must be used */
  4327. if (php_pgsql_convert_match(Z_STRVAL_PP(val), "^([0-9]{4}[/-][0-9]{1,2}[/-][0-9]{1,2})([ \\t]+(([0-9]{1,2}:[0-9]{1,2}){1}(:[0-9]{1,2}){0,1}(\\.[0-9]+){0,1}([ \\t]*([+-][0-9]{1,2}(:[0-9]{1,2}){0,1}|[a-zA-Z]{1,5})){0,1})){0,1}$", 1 TSRMLS_CC) == FAILURE) {
  4328. err = 1;
  4329. }
  4330. else {
  4331. ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
  4332. php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
  4333. }
  4334. }
  4335. break;
  4336. case IS_NULL:
  4337. ZVAL_STRING(new_val, "NULL", 1);
  4338. break;
  4339. default:
  4340. err = 1;
  4341. }
  4342. PGSQL_CONV_CHECK_IGNORE();
  4343. if (err) {
  4344. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
  4345. }
  4346. break;
  4347. case PG_DATE:
  4348. switch(Z_TYPE_PP(val)) {
  4349. case IS_STRING:
  4350. if (Z_STRLEN_PP(val) == 0) {
  4351. ZVAL_STRING(new_val, "NULL", 1);
  4352. }
  4353. else {
  4354. /* FIXME: better regex must be used */
  4355. if (php_pgsql_convert_match(Z_STRVAL_PP(val), "^([0-9]{4}[/-][0-9]{1,2}[/-][0-9]{1,2})$", 1 TSRMLS_CC) == FAILURE) {
  4356. err = 1;
  4357. }
  4358. else {
  4359. ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
  4360. php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
  4361. }
  4362. }
  4363. break;
  4364. case IS_NULL:
  4365. ZVAL_STRING(new_val, "NULL", 1);
  4366. break;
  4367. default:
  4368. err = 1;
  4369. }
  4370. PGSQL_CONV_CHECK_IGNORE();
  4371. if (err) {
  4372. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
  4373. }
  4374. break;
  4375. case PG_TIME:
  4376. switch(Z_TYPE_PP(val)) {
  4377. case IS_STRING:
  4378. if (Z_STRLEN_PP(val) == 0) {
  4379. ZVAL_STRING(new_val, "NULL", 1);
  4380. }
  4381. else {
  4382. /* FIXME: better regex must be used */
  4383. if (php_pgsql_convert_match(Z_STRVAL_PP(val), "^(([0-9]{1,2}:[0-9]{1,2}){1}(:[0-9]{1,2}){0,1})){0,1}$", 1 TSRMLS_CC) == FAILURE) {
  4384. err = 1;
  4385. }
  4386. else {
  4387. ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
  4388. php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
  4389. }
  4390. }
  4391. break;
  4392. case IS_NULL:
  4393. ZVAL_STRING(new_val, "NULL", 1);
  4394. break;
  4395. default:
  4396. err = 1;
  4397. }
  4398. PGSQL_CONV_CHECK_IGNORE();
  4399. if (err) {
  4400. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
  4401. }
  4402. break;
  4403. case PG_INTERVAL:
  4404. switch(Z_TYPE_PP(val)) {
  4405. case IS_STRING:
  4406. if (Z_STRLEN_PP(val) == 0) {
  4407. ZVAL_STRING(new_val, "NULL", 1);
  4408. }
  4409. else {
  4410. /* From the Postgres docs:
  4411. interval values can be written with the following syntax:
  4412. [@] quantity unit [quantity unit...] [direction]
  4413. Where: quantity is a number (possibly signed); unit is second, minute, hour,
  4414. day, week, month, year, decade, century, millennium, or abbreviations or
  4415. plurals of these units [note not *all* abbreviations] ; direction can be
  4416. ago or empty. The at sign (@) is optional noise.
  4417. ...
  4418. Quantities of days, hours, minutes, and seconds can be specified without explicit
  4419. unit markings. For example, '1 12:59:10' is read the same as '1 day 12 hours 59 min 10
  4420. sec'.
  4421. */
  4422. if (php_pgsql_convert_match(Z_STRVAL_PP(val),
  4423. "^(@?[ \\t]+)?("
  4424. /* Textual time units and their abbreviations: */
  4425. "(([-+]?[ \\t]+)?"
  4426. "[0-9]+(\\.[0-9]*)?[ \\t]*"
  4427. "(millenniums|millennia|millennium|mil|mils|"
  4428. "centuries|century|cent|c|"
  4429. "decades|decade|dec|decs|"
  4430. "years|year|y|"
  4431. "months|month|mon|"
  4432. "weeks|week|w|"
  4433. "days|day|d|"
  4434. "hours|hour|hr|hrs|h|"
  4435. "minutes|minute|mins|min|m|"
  4436. "seconds|second|secs|sec|s))+|"
  4437. /* Textual time units plus (dd)* hh[:mm[:ss]] */
  4438. "((([-+]?[ \\t]+)?"
  4439. "[0-9]+(\\.[0-9]*)?[ \\t]*"
  4440. "(millenniums|millennia|millennium|mil|mils|"
  4441. "centuries|century|cent|c|"
  4442. "decades|decade|dec|decs|"
  4443. "years|year|y|"
  4444. "months|month|mon|"
  4445. "weeks|week|w|"
  4446. "days|day|d))+"
  4447. "([-+]?[ \\t]+"
  4448. "([0-9]+[ \\t]+)+" /* dd */
  4449. "(([0-9]{1,2}:){0,2}[0-9]{0,2})" /* hh:[mm:[ss]] */
  4450. ")?))"
  4451. "([ \\t]+ago)?$",
  4452. 1 TSRMLS_CC) == FAILURE) {
  4453. err = 1;
  4454. }
  4455. else {
  4456. ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
  4457. php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
  4458. }
  4459. }
  4460. break;
  4461. case IS_NULL:
  4462. ZVAL_STRING(new_val, "NULL", 1);
  4463. break;
  4464. default:
  4465. err = 1;
  4466. }
  4467. PGSQL_CONV_CHECK_IGNORE();
  4468. if (err) {
  4469. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
  4470. }
  4471. break;
  4472. #ifdef HAVE_PQESCAPE
  4473. case PG_BYTEA:
  4474. switch (Z_TYPE_PP(val)) {
  4475. case IS_STRING:
  4476. if (Z_STRLEN_PP(val) == 0) {
  4477. ZVAL_STRING(new_val, "NULL", 1);
  4478. }
  4479. else {
  4480. unsigned char *tmp;
  4481. size_t to_len;
  4482. tmp = PQescapeBytea(Z_STRVAL_PP(val), Z_STRLEN_PP(val), &to_len);
  4483. Z_TYPE_P(new_val) = IS_STRING;
  4484. Z_STRLEN_P(new_val) = to_len-1; /* PQescapeBytea's to_len includes additional '\0' */
  4485. Z_STRVAL_P(new_val) = emalloc(to_len);
  4486. memcpy(Z_STRVAL_P(new_val), tmp, to_len);
  4487. free(tmp);
  4488. php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
  4489. }
  4490. break;
  4491. case IS_LONG:
  4492. ZVAL_LONG(new_val, Z_LVAL_PP(val));
  4493. convert_to_string_ex(&new_val);
  4494. break;
  4495. case IS_DOUBLE:
  4496. ZVAL_DOUBLE(new_val, Z_DVAL_PP(val));
  4497. convert_to_string_ex(&new_val);
  4498. break;
  4499. case IS_NULL:
  4500. ZVAL_STRING(new_val, "NULL", 1);
  4501. break;
  4502. default:
  4503. err = 1;
  4504. }
  4505. PGSQL_CONV_CHECK_IGNORE();
  4506. if (err) {
  4507. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_PP(type), field);
  4508. }
  4509. break;
  4510. #endif
  4511. case PG_MACADDR:
  4512. switch(Z_TYPE_PP(val)) {
  4513. case IS_STRING:
  4514. if (Z_STRLEN_PP(val) == 0) {
  4515. ZVAL_STRING(new_val, "NULL", 1);
  4516. }
  4517. else {
  4518. if (php_pgsql_convert_match(Z_STRVAL_PP(val), "^([0-9a-f]{2,2}:){5,5}[0-9a-f]{2,2}$", 1 TSRMLS_CC) == FAILURE) {
  4519. err = 1;
  4520. }
  4521. else {
  4522. ZVAL_STRING(new_val, Z_STRVAL_PP(val), 1);
  4523. php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
  4524. }
  4525. }
  4526. break;
  4527. case IS_NULL:
  4528. ZVAL_STRING(new_val, "NULL", 1);
  4529. break;
  4530. default:
  4531. err = 1;
  4532. }
  4533. PGSQL_CONV_CHECK_IGNORE();
  4534. if (err) {
  4535. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_PP(type), field);
  4536. }
  4537. break;
  4538. /* bit */
  4539. case PG_BIT:
  4540. case PG_VARBIT:
  4541. /* geometric */
  4542. case PG_LINE:
  4543. case PG_LSEG:
  4544. case PG_POINT:
  4545. case PG_BOX:
  4546. case PG_PATH:
  4547. case PG_POLYGON:
  4548. case PG_CIRCLE:
  4549. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "PostgreSQL '%s' type (%s) is not supported", Z_STRVAL_PP(type), field);
  4550. err = 1;
  4551. break;
  4552. case PG_UNKNOWN:
  4553. default:
  4554. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Unknown or system data type '%s' for '%s'", Z_STRVAL_PP(type), field);
  4555. err = 1;
  4556. break;
  4557. } /* switch */
  4558. if (err) {
  4559. zval_dtor(new_val);
  4560. FREE_ZVAL(new_val);
  4561. break; /* break out for() */
  4562. }
  4563. if (!skip_field) {
  4564. /* If field is NULL and HAS DEFAULT, should be skipped */
  4565. field = php_addslashes(field, strlen(field), &new_len, 0 TSRMLS_CC);
  4566. add_assoc_zval(result, field, new_val);
  4567. efree(field);
  4568. }
  4569. } /* for */
  4570. zval_dtor(meta);
  4571. FREE_ZVAL(meta);
  4572. if (err) {
  4573. /* shouldn't destroy & free zval here */
  4574. return FAILURE;
  4575. }
  4576. return SUCCESS;
  4577. }
  4578. /* }}} */
  4579. /* {{{ proto array pg_convert(resource db, string table, array values[, int options])
  4580. Check and convert values for PostgreSQL SQL statement */
  4581. PHP_FUNCTION(pg_convert)
  4582. {
  4583. zval *pgsql_link, *values;
  4584. char *table_name;
  4585. int table_name_len;
  4586. ulong option = 0;
  4587. PGconn *pg_link;
  4588. int id = -1;
  4589. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
  4590. "rsa|l", &pgsql_link, &table_name, &table_name_len, &values, &option) == FAILURE) {
  4591. return;
  4592. }
  4593. if (option & ~PGSQL_CONV_OPTS) {
  4594. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
  4595. RETURN_FALSE;
  4596. }
  4597. if (!table_name_len) {
  4598. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Table name is invalid");
  4599. RETURN_FALSE;
  4600. }
  4601. ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  4602. if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
  4603. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
  4604. }
  4605. array_init(return_value);
  4606. if (php_pgsql_convert(pg_link, table_name, values, return_value, option TSRMLS_CC) == FAILURE) {
  4607. zval_dtor(return_value);
  4608. RETURN_FALSE;
  4609. }
  4610. }
  4611. /* }}} */
  4612. static int do_exec(smart_str *querystr, int expect, PGconn *pg_link, ulong opt TSRMLS_DC)
  4613. {
  4614. if (opt & PGSQL_DML_ASYNC) {
  4615. if (PQsendQuery(pg_link, querystr->c)) {
  4616. return 0;
  4617. }
  4618. }
  4619. else {
  4620. PGresult *pg_result;
  4621. pg_result = PQexec(pg_link, querystr->c);
  4622. if (PQresultStatus(pg_result) == expect) {
  4623. PQclear(pg_result);
  4624. return 0;
  4625. } else {
  4626. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to execute '%s'", querystr->c);
  4627. PQclear(pg_result);
  4628. }
  4629. }
  4630. return -1;
  4631. }
  4632. /* {{{ php_pgsql_insert
  4633. */
  4634. PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var_array, ulong opt, char **sql TSRMLS_DC)
  4635. {
  4636. zval **val, *converted = NULL;
  4637. char buf[256];
  4638. char *fld;
  4639. smart_str querystr = {0};
  4640. int key_type, ret = FAILURE;
  4641. uint fld_len;
  4642. ulong num_idx;
  4643. HashPosition pos;
  4644. assert(pg_link != NULL);
  4645. assert(table != NULL);
  4646. assert(Z_TYPE_P(var_array) == IS_ARRAY);
  4647. if (zend_hash_num_elements(Z_ARRVAL_P(var_array)) == 0) {
  4648. return FAILURE;
  4649. }
  4650. /* convert input array if needed */
  4651. if (!(opt & PGSQL_DML_NO_CONV)) {
  4652. MAKE_STD_ZVAL(converted);
  4653. array_init(converted);
  4654. if (php_pgsql_convert(pg_link, table, var_array, converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
  4655. goto cleanup;
  4656. }
  4657. var_array = converted;
  4658. }
  4659. smart_str_appends(&querystr, "INSERT INTO ");
  4660. smart_str_appends(&querystr, table);
  4661. smart_str_appends(&querystr, " (");
  4662. zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(var_array), &pos);
  4663. while ((key_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(var_array), &fld,
  4664. &fld_len, &num_idx, 0, &pos)) != HASH_KEY_NON_EXISTANT) {
  4665. if (key_type == HASH_KEY_IS_LONG) {
  4666. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects associative array for values to be inserted");
  4667. goto cleanup;
  4668. }
  4669. smart_str_appendl(&querystr, fld, fld_len - 1);
  4670. smart_str_appendc(&querystr, ',');
  4671. zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos);
  4672. }
  4673. querystr.len--;
  4674. smart_str_appends(&querystr, ") VALUES (");
  4675. /* make values string */
  4676. for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(var_array), &pos);
  4677. zend_hash_get_current_data_ex(Z_ARRVAL_P(var_array), (void **)&val, &pos) == SUCCESS;
  4678. zend_hash_move_forward_ex(Z_ARRVAL_P(var_array), &pos)) {
  4679. /* we can avoid the key_type check here, because we tested it in the other loop */
  4680. switch(Z_TYPE_PP(val)) {
  4681. case IS_STRING:
  4682. smart_str_appendl(&querystr, Z_STRVAL_PP(val), Z_STRLEN_PP(val));
  4683. break;
  4684. case IS_LONG:
  4685. smart_str_append_long(&querystr, Z_LVAL_PP(val));
  4686. break;
  4687. case IS_DOUBLE:
  4688. smart_str_appendl(&querystr, buf, snprintf(buf, sizeof(buf), "%f", Z_DVAL_PP(val)));
  4689. break;
  4690. default:
  4691. /* should not happen */
  4692. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Report this error to php-dev@lists.php.net, type = %d", Z_TYPE_PP(val));
  4693. goto cleanup;
  4694. break;
  4695. }
  4696. smart_str_appendc(&querystr, ',');
  4697. }
  4698. /* Remove the trailing "," */
  4699. querystr.len--;
  4700. smart_str_appends(&querystr, ");");
  4701. smart_str_0(&querystr);
  4702. if ((opt & (PGSQL_DML_EXEC|PGSQL_DML_ASYNC)) &&
  4703. do_exec(&querystr, PGRES_COMMAND_OK, pg_link, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == 0) {
  4704. ret = SUCCESS;
  4705. }
  4706. else if (opt & PGSQL_DML_STRING) {
  4707. ret = SUCCESS;
  4708. }
  4709. cleanup:
  4710. if (!(opt & PGSQL_DML_NO_CONV)) {
  4711. zval_dtor(converted);
  4712. FREE_ZVAL(converted);
  4713. }
  4714. if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) {
  4715. *sql = querystr.c;
  4716. }
  4717. else {
  4718. smart_str_free(&querystr);
  4719. }
  4720. return ret;
  4721. }
  4722. /* }}} */
  4723. /* {{{ proto mixed pg_insert(resource db, string table, array values[, int options])
  4724. Insert values (filed=>value) to table */
  4725. PHP_FUNCTION(pg_insert)
  4726. {
  4727. zval *pgsql_link, *values;
  4728. char *table, *sql = NULL;
  4729. int table_len;
  4730. ulong option = PGSQL_DML_EXEC;
  4731. PGconn *pg_link;
  4732. int id = -1, argc = ZEND_NUM_ARGS();
  4733. if (zend_parse_parameters(argc TSRMLS_CC, "rsa|l",
  4734. &pgsql_link, &table, &table_len, &values, &option) == FAILURE) {
  4735. return;
  4736. }
  4737. if (option & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING)) {
  4738. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
  4739. RETURN_FALSE;
  4740. }
  4741. ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  4742. if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
  4743. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
  4744. }
  4745. if (php_pgsql_insert(pg_link, table, values, option, &sql TSRMLS_CC) == FAILURE) {
  4746. RETURN_FALSE;
  4747. }
  4748. if (option & PGSQL_DML_STRING) {
  4749. RETURN_STRING(sql, 0);
  4750. }
  4751. RETURN_TRUE;
  4752. }
  4753. /* }}} */
  4754. static inline int build_assignment_string(smart_str *querystr, HashTable *ht, const char *pad, int pad_len TSRMLS_DC)
  4755. {
  4756. HashPosition pos;
  4757. uint fld_len;
  4758. int key_type;
  4759. ulong num_idx;
  4760. char *fld;
  4761. char buf[256];
  4762. zval **val;
  4763. for (zend_hash_internal_pointer_reset_ex(ht, &pos);
  4764. zend_hash_get_current_data_ex(ht, (void **)&val, &pos) == SUCCESS;
  4765. zend_hash_move_forward_ex(ht, &pos)) {
  4766. key_type = zend_hash_get_current_key_ex(ht, &fld, &fld_len, &num_idx, 0, &pos);
  4767. if (key_type == HASH_KEY_IS_LONG) {
  4768. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects associative array for values to be inserted");
  4769. return -1;
  4770. }
  4771. smart_str_appendl(querystr, fld, fld_len - 1);
  4772. smart_str_appendc(querystr, '=');
  4773. switch(Z_TYPE_PP(val)) {
  4774. case IS_STRING:
  4775. smart_str_appendl(querystr, Z_STRVAL_PP(val), Z_STRLEN_PP(val));
  4776. break;
  4777. case IS_LONG:
  4778. smart_str_append_long(querystr, Z_LVAL_PP(val));
  4779. break;
  4780. case IS_DOUBLE:
  4781. smart_str_appendl(querystr, buf, sprintf(buf, "%f", Z_DVAL_PP(val)));
  4782. break;
  4783. default:
  4784. /* should not happen */
  4785. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects scaler values other than NULL. Need to convert?");
  4786. return -1;
  4787. }
  4788. smart_str_appendl(querystr, pad, pad_len);
  4789. }
  4790. querystr->len -= pad_len;
  4791. return 0;
  4792. }
  4793. /* {{{ php_pgsql_update
  4794. */
  4795. PHP_PGSQL_API int php_pgsql_update(PGconn *pg_link, const char *table, zval *var_array, zval *ids_array, ulong opt, char **sql TSRMLS_DC)
  4796. {
  4797. zval *var_converted = NULL, *ids_converted = NULL;
  4798. smart_str querystr = {0};
  4799. int ret = FAILURE;
  4800. assert(pg_link != NULL);
  4801. assert(table != NULL);
  4802. assert(Z_TYPE_P(var_array) == IS_ARRAY);
  4803. assert(Z_TYPE_P(ids_array) == IS_ARRAY);
  4804. assert(!(opt & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING)));
  4805. if (zend_hash_num_elements(Z_ARRVAL_P(var_array)) == 0
  4806. || zend_hash_num_elements(Z_ARRVAL_P(ids_array)) == 0) {
  4807. return FAILURE;
  4808. }
  4809. if (!(opt & PGSQL_DML_NO_CONV)) {
  4810. MAKE_STD_ZVAL(var_converted);
  4811. array_init(var_converted);
  4812. if (php_pgsql_convert(pg_link, table, var_array, var_converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
  4813. goto cleanup;
  4814. }
  4815. var_array = var_converted;
  4816. MAKE_STD_ZVAL(ids_converted);
  4817. array_init(ids_converted);
  4818. if (php_pgsql_convert(pg_link, table, ids_array, ids_converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
  4819. goto cleanup;
  4820. }
  4821. ids_array = ids_converted;
  4822. }
  4823. smart_str_appends(&querystr, "UPDATE ");
  4824. smart_str_appends(&querystr, table);
  4825. smart_str_appends(&querystr, " SET ");
  4826. if (build_assignment_string(&querystr, Z_ARRVAL_P(var_array), ",", 1 TSRMLS_CC))
  4827. goto cleanup;
  4828. smart_str_appends(&querystr, " WHERE ");
  4829. if (build_assignment_string(&querystr, Z_ARRVAL_P(ids_array), " AND ", sizeof(" AND ")-1 TSRMLS_CC))
  4830. goto cleanup;
  4831. smart_str_appendc(&querystr, ';');
  4832. smart_str_0(&querystr);
  4833. if ((opt & PGSQL_DML_EXEC) && do_exec(&querystr, PGRES_COMMAND_OK, pg_link, opt TSRMLS_CC) == 0) {
  4834. ret = SUCCESS;
  4835. } else if (opt & PGSQL_DML_STRING) {
  4836. ret = SUCCESS;
  4837. }
  4838. cleanup:
  4839. if (var_converted) {
  4840. zval_dtor(var_converted);
  4841. FREE_ZVAL(var_converted);
  4842. }
  4843. if (ids_converted) {
  4844. zval_dtor(ids_converted);
  4845. FREE_ZVAL(ids_converted);
  4846. }
  4847. if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) {
  4848. *sql = querystr.c;
  4849. }
  4850. else {
  4851. smart_str_free(&querystr);
  4852. }
  4853. return ret;
  4854. }
  4855. /* }}} */
  4856. /* {{{ proto mixed pg_update(resource db, string table, array fields, array ids[, int options])
  4857. Update table using values (field=>value) and ids (id=>value) */
  4858. PHP_FUNCTION(pg_update)
  4859. {
  4860. zval *pgsql_link, *values, *ids;
  4861. char *table, *sql = NULL;
  4862. int table_len;
  4863. ulong option = PGSQL_DML_EXEC;
  4864. PGconn *pg_link;
  4865. int id = -1, argc = ZEND_NUM_ARGS();
  4866. if (zend_parse_parameters(argc TSRMLS_CC, "rsaa|l",
  4867. &pgsql_link, &table, &table_len, &values, &ids, &option) == FAILURE) {
  4868. return;
  4869. }
  4870. if (option & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING)) {
  4871. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
  4872. RETURN_FALSE;
  4873. }
  4874. ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  4875. if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
  4876. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
  4877. }
  4878. if (php_pgsql_update(pg_link, table, values, ids, option, &sql TSRMLS_CC) == FAILURE) {
  4879. RETURN_FALSE;
  4880. }
  4881. if (option & PGSQL_DML_STRING) {
  4882. RETURN_STRING(sql, 0);
  4883. }
  4884. RETURN_TRUE;
  4885. }
  4886. /* }}} */
  4887. /* {{{ php_pgsql_delete
  4888. */
  4889. PHP_PGSQL_API int php_pgsql_delete(PGconn *pg_link, const char *table, zval *ids_array, ulong opt, char **sql TSRMLS_DC)
  4890. {
  4891. zval *ids_converted = NULL;
  4892. smart_str querystr = {0};
  4893. int ret = FAILURE;
  4894. assert(pg_link != NULL);
  4895. assert(table != NULL);
  4896. assert(Z_TYPE_P(ids_array) == IS_ARRAY);
  4897. assert(!(opt & ~(PGSQL_CONV_FORCE_NULL|PGSQL_DML_EXEC|PGSQL_DML_STRING)));
  4898. if (zend_hash_num_elements(Z_ARRVAL_P(ids_array)) == 0) {
  4899. return FAILURE;
  4900. }
  4901. if (!(opt & PGSQL_DML_NO_CONV)) {
  4902. MAKE_STD_ZVAL(ids_converted);
  4903. array_init(ids_converted);
  4904. if (php_pgsql_convert(pg_link, table, ids_array, ids_converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
  4905. goto cleanup;
  4906. }
  4907. ids_array = ids_converted;
  4908. }
  4909. smart_str_appends(&querystr, "DELETE FROM ");
  4910. smart_str_appends(&querystr, table);
  4911. smart_str_appends(&querystr, " WHERE ");
  4912. if (build_assignment_string(&querystr, Z_ARRVAL_P(ids_array), " AND ", sizeof(" AND ")-1 TSRMLS_CC))
  4913. goto cleanup;
  4914. smart_str_appendc(&querystr, ';');
  4915. smart_str_0(&querystr);
  4916. if ((opt & PGSQL_DML_EXEC) && do_exec(&querystr, PGRES_COMMAND_OK, pg_link, opt TSRMLS_CC) == 0) {
  4917. ret = SUCCESS;
  4918. } else if (opt & PGSQL_DML_STRING) {
  4919. ret = SUCCESS;
  4920. }
  4921. cleanup:
  4922. if (!(opt & PGSQL_DML_NO_CONV)) {
  4923. zval_dtor(ids_converted);
  4924. FREE_ZVAL(ids_converted);
  4925. }
  4926. if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) {
  4927. *sql = estrdup(querystr.c);
  4928. }
  4929. else {
  4930. smart_str_free(&querystr);
  4931. }
  4932. return ret;
  4933. }
  4934. /* }}} */
  4935. /* {{{ proto mixed pg_delete(resource db, string table, array ids[, int options])
  4936. Delete records has ids (id=>value) */
  4937. PHP_FUNCTION(pg_delete)
  4938. {
  4939. zval *pgsql_link, *ids;
  4940. char *table, *sql = NULL;
  4941. int table_len;
  4942. ulong option = PGSQL_DML_EXEC;
  4943. PGconn *pg_link;
  4944. int id = -1, argc = ZEND_NUM_ARGS();
  4945. if (zend_parse_parameters(argc TSRMLS_CC, "rsa|l",
  4946. &pgsql_link, &table, &table_len, &ids, &option) == FAILURE) {
  4947. return;
  4948. }
  4949. if (option & ~(PGSQL_CONV_FORCE_NULL|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING)) {
  4950. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
  4951. RETURN_FALSE;
  4952. }
  4953. ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  4954. if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
  4955. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
  4956. }
  4957. if (php_pgsql_delete(pg_link, table, ids, option, &sql TSRMLS_CC) == FAILURE) {
  4958. RETURN_FALSE;
  4959. }
  4960. if (option & PGSQL_DML_STRING) {
  4961. RETURN_STRING(sql, 0);
  4962. }
  4963. RETURN_TRUE;
  4964. }
  4965. /* }}} */
  4966. /* {{{ php_pgsql_result2array
  4967. */
  4968. PHP_PGSQL_API int php_pgsql_result2array(PGresult *pg_result, zval *ret_array TSRMLS_DC)
  4969. {
  4970. zval *row;
  4971. char *field_name, *element, *data;
  4972. size_t num_fields, element_len, data_len;
  4973. int pg_numrows, pg_row;
  4974. uint i;
  4975. assert(Z_TYPE_P(ret_array) == IS_ARRAY);
  4976. if ((pg_numrows = PQntuples(pg_result)) <= 0) {
  4977. return FAILURE;
  4978. }
  4979. for (pg_row = 0; pg_row < pg_numrows; pg_row++) {
  4980. MAKE_STD_ZVAL(row);
  4981. array_init(row);
  4982. add_index_zval(ret_array, pg_row, row);
  4983. for (i = 0, num_fields = PQnfields(pg_result); i < num_fields; i++) {
  4984. if (PQgetisnull(pg_result, pg_row, i)) {
  4985. field_name = PQfname(pg_result, i);
  4986. add_assoc_null(row, field_name);
  4987. } else {
  4988. element = PQgetvalue(pg_result, pg_row, i);
  4989. element_len = (element ? strlen(element) : 0);
  4990. if (element) {
  4991. if (PG(magic_quotes_runtime)) {
  4992. data = php_addslashes(element, element_len, &data_len, 0 TSRMLS_CC);
  4993. } else {
  4994. data = safe_estrndup(element, element_len);
  4995. data_len = element_len;
  4996. }
  4997. field_name = PQfname(pg_result, i);
  4998. add_assoc_stringl(row, field_name, data, data_len, 0);
  4999. }
  5000. }
  5001. }
  5002. }
  5003. return SUCCESS;
  5004. }
  5005. /* }}} */
  5006. /* {{{ php_pgsql_select
  5007. */
  5008. PHP_PGSQL_API int php_pgsql_select(PGconn *pg_link, const char *table, zval *ids_array, zval *ret_array, ulong opt, char **sql TSRMLS_DC)
  5009. {
  5010. zval *ids_converted = NULL;
  5011. smart_str querystr = {0};
  5012. int ret = FAILURE;
  5013. PGresult *pg_result;
  5014. assert(pg_link != NULL);
  5015. assert(table != NULL);
  5016. assert(Z_TYPE_P(ids_array) == IS_ARRAY);
  5017. assert(Z_TYPE_P(ret_array) == IS_ARRAY);
  5018. assert(!(opt & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING)));
  5019. if (zend_hash_num_elements(Z_ARRVAL_P(ids_array)) == 0) {
  5020. return FAILURE;
  5021. }
  5022. if (!(opt & PGSQL_DML_NO_CONV)) {
  5023. MAKE_STD_ZVAL(ids_converted);
  5024. array_init(ids_converted);
  5025. if (php_pgsql_convert(pg_link, table, ids_array, ids_converted, (opt & PGSQL_CONV_OPTS) TSRMLS_CC) == FAILURE) {
  5026. goto cleanup;
  5027. }
  5028. ids_array = ids_converted;
  5029. }
  5030. smart_str_appends(&querystr, "SELECT * FROM ");
  5031. smart_str_appends(&querystr, table);
  5032. smart_str_appends(&querystr, " WHERE ");
  5033. if (build_assignment_string(&querystr, Z_ARRVAL_P(ids_array), " AND ", sizeof(" AND ")-1 TSRMLS_CC))
  5034. goto cleanup;
  5035. smart_str_appendc(&querystr, ';');
  5036. smart_str_0(&querystr);
  5037. pg_result = PQexec(pg_link, querystr.c);
  5038. if (PQresultStatus(pg_result) == PGRES_TUPLES_OK) {
  5039. ret = php_pgsql_result2array(pg_result, ret_array TSRMLS_CC);
  5040. } else {
  5041. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to execute '%s'", querystr.c);
  5042. }
  5043. PQclear(pg_result);
  5044. cleanup:
  5045. if (!(opt & PGSQL_DML_NO_CONV)) {
  5046. zval_dtor(ids_converted);
  5047. FREE_ZVAL(ids_converted);
  5048. }
  5049. if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) {
  5050. *sql = querystr.c;
  5051. }
  5052. else {
  5053. smart_str_free(&querystr);
  5054. }
  5055. return ret;
  5056. }
  5057. /* }}} */
  5058. /* {{{ proto mixed pg_select(resource db, string table, array ids[, int options])
  5059. Select records that has ids (id=>value) */
  5060. PHP_FUNCTION(pg_select)
  5061. {
  5062. zval *pgsql_link, *ids;
  5063. char *table, *sql = NULL;
  5064. int table_len;
  5065. ulong option = PGSQL_DML_EXEC;
  5066. PGconn *pg_link;
  5067. int id = -1, argc = ZEND_NUM_ARGS();
  5068. if (zend_parse_parameters(argc TSRMLS_CC, "rsa|l",
  5069. &pgsql_link, &table, &table_len, &ids, &option) == FAILURE) {
  5070. return;
  5071. }
  5072. if (option & ~(PGSQL_CONV_FORCE_NULL|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING)) {
  5073. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid option is specified");
  5074. RETURN_FALSE;
  5075. }
  5076. ZEND_FETCH_RESOURCE2(pg_link, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
  5077. if (php_pgsql_flush_query(pg_link TSRMLS_CC)) {
  5078. php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Detected unhandled result(s) in connection");
  5079. }
  5080. array_init(return_value);
  5081. if (php_pgsql_select(pg_link, table, ids, return_value, option, &sql TSRMLS_CC) == FAILURE) {
  5082. zval_dtor(return_value);
  5083. RETURN_FALSE;
  5084. }
  5085. if (option & PGSQL_DML_STRING) {
  5086. zval_dtor(return_value);
  5087. RETURN_STRING(sql, 0);
  5088. }
  5089. return;
  5090. }
  5091. /* }}} */
  5092. #endif
  5093. /*
  5094. * Local variables:
  5095. * tab-width: 4
  5096. * c-basic-offset: 4
  5097. * End:
  5098. * vim600: sw=4 ts=4 fdm=marker
  5099. * vim<600: sw=4 ts=4
  5100. */