2
// vim: set et ts=4 sw=4 fdm=marker:
3
// +----------------------------------------------------------------------+
4
// | PHP versions 4 and 5 |
5
// +----------------------------------------------------------------------+
6
// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
7
// | Stig. S. Bakken, Lukas Smith |
8
// | All rights reserved. |
9
// +----------------------------------------------------------------------+
10
// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
11
// | API as well as database abstraction for PHP applications. |
12
// | This LICENSE is in the BSD license style. |
14
// | Redistribution and use in source and binary forms, with or without |
15
// | modification, are permitted provided that the following conditions |
18
// | Redistributions of source code must retain the above copyright |
19
// | notice, this list of conditions and the following disclaimer. |
21
// | Redistributions in binary form must reproduce the above copyright |
22
// | notice, this list of conditions and the following disclaimer in the |
23
// | documentation and/or other materials provided with the distribution. |
25
// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
26
// | Lukas Smith nor the names of his contributors may be used to endorse |
27
// | or promote products derived from this software without specific prior|
28
// | written permission. |
30
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
31
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
32
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
33
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
34
// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
35
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
36
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
37
// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
38
// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
39
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
40
// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
41
// | POSSIBILITY OF SUCH DAMAGE. |
42
// +----------------------------------------------------------------------+
43
// | Author: Paul Cooper <pgc@ucecom.com> |
44
// +----------------------------------------------------------------------+
46
// $Id: pgsql.php,v 1.173 2007/05/02 22:00:08 quipo Exp $
49
* MDB2 PostGreSQL driver
53
* @author Paul Cooper <pgc@ucecom.com>
55
class MDB2_Driver_pgsql extends MDB2_Driver_Common
58
var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
60
var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
67
function __construct()
69
parent::__construct();
71
$this->phptype = 'pgsql';
72
$this->dbsyntax = 'pgsql';
74
$this->supported['sequences'] = true;
75
$this->supported['indexes'] = true;
76
$this->supported['affected_rows'] = true;
77
$this->supported['summary_functions'] = true;
78
$this->supported['order_by_text'] = true;
79
$this->supported['transactions'] = true;
80
$this->supported['savepoints'] = true;
81
$this->supported['current_id'] = true;
82
$this->supported['limit_queries'] = true;
83
$this->supported['LOBs'] = true;
84
$this->supported['replace'] = 'emulated';
85
$this->supported['sub_selects'] = true;
86
$this->supported['auto_increment'] = 'emulated';
87
$this->supported['primary_key'] = true;
88
$this->supported['result_introspection'] = true;
89
$this->supported['prepared_statements'] = true;
90
$this->supported['identifier_quoting'] = true;
91
$this->supported['pattern_escaping'] = true;
92
$this->supported['new_link'] = true;
94
$this->options['multi_query'] = false;
101
* This method is used to collect information about an error
103
* @param integer $error
107
function errorInfo($error = null)
109
// Fall back to MDB2_ERROR if there was no mapping.
110
$error_code = MDB2_ERROR;
113
if (is_resource($error)) {
114
$native_msg = @pg_result_error($error);
115
} elseif ($this->connection) {
116
$native_msg = @pg_last_error($this->connection);
117
if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
118
$native_msg = 'Database connection has been lost.';
119
$error_code = MDB2_ERROR_CONNECT_FAILED;
123
static $error_regexps;
124
if (empty($error_regexps)) {
125
$error_regexps = array(
126
'/column .* (of relation .*)?does not exist/i'
127
=> MDB2_ERROR_NOSUCHFIELD,
128
'/(relation|sequence|table).*does not exist|class .* not found/i'
129
=> MDB2_ERROR_NOSUCHTABLE,
130
'/index .* does not exist/'
131
=> MDB2_ERROR_NOT_FOUND,
132
'/relation .* already exists/i'
133
=> MDB2_ERROR_ALREADY_EXISTS,
134
'/(divide|division) by zero$/i'
135
=> MDB2_ERROR_DIVZERO,
136
'/pg_atoi: error in .*: can\'t parse /i'
137
=> MDB2_ERROR_INVALID_NUMBER,
138
'/invalid input syntax for( type)? (integer|numeric)/i'
139
=> MDB2_ERROR_INVALID_NUMBER,
140
'/value .* is out of range for type \w*int/i'
141
=> MDB2_ERROR_INVALID_NUMBER,
142
'/integer out of range/i'
143
=> MDB2_ERROR_INVALID_NUMBER,
144
'/value too long for type character/i'
145
=> MDB2_ERROR_INVALID,
146
'/attribute .* not found|relation .* does not have attribute/i'
147
=> MDB2_ERROR_NOSUCHFIELD,
148
'/column .* specified in USING clause does not exist in (left|right) table/i'
149
=> MDB2_ERROR_NOSUCHFIELD,
150
'/parser: parse error at or near/i'
151
=> MDB2_ERROR_SYNTAX,
153
=> MDB2_ERROR_SYNTAX,
154
'/column reference .* is ambiguous/i'
155
=> MDB2_ERROR_SYNTAX,
156
'/permission denied/'
157
=> MDB2_ERROR_ACCESS_VIOLATION,
158
'/violates not-null constraint/'
159
=> MDB2_ERROR_CONSTRAINT_NOT_NULL,
160
'/violates [\w ]+ constraint/'
161
=> MDB2_ERROR_CONSTRAINT,
162
'/referential integrity violation/'
163
=> MDB2_ERROR_CONSTRAINT,
164
'/more expressions than target columns/i'
165
=> MDB2_ERROR_VALUE_COUNT_ON_ROW,
168
if (is_numeric($error) && $error < 0) {
169
$error_code = $error;
171
foreach ($error_regexps as $regexp => $code) {
172
if (preg_match($regexp, $native_msg)) {
178
return array($error_code, null, $native_msg);
185
* Quotes a string so it can be safely used in a query. It will quote
186
* the text so it can safely be used within a query.
188
* @param string the input string to quote
189
* @param bool escape wildcards
191
* @return string quoted string
195
function escape($text, $escape_wildcards = false)
197
if ($escape_wildcards) {
198
$text = $this->escapePattern($text);
200
$connection = $this->getConnection();
201
if (PEAR::isError($connection)) {
204
if (version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {
205
$text = @pg_escape_string($connection, $text);
207
$text = @pg_escape_string($text);
213
// {{{ beginTransaction()
216
* Start a transaction or set a savepoint.
218
* @param string name of a savepoint to set
219
* @return mixed MDB2_OK on success, a MDB2 error on failure
223
function beginTransaction($savepoint = null)
225
$this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
226
if (!is_null($savepoint)) {
227
if (!$this->in_transaction) {
228
return $this->raiseError(MDB2_ERROR_INVALID, null, null,
229
'savepoint cannot be released when changes are auto committed', __FUNCTION__);
231
$query = 'SAVEPOINT '.$savepoint;
232
return $this->_doQuery($query, true);
233
} elseif ($this->in_transaction) {
234
return MDB2_OK; //nothing to do
236
if (!$this->destructor_registered && $this->opened_persistent) {
237
$this->destructor_registered = true;
238
register_shutdown_function('MDB2_closeOpenTransactions');
240
$result =& $this->_doQuery('BEGIN', true);
241
if (PEAR::isError($result)) {
244
$this->in_transaction = true;
252
* Commit the database changes done during a transaction that is in
253
* progress or release a savepoint. This function may only be called when
254
* auto-committing is disabled, otherwise it will fail. Therefore, a new
255
* transaction is implicitly started after committing the pending changes.
257
* @param string name of a savepoint to release
258
* @return mixed MDB2_OK on success, a MDB2 error on failure
262
function commit($savepoint = null)
264
$this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
265
if (!$this->in_transaction) {
266
return $this->raiseError(MDB2_ERROR_INVALID, null, null,
267
'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
269
if (!is_null($savepoint)) {
270
$query = 'RELEASE SAVEPOINT '.$savepoint;
271
return $this->_doQuery($query, true);
274
$result =& $this->_doQuery('COMMIT', true);
275
if (PEAR::isError($result)) {
278
$this->in_transaction = false;
286
* Cancel any database changes done during a transaction or since a specific
287
* savepoint that is in progress. This function may only be called when
288
* auto-committing is disabled, otherwise it will fail. Therefore, a new
289
* transaction is implicitly started after canceling the pending changes.
291
* @param string name of a savepoint to rollback to
292
* @return mixed MDB2_OK on success, a MDB2 error on failure
296
function rollback($savepoint = null)
298
$this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
299
if (!$this->in_transaction) {
300
return $this->raiseError(MDB2_ERROR_INVALID, null, null,
301
'rollback cannot be done changes are auto committed', __FUNCTION__);
303
if (!is_null($savepoint)) {
304
$query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
305
return $this->_doQuery($query, true);
309
$result =& $this->_doQuery($query, true);
310
if (PEAR::isError($result)) {
313
$this->in_transaction = false;
318
// {{{ function setTransactionIsolation()
321
* Set the transacton isolation level.
323
* @param string standard isolation level
324
* READ UNCOMMITTED (allows dirty reads)
325
* READ COMMITTED (prevents dirty reads)
326
* REPEATABLE READ (prevents nonrepeatable reads)
327
* SERIALIZABLE (prevents phantom reads)
328
* @return mixed MDB2_OK on success, a MDB2 error on failure
333
function setTransactionIsolation($isolation)
335
$this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
336
switch ($isolation) {
337
case 'READ UNCOMMITTED':
338
case 'READ COMMITTED':
339
case 'REPEATABLE READ':
343
return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
344
'isolation level is not supported: '.$isolation, __FUNCTION__);
347
$query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";
348
return $this->_doQuery($query, true);
355
* Does the grunt work of connecting to the database
357
* @return mixed connection resource on success, MDB2 Error Object on failure
360
function _doConnect($database_name, $persistent = false)
362
if ($database_name == '') {
363
$database_name = 'template1';
366
$protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';
369
if ($protocol == 'tcp') {
370
if ($this->dsn['hostspec']) {
371
$params[0].= 'host=' . $this->dsn['hostspec'];
373
if ($this->dsn['port']) {
374
$params[0].= ' port=' . $this->dsn['port'];
376
} elseif ($protocol == 'unix') {
377
// Allow for pg socket in non-standard locations.
378
if ($this->dsn['socket']) {
379
$params[0].= 'host=' . $this->dsn['socket'];
381
if ($this->dsn['port']) {
382
$params[0].= ' port=' . $this->dsn['port'];
385
if ($database_name) {
386
$params[0].= ' dbname=\'' . addslashes($database_name) . '\'';
388
if ($this->dsn['username']) {
389
$params[0].= ' user=\'' . addslashes($this->dsn['username']) . '\'';
391
if ($this->dsn['password']) {
392
$params[0].= ' password=\'' . addslashes($this->dsn['password']) . '\'';
394
if (!empty($this->dsn['options'])) {
395
$params[0].= ' options=' . $this->dsn['options'];
397
if (!empty($this->dsn['tty'])) {
398
$params[0].= ' tty=' . $this->dsn['tty'];
400
if (!empty($this->dsn['connect_timeout'])) {
401
$params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];
403
if (!empty($this->dsn['sslmode'])) {
404
$params[0].= ' sslmode=' . $this->dsn['sslmode'];
406
if (!empty($this->dsn['service'])) {
407
$params[0].= ' service=' . $this->dsn['service'];
410
if (!empty($this->dsn['new_link'])
411
&& ($this->dsn['new_link'] == 'true' || $this->dsn['new_link'] === true))
413
if (version_compare(phpversion(), '4.3.0', '>=')) {
414
$params[] = PGSQL_CONNECT_FORCE_NEW;
418
$connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
420
$connection = @call_user_func_array($connect_function, $params);
422
return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
423
'unable to establish a connection', __FUNCTION__);
426
if (empty($this->dsn['disable_iso_date'])) {
427
if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {
428
return $this->raiseError(null, null, null,
429
'Unable to set date style to iso', __FUNCTION__);
433
if (!empty($this->dsn['charset'])) {
434
$result = $this->setCharset($this->dsn['charset'], $connection);
435
if (PEAR::isError($result)) {
447
* Connect to the database
449
* @return true on success, MDB2 Error Object on failure
454
if (is_resource($this->connection)) {
455
if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
456
&& $this->connected_database_name == $this->database_name
457
&& ($this->opened_persistent == $this->options['persistent'])
461
$this->disconnect(false);
464
if (!PEAR::loadExtension($this->phptype)) {
465
return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
466
'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
469
if ($this->database_name) {
470
$connection = $this->_doConnect($this->database_name, $this->options['persistent']);
471
if (PEAR::isError($connection)) {
474
$this->connection = $connection;
475
$this->connected_dsn = $this->dsn;
476
$this->connected_database_name = $this->database_name;
477
$this->opened_persistent = $this->options['persistent'];
478
$this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
487
* Set the charset on the current connection
489
* @param string charset
490
* @param resource connection handle
492
* @return true on success, MDB2 Error Object on failure
494
function setCharset($charset, $connection = null)
496
if (is_null($connection)) {
497
$connection = $this->getConnection();
498
if (PEAR::isError($connection)) {
503
$result = @pg_set_client_encoding($connection, $charset);
505
return $this->raiseError(null, null, null,
506
'Unable to set client charset: '.$charset, __FUNCTION__);
515
* Log out and disconnect from the database.
517
* @param boolean $force if the disconnect should be forced even if the
518
* connection is opened persistently
519
* @return mixed true on success, false if not connected and error
523
function disconnect($force = true)
525
if (is_resource($this->connection)) {
526
if ($this->in_transaction) {
528
$database_name = $this->database_name;
529
$persistent = $this->options['persistent'];
530
$this->dsn = $this->connected_dsn;
531
$this->database_name = $this->connected_database_name;
532
$this->options['persistent'] = $this->opened_persistent;
535
$this->database_name = $database_name;
536
$this->options['persistent'] = $persistent;
539
if (!$this->opened_persistent || $force) {
540
@pg_close($this->connection);
543
return parent::disconnect($force);
547
// {{{ standaloneQuery()
550
* execute a query as DBA
552
* @param string $query the SQL query
553
* @param mixed $types array that contains the types of the columns in
555
* @param boolean $is_manip if the query is a manipulation query
556
* @return mixed MDB2_OK on success, a MDB2 error on failure
559
function &standaloneQuery($query, $types = null, $is_manip = false)
561
$connection = $this->_doConnect('template1', false);
562
if (PEAR::isError($connection)) {
563
$err =& $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
564
'Cannot connect to template1', __FUNCTION__);
568
$offset = $this->offset;
569
$limit = $this->limit;
570
$this->offset = $this->limit = 0;
571
$query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
573
$result =& $this->_doQuery($query, $is_manip, $connection, false);
574
@pg_close($connection);
575
if (PEAR::isError($result)) {
580
$affected_rows = $this->_affectedRows($connection, $result);
581
return $affected_rows;
583
$result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
592
* @param string $query query
593
* @param boolean $is_manip if the query is a manipulation query
594
* @param resource $connection
595
* @param string $database_name
596
* @return result or error object
599
function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
601
$this->last_query = $query;
602
$result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
604
if (PEAR::isError($result)) {
609
if ($this->options['disable_query']) {
610
$result = $is_manip ? 0 : null;
614
if (is_null($connection)) {
615
$connection = $this->getConnection();
616
if (PEAR::isError($connection)) {
621
$function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';
622
$result = @$function($connection, $query);
624
$err =& $this->raiseError(null, null, null,
625
'Could not execute statement', __FUNCTION__);
627
} elseif ($this->options['multi_query']) {
628
if (!($result = @pg_get_result($connection))) {
629
$err =& $this->raiseError(null, null, null,
630
'Could not get the first result from a multi query', __FUNCTION__);
635
$this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
640
// {{{ _affectedRows()
643
* Returns the number of rows affected
645
* @param resource $result
646
* @param resource $connection
647
* @return mixed MDB2 Error Object or the number of rows affected
650
function _affectedRows($connection, $result = null)
652
if (is_null($connection)) {
653
$connection = $this->getConnection();
654
if (PEAR::isError($connection)) {
658
return @pg_affected_rows($result);
662
// {{{ _modifyQuery()
665
* Changes a query string for various DBMS specific reasons
667
* @param string $query query to modify
668
* @param boolean $is_manip if it is a DML query
669
* @param integer $limit limit the number of rows
670
* @param integer $offset start reading from given offset
671
* @return string modified query
674
function _modifyQuery($query, $is_manip, $limit, $offset)
677
&& !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
679
$query = rtrim($query);
680
if (substr($query, -1) == ';') {
681
$query = substr($query, 0, -1);
684
$query = $this->_modifyManipQuery($query, $limit);
686
$query.= " LIMIT $limit OFFSET $offset";
693
// {{{ _modifyManipQuery()
696
* Changes a manip query string for various DBMS specific reasons
698
* @param string $query query to modify
699
* @param integer $limit limit the number of rows
700
* @return string modified query
703
function _modifyManipQuery($query, $limit)
705
$pos = strpos(strtolower($query), 'where');
706
$where = $pos ? substr($query, $pos) : '';
708
$manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';
709
$from_clause = '([\w\.]+)';
710
$where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';
711
$pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';
712
$matches = preg_match($pattern, $query, $match);
716
$what = (count($matches) == 6) ? $match[5] : $match[3];
717
return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
724
// {{{ getServerVersion()
727
* return version information about the server
729
* @param bool $native determines if the raw version string should be returned
730
* @return mixed array/string with version information or MDB2 error object
733
function getServerVersion($native = false)
735
$query = 'SHOW SERVER_VERSION';
736
if ($this->connected_server_info) {
737
$server_info = $this->connected_server_info;
739
$server_info = $this->queryOne($query, 'text');
740
if (PEAR::isError($server_info)) {
745
$this->connected_server_info = $server_info;
746
if (!$native && !PEAR::isError($server_info)) {
747
$tmp = explode('.', $server_info, 3);
750
&& preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)
752
$server_info = array(
757
'native' => $server_info,
760
$server_info = array(
761
'major' => isset($tmp[0]) ? $tmp[0] : null,
762
'minor' => isset($tmp[1]) ? $tmp[1] : null,
763
'patch' => isset($tmp[2]) ? $tmp[2] : null,
765
'native' => $server_info,
776
* Prepares a query for multiple execution with execute().
777
* With some database backends, this is emulated.
778
* prepare() requires a generic query as string like
779
* 'INSERT INTO numbers VALUES(?,?)' or
780
* 'INSERT INTO numbers VALUES(:foo,:bar)'.
781
* The ? and :[a-zA-Z] and are placeholders which can be set using
782
* bindParam() and the query can be send off using the execute() method.
784
* @param string $query the query to prepare
785
* @param mixed $types array that contains the types of the placeholders
786
* @param mixed $result_types array that contains the types of the columns in
787
* the result set or MDB2_PREPARE_RESULT, if set to
788
* MDB2_PREPARE_MANIP the query is handled as a manipulation query
789
* @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
790
* @return mixed resource handle for the prepared query on success, a MDB2
793
* @see bindParam, execute
795
function &prepare($query, $types = null, $result_types = null, $lobs = array())
797
if ($this->options['emulate_prepared']) {
798
$obj =& parent::prepare($query, $types, $result_types, $lobs);
801
$is_manip = ($result_types === MDB2_PREPARE_MANIP);
802
$offset = $this->offset;
803
$limit = $this->limit;
804
$this->offset = $this->limit = 0;
805
$result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
807
if (PEAR::isError($result)) {
812
$pgtypes = function_exists('pg_prepare') ? false : array();
813
if ($pgtypes !== false && !empty($types)) {
814
$this->loadModule('Datatype', null, true);
816
$query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
817
$placeholder_type_guess = $placeholder_type = null;
820
$positions = array();
821
$position = $parameter = 0;
822
while ($position < strlen($query)) {
823
$q_position = strpos($query, $question, $position);
824
$c_position = strpos($query, $colon, $position);
825
if ($q_position && $c_position) {
826
$p_position = min($q_position, $c_position);
827
} elseif ($q_position) {
828
$p_position = $q_position;
829
} elseif ($c_position) {
830
$p_position = $c_position;
834
if (is_null($placeholder_type)) {
835
$placeholder_type_guess = $query[$p_position];
838
$new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
839
if (PEAR::isError($new_pos)) {
842
if ($new_pos != $position) {
843
$position = $new_pos;
844
continue; //evaluate again starting from the new position
847
if ($query[$position] == $placeholder_type_guess) {
848
if (is_null($placeholder_type)) {
849
$placeholder_type = $query[$p_position];
850
$question = $colon = $placeholder_type;
851
if (!empty($types) && is_array($types)) {
852
if ($placeholder_type == ':') {
854
$types = array_values($types);
858
if ($placeholder_type_guess == '?') {
862
$name = preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si', '\\1', $query);
864
$err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
865
'named parameter with an empty name', __FUNCTION__);
868
$length = strlen($name) + 1;
870
if ($pgtypes !== false) {
871
if (is_array($types) && array_key_exists($name, $types)) {
872
$pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);
873
} elseif (is_array($types) && array_key_exists($parameter, $types)) {
874
$pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);
879
if (($key_parameter = array_search($name, $positions))) {
881
foreach ($positions as $key => $value) {
882
if ($key_parameter == $key) {
889
$next_parameter = $parameter;
890
$positions[] = $name;
892
$query = substr_replace($query, '$'.$parameter, $position, $length);
893
$position = $p_position + strlen($parameter);
895
$position = $p_position;
898
$connection = $this->getConnection();
899
if (PEAR::isError($connection)) {
903
$statement_name = sprintf($this->options['statement_format'], $this->phptype, md5(time() + rand()));
904
$statement_name = strtolower($statement_name);
905
if ($pgtypes === false) {
906
$result = @pg_prepare($connection, $statement_name, $query);
908
$err =& $this->raiseError(null, null, null,
909
'Unable to create prepared statement handle', __FUNCTION__);
915
$types_string = ' ('.implode(', ', $pgtypes).') ';
917
$query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
918
$statement =& $this->_doQuery($query, true, $connection);
919
if (PEAR::isError($statement)) {
924
$class_name = 'MDB2_Statement_'.$this->phptype;
925
$obj =& new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
926
$this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
931
// {{{ function getSequenceName($sqn)
934
* adds sequence name formatting to a sequence name
936
* @param string name of the sequence
938
* @return string formatted sequence name
942
function getSequenceName($sqn)
944
list($table, $field) = explode('_', $sqn);
945
$query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
947
WHERE d.adrelid = a.attrelid
948
AND d.adnum = a.attnum
950
) FROM 'nextval[^\']*\'([^\']*)')
952
LEFT JOIN pg_class c ON c.oid = a.attrelid
953
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
954
WHERE (c.relname = ".$this->quote($sqn, 'text');
955
if (!empty($field)) {
956
$query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
959
AND NOT a.attisdropped
961
AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
963
$seqname = $this->queryOne($query);
964
if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {
968
return sprintf($this->options['seqname_format'],
969
preg_replace('/[^\w\$.]/i', '_', $sqn));
976
* Returns the next free id of a sequence
978
* @param string $seq_name name of the sequence
979
* @param boolean $ondemand when true the sequence is
980
* automatic created, if it
982
* @return mixed MDB2 Error Object or id
985
function nextID($seq_name, $ondemand = true)
987
$sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
988
$query = "SELECT NEXTVAL('$sequence_name')";
989
$this->expectError(MDB2_ERROR_NOSUCHTABLE);
990
$result = $this->queryOne($query, 'integer');
992
if (PEAR::isError($result)) {
993
if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
994
$this->loadModule('Manager', null, true);
995
$result = $this->manager->createSequence($seq_name);
996
if (PEAR::isError($result)) {
997
return $this->raiseError($result, null, null,
998
'on demand sequence could not be created', __FUNCTION__);
1000
return $this->nextId($seq_name, false);
1007
// {{{ lastInsertID()
1010
* Returns the autoincrement ID if supported or $id or fetches the current
1011
* ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
1013
* @param string $table name of the table into which a new row was inserted
1014
* @param string $field name of the field into which a new row was inserted
1015
* @return mixed MDB2 Error Object or id
1018
function lastInsertID($table = null, $field = null)
1020
if (empty($table) && empty($field)) {
1021
return $this->queryOne('SELECT lastval()', 'integer');
1023
$seq = $table.(empty($field) ? '' : '_'.$field);
1024
$sequence_name = $this->getSequenceName($seq);
1025
return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
1032
* Returns the current id of a sequence
1034
* @param string $seq_name name of the sequence
1035
* @return mixed MDB2 Error Object or id
1038
function currID($seq_name)
1040
$sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
1041
return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
1046
* MDB2 PostGreSQL result driver
1049
* @category Database
1050
* @author Paul Cooper <pgc@ucecom.com>
1052
class MDB2_Result_pgsql extends MDB2_Result_Common
1058
* Fetch a row and insert the data into an existing array.
1060
* @param int $fetchmode how the array data should be indexed
1061
* @param int $rownum number of the row where the data can be found
1062
* @return int data array on success, a MDB2 error on failure
1065
function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
1067
if (!is_null($rownum)) {
1068
$seek = $this->seek($rownum);
1069
if (PEAR::isError($seek)) {
1073
if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
1074
$fetchmode = $this->db->fetchmode;
1076
if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
1077
$row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
1079
&& $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
1081
$row = array_change_key_case($row, $this->db->options['field_case']);
1084
$row = @pg_fetch_row($this->result);
1087
if ($this->result === false) {
1088
$err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1089
'resultset has already been freed', __FUNCTION__);
1095
$mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
1097
if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
1098
if (empty($this->types)) {
1099
$mode += MDB2_PORTABILITY_RTRIM;
1105
$this->db->_fixResultArrayValues($row, $mode);
1107
if (!empty($this->types)) {
1108
$row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
1110
if (!empty($this->values)) {
1111
$this->_assignBindColumns($row);
1113
if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
1114
$object_class = $this->db->options['fetch_class'];
1115
if ($object_class == 'stdClass') {
1116
$row = (object) $row;
1118
$row = &new $object_class($row);
1126
// {{{ _getColumnNames()
1129
* Retrieve the names of columns returned by the DBMS in a query result.
1131
* @return mixed Array variable that holds the names of columns as keys
1132
* or an MDB2 error on failure.
1133
* Some DBMS may not return any columns when the result set
1134
* does not contain any rows.
1137
function _getColumnNames()
1140
$numcols = $this->numCols();
1141
if (PEAR::isError($numcols)) {
1144
for ($column = 0; $column < $numcols; $column++) {
1145
$column_name = @pg_field_name($this->result, $column);
1146
$columns[$column_name] = $column;
1148
if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
1149
$columns = array_change_key_case($columns, $this->db->options['field_case']);
1158
* Count the number of columns returned by the DBMS in a query result.
1161
* @return mixed integer value with the number of columns, a MDB2 error
1166
$cols = @pg_num_fields($this->result);
1167
if (is_null($cols)) {
1168
if ($this->result === false) {
1169
return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1170
'resultset has already been freed', __FUNCTION__);
1171
} elseif (is_null($this->result)) {
1172
return count($this->types);
1174
return $this->db->raiseError(null, null, null,
1175
'Could not get column count', __FUNCTION__);
1184
* Move the internal result pointer to the next available result
1186
* @return true on success, false if there is no more result set or an error object on failure
1189
function nextResult()
1191
$connection = $this->db->getConnection();
1192
if (PEAR::isError($connection)) {
1196
if (!($this->result = @pg_get_result($connection))) {
1206
* Free the internal resources associated with result.
1208
* @return boolean true on success, false if result is invalid
1213
if (is_resource($this->result) && $this->db->connection) {
1214
$free = @pg_free_result($this->result);
1215
if ($free === false) {
1216
return $this->db->raiseError(null, null, null,
1217
'Could not free result', __FUNCTION__);
1220
$this->result = false;
1226
* MDB2 PostGreSQL buffered result driver
1229
* @category Database
1230
* @author Paul Cooper <pgc@ucecom.com>
1232
class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
1237
* Seek to a specific row in a result set
1239
* @param int $rownum number of the row where the data can be found
1240
* @return mixed MDB2_OK on success, a MDB2 error on failure
1243
function seek($rownum = 0)
1245
if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
1246
if ($this->result === false) {
1247
return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1248
'resultset has already been freed', __FUNCTION__);
1249
} elseif (is_null($this->result)) {
1252
return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
1253
'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
1255
$this->rownum = $rownum - 1;
1263
* Check if the end of the result set has been reached
1265
* @return mixed true or false on sucess, a MDB2 error on failure
1270
$numrows = $this->numRows();
1271
if (PEAR::isError($numrows)) {
1274
return $this->rownum < ($numrows - 1);
1281
* Returns the number of rows in a result object
1283
* @return mixed MDB2 Error Object or the number of rows
1288
$rows = @pg_num_rows($this->result);
1289
if (is_null($rows)) {
1290
if ($this->result === false) {
1291
return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1292
'resultset has already been freed', __FUNCTION__);
1293
} elseif (is_null($this->result)) {
1296
return $this->db->raiseError(null, null, null,
1297
'Could not get row count', __FUNCTION__);
1304
* MDB2 PostGreSQL statement driver
1307
* @category Database
1308
* @author Paul Cooper <pgc@ucecom.com>
1310
class MDB2_Statement_pgsql extends MDB2_Statement_Common
1315
* Execute a prepared query statement helper method.
1317
* @param mixed $result_class string which specifies which result class to use
1318
* @param mixed $result_wrap_class string which specifies which class to wrap results in
1319
* @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
1322
function &_execute($result_class = true, $result_wrap_class = false)
1324
if (is_null($this->statement)) {
1325
$result =& parent::_execute($result_class, $result_wrap_class);
1328
$this->db->last_query = $this->query;
1329
$this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
1330
if ($this->db->getOption('disable_query')) {
1331
$result = $this->is_manip ? 0 : null;
1335
$connection = $this->db->getConnection();
1336
if (PEAR::isError($connection)) {
1341
$parameters = array();
1342
// todo: disabled until pg_execute() bytea issues are cleared up
1343
if (true || !function_exists('pg_execute')) {
1344
$query = 'EXECUTE '.$this->statement;
1346
if (!empty($this->positions)) {
1347
foreach ($this->positions as $parameter) {
1348
if (!array_key_exists($parameter, $this->values)) {
1349
return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
1350
'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
1352
$value = $this->values[$parameter];
1353
$type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
1354
if (is_resource($value) || $type == 'clob' || $type == 'blob') {
1355
if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
1356
if ($match[1] == 'file://') {
1359
$value = @fopen($value, 'r');
1362
if (is_resource($value)) {
1364
while (!@feof($value)) {
1365
$data.= @fread($value, $this->db->options['lob_buffer_length']);
1373
$parameters[] = $this->db->quote($value, $type, $query);
1376
$query.= ' ('.implode(', ', $parameters).')';
1381
$result = @pg_execute($connection, $this->statement, $parameters);
1383
$err =& $this->db->raiseError(null, null, null,
1384
'Unable to execute statement', __FUNCTION__);
1388
$result = $this->db->_doQuery($query, $this->is_manip, $connection);
1389
if (PEAR::isError($result)) {
1394
if ($this->is_manip) {
1395
$affected_rows = $this->db->_affectedRows($connection, $result);
1396
return $affected_rows;
1399
$result =& $this->db->_wrapResult($result, $this->result_types,
1400
$result_class, $result_wrap_class, $this->limit, $this->offset);
1401
$this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
1409
* Release resources allocated for the specified prepared query.
1411
* @return mixed MDB2_OK on success, a MDB2 error on failure
1416
if (is_null($this->positions)) {
1417
return $this->db->raiseError(MDB2_ERROR, null, null,
1418
'Prepared statement has already been freed', __FUNCTION__);
1422
if (!is_null($this->statement)) {
1423
$connection = $this->db->getConnection();
1424
if (PEAR::isError($connection)) {
1427
$query = 'DEALLOCATE PREPARE '.$this->statement;
1428
$result = $this->db->_doQuery($query, true, $connection);
b'\\ No newline at end of file'