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 pdo_pgsql_transaction_cmd(const char *cmd, pdo_dbh_t *dbh TSRMLS_DC)
469{
470    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
471    PGresult *res;
472    int ret = 1;
473
474    res = PQexec(H->server, cmd);
475
476    if (PQresultStatus(res) != PGRES_COMMAND_OK) {
477        pdo_pgsql_error(dbh, PQresultStatus(res), pdo_pgsql_sqlstate(res));
478        ret = 0;
479    }
480
481    PQclear(res);
482    return ret;
483}
484
485static int pgsql_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)
486{
487    return pdo_pgsql_transaction_cmd("BEGIN", dbh TSRMLS_CC);
488}
489
490static int pgsql_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)
491{
492    return pdo_pgsql_transaction_cmd("COMMIT", dbh TSRMLS_CC);
493}
494
495static int pgsql_handle_rollback(pdo_dbh_t *dbh TSRMLS_DC)
496{
497    return pdo_pgsql_transaction_cmd("ROLLBACK", dbh TSRMLS_CC);
498}
499
500static int pgsql_handle_in_transaction(pdo_dbh_t *dbh TSRMLS_DC)
501{
502    pdo_pgsql_db_handle *H;
503
504    H = (pdo_pgsql_db_handle *)dbh->driver_data;
505
506    return PQtransactionStatus(H->server);
507}
508
509/* {{{ proto string PDO::pgsqlCopyFromArray(string $table_name , array $rows [, string $delimiter [, string $null_as ] [, string $fields])
510   Returns true if the copy worked fine or false if error */
511static PHP_METHOD(PDO, pgsqlCopyFromArray)
512{
513    pdo_dbh_t *dbh;
514    pdo_pgsql_db_handle *H;
515
516    zval *pg_rows;
517
518    char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
519    int table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
520    char *query;
521
522    PGresult *pgsql_result;
523    ExecStatusType status;
524
525    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s/a|sss",
526                    &table_name, &table_name_len, &pg_rows,
527                    &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
528        return;
529    }
530
531    if (!zend_hash_num_elements(Z_ARRVAL_P(pg_rows))) {
532        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot copy from an empty array");
533        RETURN_FALSE;
534    }
535
536    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
537    PDO_CONSTRUCT_CHECK;
538    PDO_DBH_CLEAR_ERR();
539
540    /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
541    if (pg_fields) {
542        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"));
543    } else {
544        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"));
545    }
546
547    /* Obtain db Handle */
548    H = (pdo_pgsql_db_handle *)dbh->driver_data;
549
550    while ((pgsql_result = PQgetResult(H->server))) {
551        PQclear(pgsql_result);
552    }
553    pgsql_result = PQexec(H->server, query);
554
555    efree(query);
556    query = NULL;
557
558    if (pgsql_result) {
559        status = PQresultStatus(pgsql_result);
560    } else {
561        status = (ExecStatusType) PQstatus(H->server);
562    }
563
564    if (status == PGRES_COPY_IN && pgsql_result) {
565        int command_failed = 0;
566        int buffer_len = 0;
567        zval **tmp;
568        HashPosition pos;
569
570        PQclear(pgsql_result);
571        zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos);
572        while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
573            int query_len;
574            convert_to_string_ex(tmp);
575
576            if (buffer_len < Z_STRLEN_PP(tmp)) {
577                buffer_len = Z_STRLEN_PP(tmp);
578                query = erealloc(query, buffer_len + 2); /* room for \n\0 */
579            }
580            memcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));
581            query_len = Z_STRLEN_PP(tmp);
582            if (query[query_len - 1] != '\n') {
583                query[query_len++] = '\n';
584            }
585            query[query_len] = '\0';
586            if (PQputCopyData(H->server, query, query_len) != 1) {
587                            efree(query);
588                            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
589                PDO_HANDLE_DBH_ERR();
590                            RETURN_FALSE;
591                    }
592            zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
593                }
594        if (query) {
595            efree(query);
596        }
597
598        if (PQputCopyEnd(H->server, NULL) != 1) {
599            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
600            PDO_HANDLE_DBH_ERR();
601            RETURN_FALSE;
602        }
603
604        while ((pgsql_result = PQgetResult(H->server))) {
605            if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
606                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
607                command_failed = 1;
608            }
609            PQclear(pgsql_result);
610        }
611
612        PDO_HANDLE_DBH_ERR();
613        RETURN_BOOL(!command_failed);
614    } else {
615        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
616        PQclear(pgsql_result);
617        PDO_HANDLE_DBH_ERR();
618        RETURN_FALSE;
619    }
620}
621/* }}} */
622
623/* {{{ proto string PDO::pgsqlCopyFromFile(string $table_name , string $filename [, string $delimiter [, string $null_as ] [, string $fields])
624   Returns true if the copy worked fine or false if error */
625static PHP_METHOD(PDO, pgsqlCopyFromFile)
626{
627    pdo_dbh_t *dbh;
628    pdo_pgsql_db_handle *H;
629
630    char *table_name, *filename, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
631    int  table_name_len, filename_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
632    char *query;
633    PGresult *pgsql_result;
634    ExecStatusType status;
635    php_stream *stream;
636
637    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp|sss",
638                &table_name, &table_name_len, &filename, &filename_len,
639                &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
640        return;
641    }
642
643    /* Obtain db Handler */
644    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
645    PDO_CONSTRUCT_CHECK;
646    PDO_DBH_CLEAR_ERR();
647
648    stream = php_stream_open_wrapper_ex(filename, "rb", ENFORCE_SAFE_MODE, NULL, FG(default_context));
649    if (!stream) {
650        pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to open the file");
651        PDO_HANDLE_DBH_ERR();
652        RETURN_FALSE;
653    }
654
655    /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
656    if (pg_fields) {
657        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"));
658    } else {
659        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"));
660    }
661
662    H = (pdo_pgsql_db_handle *)dbh->driver_data;
663
664    while ((pgsql_result = PQgetResult(H->server))) {
665        PQclear(pgsql_result);
666    }
667    pgsql_result = PQexec(H->server, query);
668
669    efree(query);
670
671    if (pgsql_result) {
672        status = PQresultStatus(pgsql_result);
673    } else {
674        status = (ExecStatusType) PQstatus(H->server);
675    }
676
677    if (status == PGRES_COPY_IN && pgsql_result) {
678        char *buf;
679        int command_failed = 0;
680        size_t line_len = 0;
681
682        PQclear(pgsql_result);
683        while ((buf = php_stream_get_line(stream, NULL, 0, &line_len)) != NULL) {
684            if (PQputCopyData(H->server, buf, line_len) != 1) {
685                            efree(buf);
686                            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
687                php_stream_close(stream);
688                PDO_HANDLE_DBH_ERR();
689                RETURN_FALSE;
690            }
691            efree(buf);
692        }
693        php_stream_close(stream);
694
695        if (PQputCopyEnd(H->server, NULL) != 1) {
696            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
697            PDO_HANDLE_DBH_ERR();
698            RETURN_FALSE;
699        }
700
701        while ((pgsql_result = PQgetResult(H->server))) {
702            if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
703                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
704                command_failed = 1;
705            }
706            PQclear(pgsql_result);
707        }
708
709        PDO_HANDLE_DBH_ERR();
710        RETURN_BOOL(!command_failed);
711    } else {
712        php_stream_close(stream);
713        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
714        PQclear(pgsql_result);
715        PDO_HANDLE_DBH_ERR();
716        RETURN_FALSE;
717    }
718}
719/* }}} */
720
721
722/* {{{ proto string PDO::pgsqlCopyToFile(string $table_name , $filename, [string $delimiter [, string $null_as [, string $fields]]])
723   Returns true if the copy worked fine or false if error */
724static PHP_METHOD(PDO, pgsqlCopyToFile)
725{
726    pdo_dbh_t *dbh;
727    pdo_pgsql_db_handle *H;
728
729    char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL, *filename = NULL;
730    int table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len, filename_len;
731    char *query;
732
733    PGresult *pgsql_result;
734    ExecStatusType status;
735
736    php_stream *stream;
737
738    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp|sss",
739                    &table_name, &table_name_len, &filename, &filename_len,
740                    &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
741        return;
742    }
743
744    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
745    PDO_CONSTRUCT_CHECK;
746    PDO_DBH_CLEAR_ERR();
747
748    H = (pdo_pgsql_db_handle *)dbh->driver_data;
749
750    stream = php_stream_open_wrapper_ex(filename, "wb", ENFORCE_SAFE_MODE, NULL, FG(default_context));
751    if (!stream) {
752        pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to open the file for writing");
753        PDO_HANDLE_DBH_ERR();
754        RETURN_FALSE;
755    }
756
757    while ((pgsql_result = PQgetResult(H->server))) {
758        PQclear(pgsql_result);
759    }
760
761    /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
762    if (pg_fields) {
763        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"));
764    } else {
765        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"));
766    }
767    pgsql_result = PQexec(H->server, query);
768    efree(query);
769
770    if (pgsql_result) {
771        status = PQresultStatus(pgsql_result);
772    } else {
773        status = (ExecStatusType) PQstatus(H->server);
774    }
775
776    if (status == PGRES_COPY_OUT && pgsql_result) {
777        PQclear(pgsql_result);
778        while (1) {
779            char *csv = NULL;
780            int ret = PQgetCopyData(H->server, &csv, 0);
781
782            if (ret == -1) {
783                break; /* done */
784            } else if (ret > 0) {
785                if (php_stream_write(stream, csv, ret) != ret) {
786                    pdo_pgsql_error_msg(dbh, PGRES_FATAL_ERROR, "Unable to write to file");
787                    PQfreemem(csv);
788                    php_stream_close(stream);
789                    PDO_HANDLE_DBH_ERR();
790                    RETURN_FALSE;
791                } else {
792                    PQfreemem(csv);
793                }
794            } else {
795                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
796                php_stream_close(stream);
797                PDO_HANDLE_DBH_ERR();
798                RETURN_FALSE;
799            }
800        }
801        php_stream_close(stream);
802
803        while ((pgsql_result = PQgetResult(H->server))) {
804            PQclear(pgsql_result);
805        }
806        RETURN_TRUE;
807    } else {
808        php_stream_close(stream);
809        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
810        PQclear(pgsql_result);
811        PDO_HANDLE_DBH_ERR();
812        RETURN_FALSE;
813    }
814}
815/* }}} */
816
817/* {{{ proto string PDO::pgsqlCopyToArray(string $table_name , [string $delimiter [, string $null_as [, string $fields]]])
818   Returns true if the copy worked fine or false if error */
819static PHP_METHOD(PDO, pgsqlCopyToArray)
820{
821    pdo_dbh_t *dbh;
822    pdo_pgsql_db_handle *H;
823
824    char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
825    int table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
826    char *query;
827
828    PGresult *pgsql_result;
829    ExecStatusType status;
830
831    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sss",
832        &table_name, &table_name_len,
833        &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
834        return;
835    }
836
837    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
838    PDO_CONSTRUCT_CHECK;
839    PDO_DBH_CLEAR_ERR();
840
841    H = (pdo_pgsql_db_handle *)dbh->driver_data;
842
843    while ((pgsql_result = PQgetResult(H->server))) {
844        PQclear(pgsql_result);
845    }
846
847    /* using pre-9.0 syntax as PDO_pgsql is 7.4+ compatible */
848    if (pg_fields) {
849        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"));
850    } else {
851        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"));
852    }
853    pgsql_result = PQexec(H->server, query);
854    efree(query);
855
856    if (pgsql_result) {
857        status = PQresultStatus(pgsql_result);
858    } else {
859        status = (ExecStatusType) PQstatus(H->server);
860    }
861
862    if (status == PGRES_COPY_OUT && pgsql_result) {
863        PQclear(pgsql_result);
864                array_init(return_value);
865
866        while (1) {
867            char *csv = NULL;
868            int ret = PQgetCopyData(H->server, &csv, 0);
869            if (ret == -1) {
870                break; /* copy done */
871            } else if (ret > 0) {
872                add_next_index_stringl(return_value, csv, ret, 1);
873                PQfreemem(csv);
874            } else {
875                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
876                PDO_HANDLE_DBH_ERR();
877                RETURN_FALSE;
878            }
879        }
880
881        while ((pgsql_result = PQgetResult(H->server))) {
882            PQclear(pgsql_result);
883        }
884    } else {
885        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, pdo_pgsql_sqlstate(pgsql_result));
886        PQclear(pgsql_result);
887        PDO_HANDLE_DBH_ERR();
888        RETURN_FALSE;
889    }
890}
891/* }}} */
892
893
894/* {{{ proto string PDO::pgsqlLOBCreate()
895   Creates a new large object, returning its identifier.  Must be called inside a transaction. */
896static PHP_METHOD(PDO, pgsqlLOBCreate)
897{
898    pdo_dbh_t *dbh;
899    pdo_pgsql_db_handle *H;
900    Oid lfd;
901
902    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
903    PDO_CONSTRUCT_CHECK;
904    PDO_DBH_CLEAR_ERR();
905
906    H = (pdo_pgsql_db_handle *)dbh->driver_data;
907    lfd = lo_creat(H->server, INV_READ|INV_WRITE);
908
909    if (lfd != InvalidOid) {
910        char *buf;
911        spprintf(&buf, 0, "%lu", (long) lfd);
912        RETURN_STRING(buf, 0);
913    }
914
915    pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
916    PDO_HANDLE_DBH_ERR();
917    RETURN_FALSE;
918}
919/* }}} */
920
921/* {{{ proto resource PDO::pgsqlLOBOpen(string oid [, string mode = 'rb'])
922   Opens an existing large object stream.  Must be called inside a transaction. */
923static PHP_METHOD(PDO, pgsqlLOBOpen)
924{
925    pdo_dbh_t *dbh;
926    pdo_pgsql_db_handle *H;
927    Oid oid;
928    int lfd;
929    char *oidstr;
930    int oidstrlen;
931    char *modestr = "rb";
932    int modestrlen;
933    int mode = INV_READ;
934    char *end_ptr;
935
936    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
937                &oidstr, &oidstrlen, &modestr, &modestrlen)) {
938        RETURN_FALSE;
939    }
940
941    oid = (Oid)strtoul(oidstr, &end_ptr, 10);
942    if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
943        RETURN_FALSE;
944    }
945
946    if (strpbrk(modestr, "+w")) {
947        mode = INV_READ|INV_WRITE;
948    }
949
950    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
951    PDO_CONSTRUCT_CHECK;
952    PDO_DBH_CLEAR_ERR();
953
954    H = (pdo_pgsql_db_handle *)dbh->driver_data;
955
956    lfd = lo_open(H->server, oid, mode);
957
958    if (lfd >= 0) {
959        php_stream *stream = pdo_pgsql_create_lob_stream(dbh, lfd, oid TSRMLS_CC);
960        if (stream) {
961            php_stream_to_zval(stream, return_value);
962            return;
963        }
964    } else {
965        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
966    }
967
968    PDO_HANDLE_DBH_ERR();
969    RETURN_FALSE;
970}
971/* }}} */
972
973/* {{{ proto bool PDO::pgsqlLOBUnlink(string oid)
974   Deletes the large object identified by oid.  Must be called inside a transaction. */
975static PHP_METHOD(PDO, pgsqlLOBUnlink)
976{
977    pdo_dbh_t *dbh;
978    pdo_pgsql_db_handle *H;
979    Oid oid;
980    char *oidstr, *end_ptr;
981    int oidlen;
982
983    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
984                &oidstr, &oidlen)) {
985        RETURN_FALSE;
986    }
987
988    oid = (Oid)strtoul(oidstr, &end_ptr, 10);
989    if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
990        RETURN_FALSE;
991    }
992
993    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
994    PDO_CONSTRUCT_CHECK;
995    PDO_DBH_CLEAR_ERR();
996
997    H = (pdo_pgsql_db_handle *)dbh->driver_data;
998
999    if (1 == lo_unlink(H->server, oid)) {
1000        RETURN_TRUE;
1001    }
1002
1003    pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
1004    PDO_HANDLE_DBH_ERR();
1005    RETURN_FALSE;
1006}
1007/* }}} */
1008
1009/* {{{ proto mixed PDO::pgsqlGetNotify([ int $result_type = PDO::FETCH_USE_DEFAULT] [, int $ms_timeout = 0 ]])
1010   Get asyncronous notification */
1011static PHP_METHOD(PDO, pgsqlGetNotify)
1012{
1013    pdo_dbh_t *dbh;
1014    pdo_pgsql_db_handle *H;
1015    long result_type = PDO_FETCH_USE_DEFAULT;
1016    long ms_timeout = 0;
1017    PGnotify *pgsql_notify;
1018
1019    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|ll",
1020                &result_type, &ms_timeout)) {
1021        RETURN_FALSE;
1022    }
1023
1024    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
1025    PDO_CONSTRUCT_CHECK;
1026
1027    if (result_type == PDO_FETCH_USE_DEFAULT) {
1028        result_type = dbh->default_fetch_type;
1029    }
1030
1031    if (result_type != PDO_FETCH_BOTH && result_type != PDO_FETCH_ASSOC && result_type != PDO_FETCH_NUM) {
1032        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid result type");
1033        RETURN_FALSE;
1034    }
1035
1036    if (ms_timeout < 0) {
1037        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid timeout");
1038        RETURN_FALSE;
1039    }
1040
1041    H = (pdo_pgsql_db_handle *)dbh->driver_data;
1042
1043    PQconsumeInput(H->server);
1044    pgsql_notify = PQnotifies(H->server);
1045
1046    if (ms_timeout && !pgsql_notify) {
1047        php_pollfd_for_ms(PQsocket(H->server), PHP_POLLREADABLE, ms_timeout);
1048
1049        PQconsumeInput(H->server);
1050        pgsql_notify = PQnotifies(H->server);
1051    }
1052
1053    if (!pgsql_notify) {
1054        RETURN_FALSE;
1055    }
1056
1057    array_init(return_value);
1058    if (result_type == PDO_FETCH_NUM || result_type == PDO_FETCH_BOTH) {
1059        add_index_string(return_value, 0, pgsql_notify->relname, 1);
1060        add_index_long(return_value, 1, pgsql_notify->be_pid);
1061        if (pgsql_notify->extra && pgsql_notify->extra[0]) {
1062            add_index_string(return_value, 2, pgsql_notify->extra, 1);
1063        }
1064    }
1065    if (result_type == PDO_FETCH_ASSOC || result_type == PDO_FETCH_BOTH) {
1066        add_assoc_string(return_value, "message", pgsql_notify->relname, 1);
1067        add_assoc_long(return_value, "pid", pgsql_notify->be_pid);
1068        if (pgsql_notify->extra && pgsql_notify->extra[0]) {
1069            add_assoc_string(return_value, "payload", pgsql_notify->extra, 1);
1070        }
1071    }
1072
1073    PQfreemem(pgsql_notify);
1074}
1075/* }}} */
1076
1077/* {{{ proto int PDO::pgsqlGetPid()
1078   Get backend(server) pid */
1079static PHP_METHOD(PDO, pgsqlGetPid)
1080{
1081    pdo_dbh_t *dbh;
1082    pdo_pgsql_db_handle *H;
1083
1084    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
1085    PDO_CONSTRUCT_CHECK;
1086
1087    H = (pdo_pgsql_db_handle *)dbh->driver_data;
1088
1089    RETURN_LONG(PQbackendPID(H->server));
1090}
1091/* }}} */
1092
1093
1094static const zend_function_entry dbh_methods[] = {
1095    PHP_ME(PDO, pgsqlLOBCreate, NULL, ZEND_ACC_PUBLIC)
1096    PHP_ME(PDO, pgsqlLOBOpen, NULL, ZEND_ACC_PUBLIC)
1097    PHP_ME(PDO, pgsqlLOBUnlink, NULL, ZEND_ACC_PUBLIC)
1098    PHP_ME(PDO, pgsqlCopyFromArray, NULL, ZEND_ACC_PUBLIC)
1099    PHP_ME(PDO, pgsqlCopyFromFile, NULL, ZEND_ACC_PUBLIC)
1100    PHP_ME(PDO, pgsqlCopyToArray, NULL, ZEND_ACC_PUBLIC)
1101    PHP_ME(PDO, pgsqlCopyToFile, NULL, ZEND_ACC_PUBLIC)
1102        PHP_ME(PDO, pgsqlGetNotify, NULL, ZEND_ACC_PUBLIC)
1103        PHP_ME(PDO, pgsqlGetPid, NULL, ZEND_ACC_PUBLIC)
1104    PHP_FE_END
1105};
1106
1107static const zend_function_entry *pdo_pgsql_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)
1108{
1109    switch (kind) {
1110        case PDO_DBH_DRIVER_METHOD_KIND_DBH:
1111            return dbh_methods;
1112        default:
1113            return NULL;
1114    }
1115}
1116
1117static int pdo_pgsql_set_attr(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)
1118{
1119    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
1120
1121    switch (attr) {
1122        case PDO_ATTR_EMULATE_PREPARES:
1123            H->emulate_prepares = Z_LVAL_P(val);
1124            return 1;
1125        case PDO_PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT:
1126            php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT is deprecated, use PDO::ATTR_EMULATE_PREPARES instead");
1127            H->disable_native_prepares = Z_LVAL_P(val);
1128            return 1;
1129        case PDO_PGSQL_ATTR_DISABLE_PREPARES:
1130            H->disable_prepares = Z_LVAL_P(val);
1131            return 1;
1132        default:
1133            return 0;
1134    }
1135}
1136
1137static struct pdo_dbh_methods pgsql_methods = {
1138    pgsql_handle_closer,
1139    pgsql_handle_preparer,
1140    pgsql_handle_doer,
1141    pgsql_handle_quoter,
1142    pgsql_handle_begin,
1143    pgsql_handle_commit,
1144    pgsql_handle_rollback,
1145    pdo_pgsql_set_attr,
1146    pdo_pgsql_last_insert_id,
1147    pdo_pgsql_fetch_error_func,
1148    pdo_pgsql_get_attribute,
1149    pdo_pgsql_check_liveness,   /* check_liveness */
1150    pdo_pgsql_get_driver_methods,  /* get_driver_methods */
1151    NULL,
1152    pgsql_handle_in_transaction,
1153};
1154
1155static int pdo_pgsql_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC) /* {{{ */
1156{
1157    pdo_pgsql_db_handle *H;
1158    int ret = 0;
1159    char *conn_str, *p, *e;
1160    char *tmp_pass;
1161    long connect_timeout = 30;
1162
1163    H = pecalloc(1, sizeof(pdo_pgsql_db_handle), dbh->is_persistent);
1164    dbh->driver_data = H;
1165
1166    H->einfo.errcode = 0;
1167    H->einfo.errmsg = NULL;
1168
1169    /* PostgreSQL wants params in the connect string to be separated by spaces,
1170     * if the PDO standard semicolons are used, we convert them to spaces
1171     */
1172    e = (char *) dbh->data_source + strlen(dbh->data_source);
1173    p = (char *) dbh->data_source;
1174    while ((p = memchr(p, ';', (e - p)))) {
1175        *p = ' ';
1176    }
1177
1178    if (driver_options) {
1179        connect_timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30 TSRMLS_CC);
1180    }
1181
1182    if (dbh->password) {
1183        if (dbh->password[0] != '\'' && dbh->password[strlen(dbh->password) - 1] != '\'') {
1184            char *pwd = dbh->password;
1185            int pos = 1;
1186
1187            tmp_pass = safe_emalloc(2, strlen(dbh->password), 3);
1188            tmp_pass[0] = '\'';
1189
1190            while (*pwd != '\0') {
1191                if (*pwd == '\\' || *pwd == '\'') {
1192                    tmp_pass[pos++] = '\\';
1193                }
1194
1195                tmp_pass[pos++] = *pwd++;
1196            }
1197
1198            tmp_pass[pos++] = '\'';
1199            tmp_pass[pos] = '\0';
1200        } else {
1201            tmp_pass = dbh->password;
1202        }
1203    }
1204
1205    /* support both full connection string & connection string + login and/or password */
1206    if (dbh->username && dbh->password) {
1207        spprintf(&conn_str, 0, "%s user=%s password=%s connect_timeout=%ld", dbh->data_source, dbh->username, tmp_pass, connect_timeout);
1208    } else if (dbh->username) {
1209        spprintf(&conn_str, 0, "%s user=%s connect_timeout=%ld", dbh->data_source, dbh->username, connect_timeout);
1210    } else if (dbh->password) {
1211        spprintf(&conn_str, 0, "%s password=%s connect_timeout=%ld", dbh->data_source, tmp_pass, connect_timeout);
1212    } else {
1213        spprintf(&conn_str, 0, "%s connect_timeout=%ld", (char *) dbh->data_source, connect_timeout);
1214    }
1215
1216    H->server = PQconnectdb(conn_str);
1217    if (dbh->password && tmp_pass != dbh->password) {
1218        efree(tmp_pass);
1219    }
1220
1221    efree(conn_str);
1222
1223    if (PQstatus(H->server) != CONNECTION_OK) {
1224        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, PHP_PDO_PGSQL_CONNECTION_FAILURE_SQLSTATE);
1225        goto cleanup;
1226    }
1227
1228    PQsetNoticeProcessor(H->server, (void(*)(void*,const char*))_pdo_pgsql_notice, (void *)&dbh);
1229
1230    H->attached = 1;
1231    H->pgoid = -1;
1232
1233    dbh->methods = &pgsql_methods;
1234    dbh->alloc_own_columns = 1;
1235    dbh->max_escaped_char_length = 2;
1236
1237    ret = 1;
1238
1239cleanup:
1240    dbh->methods = &pgsql_methods;
1241    if (!ret) {
1242        pgsql_handle_closer(dbh TSRMLS_CC);
1243    }
1244
1245    return ret;
1246}
1247/* }}} */
1248
1249pdo_driver_t pdo_pgsql_driver = {
1250    PDO_DRIVER_HEADER(pgsql),
1251    pdo_pgsql_handle_factory
1252};
1253
1254/*
1255 * Local variables:
1256 * tab-width: 4
1257 * c-basic-offset: 4
1258 * End:
1259 * vim600: noet sw=4 ts=4 fdm=marker
1260 * vim<600: noet sw=4 ts=4
1261 */
1262