1/*
2  +----------------------------------------------------------------------+
3  | PHP Version 5                                                        |
4  +----------------------------------------------------------------------+
5  | Copyright (c) 1997-2014 The PHP Group                                |
6  +----------------------------------------------------------------------+
7  | This source file is subject to version 3.01 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_01.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: Edin Kadribasic <edink@emini.dk>                            |
16  |          Ilia Alshanestsky <ilia@prohost.org>                        |
17  |          Wez Furlong <wez@php.net>                                   |
18  +----------------------------------------------------------------------+
19*/
20
21/* $Id$ */
22
23#ifdef HAVE_CONFIG_H
24#include "config.h"
25#endif
26
27#include "php.h"
28#include "php_ini.h"
29#include "ext/standard/info.h"
30#include "main/php_network.h"
31#include "pdo/php_pdo.h"
32#include "pdo/php_pdo_driver.h"
33#include "pdo/php_pdo_error.h"
34#include "ext/standard/file.h"
35
36#undef PACKAGE_BUGREPORT
37#undef PACKAGE_NAME
38#undef PACKAGE_STRING
39#undef PACKAGE_TARNAME
40#undef PACKAGE_VERSION
41#include "pg_config.h" /* needed for PG_VERSION */
42#include "php_pdo_pgsql.h"
43#include "php_pdo_pgsql_int.h"
44#include "zend_exceptions.h"
45
46static char * _pdo_pgsql_trim_message(const char *message, int persistent)
47{
48    register int i = strlen(message)-1;
49    char *tmp;
50
51    if (i>1 && (message[i-1] == '\r' || message[i-1] == '\n') && message[i] == '.') {
52        --i;
53    }
54    while (i>0 && (message[i] == '\r' || message[i] == '\n')) {
55        --i;
56    }
57    ++i;
58    tmp = pemalloc(i + 1, persistent);
59    memcpy(tmp, message, i);
60    tmp[i] = '\0';
61
62    return tmp;
63}
64
65int _pdo_pgsql_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, int errcode, const char *sqlstate, const char *msg, const char *file, int line TSRMLS_DC) /* {{{ */
66{
67    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
68    pdo_error_type *pdo_err = stmt ? &stmt->error_code : &dbh->error_code;
69    pdo_pgsql_error_info *einfo = &H->einfo;
70    char *errmsg = PQerrorMessage(H->server);
71
72    einfo->errcode = errcode;
73    einfo->file = file;
74    einfo->line = line;
75
76    if (einfo->errmsg) {
77        pefree(einfo->errmsg, dbh->is_persistent);
78        einfo->errmsg = NULL;
79    }
80
81    if (sqlstate == NULL || strlen(sqlstate) >= sizeof(pdo_error_type)) {
82        strcpy(*pdo_err, "HY000");
83    }
84    else {
85        strcpy(*pdo_err, sqlstate);
86    }
87
88    if (msg) {
89        einfo->errmsg = estrdup(msg);
90    }
91    else if (errmsg) {
92        einfo->errmsg = _pdo_pgsql_trim_message(errmsg, dbh->is_persistent);
93    }
94
95    if (!dbh->methods) {
96        zend_throw_exception_ex(php_pdo_get_exception(), einfo->errcode TSRMLS_CC, "SQLSTATE[%s] [%d] %s",
97                *pdo_err, einfo->errcode, einfo->errmsg);
98    }
99
100    return errcode;
101}
102/* }}} */
103
104static void _pdo_pgsql_notice(pdo_dbh_t *dbh, const char *message) /* {{{ */
105{
106/*  pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data; */
107}
108/* }}} */
109
110static int pdo_pgsql_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info TSRMLS_DC) /* {{{ */
111{
112    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
113    pdo_pgsql_error_info *einfo = &H->einfo;
114
115    if (einfo->errcode) {
116        add_next_index_long(info, einfo->errcode);
117        add_next_index_string(info, einfo->errmsg, 1);
118    }
119
120    return 1;
121}
122/* }}} */
123
124/* {{{ pdo_pgsql_create_lob_stream */
125static size_t pgsql_lob_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC)
126{
127    struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
128    return lo_write(self->conn, self->lfd, (char*)buf, count);
129}
130
131static size_t pgsql_lob_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
132{
133    struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
134    return lo_read(self->conn, self->lfd, buf, count);
135}
136
137static int pgsql_lob_close(php_stream *stream, int close_handle TSRMLS_DC)
138{
139    struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
140    pdo_dbh_t *dbh = self->dbh;
141
142    if (close_handle) {
143        lo_close(self->conn, self->lfd);
144    }
145    efree(self);
146    php_pdo_dbh_delref(dbh TSRMLS_CC);
147    return 0;
148}
149
150static int pgsql_lob_flush(php_stream *stream TSRMLS_DC)
151{
152    return 0;
153}
154
155static int pgsql_lob_seek(php_stream *stream, off_t offset, int whence,
156        off_t *newoffset TSRMLS_DC)
157{
158    struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
159    int pos = lo_lseek(self->conn, self->lfd, offset, whence);
160    *newoffset = pos;
161    return pos >= 0 ? 0 : -1;
162}
163
164php_stream_ops pdo_pgsql_lob_stream_ops = {
165    pgsql_lob_write,
166    pgsql_lob_read,
167    pgsql_lob_close,
168    pgsql_lob_flush,
169    "pdo_pgsql lob stream",
170    pgsql_lob_seek,
171    NULL,
172    NULL,
173    NULL
174};
175
176php_stream *pdo_pgsql_create_lob_stream(pdo_dbh_t *dbh, int lfd, Oid oid TSRMLS_DC)
177{
178    php_stream *stm;
179    struct pdo_pgsql_lob_self *self = ecalloc(1, sizeof(*self));
180    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
181
182    self->dbh = dbh;
183    self->lfd = lfd;
184    self->oid = oid;
185    self->conn = H->server;
186
187    stm = php_stream_alloc(&pdo_pgsql_lob_stream_ops, self, 0, "r+b");
188
189    if (stm) {
190        php_pdo_dbh_addref(dbh TSRMLS_CC);
191        return stm;
192    }
193
194    efree(self);
195    return NULL;
196}
197/* }}} */
198
199static int pgsql_handle_closer(pdo_dbh_t *dbh TSRMLS_DC) /* {{{ */
200{
201    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
202    if (H) {
203        if (H->server) {
204            PQfinish(H->server);
205            H->server = NULL;
206        }
207        if (H->einfo.errmsg) {
208            pefree(H->einfo.errmsg, dbh->is_persistent);
209            H->einfo.errmsg = NULL;
210        }
211        pefree(H, dbh->is_persistent);
212        dbh->driver_data = NULL;
213    }
214    return 0;
215}
216/* }}} */
217
218static int pgsql_handle_preparer(pdo_dbh_t *dbh, const char *sql, long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
219{
220    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
221    pdo_pgsql_stmt *S = ecalloc(1, sizeof(pdo_pgsql_stmt));
222    int scrollable;
223    int ret;
224    char *nsql = NULL;
225    int nsql_len = 0;
226    int emulate = 0;
227    int execute_only = 0;
228
229    S->H = H;
230    stmt->driver_data = S;
231    stmt->methods = &pgsql_stmt_methods;
232
233    scrollable = pdo_attr_lval(driver_options, PDO_ATTR_CURSOR,
234        PDO_CURSOR_FWDONLY TSRMLS_CC) == PDO_CURSOR_SCROLL;
235
236    if (scrollable) {
237        if (S->cursor_name) {
238            efree(S->cursor_name);
239        }
240        spprintf(&S->cursor_name, 0, "pdo_crsr_%08x", ++H->stmt_counter);
241        emulate = 1;
242    } else if (driver_options) {
243        if (pdo_attr_lval(driver_options, PDO_PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT, H->disable_native_prepares TSRMLS_CC) == 1) {
244            php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT is deprecated, use PDO::ATTR_EMULATE_PREPARES instead");
245            emulate = 1;
246        }
247        if (pdo_attr_lval(driver_options, PDO_ATTR_EMULATE_PREPARES, H->emulate_prepares TSRMLS_CC) == 1) {
248            emulate = 1;
249        }
250        if (pdo_attr_lval(driver_options, PDO_PGSQL_ATTR_DISABLE_PREPARES, H->disable_prepares TSRMLS_CC) == 1) {
251            execute_only = 1;
252        }
253    } else {
254        emulate = H->disable_native_prepares || H->emulate_prepares;
255        execute_only = H->disable_prepares;
256    }
257
258    if (!emulate && PQprotocolVersion(H->server) > 2) {
259        stmt->supports_placeholders = PDO_PLACEHOLDER_NAMED;
260        stmt->named_rewrite_template = "$%d";
261        ret = pdo_parse_params(stmt, (char*)sql, sql_len, &nsql, &nsql_len TSRMLS_CC);
262
263        if (ret == 1) {
264            /* query was re-written */
265            sql = nsql;
266        } else if (ret == -1) {
267            /* couldn't grok it */
268            strcpy(dbh->error_code, stmt->error_code);
269            return 0;
270        }
271
272        if (!execute_only) {
273            /* prepared query: set the query name and defer the
274               actual prepare until the first execute call */
275            spprintf(&S->stmt_name, 0, "pdo_stmt_%08x", ++H->stmt_counter);
276        }
277
278        if (nsql) {
279            S->query = nsql;
280        } else {
281            S->query = estrdup(sql);
282        }
283
284        return 1;
285    }
286
287    stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;
288    return 1;
289}
290
291static long pgsql_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)
292{
293    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
294    PGresult *res;
295    long ret = 1;
296    ExecStatusType qs;
297
298    if (!(res = PQexec(H->server, sql))) {
299        /* fatal error */
300        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
301        return -1;
302    }
303    qs = PQresultStatus(res);
304    if (qs != PGRES_COMMAND_OK && qs != PGRES_TUPLES_OK) {
305        pdo_pgsql_error(dbh, qs, pdo_pgsql_sqlstate(res));
306        PQclear(res);
307        return -1;
308    }
309    H->pgoid = PQoidValue(res);
310    ret = (qs == PGRES_COMMAND_OK) ? atol(PQcmdTuples(res)) : 0L;
311    PQclear(res);
312
313    return ret;
314}
315
316static int pgsql_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, char **quoted, int *quotedlen, enum pdo_param_type paramtype TSRMLS_DC)
317{
318    unsigned char *escaped;
319    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
320    size_t tmp_len;
321
322    switch (paramtype) {
323        case PDO_PARAM_LOB:
324            /* escapedlen returned by PQescapeBytea() accounts for trailing 0 */
325            escaped = PQescapeByteaConn(H->server, (unsigned char *)unquoted, (size_t)unquotedlen, &tmp_len);
326            *quotedlen = (int)tmp_len + 1;
327            *quoted = emalloc(*quotedlen + 1);
328            memcpy((*quoted)+1, escaped, *quotedlen-2);
329            (*quoted)[0] = '\'';
330            (*quoted)[*quotedlen-1] = '\'';
331            (*quoted)[*quotedlen] = '\0';
332            PQfreemem(escaped);
333            break;
334        default:
335            *quoted = safe_emalloc(2, unquotedlen, 3);
336            (*quoted)[0] = '\'';
337            *quotedlen = PQescapeStringConn(H->server, *quoted + 1, unquoted, (size_t)unquotedlen, NULL);
338            (*quoted)[*quotedlen + 1] = '\'';
339            (*quoted)[*quotedlen + 2] = '\0';
340            *quotedlen += 2;
341    }
342    return 1;
343}
344
345static char *pdo_pgsql_last_insert_id(pdo_dbh_t *dbh, const char *name, unsigned int *len TSRMLS_DC)
346{
347    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
348    char *id = NULL;
349
350    if (name == NULL) {
351        if (H->pgoid == InvalidOid) {
352            return NULL;
353        }
354        *len = spprintf(&id, 0, "%ld", (long) H->pgoid);
355    } else {
356        PGresult *res;
357        ExecStatusType status;
358        const char *q[1];
359        q[0] = name;
360        res = PQexecParams(H->server, "SELECT CURRVAL($1)", 1, NULL, q, NULL, NULL, 0);
361        status = PQresultStatus(res);
362
363        if (res && (status == PGRES_TUPLES_OK)) {
364            id = estrdup((char *)PQgetvalue(res, 0, 0));
365            *len = PQgetlength(res, 0, 0);
366        } else {
367            pdo_pgsql_error(dbh, status, pdo_pgsql_sqlstate(res));
368        }
369
370        if (res) {
371            PQclear(res);
372        }
373    }
374    return id;
375}
376
377static int pdo_pgsql_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC)
378{
379    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
380
381    switch (attr) {
382        case PDO_ATTR_CLIENT_VERSION:
383            ZVAL_STRING(return_value, PG_VERSION, 1);
384            break;
385
386        case PDO_ATTR_SERVER_VERSION:
387            if (PQprotocolVersion(H->server) >= 3) { /* PostgreSQL 7.4 or later */
388                ZVAL_STRING(return_value, (char*)PQparameterStatus(H->server, "server_version"), 1);
389            } else /* emulate above via a query */
390            {
391                PGresult *res = PQexec(H->server, "SELECT VERSION()");
392                if (res && PQresultStatus(res) == PGRES_TUPLES_OK) {
393                    ZVAL_STRING(return_value, (char *)PQgetvalue(res, 0, 0), 1);
394                }
395
396                if (res) {
397                    PQclear(res);
398                }
399            }
400            break;
401
402        case PDO_ATTR_CONNECTION_STATUS:
403            switch (PQstatus(H->server)) {
404                case CONNECTION_STARTED:
405                    ZVAL_STRINGL(return_value, "Waiting for connection to be made.", sizeof("Waiting for connection to be made.")-1, 1);
406                    break;
407
408                case CONNECTION_MADE:
409                case CONNECTION_OK:
410                    ZVAL_STRINGL(return_value, "Connection OK; waiting to send.", sizeof("Connection OK; waiting to send.")-1, 1);
411                    break;
412
413                case CONNECTION_AWAITING_RESPONSE:
414                    ZVAL_STRINGL(return_value, "Waiting for a response from the server.", sizeof("Waiting for a response from the server.")-1, 1);
415                    break;
416
417                case CONNECTION_AUTH_OK:
418                    ZVAL_STRINGL(return_value, "Received authentication; waiting for backend start-up to finish.", sizeof("Received authentication; waiting for backend start-up to finish.")-1, 1);
419                    break;
420#ifdef CONNECTION_SSL_STARTUP
421                case CONNECTION_SSL_STARTUP:
422                    ZVAL_STRINGL(return_value, "Negotiating SSL encryption.", sizeof("Negotiating SSL encryption.")-1, 1);
423                    break;
424#endif
425                case CONNECTION_SETENV:
426                    ZVAL_STRINGL(return_value, "Negotiating environment-driven parameter settings.", sizeof("Negotiating environment-driven parameter settings.")-1, 1);
427                    break;
428
429                case CONNECTION_BAD:
430                default:
431                    ZVAL_STRINGL(return_value, "Bad connection.", sizeof("Bad connection.")-1, 1);
432                    break;
433            }
434            break;
435
436        case PDO_ATTR_SERVER_INFO: {
437            int spid = PQbackendPID(H->server);
438            char *tmp;
439            spprintf(&tmp, 0,
440                "PID: %d; Client Encoding: %s; Is Superuser: %s; Session Authorization: %s; Date Style: %s",
441                spid,
442                (char*)PQparameterStatus(H->server, "client_encoding"),
443                (char*)PQparameterStatus(H->server, "is_superuser"),
444                (char*)PQparameterStatus(H->server, "session_authorization"),
445                (char*)PQparameterStatus(H->server, "DateStyle"));
446            ZVAL_STRING(return_value, tmp, 0);
447        }
448            break;
449
450        default:
451            return 0;
452    }
453
454    return 1;
455}
456
457/* {{{ */
458static int pdo_pgsql_check_liveness(pdo_dbh_t *dbh TSRMLS_DC)
459{
460    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
461    if (PQstatus(H->server) == CONNECTION_BAD) {
462        PQreset(H->server);
463    }
464    return (PQstatus(H->server) == CONNECTION_OK) ? SUCCESS : FAILURE;
465}
466/* }}} */
467
468static int pgsql_handle_in_transaction(pdo_dbh_t *dbh TSRMLS_DC)
469{
470    pdo_pgsql_db_handle *H;
471
472    H = (pdo_pgsql_db_handle *)dbh->driver_data;
473
474    return PQtransactionStatus(H->server) > PQTRANS_IDLE;
475}
476
477static int pdo_pgsql_transaction_cmd(const char *cmd, pdo_dbh_t *dbh TSRMLS_DC)
478{
479    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
480    PGresult *res;
481    int ret = 1;
482
483    res = PQexec(H->server, cmd);
484
485    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
486        pdo_pgsql_error(dbh, PQresultStatus(res), pdo_pgsql_sqlstate(res));
487        ret = 0;
488    }
489
490    PQclear(res);
491    return ret;
492}
493
494static int pgsql_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)
495{
496    return pdo_pgsql_transaction_cmd("BEGIN", dbh TSRMLS_CC);
497}
498
499static int pgsql_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)
500{
501    int ret = pdo_pgsql_transaction_cmd("COMMIT", dbh TSRMLS_CC);
502
503    /* When deferred constraints are used the commit could
504       fail, and a ROLLBACK implicitly ran. See bug #67462 */
505    if (!ret) {
506        dbh->in_txn = pgsql_handle_in_transaction(dbh TSRMLS_CC);
507    }
508
509    return ret;
510}
511
512static int pgsql_handle_rollback(pdo_dbh_t *dbh TSRMLS_DC)
513{
514    return pdo_pgsql_transaction_cmd("ROLLBACK", dbh TSRMLS_CC);
515}
516
517/* {{{ proto string PDO::pgsqlCopyFromArray(string $table_name , array $rows [, string $delimiter [, string $null_as ] [, string $fields])
518   Returns true if the copy worked fine or false if error */
519static PHP_METHOD(PDO, pgsqlCopyFromArray)
520{
521    pdo_dbh_t *dbh;
522    pdo_pgsql_db_handle *H;
523
524    zval *pg_rows;
525
526    char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
527    int table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
528    char *query;
529
530    PGresult *pgsql_result;
531    ExecStatusType status;
532
533    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s/a|sss",
534                    &table_name, &table_name_len, &pg_rows,
535                    &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
536        return;
537    }
538
539    if (!zend_hash_num_elements(Z_ARRVAL_P(pg_rows))) {
540        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot copy from an empty array");
541        RETURN_FALSE;
542    }
543
544    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
545    PDO_CONSTRUCT_CHECK;
546    PDO_DBH_CLEAR_ERR();
547
548    /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
549    if (pg_fields) {
550        spprintf(&query, 0, "COPY %s (%s) FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
551    } else {
552        spprintf(&query, 0, "COPY %s FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
553    }
554
555    /* Obtain db Handle */
556    H = (pdo_pgsql_db_handle *)dbh->driver_data;
557
558    while ((pgsql_result = PQgetResult(H->server))) {
559        PQclear(pgsql_result);
560    }
561    pgsql_result = PQexec(H->server, query);
562
563    efree(query);
564    query = NULL;
565
566    if (pgsql_result) {
567        status = PQresultStatus(pgsql_result);
568    } else {
569        status = (ExecStatusType) PQstatus(H->server);
570    }
571
572    if (status == PGRES_COPY_IN && pgsql_result) {
573        int command_failed = 0;
574        int buffer_len = 0;
575        zval **tmp;
576        HashPosition pos;
577
578        PQclear(pgsql_result);
579        zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos);
580        while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
581            int query_len;
582            convert_to_string_ex(tmp);
583
584            if (buffer_len < Z_STRLEN_PP(tmp)) {
585                buffer_len = Z_STRLEN_PP(tmp);
586                query = erealloc(query, buffer_len + 2); /* room for \n\0 */
587            }
588            memcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));
589            query_len = Z_STRLEN_PP(tmp);
590            if (query[query_len - 1] != '\n') {
591                query[query_len++] = '\n';
592            }
593            query[query_len] = '\0';
594            if (PQputCopyData(H->server, query, query_len) != 1) {
595                            efree(query);
596                            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
597                PDO_HANDLE_DBH_ERR();
598                            RETURN_FALSE;
599                    }
600            zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
601                }
602        if (query) {
603            efree(query);
604        }
605
606        if (PQputCopyEnd(H->server, NULL) != 1) {
607            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
608            PDO_HANDLE_DBH_ERR();
609            RETURN_FALSE;
610        }
611
612        while ((pgsql_result = PQgetResult(H->server))) {
613            if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
614                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
615                command_failed = 1;
616            }
617            PQclear(pgsql_result);
618        }
619
620        PDO_HANDLE_DBH_ERR();
621        RETURN_BOOL(!command_failed);
622    } else {
623        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
624        PQclear(pgsql_result);
625        PDO_HANDLE_DBH_ERR();
626        RETURN_FALSE;
627    }
628}
629/* }}} */
630
631/* {{{ proto string PDO::pgsqlCopyFromFile(string $table_name , string $filename [, string $delimiter [, string $null_as ] [, string $fields])
632   Returns true if the copy worked fine or false if error */
633static PHP_METHOD(PDO, pgsqlCopyFromFile)
634{
635    pdo_dbh_t *dbh;
636    pdo_pgsql_db_handle *H;
637
638    char *table_name, *filename, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
639    int  table_name_len, filename_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
640    char *query;
641    PGresult *pgsql_result;
642    ExecStatusType status;
643    php_stream *stream;
644
645    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp|sss",
646                &table_name, &table_name_len, &filename, &filename_len,
647                &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
648        return;
649    }
650
651    /* Obtain db Handler */
652    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
653    PDO_CONSTRUCT_CHECK;
654    PDO_DBH_CLEAR_ERR();
655
656    stream = php_stream_open_wrapper_ex(filename, "rb", ENFORCE_SAFE_MODE, NULL, FG(default_context));
657    if (!stream) {
658        pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to open the file");
659        PDO_HANDLE_DBH_ERR();
660        RETURN_FALSE;
661    }
662
663    /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
664    if (pg_fields) {
665        spprintf(&query, 0, "COPY %s (%s) FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
666    } else {
667        spprintf(&query, 0, "COPY %s FROM STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
668    }
669
670    H = (pdo_pgsql_db_handle *)dbh->driver_data;
671
672    while ((pgsql_result = PQgetResult(H->server))) {
673        PQclear(pgsql_result);
674    }
675    pgsql_result = PQexec(H->server, query);
676
677    efree(query);
678
679    if (pgsql_result) {
680        status = PQresultStatus(pgsql_result);
681    } else {
682        status = (ExecStatusType) PQstatus(H->server);
683    }
684
685    if (status == PGRES_COPY_IN && pgsql_result) {
686        char *buf;
687        int command_failed = 0;
688        size_t line_len = 0;
689
690        PQclear(pgsql_result);
691        while ((buf = php_stream_get_line(stream, NULL, 0, &line_len)) != NULL) {
692            if (PQputCopyData(H->server, buf, line_len) != 1) {
693                            efree(buf);
694                            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
695                php_stream_close(stream);
696                PDO_HANDLE_DBH_ERR();
697                RETURN_FALSE;
698            }
699            efree(buf);
700        }
701        php_stream_close(stream);
702
703        if (PQputCopyEnd(H->server, NULL) != 1) {
704            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
705            PDO_HANDLE_DBH_ERR();
706            RETURN_FALSE;
707        }
708
709        while ((pgsql_result = PQgetResult(H->server))) {
710            if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
711                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
712                command_failed = 1;
713            }
714            PQclear(pgsql_result);
715        }
716
717        PDO_HANDLE_DBH_ERR();
718        RETURN_BOOL(!command_failed);
719    } else {
720        php_stream_close(stream);
721        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
722        PQclear(pgsql_result);
723        PDO_HANDLE_DBH_ERR();
724        RETURN_FALSE;
725    }
726}
727/* }}} */
728
729
730/* {{{ proto string PDO::pgsqlCopyToFile(string $table_name , $filename, [string $delimiter [, string $null_as [, string $fields]]])
731   Returns true if the copy worked fine or false if error */
732static PHP_METHOD(PDO, pgsqlCopyToFile)
733{
734    pdo_dbh_t *dbh;
735    pdo_pgsql_db_handle *H;
736
737    char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL, *filename = NULL;
738    int table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len, filename_len;
739    char *query;
740
741    PGresult *pgsql_result;
742    ExecStatusType status;
743
744    php_stream *stream;
745
746    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp|sss",
747                    &table_name, &table_name_len, &filename, &filename_len,
748                    &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
749        return;
750    }
751
752    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
753    PDO_CONSTRUCT_CHECK;
754    PDO_DBH_CLEAR_ERR();
755
756    H = (pdo_pgsql_db_handle *)dbh->driver_data;
757
758    stream = php_stream_open_wrapper_ex(filename, "wb", ENFORCE_SAFE_MODE, NULL, FG(default_context));
759    if (!stream) {
760        pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to open the file for writing");
761        PDO_HANDLE_DBH_ERR();
762        RETURN_FALSE;
763    }
764
765    while ((pgsql_result = PQgetResult(H->server))) {
766        PQclear(pgsql_result);
767    }
768
769    /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
770    if (pg_fields) {
771        spprintf(&query, 0, "COPY %s (%s) TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
772    } else {
773        spprintf(&query, 0, "COPY %s TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
774    }
775    pgsql_result = PQexec(H->server, query);
776    efree(query);
777
778    if (pgsql_result) {
779        status = PQresultStatus(pgsql_result);
780    } else {
781        status = (ExecStatusType) PQstatus(H->server);
782    }
783
784    if (status == PGRES_COPY_OUT && pgsql_result) {
785        PQclear(pgsql_result);
786        while (1) {
787            char *csv = NULL;
788            int ret = PQgetCopyData(H->server, &csv, 0);
789
790            if (ret == -1) {
791                break; /* done */
792            } else if (ret > 0) {
793                if (php_stream_write(stream, csv, ret) != ret) {
794                    pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to write to file");
795                    PQfreemem(csv);
796                    php_stream_close(stream);
797                    PDO_HANDLE_DBH_ERR();
798                    RETURN_FALSE;
799                } else {
800                    PQfreemem(csv);
801                }
802            } else {
803                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
804                php_stream_close(stream);
805                PDO_HANDLE_DBH_ERR();
806                RETURN_FALSE;
807            }
808        }
809        php_stream_close(stream);
810
811        while ((pgsql_result = PQgetResult(H->server))) {
812            PQclear(pgsql_result);
813        }
814        RETURN_TRUE;
815    } else {
816        php_stream_close(stream);
817        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
818        PQclear(pgsql_result);
819        PDO_HANDLE_DBH_ERR();
820        RETURN_FALSE;
821    }
822}
823/* }}} */
824
825/* {{{ proto string PDO::pgsqlCopyToArray(string $table_name , [string $delimiter [, string $null_as [, string $fields]]])
826   Returns true if the copy worked fine or false if error */
827static PHP_METHOD(PDO, pgsqlCopyToArray)
828{
829    pdo_dbh_t *dbh;
830    pdo_pgsql_db_handle *H;
831
832    char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
833    int table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
834    char *query;
835
836    PGresult *pgsql_result;
837    ExecStatusType status;
838
839    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sss",
840        &table_name, &table_name_len,
841        &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
842        return;
843    }
844
845    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
846    PDO_CONSTRUCT_CHECK;
847    PDO_DBH_CLEAR_ERR();
848
849    H = (pdo_pgsql_db_handle *)dbh->driver_data;
850
851    while ((pgsql_result = PQgetResult(H->server))) {
852        PQclear(pgsql_result);
853    }
854
855    /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
856    if (pg_fields) {
857        spprintf(&query, 0, "COPY %s (%s) TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
858    } else {
859        spprintf(&query, 0, "COPY %s TO STDIN WITH DELIMITER E'%c' NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
860    }
861    pgsql_result = PQexec(H->server, query);
862    efree(query);
863
864    if (pgsql_result) {
865        status = PQresultStatus(pgsql_result);
866    } else {
867        status = (ExecStatusType) PQstatus(H->server);
868    }
869
870    if (status == PGRES_COPY_OUT && pgsql_result) {
871        PQclear(pgsql_result);
872                array_init(return_value);
873
874        while (1) {
875            char *csv = NULL;
876            int ret = PQgetCopyData(H->server, &csv, 0);
877            if (ret == -1) {
878                break; /* copy done */
879            } else if (ret > 0) {
880                add_next_index_stringl(return_value, csv, ret, 1);
881                PQfreemem(csv);
882            } else {
883                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
884                PDO_HANDLE_DBH_ERR();
885                RETURN_FALSE;
886            }
887        }
888
889        while ((pgsql_result = PQgetResult(H->server))) {
890            PQclear(pgsql_result);
891        }
892    } else {
893        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
894        PQclear(pgsql_result);
895        PDO_HANDLE_DBH_ERR();
896        RETURN_FALSE;
897    }
898}
899/* }}} */
900
901
902/* {{{ proto string PDO::pgsqlLOBCreate()
903   Creates a new large object, returning its identifier.  Must be called inside a transaction. */
904static PHP_METHOD(PDO, pgsqlLOBCreate)
905{
906    pdo_dbh_t *dbh;
907    pdo_pgsql_db_handle *H;
908    Oid lfd;
909
910    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
911    PDO_CONSTRUCT_CHECK;
912    PDO_DBH_CLEAR_ERR();
913
914    H = (pdo_pgsql_db_handle *)dbh->driver_data;
915    lfd = lo_creat(H->server, INV_READ|INV_WRITE);
916
917    if (lfd != InvalidOid) {
918        char *buf;
919        spprintf(&buf, 0, "%lu", (long) lfd);
920        RETURN_STRING(buf, 0);
921    }
922
923    pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
924    PDO_HANDLE_DBH_ERR();
925    RETURN_FALSE;
926}
927/* }}} */
928
929/* {{{ proto resource PDO::pgsqlLOBOpen(string oid [, string mode = 'rb'])
930   Opens an existing large object stream.  Must be called inside a transaction. */
931static PHP_METHOD(PDO, pgsqlLOBOpen)
932{
933    pdo_dbh_t *dbh;
934    pdo_pgsql_db_handle *H;
935    Oid oid;
936    int lfd;
937    char *oidstr;
938    int oidstrlen;
939    char *modestr = "rb";
940    int modestrlen;
941    int mode = INV_READ;
942    char *end_ptr;
943
944    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
945                &oidstr, &oidstrlen, &modestr, &modestrlen)) {
946        RETURN_FALSE;
947    }
948
949    oid = (Oid)strtoul(oidstr, &end_ptr, 10);
950    if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
951        RETURN_FALSE;
952    }
953
954    if (strpbrk(modestr, "+w")) {
955        mode = INV_READ|INV_WRITE;
956    }
957
958    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
959    PDO_CONSTRUCT_CHECK;
960    PDO_DBH_CLEAR_ERR();
961
962    H = (pdo_pgsql_db_handle *)dbh->driver_data;
963
964    lfd = lo_open(H->server, oid, mode);
965
966    if (lfd >= 0) {
967        php_stream *stream = pdo_pgsql_create_lob_stream(dbh, lfd, oid TSRMLS_CC);
968        if (stream) {
969            php_stream_to_zval(stream, return_value);
970            return;
971        }
972    } else {
973        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
974    }
975
976    PDO_HANDLE_DBH_ERR();
977    RETURN_FALSE;
978}
979/* }}} */
980
981/* {{{ proto bool PDO::pgsqlLOBUnlink(string oid)
982   Deletes the large object identified by oid.  Must be called inside a transaction. */
983static PHP_METHOD(PDO, pgsqlLOBUnlink)
984{
985    pdo_dbh_t *dbh;
986    pdo_pgsql_db_handle *H;
987    Oid oid;
988    char *oidstr, *end_ptr;
989    int oidlen;
990
991    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
992                &oidstr, &oidlen)) {
993        RETURN_FALSE;
994    }
995
996    oid = (Oid)strtoul(oidstr, &end_ptr, 10);
997    if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
998        RETURN_FALSE;
999    }
1000
1001    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
1002    PDO_CONSTRUCT_CHECK;
1003    PDO_DBH_CLEAR_ERR();
1004
1005    H = (pdo_pgsql_db_handle *)dbh->driver_data;
1006
1007    if (1 == lo_unlink(H->server, oid)) {
1008        RETURN_TRUE;
1009    }
1010
1011    pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1012    PDO_HANDLE_DBH_ERR();
1013    RETURN_FALSE;
1014}
1015/* }}} */
1016
1017/* {{{ proto mixed PDO::pgsqlGetNotify([ int $result_type = PDO::FETCH_USE_DEFAULT] [, int $ms_timeout = 0 ]])
1018   Get asyncronous notification */
1019static PHP_METHOD(PDO, pgsqlGetNotify)
1020{
1021    pdo_dbh_t *dbh;
1022    pdo_pgsql_db_handle *H;
1023    long result_type = PDO_FETCH_USE_DEFAULT;
1024    long ms_timeout = 0;
1025    PGnotify *pgsql_notify;
1026
1027    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ll",
1028                &result_type, &ms_timeout)) {
1029        RETURN_FALSE;
1030    }
1031
1032    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
1033    PDO_CONSTRUCT_CHECK;
1034
1035    if (result_type == PDO_FETCH_USE_DEFAULT) {
1036        result_type = dbh->default_fetch_type;
1037    }
1038
1039    if (result_type != PDO_FETCH_BOTH && result_type != PDO_FETCH_ASSOC && result_type != PDO_FETCH_NUM) {
1040        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
1041        RETURN_FALSE;
1042    }
1043
1044    if (ms_timeout < 0) {
1045        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid timeout");
1046        RETURN_FALSE;
1047    }
1048
1049    H = (pdo_pgsql_db_handle *)dbh->driver_data;
1050
1051    PQconsumeInput(H->server);
1052    pgsql_notify = PQnotifies(H->server);
1053
1054    if (ms_timeout && !pgsql_notify) {
1055        php_pollfd_for_ms(PQsocket(H->server), PHP_POLLREADABLE, ms_timeout);
1056
1057        PQconsumeInput(H->server);
1058        pgsql_notify = PQnotifies(H->server);
1059    }
1060
1061    if (!pgsql_notify) {
1062        RETURN_FALSE;
1063    }
1064
1065    array_init(return_value);
1066    if (result_type == PDO_FETCH_NUM || result_type == PDO_FETCH_BOTH) {
1067        add_index_string(return_value, 0, pgsql_notify->relname, 1);
1068        add_index_long(return_value, 1, pgsql_notify->be_pid);
1069        if (pgsql_notify->extra && pgsql_notify->extra[0]) {
1070            add_index_string(return_value, 2, pgsql_notify->extra, 1);
1071        }
1072    }
1073    if (result_type == PDO_FETCH_ASSOC || result_type == PDO_FETCH_BOTH) {
1074        add_assoc_string(return_value, "message", pgsql_notify->relname, 1);
1075        add_assoc_long(return_value, "pid", pgsql_notify->be_pid);
1076        if (pgsql_notify->extra && pgsql_notify->extra[0]) {
1077            add_assoc_string(return_value, "payload", pgsql_notify->extra, 1);
1078        }
1079    }
1080
1081    PQfreemem(pgsql_notify);
1082}
1083/* }}} */
1084
1085/* {{{ proto int PDO::pgsqlGetPid()
1086   Get backend(server) pid */
1087static PHP_METHOD(PDO, pgsqlGetPid)
1088{
1089    pdo_dbh_t *dbh;
1090    pdo_pgsql_db_handle *H;
1091
1092    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
1093    PDO_CONSTRUCT_CHECK;
1094
1095    H = (pdo_pgsql_db_handle *)dbh->driver_data;
1096
1097    RETURN_LONG(PQbackendPID(H->server));
1098}
1099/* }}} */
1100
1101
1102static const zend_function_entry dbh_methods[] = {
1103    PHP_ME(PDO, pgsqlLOBCreate, NULL, ZEND_ACC_PUBLIC)
1104    PHP_ME(PDO, pgsqlLOBOpen, NULL, ZEND_ACC_PUBLIC)
1105    PHP_ME(PDO, pgsqlLOBUnlink, NULL, ZEND_ACC_PUBLIC)
1106    PHP_ME(PDO, pgsqlCopyFromArray, NULL, ZEND_ACC_PUBLIC)
1107    PHP_ME(PDO, pgsqlCopyFromFile, NULL, ZEND_ACC_PUBLIC)
1108    PHP_ME(PDO, pgsqlCopyToArray, NULL, ZEND_ACC_PUBLIC)
1109    PHP_ME(PDO, pgsqlCopyToFile, NULL, ZEND_ACC_PUBLIC)
1110        PHP_ME(PDO, pgsqlGetNotify, NULL, ZEND_ACC_PUBLIC)
1111        PHP_ME(PDO, pgsqlGetPid, NULL, ZEND_ACC_PUBLIC)
1112    PHP_FE_END
1113};
1114
1115static const zend_function_entry *pdo_pgsql_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)
1116{
1117    switch (kind) {
1118        case PDO_DBH_DRIVER_METHOD_KIND_DBH:
1119            return dbh_methods;
1120        default:
1121            return NULL;
1122    }
1123}
1124
1125static int pdo_pgsql_set_attr(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)
1126{
1127    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
1128
1129    switch (attr) {
1130        case PDO_ATTR_EMULATE_PREPARES:
1131            H->emulate_prepares = Z_LVAL_P(val);
1132            return 1;
1133        case PDO_PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT:
1134            php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT is deprecated, use PDO::ATTR_EMULATE_PREPARES instead");
1135            H->disable_native_prepares = Z_LVAL_P(val);
1136            return 1;
1137        case PDO_PGSQL_ATTR_DISABLE_PREPARES:
1138            H->disable_prepares = Z_LVAL_P(val);
1139            return 1;
1140        default:
1141            return 0;
1142    }
1143}
1144
1145static struct pdo_dbh_methods pgsql_methods = {
1146    pgsql_handle_closer,
1147    pgsql_handle_preparer,
1148    pgsql_handle_doer,
1149    pgsql_handle_quoter,
1150    pgsql_handle_begin,
1151    pgsql_handle_commit,
1152    pgsql_handle_rollback,
1153    pdo_pgsql_set_attr,
1154    pdo_pgsql_last_insert_id,
1155    pdo_pgsql_fetch_error_func,
1156    pdo_pgsql_get_attribute,
1157    pdo_pgsql_check_liveness,   /* check_liveness */
1158    pdo_pgsql_get_driver_methods,  /* get_driver_methods */
1159    NULL,
1160    pgsql_handle_in_transaction,
1161};
1162
1163static int pdo_pgsql_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC) /* {{{ */
1164{
1165    pdo_pgsql_db_handle *H;
1166    int ret = 0;
1167    char *conn_str, *p, *e;
1168    char *tmp_pass;
1169    long connect_timeout = 30;
1170
1171    H = pecalloc(1, sizeof(pdo_pgsql_db_handle), dbh->is_persistent);
1172    dbh->driver_data = H;
1173
1174    H->einfo.errcode = 0;
1175    H->einfo.errmsg = NULL;
1176
1177    /* PostgreSQL wants params in the connect string to be separated by spaces,
1178     * if the PDO standard semicolons are used, we convert them to spaces
1179     */
1180    e = (char *) dbh->data_source + strlen(dbh->data_source);
1181    p = (char *) dbh->data_source;
1182    while ((p = memchr(p, ';', (e - p)))) {
1183        *p = ' ';
1184    }
1185
1186    if (driver_options) {
1187        connect_timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30 TSRMLS_CC);
1188    }
1189
1190    if (dbh->password) {
1191        if (dbh->password[0] != '\'' && dbh->password[strlen(dbh->password) - 1] != '\'') {
1192            char *pwd = dbh->password;
1193            int pos = 1;
1194
1195            tmp_pass = safe_emalloc(2, strlen(dbh->password), 3);
1196            tmp_pass[0] = '\'';
1197
1198            while (*pwd != '\0') {
1199                if (*pwd == '\\' || *pwd == '\'') {
1200                    tmp_pass[pos++] = '\\';
1201                }
1202
1203                tmp_pass[pos++] = *pwd++;
1204            }
1205
1206            tmp_pass[pos++] = '\'';
1207            tmp_pass[pos] = '\0';
1208        } else {
1209            tmp_pass = dbh->password;
1210        }
1211    }
1212
1213    /* support both full connection string & connection string + login and/or password */
1214    if (dbh->username && dbh->password) {
1215        spprintf(&conn_str, 0, "%s user=%s password=%s connect_timeout=%ld", dbh->data_source, dbh->username, tmp_pass, connect_timeout);
1216    } else if (dbh->username) {
1217        spprintf(&conn_str, 0, "%s user=%s connect_timeout=%ld", dbh->data_source, dbh->username, connect_timeout);
1218    } else if (dbh->password) {
1219        spprintf(&conn_str, 0, "%s password=%s connect_timeout=%ld", dbh->data_source, tmp_pass, connect_timeout);
1220    } else {
1221        spprintf(&conn_str, 0, "%s connect_timeout=%ld", (char *) dbh->data_source, connect_timeout);
1222    }
1223
1224    H->server = PQconnectdb(conn_str);
1225    if (dbh->password && tmp_pass != dbh->password) {
1226        efree(tmp_pass);
1227    }
1228
1229    efree(conn_str);
1230
1231    if (PQstatus(H->server) != CONNECTION_OK) {
1232        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, PHP_PDO_PGSQL_CONNECTION_FAILURE_SQLSTATE);
1233        goto cleanup;
1234    }
1235
1236    PQsetNoticeProcessor(H->server, (void(*)(void*,const char*))_pdo_pgsql_notice, (void *)&dbh);
1237
1238    H->attached = 1;
1239    H->pgoid = -1;
1240
1241    dbh->methods = &pgsql_methods;
1242    dbh->alloc_own_columns = 1;
1243    dbh->max_escaped_char_length = 2;
1244
1245    ret = 1;
1246
1247cleanup:
1248    dbh->methods = &pgsql_methods;
1249    if (!ret) {
1250        pgsql_handle_closer(dbh TSRMLS_CC);
1251    }
1252
1253    return ret;
1254}
1255/* }}} */
1256
1257pdo_driver_t pdo_pgsql_driver = {
1258    PDO_DRIVER_HEADER(pgsql),
1259    pdo_pgsql_handle_factory
1260};
1261
1262/*
1263 * Local variables:
1264 * tab-width: 4
1265 * c-basic-offset: 4
1266 * End:
1267 * vim600: noet sw=4 ts=4 fdm=marker
1268 * vim<600: noet sw=4 ts=4
1269 */
1270