3 * This is the Postgres database abstraction layer.
9 class PostgresField
implements Field
{
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
12 static function fromText($db, $table, $field) {
17 attnotnull, attlen, COALESCE(conname, '') AS conname,
18 COALESCE(condeferred, 'f') AS deferred,
19 COALESCE(condeferrable, 'f') AS deferrable,
20 CASE WHEN typname = 'int2' THEN 'smallint'
21 WHEN typname = 'int4' THEN 'integer'
22 WHEN typname = 'int8' THEN 'bigint'
23 WHEN typname = 'bpchar' THEN 'char'
24 ELSE typname END AS typname
26 JOIN pg_namespace n ON (n.oid = c.relnamespace)
27 JOIN pg_attribute a ON (a.attrelid = c.oid)
28 JOIN pg_type t ON (t.oid = a.atttypid)
29 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
36 $table = $db->tableName( $table );
39 $db->addQuotes( $wgDBmwschema ),
40 $db->addQuotes( $table ),
41 $db->addQuotes( $field )
44 $row = $db->fetchObject( $res );
48 $n = new PostgresField
;
49 $n->type
= $row->typname
;
50 $n->nullable
= ( $row->attnotnull
== 'f' );
52 $n->tablename
= $table;
53 $n->max_length
= $row->attlen
;
54 $n->deferrable
= ( $row->deferrable
== 't' );
55 $n->deferred
= ( $row->deferred
== 't' );
56 $n->conname
= $row->conname
;
64 function tableName() {
65 return $this->tablename
;
72 function isNullable() {
73 return $this->nullable
;
76 function maxLength() {
77 return $this->max_length
;
80 function is_deferrable() {
81 return $this->deferrable
;
84 function is_deferred() {
85 return $this->deferred
;
89 return $this->conname
;
97 class DatabasePostgres
extends DatabaseBase
{
98 var $mInsertId = null;
99 var $mLastResult = null;
100 var $numeric_version = null;
101 var $mAffectedRows = null;
107 function cascadingDeletes() {
110 function cleanupTriggers() {
113 function strictIPs() {
116 function realTimestamps() {
119 function implicitGroupby() {
122 function implicitOrderby() {
125 function searchableIPs() {
128 function functionalIndexes() {
132 function hasConstraint( $name ) {
133 global $wgDBmwschema;
134 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
135 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $wgDBmwschema ) ."'";
136 $res = $this->doQuery( $SQL );
137 return $this->numRows( $res );
141 * Usually aborts on failure
143 function open( $server, $user, $password, $dbName ) {
144 # Test for Postgres support, to avoid suppressed fatal error
145 if ( !function_exists( 'pg_connect' ) ) {
146 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" );
151 if ( !strlen( $user ) ) { # e.g. the class is being loaded
156 $this->mServer
= $server;
157 $this->mPort
= $port = $wgDBport;
158 $this->mUser
= $user;
159 $this->mPassword
= $password;
160 $this->mDBname
= $dbName;
162 $connectVars = array(
165 'password' => $password
167 if ( $server != false && $server != '' ) {
168 $connectVars['host'] = $server;
170 if ( $port != false && $port != '' ) {
171 $connectVars['port'] = $port;
173 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
175 $this->installErrorHandler();
176 $this->mConn
= pg_connect( $connectString );
177 $phpError = $this->restoreErrorHandler();
179 if ( !$this->mConn
) {
180 wfDebug( "DB connection error\n" );
181 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
182 wfDebug( $this->lastError() . "\n" );
183 throw new DBConnectionError( $this, $phpError );
186 $this->mOpened
= true;
188 global $wgCommandLineMode;
189 # If called from the command-line (e.g. importDump), only show errors
190 if ( $wgCommandLineMode ) {
191 $this->doQuery( "SET client_min_messages = 'ERROR'" );
194 $this->doQuery( "SET client_encoding='UTF8'" );
195 $this->doQuery( "SET datestyle = 'ISO, YMD'" );
196 $this->doQuery( "SET timezone = 'GMT'" );
198 global $wgDBmwschema;
199 if ( isset( $wgDBmwschema )
200 && $wgDBmwschema !== 'mediawiki'
201 && preg_match( '/^\w+$/', $wgDBmwschema )
203 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
204 $this->doQuery( "SET search_path = $safeschema, public" );
210 function makeConnectionString( $vars ) {
212 foreach ( $vars as $name => $value ) {
213 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
219 function initial_setup( $superuser, $password, $dbName ) {
220 // If this is the initial connection, setup the schema stuff and possibly create the user
221 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBmwschema, $wgDBts2schema;
223 $safeuser = $this->addIdentifierQuotes( $wgDBuser );
224 // Are we connecting as a superuser for the first time?
226 // Are we really a superuser? Check out our rights
228 CASE WHEN usesuper IS TRUE THEN
229 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
230 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
232 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $superuser );
233 $rows = $this->numRows( $res = $this->doQuery( $SQL ) );
235 print '<li>ERROR: Could not read permissions for user "' . htmlspecialchars( $superuser ) . "\"</li>\n";
238 $perms = pg_fetch_result( $res, 0, 0 );
240 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $wgDBuser );
241 $rows = $this->numRows( $this->doQuery( $SQL ) );
243 print '<li>User "' . htmlspecialchars( $wgDBuser ) . '" already exists, skipping account creation.</li>';
245 if ( $perms != 1 && $perms != 3 ) {
246 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create other users. ';
247 print 'Please use a different Postgres user.</li>';
250 print '<li>Creating user <b>' . htmlspecialchars( $wgDBuser ) . '</b>...';
251 $safepass = $this->addQuotes( $wgDBpassword );
252 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
253 $this->doQuery( $SQL );
256 // User now exists, check out the database
257 if ( $dbName != $wgDBname ) {
258 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes( $wgDBname );
259 $rows = $this->numRows( $this->doQuery( $SQL ) );
261 print '<li>Database "' . htmlspecialchars( $wgDBname ) . '" already exists, skipping database creation.</li>';
264 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create databases. ';
265 print 'Please use a different Postgres user.</li>';
268 print '<li>Creating database <b>' . htmlspecialchars( $wgDBname ) . '</b>...';
269 $safename = $this->addIdentifierQuotes( $wgDBname );
270 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
271 $this->doQuery( $SQL );
273 // Hopefully tsearch2 and plpgsql are in template1...
276 // Reconnect to check out tsearch2 rights for this user
277 print '<li>Connecting to "' . htmlspecialchars( $wgDBname ) . '" as superuser "' .
278 htmlspecialchars( $superuser ) . '" to check rights...';
280 $connectVars = array();
281 if ( $this->mServer
!= false && $this->mServer
!= '' ) {
282 $connectVars['host'] = $this->mServer
;
284 if ( $this->mPort
!= false && $this->mPort
!= '' ) {
285 $connectVars['port'] = $this->mPort
;
287 $connectVars['dbname'] = $wgDBname;
288 $connectVars['user'] = $superuser;
289 $connectVars['password'] = $password;
291 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
292 if ( !$this->mConn
) {
293 print "<b>FAILED TO CONNECT!</b></li>";
299 // Setup the schema for this user if needed
300 $result = $this->schemaExists( $wgDBmwschema );
301 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
303 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
304 $result = $this->doQuery( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
306 print "<b>FAILED</b>.</li>\n";
311 print "<li>Schema already exists, explicitly granting rights...\n";
312 $safeschema2 = $this->addQuotes( $wgDBmwschema );
313 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
314 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
315 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
316 "AND p.relkind IN ('r','S','v')\n";
318 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
319 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
320 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
321 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
322 $res = $this->doQuery( $SQL );
324 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
327 $this->doQuery( "SET search_path = $safeschema" );
328 $rows = $this->numRows( $res );
331 $this->doQuery( pg_fetch_result( $res, $rows, 0 ) );
336 // Install plpgsql if needed
337 $this->setup_plpgsql();
339 return true; // Reconnect as regular user
343 if ( !defined( 'POSTGRES_SEARCHPATH' ) ) {
344 // Install plpgsql if needed
345 $this->setup_plpgsql();
347 // Does the schema already exist? Who owns it?
348 $result = $this->schemaExists( $wgDBmwschema );
350 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
351 error_reporting( 0 );
352 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
353 $result = $this->doQuery( "CREATE SCHEMA $safeschema" );
354 error_reporting( E_ALL
);
356 print '<b>FAILED</b>. The user "' . htmlspecialchars( $wgDBuser ) .
357 '" must be able to access the schema. '.
358 'You can try making them the owner of the database, or try creating the schema with a '.
359 'different user, and then grant access to the "' .
360 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
364 } elseif ( $result != $wgDBuser ) {
365 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists but is not owned by "' .
366 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
368 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists and is owned by "' .
369 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
372 // Always return GMT time to accomodate the existing integer-based timestamp assumption
373 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . '" ...';
374 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
375 $result = pg_query( $this->mConn
, $SQL );
377 print "<b>FAILED</b>.</li>\n";
381 // Set for the rest of this session
382 $SQL = "SET timezone = 'GMT'";
383 $result = pg_query( $this->mConn
, $SQL );
385 print "<li>Failed to set timezone</li>\n";
389 print '<li>Setting the datestyle to ISO, YMD for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
390 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
391 $result = pg_query( $this->mConn
, $SQL );
393 print "<b>FAILED</b>.</li>\n";
397 // Set for the rest of this session
398 $SQL = "SET datestyle = 'ISO, YMD'";
399 $result = pg_query( $this->mConn
, $SQL );
401 print "<li>Failed to set datestyle</li>\n";
405 // Fix up the search paths if needed
406 print '<li>Setting the search path for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
407 $path = $this->addIdentifierQuotes( $wgDBmwschema );
408 if ( $wgDBts2schema !== $wgDBmwschema ) {
409 $path .= ', '. $this->addIdentifierQuotes( $wgDBts2schema );
411 if ( $wgDBmwschema !== 'public' && $wgDBts2schema !== 'public' ) {
414 $SQL = "ALTER USER $safeuser SET search_path = $path";
415 $result = pg_query( $this->mConn
, $SQL );
417 print "<b>FAILED</b>.</li>\n";
421 // Set for the rest of this session
422 $SQL = "SET search_path = $path";
423 $result = pg_query( $this->mConn
, $SQL );
425 print "<li>Failed to set search_path</li>\n";
428 define( 'POSTGRES_SEARCHPATH', $path );
433 * Closes a database connection, if it is open
434 * Returns success, true if already closed
437 $this->mOpened
= false;
438 if ( $this->mConn
) {
439 return pg_close( $this->mConn
);
445 function doQuery( $sql ) {
446 if ( function_exists( 'mb_convert_encoding' ) ) {
447 $sql = mb_convert_encoding( $sql, 'UTF-8' );
449 $this->mLastResult
= pg_query( $this->mConn
, $sql );
450 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
451 return $this->mLastResult
;
454 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
455 return $this->query( $sql, $fname, true );
458 function freeResult( $res ) {
459 if ( $res instanceof ResultWrapper
) {
462 if ( !@pg_free_result
( $res ) ) {
463 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
467 function fetchObject( $res ) {
468 if ( $res instanceof ResultWrapper
) {
471 @$row = pg_fetch_object( $res );
472 # FIXME: HACK HACK HACK HACK debug
475 # hashar : not sure if the following test really trigger if the object
477 if( pg_last_error( $this->mConn
) ) {
478 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
483 function fetchRow( $res ) {
484 if ( $res instanceof ResultWrapper
) {
487 @$row = pg_fetch_array( $res );
488 if( pg_last_error( $this->mConn
) ) {
489 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
494 function numRows( $res ) {
495 if ( $res instanceof ResultWrapper
) {
498 @$n = pg_num_rows( $res );
499 if( pg_last_error( $this->mConn
) ) {
500 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
505 function numFields( $res ) {
506 if ( $res instanceof ResultWrapper
) {
509 return pg_num_fields( $res );
512 function fieldName( $res, $n ) {
513 if ( $res instanceof ResultWrapper
) {
516 return pg_field_name( $res, $n );
520 * This must be called after nextSequenceVal
522 function insertId() {
523 return $this->mInsertId
;
526 function dataSeek( $res, $row ) {
527 if ( $res instanceof ResultWrapper
) {
530 return pg_result_seek( $res, $row );
533 function lastError() {
534 if ( $this->mConn
) {
535 return pg_last_error();
537 return 'No database connection';
540 function lastErrno() {
541 return pg_last_error() ?
1 : 0;
544 function affectedRows() {
545 if ( !is_null( $this->mAffectedRows
) ) {
546 // Forced result for simulated queries
547 return $this->mAffectedRows
;
549 if( empty( $this->mLastResult
) ) {
552 return pg_affected_rows( $this->mLastResult
);
556 * Estimate rows in dataset
557 * Returns estimated count, based on EXPLAIN output
558 * This is not necessarily an accurate estimate, so use sparingly
559 * Returns -1 if count cannot be found
560 * Takes same arguments as Database::select()
562 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
563 $options['EXPLAIN'] = true;
564 $res = $this->select( $table, $vars, $conds, $fname, $options );
567 $row = $this->fetchRow( $res );
569 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
577 * Returns information about an index
578 * If errors are explicitly ignored, returns NULL on failure
580 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
581 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
582 $res = $this->query( $sql, $fname );
586 foreach ( $res as $row ) {
587 if ( $row->indexname
== $this->indexName( $index ) ) {
594 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
595 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
596 " AND indexdef LIKE 'CREATE UNIQUE%(" .
597 $this->strencode( $this->indexName( $index ) ) .
599 $res = $this->query( $sql, $fname );
603 foreach ( $res as $row ) {
610 * INSERT wrapper, inserts an array into a table
612 * $args may be a single associative array, or an array of these with numeric keys,
613 * for multi-row insert (Postgres version 8.2 and above only).
615 * @param $table String: Name of the table to insert to.
616 * @param $args Array: Items to insert into the table.
617 * @param $fname String: Name of the function, for profiling
618 * @param $options String or Array. Valid options: IGNORE
620 * @return bool Success of insert operation. IGNORE always returns true.
622 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
623 if ( !count( $args ) ) {
627 $table = $this->tableName( $table );
628 if (! isset( $this->numeric_version
) ) {
629 $this->getServerVersion();
632 if ( !is_array( $options ) ) {
633 $options = array( $options );
636 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
638 $keys = array_keys( $args[0] );
641 $keys = array_keys( $args );
644 // If IGNORE is set, we use savepoints to emulate mysql's behavior
645 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
647 // If we are not in a transaction, we need to be for savepoint trickery
650 if ( !$this->mTrxLevel
) {
654 $olde = error_reporting( 0 );
655 // For future use, we may want to track the number of actual inserts
656 // Right now, insert (all writes) simply return true/false
657 $numrowsinserted = 0;
660 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
663 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
665 foreach ( $args as $row ) {
671 $sql .= '(' . $this->makeList( $row ) . ')';
673 $res = (bool)$this->query( $sql, $fname, $ignore );
677 foreach ( $args as $row ) {
679 $tempsql .= '(' . $this->makeList( $row ) . ')';
682 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
685 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
688 $bar = pg_last_error();
689 if ( $bar != false ) {
690 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
692 pg_query( $this->mConn
, "RELEASE $ignore" );
697 // If any of them fail, we fail overall for this function call
698 // Note that this will be ignored if IGNORE is set
705 // Not multi, just a lone insert
707 pg_query($this->mConn
, "SAVEPOINT $ignore");
710 $sql .= '(' . $this->makeList( $args ) . ')';
711 $res = (bool)$this->query( $sql, $fname, $ignore );
713 $bar = pg_last_error();
714 if ( $bar != false ) {
715 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
717 pg_query( $this->mConn
, "RELEASE $ignore" );
723 $olde = error_reporting( $olde );
728 // Set the affected row count for the whole operation
729 $this->mAffectedRows
= $numrowsinserted;
731 // IGNORE always returns true
739 * INSERT SELECT wrapper
740 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
741 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
742 * $conds may be "*" to copy the whole table
743 * srcTable may be an array of tables.
744 * @todo FIXME: implement this a little better (seperate select/insert)?
746 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
747 $insertOptions = array(), $selectOptions = array() )
749 $destTable = $this->tableName( $destTable );
751 // If IGNORE is set, we use savepoints to emulate mysql's behavior
752 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
754 if( is_array( $insertOptions ) ) {
755 $insertOptions = implode( ' ', $insertOptions );
757 if( !is_array( $selectOptions ) ) {
758 $selectOptions = array( $selectOptions );
760 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
761 if( is_array( $srcTable ) ) {
762 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
764 $srcTable = $this->tableName( $srcTable );
767 // If we are not in a transaction, we need to be for savepoint trickery
770 if( !$this->mTrxLevel
) {
774 $olde = error_reporting( 0 );
775 $numrowsinserted = 0;
776 pg_query( $this->mConn
, "SAVEPOINT $ignore");
779 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
780 " SELECT $startOpts " . implode( ',', $varMap ) .
781 " FROM $srcTable $useIndex";
783 if ( $conds != '*' ) {
784 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
787 $sql .= " $tailOpts";
789 $res = (bool)$this->query( $sql, $fname, $ignore );
791 $bar = pg_last_error();
792 if( $bar != false ) {
793 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
795 pg_query( $this->mConn
, "RELEASE $ignore" );
798 $olde = error_reporting( $olde );
803 // Set the affected row count for the whole operation
804 $this->mAffectedRows
= $numrowsinserted;
806 // IGNORE always returns true
813 function tableName( $name ) {
814 # Replace reserved words with better ones
819 return 'pagecontent';
826 * Return the next in a sequence, save the value for retrieval via insertId()
828 function nextSequenceValue( $seqName ) {
829 $safeseq = str_replace( "'", "''", $seqName );
830 $res = $this->query( "SELECT nextval('$safeseq')" );
831 $row = $this->fetchRow( $res );
832 $this->mInsertId
= $row[0];
833 return $this->mInsertId
;
837 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
839 function currentSequenceValue( $seqName ) {
840 $safeseq = str_replace( "'", "''", $seqName );
841 $res = $this->query( "SELECT currval('$safeseq')" );
842 $row = $this->fetchRow( $res );
848 * REPLACE query wrapper
849 * Postgres simulates this with a DELETE followed by INSERT
850 * $row is the row to insert, an associative array
851 * $uniqueIndexes is an array of indexes. Each element may be either a
852 * field name or an array of field names
854 * It may be more efficient to leave off unique indexes which are unlikely to collide.
855 * However if you do this, you run the risk of encountering errors which wouldn't have
858 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
859 $table = $this->tableName( $table );
861 if ( count( $rows ) == 0 ) {
866 if ( !is_array( reset( $rows ) ) ) {
867 $rows = array( $rows );
870 foreach( $rows as $row ) {
871 # Delete rows which collide
872 if ( $uniqueIndexes ) {
873 $sql = "DELETE FROM $table WHERE ";
875 foreach ( $uniqueIndexes as $index ) {
882 if ( is_array( $index ) ) {
884 foreach ( $index as $col ) {
890 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
893 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
897 $this->query( $sql, $fname );
901 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
902 $this->makeList( $row, LIST_COMMA
) . ')';
903 $this->query( $sql, $fname );
907 # DELETE where the condition is a join
908 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
910 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
913 $delTable = $this->tableName( $delTable );
914 $joinTable = $this->tableName( $joinTable );
915 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
916 if ( $conds != '*' ) {
917 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
921 $this->query( $sql, $fname );
924 # Returns the size of a text field, or -1 for "unlimited"
925 function textFieldSize( $table, $field ) {
926 $table = $this->tableName( $table );
927 $sql = "SELECT t.typname as ftype,a.atttypmod as size
928 FROM pg_class c, pg_attribute a, pg_type t
929 WHERE relname='$table' AND a.attrelid=c.oid AND
930 a.atttypid=t.oid and a.attname='$field'";
931 $res =$this->query( $sql );
932 $row = $this->fetchObject( $res );
933 if ( $row->ftype
== 'varchar' ) {
934 $size = $row->size
- 4;
941 function limitResult( $sql, $limit, $offset = false ) {
942 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
945 function wasDeadlock() {
946 return $this->lastErrno() == '40P01';
949 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
950 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
953 function timestamp( $ts = 0 ) {
954 return wfTimestamp( TS_POSTGRES
, $ts );
958 * Return aggregated value function call
960 function aggregateValue( $valuedata, $valuename = 'value' ) {
964 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
965 // Ignore errors during error handling to avoid infinite recursion
966 $ignore = $this->ignoreErrors( true );
967 $this->mErrorCount++
;
969 if ( $ignore ||
$tempIgnore ) {
970 wfDebug( "SQL ERROR (ignored): $error\n" );
971 $this->ignoreErrors( $ignore );
973 $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" .
975 "Function: $fname\n" .
976 "Error: $errno $error\n";
977 throw new DBUnexpectedError( $this, $message );
982 * @return string wikitext of a link to the server software's web site
984 public static function getSoftwareLink() {
985 return '[http://www.postgresql.org/ PostgreSQL]';
989 * @return string Version information from the database
991 function getServerVersion() {
992 if ( !isset( $this->numeric_version
) ) {
993 $versionInfo = pg_version( $this->mConn
);
994 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
995 // Old client, abort install
996 $this->numeric_version
= '7.3 or earlier';
997 } elseif ( isset( $versionInfo['server'] ) ) {
999 $this->numeric_version
= $versionInfo['server'];
1001 // Bug 16937: broken pgsql extension from PHP<5.3
1002 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1005 return $this->numeric_version
;
1009 * Query whether a given relation exists (in the given schema, or the
1010 * default mw one if not given)
1012 function relationExists( $table, $types, $schema = false ) {
1013 global $wgDBmwschema;
1014 if ( !is_array( $types ) ) {
1015 $types = array( $types );
1018 $schema = $wgDBmwschema;
1020 $table = $this->tableName( $table );
1021 $etable = $this->addQuotes( $table );
1022 $eschema = $this->addQuotes( $schema );
1023 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1024 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1025 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1026 $res = $this->query( $SQL );
1027 $count = $res ?
$res->numRows() : 0;
1028 return (bool)$count;
1032 * For backward compatibility, this function checks both tables and
1035 function tableExists( $table, $schema = false ) {
1036 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1039 function sequenceExists( $sequence, $schema = false ) {
1040 return $this->relationExists( $sequence, 'S', $schema );
1043 function triggerExists( $table, $trigger ) {
1044 global $wgDBmwschema;
1047 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1048 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1049 AND tgrelid=pg_class.oid
1050 AND nspname=%s AND relname=%s AND tgname=%s
1052 $res = $this->query(
1055 $this->addQuotes( $wgDBmwschema ),
1056 $this->addQuotes( $table ),
1057 $this->addQuotes( $trigger )
1063 $rows = $res->numRows();
1067 function ruleExists( $table, $rule ) {
1068 global $wgDBmwschema;
1069 $exists = $this->selectField( 'pg_rules', 'rulename',
1071 'rulename' => $rule,
1072 'tablename' => $table,
1073 'schemaname' => $wgDBmwschema
1076 return $exists === $rule;
1079 function constraintExists( $table, $constraint ) {
1080 global $wgDBmwschema;
1081 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1082 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1083 $this->addQuotes( $wgDBmwschema ),
1084 $this->addQuotes( $table ),
1085 $this->addQuotes( $constraint )
1087 $res = $this->query( $SQL );
1091 $rows = $res->numRows();
1096 * Query whether a given schema exists. Returns the name of the owner
1098 function schemaExists( $schema ) {
1099 $eschema = str_replace( "'", "''", $schema );
1100 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1101 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1102 $res = $this->query( $SQL );
1103 if ( $res && $res->numRows() ) {
1104 $row = $res->fetchObject();
1105 $owner = $row->rolname
;
1112 function fieldInfo( $table, $field ) {
1113 return PostgresField
::fromText( $this, $table, $field );
1117 * pg_field_type() wrapper
1119 function fieldType( $res, $index ) {
1120 if ( $res instanceof ResultWrapper
) {
1121 $res = $res->result
;
1123 return pg_field_type( $res, $index );
1126 /* Not even sure why this is used in the main codebase... */
1127 function limitResultForUpdate( $sql, $num ) {
1131 function encodeBlob( $b ) {
1132 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1135 function decodeBlob( $b ) {
1136 if ( $b instanceof Blob
) {
1139 return pg_unescape_bytea( $b );
1142 function strencode( $s ) { # Should not be called by us
1143 return pg_escape_string( $this->mConn
, $s );
1146 function addQuotes( $s ) {
1147 if ( is_null( $s ) ) {
1149 } elseif ( is_bool( $s ) ) {
1150 return intval( $s );
1151 } elseif ( $s instanceof Blob
) {
1152 return "'" . $s->fetch( $s ) . "'";
1154 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1158 * Postgres specific version of replaceVars.
1159 * Calls the parent version in Database.php
1163 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1165 * @return string SQL string
1167 protected function replaceVars( $ins ) {
1168 $ins = parent
::replaceVars( $ins );
1170 if ( $this->numeric_version
>= 8.3 ) {
1171 // Thanks for not providing backwards-compatibility, 8.3
1172 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1175 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1176 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1183 * Various select options
1187 * @param $options Array: an associative array of options to be turned into
1188 * an SQL query, valid keys are listed in the function.
1191 function makeSelectOptions( $options ) {
1192 $preLimitTail = $postLimitTail = '';
1193 $startOpts = $useIndex = '';
1195 $noKeyOptions = array();
1196 foreach ( $options as $key => $option ) {
1197 if ( is_numeric( $key ) ) {
1198 $noKeyOptions[$option] = true;
1202 if ( isset( $options['GROUP BY'] ) ) {
1203 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1205 if ( isset( $options['HAVING'] ) ) {
1206 $preLimitTail .= " HAVING {$options['HAVING']}";
1208 if ( isset( $options['ORDER BY'] ) ) {
1209 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1212 //if ( isset( $options['LIMIT'] ) ) {
1213 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1214 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1218 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1219 $postLimitTail .= ' FOR UPDATE';
1221 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1222 $postLimitTail .= ' LOCK IN SHARE MODE';
1224 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1225 $startOpts .= 'DISTINCT';
1228 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1231 function setFakeMaster( $enabled = true ) {}
1233 function getDBname() {
1234 return $this->mDBname
;
1237 function getServer() {
1238 return $this->mServer
;
1241 function buildConcat( $stringList ) {
1242 return implode( ' || ', $stringList );
1245 public function getSearchEngine() {
1246 return 'SearchPostgres';
1248 } // end DatabasePostgres class