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
155 $this->mServer
= $server;
156 $this->mPort
= $port = $wgDBport;
157 $this->mUser
= $user;
158 $this->mPassword
= $password;
159 $this->mDBname
= $dbName;
161 $connectVars = array(
164 'password' => $password
166 if ( $server != false && $server != '' ) {
167 $connectVars['host'] = $server;
169 if ( $port != false && $port != '' ) {
170 $connectVars['port'] = $port;
172 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
174 $this->installErrorHandler();
175 $this->mConn
= pg_connect( $connectString );
176 $phpError = $this->restoreErrorHandler();
178 if ( !$this->mConn
) {
179 wfDebug( "DB connection error\n" );
180 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
181 wfDebug( $this->lastError() . "\n" );
182 throw new DBConnectionError( $this, $phpError );
185 $this->mOpened
= true;
187 global $wgCommandLineMode;
188 # If called from the command-line (e.g. importDump), only show errors
189 if ( $wgCommandLineMode ) {
190 $this->doQuery( "SET client_min_messages = 'ERROR'" );
193 $this->doQuery( "SET client_encoding='UTF8'" );
195 global $wgDBmwschema;
196 if ( isset( $wgDBmwschema )
197 && $wgDBmwschema !== 'mediawiki'
198 && preg_match( '/^\w+$/', $wgDBmwschema )
200 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
201 $this->doQuery( "SET search_path = $safeschema, public" );
207 function makeConnectionString( $vars ) {
209 foreach ( $vars as $name => $value ) {
210 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
216 function initial_setup( $superuser, $password, $dbName ) {
217 // If this is the initial connection, setup the schema stuff and possibly create the user
218 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBmwschema, $wgDBts2schema;
220 $safeuser = $this->addIdentifierQuotes( $wgDBuser );
221 // Are we connecting as a superuser for the first time?
223 // Are we really a superuser? Check out our rights
225 CASE WHEN usesuper IS TRUE THEN
226 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
227 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
229 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $superuser );
230 $rows = $this->numRows( $res = $this->doQuery( $SQL ) );
232 print '<li>ERROR: Could not read permissions for user "' . htmlspecialchars( $superuser ) . "\"</li>\n";
235 $perms = pg_fetch_result( $res, 0, 0 );
237 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $wgDBuser );
238 $rows = $this->numRows( $this->doQuery( $SQL ) );
240 print '<li>User "' . htmlspecialchars( $wgDBuser ) . '" already exists, skipping account creation.</li>';
242 if ( $perms != 1 && $perms != 3 ) {
243 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create other users. ';
244 print 'Please use a different Postgres user.</li>';
247 print '<li>Creating user <b>' . htmlspecialchars( $wgDBuser ) . '</b>...';
248 $safepass = $this->addQuotes( $wgDBpassword );
249 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
250 $this->doQuery( $SQL );
253 // User now exists, check out the database
254 if ( $dbName != $wgDBname ) {
255 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes( $wgDBname );
256 $rows = $this->numRows( $this->doQuery( $SQL ) );
258 print '<li>Database "' . htmlspecialchars( $wgDBname ) . '" already exists, skipping database creation.</li>';
261 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create databases. ';
262 print 'Please use a different Postgres user.</li>';
265 print '<li>Creating database <b>' . htmlspecialchars( $wgDBname ) . '</b>...';
266 $safename = $this->addIdentifierQuotes( $wgDBname );
267 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
268 $this->doQuery( $SQL );
270 // Hopefully tsearch2 and plpgsql are in template1...
273 // Reconnect to check out tsearch2 rights for this user
274 print '<li>Connecting to "' . htmlspecialchars( $wgDBname ) . '" as superuser "' .
275 htmlspecialchars( $superuser ) . '" to check rights...';
277 $connectVars = array();
278 if ( $this->mServer
!= false && $this->mServer
!= '' ) {
279 $connectVars['host'] = $this->mServer
;
281 if ( $this->mPort
!= false && $this->mPort
!= '' ) {
282 $connectVars['port'] = $this->mPort
;
284 $connectVars['dbname'] = $wgDBname;
285 $connectVars['user'] = $superuser;
286 $connectVars['password'] = $password;
288 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
289 if ( !$this->mConn
) {
290 print "<b>FAILED TO CONNECT!</b></li>";
296 // Setup the schema for this user if needed
297 $result = $this->schemaExists( $wgDBmwschema );
298 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
300 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
301 $result = $this->doQuery( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
303 print "<b>FAILED</b>.</li>\n";
308 print "<li>Schema already exists, explicitly granting rights...\n";
309 $safeschema2 = $this->addQuotes( $wgDBmwschema );
310 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
311 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
312 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
313 "AND p.relkind IN ('r','S','v')\n";
315 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
316 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
317 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
318 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
319 $res = $this->doQuery( $SQL );
321 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
324 $this->doQuery( "SET search_path = $safeschema" );
325 $rows = $this->numRows( $res );
328 $this->doQuery( pg_fetch_result( $res, $rows, 0 ) );
333 // Install plpgsql if needed
334 $this->setup_plpgsql();
336 return true; // Reconnect as regular user
340 if ( !defined( 'POSTGRES_SEARCHPATH' ) ) {
341 // Install plpgsql if needed
342 $this->setup_plpgsql();
344 // Does the schema already exist? Who owns it?
345 $result = $this->schemaExists( $wgDBmwschema );
347 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
348 error_reporting( 0 );
349 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
350 $result = $this->doQuery( "CREATE SCHEMA $safeschema" );
351 error_reporting( E_ALL
);
353 print '<b>FAILED</b>. The user "' . htmlspecialchars( $wgDBuser ) .
354 '" must be able to access the schema. '.
355 'You can try making them the owner of the database, or try creating the schema with a '.
356 'different user, and then grant access to the "' .
357 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
361 } elseif ( $result != $wgDBuser ) {
362 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists but is not owned by "' .
363 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
365 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists and is owned by "' .
366 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
369 // Always return GMT time to accomodate the existing integer-based timestamp assumption
370 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . '" ...';
371 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
372 $result = pg_query( $this->mConn
, $SQL );
374 print "<b>FAILED</b>.</li>\n";
378 // Set for the rest of this session
379 $SQL = "SET timezone = 'GMT'";
380 $result = pg_query( $this->mConn
, $SQL );
382 print "<li>Failed to set timezone</li>\n";
386 print '<li>Setting the datestyle to ISO, YMD for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
387 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
388 $result = pg_query( $this->mConn
, $SQL );
390 print "<b>FAILED</b>.</li>\n";
394 // Set for the rest of this session
395 $SQL = "SET datestyle = 'ISO, YMD'";
396 $result = pg_query( $this->mConn
, $SQL );
398 print "<li>Failed to set datestyle</li>\n";
402 // Fix up the search paths if needed
403 print '<li>Setting the search path for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
404 $path = $this->addIdentifierQuotes( $wgDBmwschema );
405 if ( $wgDBts2schema !== $wgDBmwschema ) {
406 $path .= ', '. $this->addIdentifierQuotes( $wgDBts2schema );
408 if ( $wgDBmwschema !== 'public' && $wgDBts2schema !== 'public' ) {
411 $SQL = "ALTER USER $safeuser SET search_path = $path";
412 $result = pg_query( $this->mConn
, $SQL );
414 print "<b>FAILED</b>.</li>\n";
418 // Set for the rest of this session
419 $SQL = "SET search_path = $path";
420 $result = pg_query( $this->mConn
, $SQL );
422 print "<li>Failed to set search_path</li>\n";
425 define( 'POSTGRES_SEARCHPATH', $path );
430 * Closes a database connection, if it is open
431 * Returns success, true if already closed
434 $this->mOpened
= false;
435 if ( $this->mConn
) {
436 return pg_close( $this->mConn
);
442 function doQuery( $sql ) {
443 if ( function_exists( 'mb_convert_encoding' ) ) {
444 $sql = mb_convert_encoding( $sql, 'UTF-8' );
446 $this->mLastResult
= pg_query( $this->mConn
, $sql );
447 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
448 return $this->mLastResult
;
451 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
452 return $this->query( $sql, $fname, true );
455 function freeResult( $res ) {
456 if ( $res instanceof ResultWrapper
) {
459 if ( !@pg_free_result
( $res ) ) {
460 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
464 function fetchObject( $res ) {
465 if ( $res instanceof ResultWrapper
) {
468 @$row = pg_fetch_object( $res );
469 # FIXME: HACK HACK HACK HACK debug
472 # hashar : not sure if the following test really trigger if the object
474 if( pg_last_error( $this->mConn
) ) {
475 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
480 function fetchRow( $res ) {
481 if ( $res instanceof ResultWrapper
) {
484 @$row = pg_fetch_array( $res );
485 if( pg_last_error( $this->mConn
) ) {
486 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
491 function numRows( $res ) {
492 if ( $res instanceof ResultWrapper
) {
495 @$n = pg_num_rows( $res );
496 if( pg_last_error( $this->mConn
) ) {
497 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
502 function numFields( $res ) {
503 if ( $res instanceof ResultWrapper
) {
506 return pg_num_fields( $res );
509 function fieldName( $res, $n ) {
510 if ( $res instanceof ResultWrapper
) {
513 return pg_field_name( $res, $n );
517 * This must be called after nextSequenceVal
519 function insertId() {
520 return $this->mInsertId
;
523 function dataSeek( $res, $row ) {
524 if ( $res instanceof ResultWrapper
) {
527 return pg_result_seek( $res, $row );
530 function lastError() {
531 if ( $this->mConn
) {
532 return pg_last_error();
534 return 'No database connection';
537 function lastErrno() {
538 return pg_last_error() ?
1 : 0;
541 function affectedRows() {
542 if ( !is_null( $this->mAffectedRows
) ) {
543 // Forced result for simulated queries
544 return $this->mAffectedRows
;
546 if( empty( $this->mLastResult
) ) {
549 return pg_affected_rows( $this->mLastResult
);
553 * Estimate rows in dataset
554 * Returns estimated count, based on EXPLAIN output
555 * This is not necessarily an accurate estimate, so use sparingly
556 * Returns -1 if count cannot be found
557 * Takes same arguments as Database::select()
559 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
560 $options['EXPLAIN'] = true;
561 $res = $this->select( $table, $vars, $conds, $fname, $options );
564 $row = $this->fetchRow( $res );
566 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
574 * Returns information about an index
575 * If errors are explicitly ignored, returns NULL on failure
577 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
578 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
579 $res = $this->query( $sql, $fname );
583 foreach ( $res as $row ) {
584 if ( $row->indexname
== $this->indexName( $index ) ) {
591 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
592 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
593 " AND indexdef LIKE 'CREATE UNIQUE%(" .
594 $this->strencode( $this->indexName( $index ) ) .
596 $res = $this->query( $sql, $fname );
600 foreach ( $res as $row ) {
607 * INSERT wrapper, inserts an array into a table
609 * $args may be a single associative array, or an array of these with numeric keys,
610 * for multi-row insert (Postgres version 8.2 and above only).
612 * @param $table String: Name of the table to insert to.
613 * @param $args Array: Items to insert into the table.
614 * @param $fname String: Name of the function, for profiling
615 * @param $options String or Array. Valid options: IGNORE
617 * @return bool Success of insert operation. IGNORE always returns true.
619 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
620 if ( !count( $args ) ) {
624 $table = $this->tableName( $table );
625 if (! isset( $this->numeric_version
) ) {
626 $this->getServerVersion();
629 if ( !is_array( $options ) ) {
630 $options = array( $options );
633 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
635 $keys = array_keys( $args[0] );
638 $keys = array_keys( $args );
641 // If IGNORE is set, we use savepoints to emulate mysql's behavior
642 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
644 // If we are not in a transaction, we need to be for savepoint trickery
647 if ( !$this->mTrxLevel
) {
651 $olde = error_reporting( 0 );
652 // For future use, we may want to track the number of actual inserts
653 // Right now, insert (all writes) simply return true/false
654 $numrowsinserted = 0;
657 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
660 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
662 foreach ( $args as $row ) {
668 $sql .= '(' . $this->makeList( $row ) . ')';
670 $res = (bool)$this->query( $sql, $fname, $ignore );
674 foreach ( $args as $row ) {
676 $tempsql .= '(' . $this->makeList( $row ) . ')';
679 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
682 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
685 $bar = pg_last_error();
686 if ( $bar != false ) {
687 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
689 pg_query( $this->mConn
, "RELEASE $ignore" );
694 // If any of them fail, we fail overall for this function call
695 // Note that this will be ignored if IGNORE is set
702 // Not multi, just a lone insert
704 pg_query($this->mConn
, "SAVEPOINT $ignore");
707 $sql .= '(' . $this->makeList( $args ) . ')';
708 $res = (bool)$this->query( $sql, $fname, $ignore );
710 $bar = pg_last_error();
711 if ( $bar != false ) {
712 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
714 pg_query( $this->mConn
, "RELEASE $ignore" );
720 $olde = error_reporting( $olde );
725 // Set the affected row count for the whole operation
726 $this->mAffectedRows
= $numrowsinserted;
728 // IGNORE always returns true
736 * INSERT SELECT wrapper
737 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
738 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
739 * $conds may be "*" to copy the whole table
740 * srcTable may be an array of tables.
741 * @todo FIXME: implement this a little better (seperate select/insert)?
743 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
744 $insertOptions = array(), $selectOptions = array() )
746 $destTable = $this->tableName( $destTable );
748 // If IGNORE is set, we use savepoints to emulate mysql's behavior
749 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
751 if( is_array( $insertOptions ) ) {
752 $insertOptions = implode( ' ', $insertOptions );
754 if( !is_array( $selectOptions ) ) {
755 $selectOptions = array( $selectOptions );
757 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
758 if( is_array( $srcTable ) ) {
759 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
761 $srcTable = $this->tableName( $srcTable );
764 // If we are not in a transaction, we need to be for savepoint trickery
767 if( !$this->mTrxLevel
) {
771 $olde = error_reporting( 0 );
772 $numrowsinserted = 0;
773 pg_query( $this->mConn
, "SAVEPOINT $ignore");
776 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
777 " SELECT $startOpts " . implode( ',', $varMap ) .
778 " FROM $srcTable $useIndex";
780 if ( $conds != '*' ) {
781 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
784 $sql .= " $tailOpts";
786 $res = (bool)$this->query( $sql, $fname, $ignore );
788 $bar = pg_last_error();
789 if( $bar != false ) {
790 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
792 pg_query( $this->mConn
, "RELEASE $ignore" );
795 $olde = error_reporting( $olde );
800 // Set the affected row count for the whole operation
801 $this->mAffectedRows
= $numrowsinserted;
803 // IGNORE always returns true
810 function tableName( $name ) {
811 # Replace reserved words with better ones
816 return 'pagecontent';
823 * Return the next in a sequence, save the value for retrieval via insertId()
825 function nextSequenceValue( $seqName ) {
826 $safeseq = str_replace( "'", "''", $seqName );
827 $res = $this->query( "SELECT nextval('$safeseq')" );
828 $row = $this->fetchRow( $res );
829 $this->mInsertId
= $row[0];
830 return $this->mInsertId
;
834 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
836 function currentSequenceValue( $seqName ) {
837 $safeseq = str_replace( "'", "''", $seqName );
838 $res = $this->query( "SELECT currval('$safeseq')" );
839 $row = $this->fetchRow( $res );
845 * REPLACE query wrapper
846 * Postgres simulates this with a DELETE followed by INSERT
847 * $row is the row to insert, an associative array
848 * $uniqueIndexes is an array of indexes. Each element may be either a
849 * field name or an array of field names
851 * It may be more efficient to leave off unique indexes which are unlikely to collide.
852 * However if you do this, you run the risk of encountering errors which wouldn't have
855 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
856 $table = $this->tableName( $table );
858 if ( count( $rows ) == 0 ) {
863 if ( !is_array( reset( $rows ) ) ) {
864 $rows = array( $rows );
867 foreach( $rows as $row ) {
868 # Delete rows which collide
869 if ( $uniqueIndexes ) {
870 $sql = "DELETE FROM $table WHERE ";
872 foreach ( $uniqueIndexes as $index ) {
879 if ( is_array( $index ) ) {
881 foreach ( $index as $col ) {
887 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
890 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
894 $this->query( $sql, $fname );
898 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
899 $this->makeList( $row, LIST_COMMA
) . ')';
900 $this->query( $sql, $fname );
904 # DELETE where the condition is a join
905 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
907 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
910 $delTable = $this->tableName( $delTable );
911 $joinTable = $this->tableName( $joinTable );
912 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
913 if ( $conds != '*' ) {
914 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
918 $this->query( $sql, $fname );
921 # Returns the size of a text field, or -1 for "unlimited"
922 function textFieldSize( $table, $field ) {
923 $table = $this->tableName( $table );
924 $sql = "SELECT t.typname as ftype,a.atttypmod as size
925 FROM pg_class c, pg_attribute a, pg_type t
926 WHERE relname='$table' AND a.attrelid=c.oid AND
927 a.atttypid=t.oid and a.attname='$field'";
928 $res =$this->query( $sql );
929 $row = $this->fetchObject( $res );
930 if ( $row->ftype
== 'varchar' ) {
931 $size = $row->size
- 4;
938 function limitResult( $sql, $limit, $offset = false ) {
939 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
942 function wasDeadlock() {
943 return $this->lastErrno() == '40P01';
946 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
947 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
950 function timestamp( $ts = 0 ) {
951 return wfTimestamp( TS_POSTGRES
, $ts );
955 * Return aggregated value function call
957 function aggregateValue( $valuedata, $valuename = 'value' ) {
961 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
962 // Ignore errors during error handling to avoid infinite recursion
963 $ignore = $this->ignoreErrors( true );
964 $this->mErrorCount++
;
966 if ( $ignore ||
$tempIgnore ) {
967 wfDebug( "SQL ERROR (ignored): $error\n" );
968 $this->ignoreErrors( $ignore );
970 $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" .
972 "Function: $fname\n" .
973 "Error: $errno $error\n";
974 throw new DBUnexpectedError( $this, $message );
979 * @return string wikitext of a link to the server software's web site
981 public static function getSoftwareLink() {
982 return '[http://www.postgresql.org/ PostgreSQL]';
986 * @return string Version information from the database
988 function getServerVersion() {
989 if ( !isset( $this->numeric_version
) ) {
990 $versionInfo = pg_version( $this->mConn
);
991 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
992 // Old client, abort install
993 $this->numeric_version
= '7.3 or earlier';
994 } elseif ( isset( $versionInfo['server'] ) ) {
996 $this->numeric_version
= $versionInfo['server'];
998 // Bug 16937: broken pgsql extension from PHP<5.3
999 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1002 return $this->numeric_version
;
1006 * Query whether a given relation exists (in the given schema, or the
1007 * default mw one if not given)
1009 function relationExists( $table, $types, $schema = false ) {
1010 global $wgDBmwschema;
1011 if ( !is_array( $types ) ) {
1012 $types = array( $types );
1015 $schema = $wgDBmwschema;
1017 $etable = $this->addQuotes( $table );
1018 $eschema = $this->addQuotes( $schema );
1019 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1020 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1021 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1022 $res = $this->query( $SQL );
1023 $count = $res ?
$res->numRows() : 0;
1024 return (bool)$count;
1028 * For backward compatibility, this function checks both tables and
1031 function tableExists( $table, $schema = false ) {
1032 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1035 function sequenceExists( $sequence, $schema = false ) {
1036 return $this->relationExists( $sequence, 'S', $schema );
1039 function triggerExists( $table, $trigger ) {
1040 global $wgDBmwschema;
1043 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1044 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1045 AND tgrelid=pg_class.oid
1046 AND nspname=%s AND relname=%s AND tgname=%s
1048 $res = $this->query(
1051 $this->addQuotes( $wgDBmwschema ),
1052 $this->addQuotes( $table ),
1053 $this->addQuotes( $trigger )
1059 $rows = $res->numRows();
1063 function ruleExists( $table, $rule ) {
1064 global $wgDBmwschema;
1065 $exists = $this->selectField( 'pg_rules', 'rulename',
1067 'rulename' => $rule,
1068 'tablename' => $table,
1069 'schemaname' => $wgDBmwschema
1072 return $exists === $rule;
1075 function constraintExists( $table, $constraint ) {
1076 global $wgDBmwschema;
1077 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1078 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1079 $this->addQuotes( $wgDBmwschema ),
1080 $this->addQuotes( $table ),
1081 $this->addQuotes( $constraint )
1083 $res = $this->query( $SQL );
1087 $rows = $res->numRows();
1092 * Query whether a given schema exists. Returns the name of the owner
1094 function schemaExists( $schema ) {
1095 $eschema = str_replace( "'", "''", $schema );
1096 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1097 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1098 $res = $this->query( $SQL );
1099 if ( $res && $res->numRows() ) {
1100 $row = $res->fetchObject();
1101 $owner = $row->rolname
;
1108 function fieldInfo( $table, $field ) {
1109 return PostgresField
::fromText( $this, $table, $field );
1113 * pg_field_type() wrapper
1115 function fieldType( $res, $index ) {
1116 if ( $res instanceof ResultWrapper
) {
1117 $res = $res->result
;
1119 return pg_field_type( $res, $index );
1122 /* Not even sure why this is used in the main codebase... */
1123 function limitResultForUpdate( $sql, $num ) {
1127 function encodeBlob( $b ) {
1128 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
1131 function decodeBlob( $b ) {
1132 if ( $b instanceof Blob
) {
1135 return pg_unescape_bytea( $b );
1138 function strencode( $s ) { # Should not be called by us
1139 return pg_escape_string( $this->mConn
, $s );
1142 function addQuotes( $s ) {
1143 if ( is_null( $s ) ) {
1145 } elseif ( is_bool( $s ) ) {
1146 return intval( $s );
1147 } elseif ( $s instanceof Blob
) {
1148 return "'" . $s->fetch( $s ) . "'";
1150 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
1154 * Postgres specific version of replaceVars.
1155 * Calls the parent version in Database.php
1159 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1161 * @return string SQL string
1163 protected function replaceVars( $ins ) {
1164 $ins = parent
::replaceVars( $ins );
1166 if ( $this->numeric_version
>= 8.3 ) {
1167 // Thanks for not providing backwards-compatibility, 8.3
1168 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1171 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
1172 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1179 * Various select options
1183 * @param $options Array: an associative array of options to be turned into
1184 * an SQL query, valid keys are listed in the function.
1187 function makeSelectOptions( $options ) {
1188 $preLimitTail = $postLimitTail = '';
1189 $startOpts = $useIndex = '';
1191 $noKeyOptions = array();
1192 foreach ( $options as $key => $option ) {
1193 if ( is_numeric( $key ) ) {
1194 $noKeyOptions[$option] = true;
1198 if ( isset( $options['GROUP BY'] ) ) {
1199 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1201 if ( isset( $options['HAVING'] ) ) {
1202 $preLimitTail .= " HAVING {$options['HAVING']}";
1204 if ( isset( $options['ORDER BY'] ) ) {
1205 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1208 //if ( isset( $options['LIMIT'] ) ) {
1209 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1210 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1214 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1215 $postLimitTail .= ' FOR UPDATE';
1217 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1218 $postLimitTail .= ' LOCK IN SHARE MODE';
1220 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1221 $startOpts .= 'DISTINCT';
1224 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1227 function setFakeMaster( $enabled = true ) {}
1229 function getDBname() {
1230 return $this->mDBname
;
1233 function getServer() {
1234 return $this->mServer
;
1237 function buildConcat( $stringList ) {
1238 return implode( ' || ', $stringList );
1241 public function getSearchEngine() {
1242 return 'SearchPostgres';
1244 } // end DatabasePostgres class