3 * This is the Postgres database abstraction layer.
9 class PostgresField
implements Field
{
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname, $sharedmConn = null;
13 * @param $db DatabaseBase
16 * @return null|PostgresField
18 static function fromText( $db, $table, $field ) {
23 attnotnull, attlen, COALESCE(conname, '') AS conname,
24 COALESCE(condeferred, 'f') AS deferred,
25 COALESCE(condeferrable, 'f') AS deferrable,
26 CASE WHEN typname = 'int2' THEN 'smallint'
27 WHEN typname = 'int4' THEN 'integer'
28 WHEN typname = 'int8' THEN 'bigint'
29 WHEN typname = 'bpchar' THEN 'char'
30 ELSE typname END AS typname
32 JOIN pg_namespace n ON (n.oid = c.relnamespace)
33 JOIN pg_attribute a ON (a.attrelid = c.oid)
34 JOIN pg_type t ON (t.oid = a.atttypid)
35 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
42 $table = $db->tableName( $table, false );
45 $db->addQuotes( $wgDBmwschema ),
46 $db->addQuotes( $table ),
47 $db->addQuotes( $field )
50 $row = $db->fetchObject( $res );
54 $n = new PostgresField
;
55 $n->type
= $row->typname
;
56 $n->nullable
= ( $row->attnotnull
== 'f' );
58 $n->tablename
= $table;
59 $n->max_length
= $row->attlen
;
60 $n->deferrable
= ( $row->deferrable
== 't' );
61 $n->deferred
= ( $row->deferred
== 't' );
62 $n->conname
= $row->conname
;
70 function tableName() {
71 return $this->tablename
;
78 function isNullable() {
79 return $this->nullable
;
82 function maxLength() {
83 return $this->max_length
;
86 function is_deferrable() {
87 return $this->deferrable
;
90 function is_deferred() {
91 return $this->deferred
;
95 return $this->conname
;
103 class DatabasePostgres
extends DatabaseBase
{
104 var $mInsertId = null;
105 var $mLastResult = null;
106 var $numeric_version = null;
107 var $mAffectedRows = null;
113 function cascadingDeletes() {
116 function cleanupTriggers() {
119 function strictIPs() {
122 function realTimestamps() {
125 function implicitGroupby() {
128 function implicitOrderby() {
131 function searchableIPs() {
134 function functionalIndexes() {
138 function hasConstraint( $name ) {
139 global $wgDBmwschema;
140 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
141 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $wgDBmwschema ) ."'";
142 $res = $this->doQuery( $SQL );
143 return $this->numRows( $res );
147 * Usually aborts on failure
149 function open( $server, $user, $password, $dbName ) {
150 # Test for Postgres support, to avoid suppressed fatal error
151 if ( !function_exists( 'pg_connect' ) ) {
152 throw new DBConnectionError( $this, "Postgres functions missing, have you compiled PHP with the --with-pgsql option?\n (Note: if you recently installed PHP, you may need to restart your webserver and database)\n" );
155 global $wgDBport, $wgSharedDB;
157 if ( !strlen( $user ) ) { # e.g. the class is being loaded
162 $this->mServer
= $server;
164 $this->mUser
= $user;
165 $this->mPassword
= $password;
166 $this->mDBname
= $dbName;
168 $connectVars = array(
171 'password' => $password
173 if ( $server != false && $server != '' ) {
174 $connectVars['host'] = $server;
176 if ( $port != false && $port != '' ) {
177 $connectVars['port'] = $port;
179 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
181 $this->installErrorHandler();
182 $this->mConn
= pg_connect( $connectString );
183 $phpError = $this->restoreErrorHandler();
185 if ( !$this->mConn
) {
186 wfDebug( "DB connection error\n" );
187 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
188 wfDebug( $this->lastError() . "\n" );
189 throw new DBConnectionError( $this, $phpError );
193 $connectVars = array(
194 'dbname' => $wgSharedDB,
196 'password' => $password );
197 if ($server!=false && $server!="") {
198 $connectVars['host'] = $server;
200 if ($port!=false && $port!="") {
201 $connectVars['port'] = $port;
203 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
205 $this->installErrorHandler();
206 $this->sharedmConn
= pg_connect( $connectString );
207 $phpError = $this->restoreErrorHandler();
208 if ( $this->sharedmConn
== false ) {
209 wfDebug( "SharedDB connection error\n" );
210 wfDebug( "Server: $server, Database: $wgSharedDB, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
211 wfDebug( $this->lastError()."\n" );
213 throw new DBConnectionError( $this, $phpError );
216 $this->mOpened
= true;
218 global $wgCommandLineMode;
219 # If called from the command-line (e.g. importDump), only show errors
220 if ( $wgCommandLineMode ) {
221 $this->doQuery( "SET client_min_messages = 'ERROR'" );
224 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
225 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
226 $this->query( "SET timezone = 'GMT'", __METHOD__
);
228 global $wgDBmwschema;
229 if ( $this->schemaExists( $wgDBmwschema ) ) {
230 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
231 $this->doQuery( "SET search_path = $safeschema" );
233 $this->doQuery( "SET search_path = public" );
240 * Postgres doesn't support selectDB in the same way MySQL does. So if the
241 * DB name doesn't match the open connection, open a new one
244 function selectDB( $db ) {
245 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
248 function makeConnectionString( $vars ) {
250 foreach ( $vars as $name => $value ) {
251 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
257 * Closes a database connection, if it is open
258 * Returns success, true if already closed
263 if ( $this->mConn
) {
264 $mainConn = pg_close ( $this->mConn
);
266 if ( isset( $this->sharedmConn
) && $this->sharedmConn
) {
267 $sharedConn = pg_close ( $this->sharedmConn
);
269 $this->mOpened
= !($mainConn && $sharedConn);
270 return !$this->mOpened
;
273 function doQuery( $sql ) {
275 if ( function_exists( 'mb_convert_encoding' ) ) {
276 $sql = mb_convert_encoding( $sql, 'UTF-8' );
278 # we can find the shared tables after FROM or UPDATE statements.
279 $FROMpos = strpos( $sql, 'FROM' );
280 if ( $FROMpos === false ) {
281 $FROMpos = strpos( $sql, 'UPDATE' );
282 if ( $FROMpos === false ) {
283 # does this query even exists?
284 $this->mLastResult
= pg_query( $this->mConn
, $sql );
285 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
286 return $this->mLastResult
;
289 # check if we should connect to the shared database
290 # skip FROM/UPDATE statement
291 $FROMquery = substr( $sql, $FROMpos +
($sql[$FROMpos] == 'F' ?
4 : 6) );
292 $trimmed = trim( $FROMquery );
293 $FROMquery = $trimmed;
294 # skip eventual comment and spaces
295 if ( substr( $FROMquery, 0, 2 ) == '/*' ) {
296 $FROMquery = substr( $FROMquery, strpos( $FROMquery, '*/') +
2 );
297 $trimmed = trim( $FROMquery );
298 $FROMquery = $trimmed;
301 $FROMquery = substr( $FROMquery, 0, strpos($FROMquery, ' ') );
302 $FROMvalue = explode( '.', $FROMquery );
303 # db is always quoted, compare it to wgSharedDB
304 if ( $FROMvalue[0] == "\"$wgSharedDB\"" ) {
305 # shared db requested. switch connection
306 $this->mLastResult
= pg_query( $this->sharedmConn
, $sql );
308 # main db: basic query
309 $this->mLastResult
= pg_query( $this->mConn
, $sql );
311 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
312 return $this->mLastResult
;
315 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
316 return $this->query( $sql, $fname, true );
319 function freeResult( $res ) {
320 if ( $res instanceof ResultWrapper
) {
323 if ( !@pg_free_result
( $res ) ) {
324 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
328 function fetchObject( $res ) {
329 if ( $res instanceof ResultWrapper
) {
332 @$row = pg_fetch_object( $res );
333 # @todo FIXME: HACK HACK HACK HACK debug
335 # @todo hashar: not sure if the following test really trigger if the object
337 if( pg_last_error( $this->mConn
) ) {
338 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
343 function fetchRow( $res ) {
344 if ( $res instanceof ResultWrapper
) {
347 @$row = pg_fetch_array( $res );
348 if( pg_last_error( $this->mConn
) ) {
349 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
354 function numRows( $res ) {
355 if ( $res instanceof ResultWrapper
) {
358 @$n = pg_num_rows( $res );
359 if( pg_last_error( $this->mConn
) ) {
360 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
365 function numFields( $res ) {
366 if ( $res instanceof ResultWrapper
) {
369 return pg_num_fields( $res );
372 function fieldName( $res, $n ) {
373 if ( $res instanceof ResultWrapper
) {
376 return pg_field_name( $res, $n );
380 * This must be called after nextSequenceVal
382 function insertId() {
383 return $this->mInsertId
;
386 function dataSeek( $res, $row ) {
387 if ( $res instanceof ResultWrapper
) {
390 return pg_result_seek( $res, $row );
393 function lastError() {
394 if ( $this->mConn
) {
395 return pg_last_error();
397 return 'No database connection';
400 function lastErrno() {
401 return pg_last_error() ?
1 : 0;
404 function affectedRows() {
405 if ( !is_null( $this->mAffectedRows
) ) {
406 // Forced result for simulated queries
407 return $this->mAffectedRows
;
409 if( empty( $this->mLastResult
) ) {
412 return pg_affected_rows( $this->mLastResult
);
416 * Estimate rows in dataset
417 * Returns estimated count, based on EXPLAIN output
418 * This is not necessarily an accurate estimate, so use sparingly
419 * Returns -1 if count cannot be found
420 * Takes same arguments as Database::select()
422 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
423 $options['EXPLAIN'] = true;
424 $res = $this->select( $table, $vars, $conds, $fname, $options );
427 $row = $this->fetchRow( $res );
429 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
437 * Returns information about an index
438 * If errors are explicitly ignored, returns NULL on failure
440 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
441 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
442 $res = $this->query( $sql, $fname );
446 foreach ( $res as $row ) {
447 if ( $row->indexname
== $this->indexName( $index ) ) {
454 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
455 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
456 " AND indexdef LIKE 'CREATE UNIQUE%(" .
457 $this->strencode( $this->indexName( $index ) ) .
459 $res = $this->query( $sql, $fname );
463 foreach ( $res as $row ) {
470 * INSERT wrapper, inserts an array into a table
472 * $args may be a single associative array, or an array of these with numeric keys,
473 * for multi-row insert (Postgres version 8.2 and above only).
475 * @param $table String: Name of the table to insert to.
476 * @param $args Array: Items to insert into the table.
477 * @param $fname String: Name of the function, for profiling
478 * @param $options String or Array. Valid options: IGNORE
480 * @return bool Success of insert operation. IGNORE always returns true.
482 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
483 if ( !count( $args ) ) {
487 $table = $this->tableName( $table );
488 if (! isset( $this->numeric_version
) ) {
489 $this->getServerVersion();
492 if ( !is_array( $options ) ) {
493 $options = array( $options );
496 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
498 $keys = array_keys( $args[0] );
501 $keys = array_keys( $args );
504 // If IGNORE is set, we use savepoints to emulate mysql's behavior
505 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
507 // If we are not in a transaction, we need to be for savepoint trickery
510 if ( !$this->mTrxLevel
) {
514 $olde = error_reporting( 0 );
515 // For future use, we may want to track the number of actual inserts
516 // Right now, insert (all writes) simply return true/false
517 $numrowsinserted = 0;
520 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
523 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
525 foreach ( $args as $row ) {
531 $sql .= '(' . $this->makeList( $row ) . ')';
533 $res = (bool)$this->query( $sql, $fname, $ignore );
537 foreach ( $args as $row ) {
539 $tempsql .= '(' . $this->makeList( $row ) . ')';
542 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
545 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
548 $bar = pg_last_error();
549 if ( $bar != false ) {
550 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
552 pg_query( $this->mConn
, "RELEASE $ignore" );
557 // If any of them fail, we fail overall for this function call
558 // Note that this will be ignored if IGNORE is set
565 // Not multi, just a lone insert
567 pg_query($this->mConn
, "SAVEPOINT $ignore");
570 $sql .= '(' . $this->makeList( $args ) . ')';
571 $res = (bool)$this->query( $sql, $fname, $ignore );
573 $bar = pg_last_error();
574 if ( $bar != false ) {
575 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
577 pg_query( $this->mConn
, "RELEASE $ignore" );
583 $olde = error_reporting( $olde );
588 // Set the affected row count for the whole operation
589 $this->mAffectedRows
= $numrowsinserted;
591 // IGNORE always returns true
599 * INSERT SELECT wrapper
600 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
601 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
602 * $conds may be "*" to copy the whole table
603 * srcTable may be an array of tables.
604 * @todo FIXME: Implement this a little better (seperate select/insert)?
606 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
607 $insertOptions = array(), $selectOptions = array() )
609 $destTable = $this->tableName( $destTable );
611 // If IGNORE is set, we use savepoints to emulate mysql's behavior
612 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
614 if( is_array( $insertOptions ) ) {
615 $insertOptions = implode( ' ', $insertOptions );
617 if( !is_array( $selectOptions ) ) {
618 $selectOptions = array( $selectOptions );
620 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
621 if( is_array( $srcTable ) ) {
622 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
624 $srcTable = $this->tableName( $srcTable );
627 // If we are not in a transaction, we need to be for savepoint trickery
630 if( !$this->mTrxLevel
) {
634 $olde = error_reporting( 0 );
635 $numrowsinserted = 0;
636 pg_query( $this->mConn
, "SAVEPOINT $ignore");
639 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
640 " SELECT $startOpts " . implode( ',', $varMap ) .
641 " FROM $srcTable $useIndex";
643 if ( $conds != '*' ) {
644 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
647 $sql .= " $tailOpts";
649 $res = (bool)$this->query( $sql, $fname, $ignore );
651 $bar = pg_last_error();
652 if( $bar != false ) {
653 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
655 pg_query( $this->mConn
, "RELEASE $ignore" );
658 $olde = error_reporting( $olde );
663 // Set the affected row count for the whole operation
664 $this->mAffectedRows
= $numrowsinserted;
666 // IGNORE always returns true
673 function tableName( $name, $quoted = true ) {
674 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgDBmwschema;
675 # Replace reserved words with better ones
684 $name = 'pagecontent';
687 $name = 'pagecontent';
690 # Skip the entire process when we have a string quoted on both ends.
691 # Note that we check the end so that we will still quote any use of
692 # use of `database`.table. But won't break things if someone wants
693 # to query a database table with a dot in the name.
694 if ( $name[0] == '"' && substr( $name, -1, 1 ) == '"' ) {
698 # Lets test for any bits of text that should never show up in a table
699 # name. Basically anything like JOIN or ON which are actually part of
700 # SQL queries, but may end up inside of the table value to combine
701 # sql. Such as how the API is doing.
702 # Note that we use a whitespace test rather than a \b test to avoid
703 # any remote case where a word like on may be inside of a table name
704 # surrounded by symbols which may be considered word breaks.
705 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
709 # Split database and table into proper variables.
710 # We reverse the explode so that database.table and table both output
712 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
713 if ( isset( $dbDetails[1] ) ) {
714 @list
( $table, $database ) = $dbDetails;
716 @list
( $table ) = $dbDetails;
718 $prefix = $this->mTablePrefix
; # Default prefix
720 # A database name has been specified in input. Quote the table name
721 # because we don't want any prefixes added.
722 if( isset($database) ) {
723 $table = ( $table[0] == '"' ?
$table : "\"{$table}\"" );
726 # Note that we use the long format because php will complain in in_array if
727 # the input is not an array, and will complain in is_array if it is not set.
728 if( !isset( $database ) # Don't use shared database if pre selected.
729 && isset( $wgSharedDB ) # We have a shared database
730 && $table[0] != '"' # Paranoia check to prevent shared tables listing '`table`'
731 && isset( $wgSharedTables )
732 && is_array( $wgSharedTables )
733 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
734 $database = $wgSharedDB;
735 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
738 # Quote the $database and $table and apply the prefix if not quoted.
739 if( isset($database) ) {
740 $database = ( $database[0] == '"' ?
$database : "\"{$database}\"" );
742 $table = ( $table[0] == '"' ?
$table : "\"{$prefix}{$table}\"" );
744 # Merge our database and table into our final table name.
745 $tableName = ( isset($database) ?
"{$database}.\"{$wgDBmwschema}\".{$table}" : "{$table}" );
747 # We're finished, return.
752 * Return the next in a sequence, save the value for retrieval via insertId()
754 function nextSequenceValue( $seqName ) {
755 $safeseq = str_replace( "'", "''", $seqName );
756 $res = $this->query( "SELECT nextval('$safeseq')" );
757 $row = $this->fetchRow( $res );
758 $this->mInsertId
= $row[0];
759 return $this->mInsertId
;
763 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
765 function currentSequenceValue( $seqName ) {
766 $safeseq = str_replace( "'", "''", $seqName );
767 $res = $this->query( "SELECT currval('$safeseq')" );
768 $row = $this->fetchRow( $res );
774 * REPLACE query wrapper
775 * Postgres simulates this with a DELETE followed by INSERT
776 * $row is the row to insert, an associative array
777 * $uniqueIndexes is an array of indexes. Each element may be either a
778 * field name or an array of field names
780 * It may be more efficient to leave off unique indexes which are unlikely to collide.
781 * However if you do this, you run the risk of encountering errors which wouldn't have
784 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
785 $table = $this->tableName( $table );
787 if ( count( $rows ) == 0 ) {
792 if ( !is_array( reset( $rows ) ) ) {
793 $rows = array( $rows );
796 foreach( $rows as $row ) {
797 # Delete rows which collide
798 if ( $uniqueIndexes ) {
799 $sql = "DELETE FROM $table WHERE ";
801 foreach ( $uniqueIndexes as $index ) {
808 if ( is_array( $index ) ) {
810 foreach ( $index as $col ) {
816 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
819 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
823 $this->query( $sql, $fname );
827 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
828 $this->makeList( $row, LIST_COMMA
) . ')';
829 $this->query( $sql, $fname );
833 # DELETE where the condition is a join
834 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
836 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
839 $delTable = $this->tableName( $delTable );
840 $joinTable = $this->tableName( $joinTable );
841 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
842 if ( $conds != '*' ) {
843 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
847 $this->query( $sql, $fname );
850 # Returns the size of a text field, or -1 for "unlimited"
851 function textFieldSize( $table, $field ) {
852 $table = $this->tableName( $table );
853 $sql = "SELECT t.typname as ftype,a.atttypmod as size
854 FROM pg_class c, pg_attribute a, pg_type t
855 WHERE relname='$table' AND a.attrelid=c.oid AND
856 a.atttypid=t.oid and a.attname='$field'";
857 $res =$this->query( $sql );
858 $row = $this->fetchObject( $res );
859 if ( $row->ftype
== 'varchar' ) {
860 $size = $row->size
- 4;
867 function limitResult( $sql, $limit, $offset = false ) {
868 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
871 function wasDeadlock() {
872 return $this->lastErrno() == '40P01';
875 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
876 $newName = $this->addIdentifierQuotes( $newName );
877 $oldName = $this->addIdentifierQuotes( $oldName );
878 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
881 function timestamp( $ts = 0 ) {
882 return wfTimestamp( TS_POSTGRES
, $ts );
886 * Return aggregated value function call
888 function aggregateValue( $valuedata, $valuename = 'value' ) {
892 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
893 // Ignore errors during error handling to avoid infinite recursion
894 $ignore = $this->ignoreErrors( true );
895 $this->mErrorCount++
;
897 if ( $ignore ||
$tempIgnore ) {
898 wfDebug( "SQL ERROR (ignored): $error\n" );
899 $this->ignoreErrors( $ignore );
901 $message = "A database error has occurred. Did you forget to run maintenance/update.php after upgrading? See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
903 "Function: $fname\n" .
904 "Error: $errno $error\n";
905 throw new DBUnexpectedError( $this, $message );
910 * @return string wikitext of a link to the server software's web site
912 public static function getSoftwareLink() {
913 return '[http://www.postgresql.org/ PostgreSQL]';
917 * @return string Version information from the database
919 function getServerVersion() {
920 if ( !isset( $this->numeric_version
) ) {
921 $versionInfo = pg_version( $this->mConn
);
922 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
923 // Old client, abort install
924 $this->numeric_version
= '7.3 or earlier';
925 } elseif ( isset( $versionInfo['server'] ) ) {
927 $this->numeric_version
= $versionInfo['server'];
929 // Bug 16937: broken pgsql extension from PHP<5.3
930 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
933 return $this->numeric_version
;
937 * Query whether a given relation exists (in the given schema, or the
938 * default mw one if not given)
940 function relationExists( $table, $types, $schema = false ) {
941 global $wgDBmwschema;
942 if ( !is_array( $types ) ) {
943 $types = array( $types );
946 $schema = $wgDBmwschema;
948 $table = $this->tableName( $table, false );
949 $etable = $this->addQuotes( $table );
950 $eschema = $this->addQuotes( $schema );
951 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
952 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
953 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
954 $res = $this->query( $SQL );
955 $count = $res ?
$res->numRows() : 0;
960 * For backward compatibility, this function checks both tables and
963 function tableExists( $table, $schema = false ) {
964 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
967 function sequenceExists( $sequence, $schema = false ) {
968 return $this->relationExists( $sequence, 'S', $schema );
971 function triggerExists( $table, $trigger ) {
972 global $wgDBmwschema;
975 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
976 WHERE relnamespace=pg_namespace.oid AND relkind='r'
977 AND tgrelid=pg_class.oid
978 AND nspname=%s AND relname=%s AND tgname=%s
983 $this->addQuotes( $wgDBmwschema ),
984 $this->addQuotes( $table ),
985 $this->addQuotes( $trigger )
991 $rows = $res->numRows();
995 function ruleExists( $table, $rule ) {
996 global $wgDBmwschema;
997 $exists = $this->selectField( 'pg_rules', 'rulename',
1000 'tablename' => $table,
1001 'schemaname' => $wgDBmwschema
1004 return $exists === $rule;
1007 function constraintExists( $table, $constraint ) {
1008 global $wgDBmwschema;
1009 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1010 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1011 $this->addQuotes( $wgDBmwschema ),
1012 $this->addQuotes( $table ),
1013 $this->addQuotes( $constraint )
1015 $res = $this->query( $SQL );
1019 $rows = $res->numRows();
1024 * Query whether a given schema exists. Returns the name of the owner
1026 function schemaExists( $schema ) {
1027 $eschema = str_replace( "'", "''", $schema );
1028 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1029 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1030 $res = $this->query( $SQL );
1031 if ( $res && $res->numRows() ) {
1032 $row = $res->fetchObject();
1033 $owner = $row->rolname
;
1040 function fieldInfo( $table, $field ) {
1041 return PostgresField
::fromText( $this, $table, $field );
1045 * pg_field_type() wrapper
1047 function fieldType( $res, $index ) {
1048 if ( $res instanceof ResultWrapper
) {
1049 $res = $res->result
;
1051 return pg_field_type( $res, $index );
1054 /* Not even sure why this is used in the main codebase... */
1055 function limitResultForUpdate( $sql, $num ) {
1063 function encodeBlob( $b ) {
1064 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1067 function decodeBlob( $b ) {
1068 if ( $b instanceof Blob
) {
1071 return pg_unescape_bytea( $b );
1074 function strencode( $s ) { # Should not be called by us
1075 return pg_escape_string( $this->mConn
, $s );
1079 * @param $s null|bool|Blob
1080 * @return int|string
1082 function addQuotes( $s ) {
1083 if ( is_null( $s ) ) {
1085 } elseif ( is_bool( $s ) ) {
1086 return intval( $s );
1087 } elseif ( $s instanceof Blob
) {
1088 return "'" . $s->fetch( $s ) . "'";
1090 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1094 * Postgres specific version of replaceVars.
1095 * Calls the parent version in Database.php
1099 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1101 * @return string SQL string
1103 protected function replaceVars( $ins ) {
1104 $ins = parent
::replaceVars( $ins );
1106 if ( $this->numeric_version
>= 8.3 ) {
1107 // Thanks for not providing backwards-compatibility, 8.3
1108 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1111 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1112 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1119 * Various select options
1123 * @param $options Array: an associative array of options to be turned into
1124 * an SQL query, valid keys are listed in the function.
1127 function makeSelectOptions( $options ) {
1128 $preLimitTail = $postLimitTail = '';
1129 $startOpts = $useIndex = '';
1131 $noKeyOptions = array();
1132 foreach ( $options as $key => $option ) {
1133 if ( is_numeric( $key ) ) {
1134 $noKeyOptions[$option] = true;
1138 if ( isset( $options['GROUP BY'] ) ) {
1139 $gb = is_array( $options['GROUP BY'] )
1140 ?
implode( ',', $options['GROUP BY'] )
1141 : $options['GROUP BY'];
1142 $preLimitTail .= " GROUP BY {$gb}";
1145 if ( isset( $options['HAVING'] ) ) {
1146 $preLimitTail .= " HAVING {$options['HAVING']}";
1149 if ( isset( $options['ORDER BY'] ) ) {
1150 $ob = is_array( $options['ORDER BY'] )
1151 ?
implode( ',', $options['ORDER BY'] )
1152 : $options['ORDER BY'];
1153 $preLimitTail .= " ORDER BY {$ob}";
1156 //if ( isset( $options['LIMIT'] ) ) {
1157 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1158 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1162 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1163 $postLimitTail .= ' FOR UPDATE';
1165 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1166 $postLimitTail .= ' LOCK IN SHARE MODE';
1168 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1169 $startOpts .= 'DISTINCT';
1172 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1175 function setFakeMaster( $enabled = true ) {}
1177 function getDBname() {
1178 return $this->mDBname
;
1181 function getServer() {
1182 return $this->mServer
;
1185 function buildConcat( $stringList ) {
1186 return implode( ' || ', $stringList );
1189 public function getSearchEngine() {
1190 return 'SearchPostgres';
1192 } // end DatabasePostgres class