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 "pdo/php_pdo.h"
31#include "pdo/php_pdo_driver.h"
32#include "ext/standard/file.h"
33
34#undef PACKAGE_BUGREPORT
35#undef PACKAGE_NAME
36#undef PACKAGE_STRING
37#undef PACKAGE_TARNAME
38#undef PACKAGE_VERSION
39#include "pg_config.h" /* needed for PG_VERSION */
40#include "php_pdo_pgsql.h"
41#include "php_pdo_pgsql_int.h"
42#include "zend_exceptions.h"
43
44static char * _pdo_pgsql_trim_message(const char *message, int persistent)
45{
46    register int i = strlen(message)-1;
47    char *tmp;
48
49    if (i>1 && (message[i-1] == '\r' || message[i-1] == '\n') && message[i] == '.') {
50        --i;
51    }
52    while (i>0 && (message[i] == '\r' || message[i] == '\n')) {
53        --i;
54    }
55    ++i;
56    tmp = pemalloc(i + 1, persistent);
57    memcpy(tmp, message, i);
58    tmp[i] = '\0';
59
60    return tmp;
61}
62
63int _pdo_pgsql_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, int errcode, const char *sqlstate, const char *file, int line TSRMLS_DC) /* {{{ */
64{
65    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
66    pdo_error_type *pdo_err = stmt ? &stmt->error_code : &dbh->error_code;
67    pdo_pgsql_error_info *einfo = &H->einfo;
68    char *errmsg = PQerrorMessage(H->server);
69
70    einfo->errcode = errcode;
71    einfo->file = file;
72    einfo->line = line;
73
74    if (einfo->errmsg) {
75        pefree(einfo->errmsg, dbh->is_persistent);
76        einfo->errmsg = NULL;
77    }
78
79    if (sqlstate == NULL || strlen(sqlstate) >= sizeof(pdo_error_type)) {
80        strcpy(*pdo_err, "HY000");
81    }
82    else {
83        strcpy(*pdo_err, sqlstate);
84    }
85
86    if (errmsg) {
87        einfo->errmsg = _pdo_pgsql_trim_message(errmsg, dbh->is_persistent);
88    }
89
90    if (!dbh->methods) {
91        zend_throw_exception_ex(php_pdo_get_exception(), einfo->errcode TSRMLS_CC, "SQLSTATE[%s] [%d] %s",
92                *pdo_err, einfo->errcode, einfo->errmsg);
93    }
94
95    return errcode;
96}
97/* }}} */
98
99static void _pdo_pgsql_notice(pdo_dbh_t *dbh, const char *message) /* {{{ */
100{
101/*  pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data; */
102}
103/* }}} */
104
105static int pdo_pgsql_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info TSRMLS_DC) /* {{{ */
106{
107    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
108    pdo_pgsql_error_info *einfo = &H->einfo;
109
110    if (einfo->errcode) {
111        add_next_index_long(info, einfo->errcode);
112        add_next_index_string(info, einfo->errmsg, 1);
113    }
114
115    return 1;
116}
117/* }}} */
118
119/* {{{ pdo_pgsql_create_lob_stream */
120static size_t pgsql_lob_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC)
121{
122    struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
123    return lo_write(self->conn, self->lfd, (char*)buf, count);
124}
125
126static size_t pgsql_lob_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
127{
128    struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
129    return lo_read(self->conn, self->lfd, buf, count);
130}
131
132static int pgsql_lob_close(php_stream *stream, int close_handle TSRMLS_DC)
133{
134    struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
135    pdo_dbh_t *dbh = self->dbh;
136
137    if (close_handle) {
138        lo_close(self->conn, self->lfd);
139    }
140    efree(self);
141    php_pdo_dbh_delref(dbh TSRMLS_CC);
142    return 0;
143}
144
145static int pgsql_lob_flush(php_stream *stream TSRMLS_DC)
146{
147    return 0;
148}
149
150static int pgsql_lob_seek(php_stream *stream, off_t offset, int whence,
151        off_t *newoffset TSRMLS_DC)
152{
153    struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stream->abstract;
154    int pos = lo_lseek(self->conn, self->lfd, offset, whence);
155    *newoffset = pos;
156    return pos >= 0 ? 0 : -1;
157}
158
159php_stream_ops pdo_pgsql_lob_stream_ops = {
160    pgsql_lob_write,
161    pgsql_lob_read,
162    pgsql_lob_close,
163    pgsql_lob_flush,
164    "pdo_pgsql lob stream",
165    pgsql_lob_seek,
166    NULL,
167    NULL,
168    NULL
169};
170
171php_stream *pdo_pgsql_create_lob_stream(pdo_dbh_t *dbh, int lfd, Oid oid TSRMLS_DC)
172{
173    php_stream *stm;
174    struct pdo_pgsql_lob_self *self = ecalloc(1, sizeof(*self));
175    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
176
177    self->dbh = dbh;
178    self->lfd = lfd;
179    self->oid = oid;
180    self->conn = H->server;
181
182    stm = php_stream_alloc(&pdo_pgsql_lob_stream_ops, self, 0, "r+b");
183
184    if (stm) {
185        php_pdo_dbh_addref(dbh TSRMLS_CC);
186        return stm;
187    }
188
189    efree(self);
190    return NULL;
191}
192/* }}} */
193
194static int pgsql_handle_closer(pdo_dbh_t *dbh TSRMLS_DC) /* {{{ */
195{
196    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
197    if (H) {
198        if (H->server) {
199            PQfinish(H->server);
200            H->server = NULL;
201        }
202        if (H->einfo.errmsg) {
203            pefree(H->einfo.errmsg, dbh->is_persistent);
204            H->einfo.errmsg = NULL;
205        }
206        pefree(H, dbh->is_persistent);
207        dbh->driver_data = NULL;
208    }
209    return 0;
210}
211/* }}} */
212
213static int pgsql_handle_preparer(pdo_dbh_t *dbh, const char *sql, long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
214{
215    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
216    pdo_pgsql_stmt *S = ecalloc(1, sizeof(pdo_pgsql_stmt));
217    int scrollable;
218#if HAVE_PQPREPARE
219    int ret;
220    char *nsql = NULL;
221    int nsql_len = 0;
222    int emulate = 0;
223#endif
224
225    S->H = H;
226    stmt->driver_data = S;
227    stmt->methods = &pgsql_stmt_methods;
228
229    scrollable = pdo_attr_lval(driver_options, PDO_ATTR_CURSOR,
230        PDO_CURSOR_FWDONLY TSRMLS_CC) == PDO_CURSOR_SCROLL;
231
232    if (scrollable) {
233        if (S->cursor_name) {
234            efree(S->cursor_name);
235        }
236        spprintf(&S->cursor_name, 0, "pdo_crsr_%08x", ++H->stmt_counter);
237#if HAVE_PQPREPARE
238        emulate = 1;
239#endif
240    }
241
242#if HAVE_PQPREPARE
243    else if (driver_options) {
244        if (pdo_attr_lval(driver_options, PDO_PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT, H->disable_native_prepares TSRMLS_CC) == 1 ||
245            pdo_attr_lval(driver_options, PDO_ATTR_EMULATE_PREPARES, H->emulate_prepares TSRMLS_CC) == 1) {
246            emulate = 1;
247        }
248    } else {
249        emulate = H->disable_native_prepares || H->emulate_prepares;
250    }
251
252    if (!emulate && PQprotocolVersion(H->server) > 2) {
253        stmt->supports_placeholders = PDO_PLACEHOLDER_NAMED;
254        stmt->named_rewrite_template = "$%d";
255        ret = pdo_parse_params(stmt, (char*)sql, sql_len, &nsql, &nsql_len TSRMLS_CC);
256
257        if (ret == 1) {
258            /* query was re-written */
259            sql = nsql;
260        } else if (ret == -1) {
261            /* couldn't grok it */
262            strcpy(dbh->error_code, stmt->error_code);
263            return 0;
264        }
265
266        spprintf(&S->stmt_name, 0, "pdo_stmt_%08x", ++H->stmt_counter);
267        /* that's all for now; we'll defer the actual prepare until the first execute call */
268
269        if (nsql) {
270            S->query = nsql;
271        } else {
272            S->query = estrdup(sql);
273        }
274
275        return 1;
276    }
277#endif
278
279    stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;
280    return 1;
281}
282
283static long pgsql_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)
284{
285    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
286    PGresult *res;
287    long ret = 1;
288    ExecStatusType qs;
289
290    if (!(res = PQexec(H->server, sql))) {
291        /* fatal error */
292        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, NULL);
293        return -1;
294    }
295    qs = PQresultStatus(res);
296    if (qs != PGRES_COMMAND_OK && qs != PGRES_TUPLES_OK) {
297        pdo_pgsql_error(dbh, qs, pdo_pgsql_sqlstate(res));
298        PQclear(res);
299        return -1;
300    }
301    H->pgoid = PQoidValue(res);
302    ret = (qs == PGRES_COMMAND_OK) ? atol(PQcmdTuples(res)) : 0L;
303    PQclear(res);
304
305    return ret;
306}
307
308static int pgsql_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, char **quoted, int *quotedlen, enum pdo_param_type paramtype TSRMLS_DC)
309{
310    unsigned char *escaped;
311    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
312    size_t tmp_len;
313
314    switch (paramtype) {
315        case PDO_PARAM_LOB:
316            /* escapedlen returned by PQescapeBytea() accounts for trailing 0 */
317#ifdef HAVE_PQESCAPE_BYTEA_CONN
318            escaped = PQescapeByteaConn(H->server, (unsigned char *)unquoted, (size_t)unquotedlen, &tmp_len);
319#else
320            escaped = PQescapeBytea((unsigned char *)unquoted, (size_t)unquotedlen, &tmp_len);
321#endif
322            *quotedlen = (int)tmp_len + 1;
323            *quoted = emalloc(*quotedlen + 1);
324            memcpy((*quoted)+1, escaped, *quotedlen-2);
325            (*quoted)[0] = '\'';
326            (*quoted)[*quotedlen-1] = '\'';
327            (*quoted)[*quotedlen] = '\0';
328            PQfreemem(escaped);
329            break;
330        default:
331            *quoted = safe_emalloc(2, unquotedlen, 3);
332            (*quoted)[0] = '\'';
333#ifndef HAVE_PQESCAPE_CONN
334            *quotedlen = PQescapeString(*quoted + 1, unquoted, (size_t)unquotedlen);
335#else
336            *quotedlen = PQescapeStringConn(H->server, *quoted + 1, unquoted, (size_t)unquotedlen, NULL);
337#endif
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
547    if (pg_fields) {
548        spprintf(&query, 0, "COPY %s (%s) FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
549    } else {
550        spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
551    }
552
553    /* Obtain db Handle */
554    H = (pdo_pgsql_db_handle *)dbh->driver_data;
555
556    while ((pgsql_result = PQgetResult(H->server))) {
557        PQclear(pgsql_result);
558    }
559    pgsql_result = PQexec(H->server, query);
560
561    efree(query);
562    query = NULL;
563
564    if (pgsql_result) {
565        status = PQresultStatus(pgsql_result);
566    } else {
567        status = (ExecStatusType) PQstatus(H->server);
568    }
569
570    if (status == PGRES_COPY_IN && pgsql_result) {
571        int command_failed = 0;
572        int buffer_len = 0;
573        zval **tmp;
574        HashPosition pos;
575
576        PQclear(pgsql_result);
577        zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(pg_rows), &pos);
578        while (zend_hash_get_current_data_ex(Z_ARRVAL_P(pg_rows), (void **) &tmp, &pos) == SUCCESS) {
579            int query_len;
580            convert_to_string_ex(tmp);
581
582            if (buffer_len < Z_STRLEN_PP(tmp)) {
583                buffer_len = Z_STRLEN_PP(tmp);
584                query = erealloc(query, buffer_len + 2); /* room for \n\0 */
585            }
586            memcpy(query, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));
587            query_len = Z_STRLEN_PP(tmp);
588            if (query[query_len - 1] != '\n') {
589                query[query_len++] = '\n';
590            }
591            query[query_len] = '\0';
592            if (PQputCopyData(H->server, query, query_len) != 1) {
593                            efree(query);
594                            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "copy failed");
595                            RETURN_FALSE;
596                    }
597            zend_hash_move_forward_ex(Z_ARRVAL_P(pg_rows), &pos);
598                }
599        if (query) {
600            efree(query);
601        }
602
603        if (PQputCopyEnd(H->server, NULL) != 1) {
604            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "putcopyend failed");
605            RETURN_FALSE;
606        }
607
608        while ((pgsql_result = PQgetResult(H->server))) {
609            if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
610                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Copy command failed");
611                command_failed = 1;
612            }
613            PQclear(pgsql_result);
614        }
615
616        RETURN_BOOL(!command_failed);
617    } else {
618        PQclear(pgsql_result);
619        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Copy command failed");
620        RETURN_FALSE;
621    }
622}
623/* }}} */
624
625/* {{{ proto string PDO::pgsqlCopyFromFile(string $table_name , string $filename [, string $delimiter [, string $null_as ] [, string $fields])
626   Returns true if the copy worked fine or false if error */
627static PHP_METHOD(PDO, pgsqlCopyFromFile)
628{
629    pdo_dbh_t *dbh;
630    pdo_pgsql_db_handle *H;
631
632    char *table_name, *filename, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
633    int  table_name_len, filename_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
634    char *query;
635    PGresult *pgsql_result;
636    ExecStatusType status;
637    php_stream *stream;
638
639    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp|sss",
640                &table_name, &table_name_len, &filename, &filename_len,
641                &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
642        return;
643    }
644
645    /* Obtain db Handler */
646    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
647    PDO_CONSTRUCT_CHECK;
648
649    stream = php_stream_open_wrapper_ex(filename, "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, FG(default_context));
650    if (!stream) {
651        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Unable to open the file");
652        RETURN_FALSE;
653    }
654
655    if (pg_fields) {
656        spprintf(&query, 0, "COPY %s (%s) FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
657    } else {
658        spprintf(&query, 0, "COPY %s FROM STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
659    }
660
661    H = (pdo_pgsql_db_handle *)dbh->driver_data;
662
663    while ((pgsql_result = PQgetResult(H->server))) {
664        PQclear(pgsql_result);
665    }
666    pgsql_result = PQexec(H->server, query);
667
668    efree(query);
669
670    if (pgsql_result) {
671        status = PQresultStatus(pgsql_result);
672    } else {
673        status = (ExecStatusType) PQstatus(H->server);
674    }
675
676    if (status == PGRES_COPY_IN && pgsql_result) {
677        char *buf;
678        int command_failed = 0;
679        size_t line_len = 0;
680
681        PQclear(pgsql_result);
682        while ((buf = php_stream_get_line(stream, NULL, 0, &line_len)) != NULL) {
683            if (PQputCopyData(H->server, buf, line_len) != 1) {
684                            efree(buf);
685                            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "copy failed");
686                php_stream_close(stream);
687                RETURN_FALSE;
688            }
689            efree(buf);
690        }
691        php_stream_close(stream);
692
693        if (PQputCopyEnd(H->server, NULL) != 1) {
694            pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "putcopyend failed");
695            RETURN_FALSE;
696        }
697
698        while ((pgsql_result = PQgetResult(H->server))) {
699            if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) {
700                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Copy command failed");
701                command_failed = 1;
702            }
703            PQclear(pgsql_result);
704        }
705
706        RETURN_BOOL(!command_failed);
707    } else {
708        PQclear(pgsql_result);
709        php_stream_close(stream);
710        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Copy command failed");
711        RETURN_FALSE;
712    }
713}
714/* }}} */
715
716
717/* {{{ proto string PDO::pgsqlCopyToFile(string $table_name , $filename, [string $delimiter [, string $null_as [, string $fields]]])
718   Returns true if the copy worked fine or false if error */
719static PHP_METHOD(PDO, pgsqlCopyToFile)
720{
721    pdo_dbh_t *dbh;
722    pdo_pgsql_db_handle *H;
723
724    char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL, *filename = NULL;
725    int table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len, filename_len;
726    char *query;
727
728    PGresult *pgsql_result;
729    ExecStatusType status;
730
731    php_stream *stream;
732
733    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp|sss",
734                    &table_name, &table_name_len, &filename, &filename_len,
735                    &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
736        return;
737    }
738
739    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
740    PDO_CONSTRUCT_CHECK;
741
742    H = (pdo_pgsql_db_handle *)dbh->driver_data;
743
744    stream = php_stream_open_wrapper_ex(filename, "wb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, FG(default_context));
745    if (!stream) {
746        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Unable to open the file for writing");
747        RETURN_FALSE;
748    }
749
750    while ((pgsql_result = PQgetResult(H->server))) {
751        PQclear(pgsql_result);
752    }
753
754    if (pg_fields) {
755        spprintf(&query, 0, "COPY %s (%s) TO STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
756    } else {
757        spprintf(&query, 0, "COPY %s TO STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
758    }
759    pgsql_result = PQexec(H->server, query);
760    efree(query);
761
762    if (pgsql_result) {
763        status = PQresultStatus(pgsql_result);
764    } else {
765        status = (ExecStatusType) PQstatus(H->server);
766    }
767
768    if (status == PGRES_COPY_OUT && pgsql_result) {
769        PQclear(pgsql_result);
770        while (1) {
771            char *csv = NULL;
772            int ret = PQgetCopyData(H->server, &csv, 0);
773
774            if (ret == -1) {
775                break; /* done */
776            } else if (ret > 0) {
777                if (php_stream_write(stream, csv, ret) != ret) {
778                    pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Unable to write to file");
779                    PQfreemem(csv);
780                    php_stream_close(stream);
781                    RETURN_FALSE;
782                } else {
783                    PQfreemem(csv);
784                }
785            } else {
786                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Copy command failed: getline failed");
787                php_stream_close(stream);
788                RETURN_FALSE;
789            }
790        }
791        php_stream_close(stream);
792
793        while ((pgsql_result = PQgetResult(H->server))) {
794            PQclear(pgsql_result);
795        }
796        RETURN_TRUE;
797    } else {
798        php_stream_close(stream);
799        PQclear(pgsql_result);
800        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Copy command failed");
801        RETURN_FALSE;
802    }
803}
804/* }}} */
805
806/* {{{ proto string PDO::pgsqlCopyToArray(string $table_name , [string $delimiter [, string $null_as [, string $fields]]])
807   Returns true if the copy worked fine or false if error */
808static PHP_METHOD(PDO, pgsqlCopyToArray)
809{
810    pdo_dbh_t *dbh;
811    pdo_pgsql_db_handle *H;
812
813    char *table_name, *pg_delim = NULL, *pg_null_as = NULL, *pg_fields = NULL;
814    int table_name_len, pg_delim_len = 0, pg_null_as_len = 0, pg_fields_len;
815    char *query;
816
817    PGresult *pgsql_result;
818    ExecStatusType status;
819
820    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|sss",
821        &table_name, &table_name_len,
822        &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len, &pg_fields, &pg_fields_len) == FAILURE) {
823        return;
824    }
825
826    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
827    PDO_CONSTRUCT_CHECK;
828
829    H = (pdo_pgsql_db_handle *)dbh->driver_data;
830
831    while ((pgsql_result = PQgetResult(H->server))) {
832        PQclear(pgsql_result);
833    }
834
835    if (pg_fields) {
836        spprintf(&query, 0, "COPY %s (%s) TO STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, pg_fields, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
837    } else {
838        spprintf(&query, 0, "COPY %s TO STDIN DELIMITERS E'%c' WITH NULL AS E'%s'", table_name, (pg_delim_len ? *pg_delim : '\t'), (pg_null_as_len ? pg_null_as : "\\\\N"));
839    }
840    pgsql_result = PQexec(H->server, query);
841    efree(query);
842
843    if (pgsql_result) {
844        status = PQresultStatus(pgsql_result);
845    } else {
846        status = (ExecStatusType) PQstatus(H->server);
847    }
848
849    if (status == PGRES_COPY_OUT && pgsql_result) {
850        PQclear(pgsql_result);
851                array_init(return_value);
852
853        while (1) {
854            char *csv = NULL;
855            int ret = PQgetCopyData(H->server, &csv, 0);
856            if (ret == -1) {
857                break; /* copy done */
858            } else if (ret > 0) {
859                add_next_index_stringl(return_value, csv, ret, 1);
860                PQfreemem(csv);
861            } else {
862                pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Copy command failed: getline failed");
863                RETURN_FALSE;
864            }
865        }
866
867        while ((pgsql_result = PQgetResult(H->server))) {
868            PQclear(pgsql_result);
869        }
870    } else {
871        PQclear(pgsql_result);
872        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "Copy command failed");
873        RETURN_FALSE;
874    }
875}
876/* }}} */
877
878
879/* {{{ proto string PDO::pgsqlLOBCreate()
880   Creates a new large object, returning its identifier.  Must be called inside a transaction. */
881static PHP_METHOD(PDO, pgsqlLOBCreate)
882{
883    pdo_dbh_t *dbh;
884    pdo_pgsql_db_handle *H;
885    Oid lfd;
886
887    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
888    PDO_CONSTRUCT_CHECK;
889
890    H = (pdo_pgsql_db_handle *)dbh->driver_data;
891    lfd = lo_creat(H->server, INV_READ|INV_WRITE);
892
893    if (lfd != InvalidOid) {
894        char *buf;
895        spprintf(&buf, 0, "%lu", (long) lfd);
896        RETURN_STRING(buf, 0);
897    }
898
899    pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "HY000");
900    RETURN_FALSE;
901}
902/* }}} */
903
904/* {{{ proto resource PDO::pgsqlLOBOpen(string oid [, string mode = 'rb'])
905   Opens an existing large object stream.  Must be called inside a transaction. */
906static PHP_METHOD(PDO, pgsqlLOBOpen)
907{
908    pdo_dbh_t *dbh;
909    pdo_pgsql_db_handle *H;
910    Oid oid;
911    int lfd;
912    char *oidstr;
913    int oidstrlen;
914    char *modestr = "rb";
915    int modestrlen;
916    int mode = INV_READ;
917    char *end_ptr;
918
919    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
920                &oidstr, &oidstrlen, &modestr, &modestrlen)) {
921        RETURN_FALSE;
922    }
923
924    oid = (Oid)strtoul(oidstr, &end_ptr, 10);
925    if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
926        RETURN_FALSE;
927    }
928
929    if (strpbrk(modestr, "+w")) {
930        mode = INV_READ|INV_WRITE;
931    }
932
933    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
934    PDO_CONSTRUCT_CHECK;
935
936    H = (pdo_pgsql_db_handle *)dbh->driver_data;
937
938    lfd = lo_open(H->server, oid, mode);
939
940    if (lfd >= 0) {
941        php_stream *stream = pdo_pgsql_create_lob_stream(dbh, lfd, oid TSRMLS_CC);
942        if (stream) {
943            php_stream_to_zval(stream, return_value);
944            return;
945        }
946    } else {
947        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "HY000");
948    }
949    RETURN_FALSE;
950}
951/* }}} */
952
953/* {{{ proto bool PDO::pgsqlLOBUnlink(string oid)
954   Deletes the large object identified by oid.  Must be called inside a transaction. */
955static PHP_METHOD(PDO, pgsqlLOBUnlink)
956{
957    pdo_dbh_t *dbh;
958    pdo_pgsql_db_handle *H;
959    Oid oid;
960    char *oidstr, *end_ptr;
961    int oidlen;
962
963    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
964                &oidstr, &oidlen)) {
965        RETURN_FALSE;
966    }
967
968    oid = (Oid)strtoul(oidstr, &end_ptr, 10);
969    if (oid == 0 && (errno == ERANGE || errno == EINVAL)) {
970        RETURN_FALSE;
971    }
972
973    dbh = zend_object_store_get_object(getThis() TSRMLS_CC);
974    PDO_CONSTRUCT_CHECK;
975
976    H = (pdo_pgsql_db_handle *)dbh->driver_data;
977
978    if (1 == lo_unlink(H->server, oid)) {
979        RETURN_TRUE;
980    }
981    pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, "HY000");
982    RETURN_FALSE;
983}
984/* }}} */
985
986
987static const zend_function_entry dbh_methods[] = {
988    PHP_ME(PDO, pgsqlLOBCreate, NULL, ZEND_ACC_PUBLIC)
989    PHP_ME(PDO, pgsqlLOBOpen, NULL, ZEND_ACC_PUBLIC)
990    PHP_ME(PDO, pgsqlLOBUnlink, NULL, ZEND_ACC_PUBLIC)
991    PHP_ME(PDO, pgsqlCopyFromArray, NULL, ZEND_ACC_PUBLIC)
992    PHP_ME(PDO, pgsqlCopyFromFile, NULL, ZEND_ACC_PUBLIC)
993    PHP_ME(PDO, pgsqlCopyToArray, NULL, ZEND_ACC_PUBLIC)
994    PHP_ME(PDO, pgsqlCopyToFile, NULL, ZEND_ACC_PUBLIC)
995    PHP_FE_END
996};
997
998static const zend_function_entry *pdo_pgsql_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)
999{
1000    switch (kind) {
1001        case PDO_DBH_DRIVER_METHOD_KIND_DBH:
1002            return dbh_methods;
1003        default:
1004            return NULL;
1005    }
1006}
1007
1008static int pdo_pgsql_set_attr(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)
1009{
1010    pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
1011
1012    switch (attr) {
1013#if HAVE_PQPREPARE
1014        case PDO_ATTR_EMULATE_PREPARES:
1015            H->emulate_prepares = Z_LVAL_P(val);
1016            return 1;
1017        case PDO_PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT:
1018            H->disable_native_prepares = Z_LVAL_P(val);
1019            return 1;
1020#endif
1021
1022        default:
1023            return 0;
1024    }
1025}
1026
1027static struct pdo_dbh_methods pgsql_methods = {
1028    pgsql_handle_closer,
1029    pgsql_handle_preparer,
1030    pgsql_handle_doer,
1031    pgsql_handle_quoter,
1032    pgsql_handle_begin,
1033    pgsql_handle_commit,
1034    pgsql_handle_rollback,
1035    pdo_pgsql_set_attr,
1036    pdo_pgsql_last_insert_id,
1037    pdo_pgsql_fetch_error_func,
1038    pdo_pgsql_get_attribute,
1039    pdo_pgsql_check_liveness,   /* check_liveness */
1040    pdo_pgsql_get_driver_methods,  /* get_driver_methods */
1041    NULL,
1042    pgsql_handle_in_transaction,
1043};
1044
1045static int pdo_pgsql_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC) /* {{{ */
1046{
1047    pdo_pgsql_db_handle *H;
1048    int ret = 0;
1049    char *conn_str, *p, *e;
1050    char *tmp_pass;
1051    long connect_timeout = 30;
1052
1053    H = pecalloc(1, sizeof(pdo_pgsql_db_handle), dbh->is_persistent);
1054    dbh->driver_data = H;
1055
1056    H->einfo.errcode = 0;
1057    H->einfo.errmsg = NULL;
1058
1059    /* PostgreSQL wants params in the connect string to be separated by spaces,
1060     * if the PDO standard semicolons are used, we convert them to spaces
1061     */
1062    e = (char *) dbh->data_source + strlen(dbh->data_source);
1063    p = (char *) dbh->data_source;
1064    while ((p = memchr(p, ';', (e - p)))) {
1065        *p = ' ';
1066    }
1067
1068    if (driver_options) {
1069        connect_timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30 TSRMLS_CC);
1070    }
1071
1072    if (dbh->password) {
1073        if (dbh->password[0] != '\'' && dbh->password[strlen(dbh->password) - 1] != '\'') {
1074            char *pwd = dbh->password;
1075            int pos = 1;
1076
1077            tmp_pass = safe_emalloc(2, strlen(dbh->password), 3);
1078            tmp_pass[0] = '\'';
1079
1080            while (*pwd != '\0') {
1081                if (*pwd == '\\' || *pwd == '\'') {
1082                    tmp_pass[pos++] = '\\';
1083                }
1084
1085                tmp_pass[pos++] = *pwd++;
1086            }
1087
1088            tmp_pass[pos++] = '\'';
1089            tmp_pass[pos] = '\0';
1090        } else {
1091            tmp_pass = dbh->password;
1092        }
1093    }
1094
1095    /* support both full connection string & connection string + login and/or password */
1096    if (dbh->username && dbh->password) {
1097        spprintf(&conn_str, 0, "%s user=%s password=%s connect_timeout=%ld", dbh->data_source, dbh->username, tmp_pass, connect_timeout);
1098    } else if (dbh->username) {
1099        spprintf(&conn_str, 0, "%s user=%s connect_timeout=%ld", dbh->data_source, dbh->username, connect_timeout);
1100    } else if (dbh->password) {
1101        spprintf(&conn_str, 0, "%s password=%s connect_timeout=%ld", dbh->data_source, tmp_pass, connect_timeout);
1102    } else {
1103        spprintf(&conn_str, 0, "%s connect_timeout=%ld", (char *) dbh->data_source, connect_timeout);
1104    }
1105
1106    H->server = PQconnectdb(conn_str);
1107    if (dbh->password && tmp_pass != dbh->password) {
1108        efree(tmp_pass);
1109    }
1110
1111    efree(conn_str);
1112
1113    if (PQstatus(H->server) != CONNECTION_OK) {
1114        pdo_pgsql_error(dbh, PGRES_FATAL_ERROR, PHP_PDO_PGSQL_CONNECTION_FAILURE_SQLSTATE);
1115        goto cleanup;
1116    }
1117
1118    PQsetNoticeProcessor(H->server, (void(*)(void*,const char*))_pdo_pgsql_notice, (void *)&dbh);
1119
1120    H->attached = 1;
1121    H->pgoid = -1;
1122
1123    dbh->methods = &pgsql_methods;
1124    dbh->alloc_own_columns = 1;
1125    dbh->max_escaped_char_length = 2;
1126
1127    ret = 1;
1128
1129cleanup:
1130    dbh->methods = &pgsql_methods;
1131    if (!ret) {
1132        pgsql_handle_closer(dbh TSRMLS_CC);
1133    }
1134
1135    return ret;
1136}
1137/* }}} */
1138
1139pdo_driver_t pdo_pgsql_driver = {
1140    PDO_DRIVER_HEADER(pgsql),
1141    pdo_pgsql_handle_factory
1142};
1143
1144/*
1145 * Local variables:
1146 * tab-width: 4
1147 * c-basic-offset: 4
1148 * End:
1149 * vim600: noet sw=4 ts=4 fdm=marker
1150 * vim<600: noet sw=4 ts=4
1151 */
1152