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'" );
196 global $wgDBmwschema;
197 if ( isset( $wgDBmwschema )
198 && $wgDBmwschema !== 'mediawiki'
199 && preg_match( '/^\w+$/', $wgDBmwschema )
201 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
202 $this->doQuery( "SET search_path = $safeschema, public" );
208 function makeConnectionString( $vars ) {
210 foreach ( $vars as $name => $value ) {
211 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
217 function initial_setup( $superuser, $password, $dbName ) {
218 // If this is the initial connection, setup the schema stuff and possibly create the user
219 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBmwschema, $wgDBts2schema;
221 $safeuser = $this->addIdentifierQuotes( $wgDBuser );
222 // Are we connecting as a superuser for the first time?
224 // Are we really a superuser? Check out our rights
226 CASE WHEN usesuper IS TRUE THEN
227 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
228 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
230 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $superuser );
231 $rows = $this->numRows( $res = $this->doQuery( $SQL ) );
233 print '<li>ERROR: Could not read permissions for user "' . htmlspecialchars( $superuser ) . "\"</li>\n";
236 $perms = pg_fetch_result( $res, 0, 0 );
238 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $wgDBuser );
239 $rows = $this->numRows( $this->doQuery( $SQL ) );
241 print '<li>User "' . htmlspecialchars( $wgDBuser ) . '" already exists, skipping account creation.</li>';
243 if ( $perms != 1 && $perms != 3 ) {
244 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create other users. ';
245 print 'Please use a different Postgres user.</li>';
248 print '<li>Creating user <b>' . htmlspecialchars( $wgDBuser ) . '</b>...';
249 $safepass = $this->addQuotes( $wgDBpassword );
250 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
251 $this->doQuery( $SQL );
254 // User now exists, check out the database
255 if ( $dbName != $wgDBname ) {
256 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes( $wgDBname );
257 $rows = $this->numRows( $this->doQuery( $SQL ) );
259 print '<li>Database "' . htmlspecialchars( $wgDBname ) . '" already exists, skipping database creation.</li>';
262 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create databases. ';
263 print 'Please use a different Postgres user.</li>';
266 print '<li>Creating database <b>' . htmlspecialchars( $wgDBname ) . '</b>...';
267 $safename = $this->addIdentifierQuotes( $wgDBname );
268 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
269 $this->doQuery( $SQL );
271 // Hopefully tsearch2 and plpgsql are in template1...
274 // Reconnect to check out tsearch2 rights for this user
275 print '<li>Connecting to "' . htmlspecialchars( $wgDBname ) . '" as superuser "' .
276 htmlspecialchars( $superuser ) . '" to check rights...';
278 $connectVars = array();
279 if ( $this->mServer
!= false && $this->mServer
!= '' ) {
280 $connectVars['host'] = $this->mServer
;
282 if ( $this->mPort
!= false && $this->mPort
!= '' ) {
283 $connectVars['port'] = $this->mPort
;
285 $connectVars['dbname'] = $wgDBname;
286 $connectVars['user'] = $superuser;
287 $connectVars['password'] = $password;
289 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
290 if ( !$this->mConn
) {
291 print "<b>FAILED TO CONNECT!</b></li>";
297 // Setup the schema for this user if needed
298 $result = $this->schemaExists( $wgDBmwschema );
299 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
301 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
302 $result = $this->doQuery( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
304 print "<b>FAILED</b>.</li>\n";
309 print "<li>Schema already exists, explicitly granting rights...\n";
310 $safeschema2 = $this->addQuotes( $wgDBmwschema );
311 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
312 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
313 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
314 "AND p.relkind IN ('r','S','v')\n";
316 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
317 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
318 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
319 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
320 $res = $this->doQuery( $SQL );
322 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
325 $this->doQuery( "SET search_path = $safeschema" );
326 $rows = $this->numRows( $res );
329 $this->doQuery( pg_fetch_result( $res, $rows, 0 ) );
334 // Install plpgsql if needed
335 $this->setup_plpgsql();
337 return true; // Reconnect as regular user
341 if ( !defined( 'POSTGRES_SEARCHPATH' ) ) {
342 // Install plpgsql if needed
343 $this->setup_plpgsql();
345 // Does the schema already exist? Who owns it?
346 $result = $this->schemaExists( $wgDBmwschema );
348 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
349 error_reporting( 0 );
350 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
351 $result = $this->doQuery( "CREATE SCHEMA $safeschema" );
352 error_reporting( E_ALL
);
354 print '<b>FAILED</b>. The user "' . htmlspecialchars( $wgDBuser ) .
355 '" must be able to access the schema. '.
356 'You can try making them the owner of the database, or try creating the schema with a '.
357 'different user, and then grant access to the "' .
358 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
362 } elseif ( $result != $wgDBuser ) {
363 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists but is not owned by "' .
364 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
366 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists and is owned by "' .
367 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
370 // Always return GMT time to accomodate the existing integer-based timestamp assumption
371 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . '" ...';
372 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
373 $result = pg_query( $this->mConn
, $SQL );
375 print "<b>FAILED</b>.</li>\n";
379 // Set for the rest of this session
380 $SQL = "SET timezone = 'GMT'";
381 $result = pg_query( $this->mConn
, $SQL );
383 print "<li>Failed to set timezone</li>\n";
387 print '<li>Setting the datestyle to ISO, YMD for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
388 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
389 $result = pg_query( $this->mConn
, $SQL );
391 print "<b>FAILED</b>.</li>\n";
395 // Set for the rest of this session
396 $SQL = "SET datestyle = 'ISO, YMD'";
397 $result = pg_query( $this->mConn
, $SQL );
399 print "<li>Failed to set datestyle</li>\n";
403 // Fix up the search paths if needed
404 print '<li>Setting the search path for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
405 $path = $this->addIdentifierQuotes( $wgDBmwschema );
406 if ( $wgDBts2schema !== $wgDBmwschema ) {
407 $path .= ', '. $this->addIdentifierQuotes( $wgDBts2schema );
409 if ( $wgDBmwschema !== 'public' && $wgDBts2schema !== 'public' ) {
412 $SQL = "ALTER USER $safeuser SET search_path = $path";
413 $result = pg_query( $this->mConn
, $SQL );
415 print "<b>FAILED</b>.</li>\n";
419 // Set for the rest of this session
420 $SQL = "SET search_path = $path";
421 $result = pg_query( $this->mConn
, $SQL );
423 print "<li>Failed to set search_path</li>\n";
426 define( 'POSTGRES_SEARCHPATH', $path );
431 * Closes a database connection, if it is open
432 * Returns success, true if already closed
435 $this->mOpened
= false;
436 if ( $this->mConn
) {
437 return pg_close( $this->mConn
);
443 function doQuery( $sql ) {
444 if ( function_exists( 'mb_convert_encoding' ) ) {
445 $sql = mb_convert_encoding( $sql, 'UTF-8' );
447 $this->mLastResult
= pg_query( $this->mConn
, $sql );
448 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
449 return $this->mLastResult
;
452 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
453 return $this->query( $sql, $fname, true );
456 function freeResult( $res ) {
457 if ( $res instanceof ResultWrapper
) {
460 if ( !@pg_free_result
( $res ) ) {
461 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
465 function fetchObject( $res ) {
466 if ( $res instanceof ResultWrapper
) {
469 @$row = pg_fetch_object( $res );
470 # FIXME: HACK HACK HACK HACK debug
473 # hashar : not sure if the following test really trigger if the object
475 if( pg_last_error( $this->mConn
) ) {
476 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
481 function fetchRow( $res ) {
482 if ( $res instanceof ResultWrapper
) {
485 @$row = pg_fetch_array( $res );
486 if( pg_last_error( $this->mConn
) ) {
487 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
492 function numRows( $res ) {
493 if ( $res instanceof ResultWrapper
) {
496 @$n = pg_num_rows( $res );
497 if( pg_last_error( $this->mConn
) ) {
498 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
503 function numFields( $res ) {
504 if ( $res instanceof ResultWrapper
) {
507 return pg_num_fields( $res );
510 function fieldName( $res, $n ) {
511 if ( $res instanceof ResultWrapper
) {
514 return pg_field_name( $res, $n );
518 * This must be called after nextSequenceVal
520 function insertId() {
521 return $this->mInsertId
;
524 function dataSeek( $res, $row ) {
525 if ( $res instanceof ResultWrapper
) {
528 return pg_result_seek( $res, $row );
531 function lastError() {
532 if ( $this->mConn
) {
533 return pg_last_error();
535 return 'No database connection';
538 function lastErrno() {
539 return pg_last_error() ?
1 : 0;
542 function affectedRows() {
543 if ( !is_null( $this->mAffectedRows
) ) {
544 // Forced result for simulated queries
545 return $this->mAffectedRows
;
547 if( empty( $this->mLastResult
) ) {
550 return pg_affected_rows( $this->mLastResult
);
554 * Estimate rows in dataset
555 * Returns estimated count, based on EXPLAIN output
556 * This is not necessarily an accurate estimate, so use sparingly
557 * Returns -1 if count cannot be found
558 * Takes same arguments as Database::select()
560 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
561 $options['EXPLAIN'] = true;
562 $res = $this->select( $table, $vars, $conds, $fname, $options );
565 $row = $this->fetchRow( $res );
567 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
575 * Returns information about an index
576 * If errors are explicitly ignored, returns NULL on failure
578 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
579 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
580 $res = $this->query( $sql, $fname );
584 foreach ( $res as $row ) {
585 if ( $row->indexname
== $this->indexName( $index ) ) {
592 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
593 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
594 " AND indexdef LIKE 'CREATE UNIQUE%(" .
595 $this->strencode( $this->indexName( $index ) ) .
597 $res = $this->query( $sql, $fname );
601 foreach ( $res as $row ) {
608 * INSERT wrapper, inserts an array into a table
610 * $args may be a single associative array, or an array of these with numeric keys,
611 * for multi-row insert (Postgres version 8.2 and above only).
613 * @param $table String: Name of the table to insert to.
614 * @param $args Array: Items to insert into the table.
615 * @param $fname String: Name of the function, for profiling
616 * @param $options String or Array. Valid options: IGNORE
618 * @return bool Success of insert operation. IGNORE always returns true.
620 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
621 if ( !count( $args ) ) {
625 $table = $this->tableName( $table );
626 if (! isset( $this->numeric_version
) ) {
627 $this->getServerVersion();
630 if ( !is_array( $options ) ) {
631 $options = array( $options );
634 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
636 $keys = array_keys( $args[0] );
639 $keys = array_keys( $args );
642 // If IGNORE is set, we use savepoints to emulate mysql's behavior
643 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
645 // If we are not in a transaction, we need to be for savepoint trickery
648 if ( !$this->mTrxLevel
) {
652 $olde = error_reporting( 0 );
653 // For future use, we may want to track the number of actual inserts
654 // Right now, insert (all writes) simply return true/false
655 $numrowsinserted = 0;
658 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
661 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
663 foreach ( $args as $row ) {
669 $sql .= '(' . $this->makeList( $row ) . ')';
671 $res = (bool)$this->query( $sql, $fname, $ignore );
675 foreach ( $args as $row ) {
677 $tempsql .= '(' . $this->makeList( $row ) . ')';
680 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
683 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
686 $bar = pg_last_error();
687 if ( $bar != false ) {
688 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
690 pg_query( $this->mConn
, "RELEASE $ignore" );
695 // If any of them fail, we fail overall for this function call
696 // Note that this will be ignored if IGNORE is set
703 // Not multi, just a lone insert
705 pg_query($this->mConn
, "SAVEPOINT $ignore");
708 $sql .= '(' . $this->makeList( $args ) . ')';
709 $res = (bool)$this->query( $sql, $fname, $ignore );
711 $bar = pg_last_error();
712 if ( $bar != false ) {
713 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
715 pg_query( $this->mConn
, "RELEASE $ignore" );
721 $olde = error_reporting( $olde );
726 // Set the affected row count for the whole operation
727 $this->mAffectedRows
= $numrowsinserted;
729 // IGNORE always returns true
737 * INSERT SELECT wrapper
738 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
739 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
740 * $conds may be "*" to copy the whole table
741 * srcTable may be an array of tables.
742 * @todo FIXME: implement this a little better (seperate select/insert)?
744 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
745 $insertOptions = array(), $selectOptions = array() )
747 $destTable = $this->tableName( $destTable );
749 // If IGNORE is set, we use savepoints to emulate mysql's behavior
750 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
752 if( is_array( $insertOptions ) ) {
753 $insertOptions = implode( ' ', $insertOptions );
755 if( !is_array( $selectOptions ) ) {
756 $selectOptions = array( $selectOptions );
758 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
759 if( is_array( $srcTable ) ) {
760 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
762 $srcTable = $this->tableName( $srcTable );
765 // If we are not in a transaction, we need to be for savepoint trickery
768 if( !$this->mTrxLevel
) {
772 $olde = error_reporting( 0 );
773 $numrowsinserted = 0;
774 pg_query( $this->mConn
, "SAVEPOINT $ignore");
777 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
778 " SELECT $startOpts " . implode( ',', $varMap ) .
779 " FROM $srcTable $useIndex";
781 if ( $conds != '*' ) {
782 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
785 $sql .= " $tailOpts";
787 $res = (bool)$this->query( $sql, $fname, $ignore );
789 $bar = pg_last_error();
790 if( $bar != false ) {
791 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
793 pg_query( $this->mConn
, "RELEASE $ignore" );
796 $olde = error_reporting( $olde );
801 // Set the affected row count for the whole operation
802 $this->mAffectedRows
= $numrowsinserted;
804 // IGNORE always returns true
811 function tableName( $name ) {
812 # Replace reserved words with better ones
817 return 'pagecontent';
824 * Return the next in a sequence, save the value for retrieval via insertId()
826 function nextSequenceValue( $seqName ) {
827 $safeseq = str_replace( "'", "''", $seqName );
828 $res = $this->query( "SELECT nextval('$safeseq')" );
829 $row = $this->fetchRow( $res );
830 $this->mInsertId
= $row[0];
831 return $this->mInsertId
;
835 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
837 function currentSequenceValue( $seqName ) {
838 $safeseq = str_replace( "'", "''", $seqName );
839 $res = $this->query( "SELECT currval('$safeseq')" );
840 $row = $this->fetchRow( $res );
846 * REPLACE query wrapper
847 * Postgres simulates this with a DELETE followed by INSERT
848 * $row is the row to insert, an associative array
849 * $uniqueIndexes is an array of indexes. Each element may be either a
850 * field name or an array of field names
852 * It may be more efficient to leave off unique indexes which are unlikely to collide.
853 * However if you do this, you run the risk of encountering errors which wouldn't have
856 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
857 $table = $this->tableName( $table );
859 if ( count( $rows ) == 0 ) {
864 if ( !is_array( reset( $rows ) ) ) {
865 $rows = array( $rows );
868 foreach( $rows as $row ) {
869 # Delete rows which collide
870 if ( $uniqueIndexes ) {
871 $sql = "DELETE FROM $table WHERE ";
873 foreach ( $uniqueIndexes as $index ) {
880 if ( is_array( $index ) ) {
882 foreach ( $index as $col ) {
888 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
891 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
895 $this->query( $sql, $fname );
899 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
900 $this->makeList( $row, LIST_COMMA
) . ')';
901 $this->query( $sql, $fname );
905 # DELETE where the condition is a join
906 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
908 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
911 $delTable = $this->tableName( $delTable );
912 $joinTable = $this->tableName( $joinTable );
913 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
914 if ( $conds != '*' ) {
915 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
919 $this->query( $sql, $fname );
922 # Returns the size of a text field, or -1 for "unlimited"
923 function textFieldSize( $table, $field ) {
924 $table = $this->tableName( $table );
925 $sql = "SELECT t.typname as ftype,a.atttypmod as size
926 FROM pg_class c, pg_attribute a, pg_type t
927 WHERE relname='$table' AND a.attrelid=c.oid AND
928 a.atttypid=t.oid and a.attname='$field'";
929 $res =$this->query( $sql );
930 $row = $this->fetchObject( $res );
931 if ( $row->ftype
== 'varchar' ) {
932 $size = $row->size
- 4;
939 function limitResult( $sql, $limit, $offset = false ) {
940 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
943 function wasDeadlock() {
944 return $this->lastErrno() == '40P01';
947 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
948 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
951 function timestamp( $ts = 0 ) {
952 return wfTimestamp( TS_POSTGRES
, $ts );
956 * Return aggregated value function call
958 function aggregateValue( $valuedata, $valuename = 'value' ) {
962 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
963 // Ignore errors during error handling to avoid infinite recursion
964 $ignore = $this->ignoreErrors( true );
965 $this->mErrorCount++
;
967 if ( $ignore ||
$tempIgnore ) {
968 wfDebug( "SQL ERROR (ignored): $error\n" );
969 $this->ignoreErrors( $ignore );
971 $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" .
973 "Function: $fname\n" .
974 "Error: $errno $error\n";
975 throw new DBUnexpectedError( $this, $message );
980 * @return string wikitext of a link to the server software's web site
982 public static function getSoftwareLink() {
983 return '[http://www.postgresql.org/ PostgreSQL]';
987 * @return string Version information from the database
989 function getServerVersion() {
990 if ( !isset( $this->numeric_version
) ) {
991 $versionInfo = pg_version( $this->mConn
);
992 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
993 // Old client, abort install
994 $this->numeric_version
= '7.3 or earlier';
995 } elseif ( isset( $versionInfo['server'] ) ) {
997 $this->numeric_version
= $versionInfo['server'];
999 // Bug 16937: broken pgsql extension from PHP<5.3
1000 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1003 return $this->numeric_version
;
1007 * Query whether a given relation exists (in the given schema, or the
1008 * default mw one if not given)
1010 function relationExists( $table, $types, $schema = false ) {
1011 global $wgDBmwschema;
1012 if ( !is_array( $types ) ) {
1013 $types = array( $types );
1016 $schema = $wgDBmwschema;
1018 $table = $this->tableName( $table );
1019 $etable = $this->addQuotes( $table );
1020 $eschema = $this->addQuotes( $schema );
1021 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1022 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1023 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1024 $res = $this->query( $SQL );
1025 $count = $res ?
$res->numRows() : 0;
1026 return (bool)$count;
1030 * For backward compatibility, this function checks both tables and
1033 function tableExists( $table, $schema = false ) {
1034 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1037 function sequenceExists( $sequence, $schema = false ) {
1038 return $this->relationExists( $sequence, 'S', $schema );
1041 function triggerExists( $table, $trigger ) {
1042 global $wgDBmwschema;
1045 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1046 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1047 AND tgrelid=pg_class.oid
1048 AND nspname=%s AND relname=%s AND tgname=%s
1050 $res = $this->query(
1053 $this->addQuotes( $wgDBmwschema ),
1054 $this->addQuotes( $table ),
1055 $this->addQuotes( $trigger )
1061 $rows = $res->numRows();
1065 function ruleExists( $table, $rule ) {
1066 global $wgDBmwschema;
1067 $exists = $this->selectField( 'pg_rules', 'rulename',
1069 'rulename' => $rule,
1070 'tablename' => $table,
1071 'schemaname' => $wgDBmwschema
1074 return $exists === $rule;
1077 function constraintExists( $table, $constraint ) {
1078 global $wgDBmwschema;
1079 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1080 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1081 $this->addQuotes( $wgDBmwschema ),
1082 $this->addQuotes( $table ),
1083 $this->addQuotes( $constraint )
1085 $res = $this->query( $SQL );
1089 $rows = $res->numRows();
1094 * Query whether a given schema exists. Returns the name of the owner
1096 function schemaExists( $schema ) {
1097 $eschema = str_replace( "'", "''", $schema );
1098 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1099 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1100 $res = $this->query( $SQL );
1101 if ( $res && $res->numRows() ) {
1102 $row = $res->fetchObject();
1103 $owner = $row->rolname
;
1110 function fieldInfo( $table, $field ) {
1111 return PostgresField
::fromText( $this, $table, $field );
1115 * pg_field_type() wrapper
1117 function fieldType( $res, $index ) {
1118 if ( $res instanceof ResultWrapper
) {
1119 $res = $res->result
;
1121 return pg_field_type( $res, $index );
1124 /* Not even sure why this is used in the main codebase... */
1125 function limitResultForUpdate( $sql, $num ) {
1129 function encodeBlob( $b ) {
1130 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1133 function decodeBlob( $b ) {
1134 if ( $b instanceof Blob
) {
1137 return pg_unescape_bytea( $b );
1140 function strencode( $s ) { # Should not be called by us
1141 return pg_escape_string( $this->mConn
, $s );
1144 function addQuotes( $s ) {
1145 if ( is_null( $s ) ) {
1147 } elseif ( is_bool( $s ) ) {
1148 return intval( $s );
1149 } elseif ( $s instanceof Blob
) {
1150 return "'" . $s->fetch( $s ) . "'";
1152 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1156 * Postgres specific version of replaceVars.
1157 * Calls the parent version in Database.php
1161 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1163 * @return string SQL string
1165 protected function replaceVars( $ins ) {
1166 $ins = parent
::replaceVars( $ins );
1168 if ( $this->numeric_version
>= 8.3 ) {
1169 // Thanks for not providing backwards-compatibility, 8.3
1170 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1173 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1174 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1181 * Various select options
1185 * @param $options Array: an associative array of options to be turned into
1186 * an SQL query, valid keys are listed in the function.
1189 function makeSelectOptions( $options ) {
1190 $preLimitTail = $postLimitTail = '';
1191 $startOpts = $useIndex = '';
1193 $noKeyOptions = array();
1194 foreach ( $options as $key => $option ) {
1195 if ( is_numeric( $key ) ) {
1196 $noKeyOptions[$option] = true;
1200 if ( isset( $options['GROUP BY'] ) ) {
1201 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1203 if ( isset( $options['HAVING'] ) ) {
1204 $preLimitTail .= " HAVING {$options['HAVING']}";
1206 if ( isset( $options['ORDER BY'] ) ) {
1207 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1210 //if ( isset( $options['LIMIT'] ) ) {
1211 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1212 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1216 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1217 $postLimitTail .= ' FOR UPDATE';
1219 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1220 $postLimitTail .= ' LOCK IN SHARE MODE';
1222 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1223 $startOpts .= 'DISTINCT';
1226 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1229 function setFakeMaster( $enabled = true ) {}
1231 function getDBname() {
1232 return $this->mDBname
;
1235 function getServer() {
1236 return $this->mServer
;
1239 function buildConcat( $stringList ) {
1240 return implode( ' || ', $stringList );
1243 public function getSearchEngine() {
1244 return 'SearchPostgres';
1246 } // end DatabasePostgres class