e85cc874d7c116978bef9196fb685aa886424065
5 * This is the Postgres database abstraction layer.
9 private $name, $tablename, $type, $nullable, $max_length;
11 static function fromText($db, $table, $field) {
16 CASE WHEN typname = 'int2' THEN 'smallint'
17 WHEN typname = 'int4' THEN 'integer'
18 WHEN typname = 'int8' THEN 'bigint'
19 WHEN typname = 'bpchar' THEN 'char'
20 ELSE typname END AS typname
,
22 FROM pg_class
, pg_namespace
, pg_attribute
, pg_type
23 WHERE relnamespace
=pg_namespace
.oid
25 AND attrelid
=pg_class
.oid
26 AND atttypid
=pg_type
.oid
31 $res = $db->query(sprintf($q,
32 $db->addQuotes($wgDBmwschema),
33 $db->addQuotes($table),
34 $db->addQuotes($field)));
35 $row = $db->fetchObject($res);
38 $n = new PostgresField
;
39 $n->type
= $row->typname
;
40 $n->nullable
= ($row->attnotnull
== 'f');
42 $n->tablename
= $table;
43 $n->max_length
= $row->attlen
;
51 function tableName() {
52 return $this->tablename
;
60 return $this->nullable
;
63 function maxLength() {
64 return $this->max_length
;
71 class DatabasePostgres
extends Database
{
72 var $mInsertId = NULL;
73 var $mLastResult = NULL;
74 var $numeric_version = NULL;
75 var $mAffectedRows = NULL;
77 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
78 $failFunction = false, $flags = 0 )
81 $this->mFailFunction
= $failFunction;
82 $this->mFlags
= $flags;
83 $this->open( $server, $user, $password, $dbName);
87 function cascadingDeletes() {
90 function cleanupTriggers() {
93 function strictIPs() {
96 function realTimestamps() {
99 function implicitGroupby() {
102 function implicitOrderby() {
105 function searchableIPs() {
108 function functionalIndexes() {
112 function hasConstraint( $name ) {
113 global $wgDBmwschema;
114 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" . pg_escape_string( $name ) . "' AND n.nspname = '" . pg_escape_string($wgDBmwschema) ."'";
115 return $this->numRows($res = $this->doQuery($SQL));
118 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
120 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
124 * Usually aborts on failure
125 * If the failFunction is set to a non-zero integer, returns success
127 function open( $server, $user, $password, $dbName ) {
128 # Test for Postgres support, to avoid suppressed fatal error
129 if ( !function_exists( 'pg_connect' ) ) {
130 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" );
136 $this->mServer
= $server;
137 $this->mPort
= $port = $wgDBport;
138 $this->mUser
= $user;
139 $this->mPassword
= $password;
140 $this->mDBname
= $dbName;
142 $connectVars = array(
145 'password' => $password );
146 if ($server!=false && $server!="") {
147 $connectVars['host'] = $server;
149 if ($port!=false && $port!="") {
150 $connectVars['port'] = $port;
152 $connectString = $this->makeConnectionString( $connectVars );
154 $this->installErrorHandler();
155 $this->mConn
= pg_connect( $connectString );
156 $phpError = $this->restoreErrorHandler();
158 if ( $this->mConn
== false ) {
159 wfDebug( "DB connection error\n" );
160 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
161 wfDebug( $this->lastError()."\n" );
162 if ( !$this->mFailFunction
) {
163 throw new DBConnectionError( $this, $phpError );
169 $this->mOpened
= true;
171 global $wgCommandLineMode;
172 ## If called from the command-line (e.g. importDump), only show errors
173 if ($wgCommandLineMode) {
174 $this->doQuery("SET client_min_messages = 'ERROR'");
177 global $wgDBmwschema, $wgDBts2schema;
178 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
179 && $wgDBmwschema !== 'mediawiki'
180 && preg_match( '/^\w+$/', $wgDBmwschema )
181 && preg_match( '/^\w+$/', $wgDBts2schema )
183 $safeschema = $this->quote_ident($wgDBmwschema);
184 $safeschema2 = $this->quote_ident($wgDBts2schema);
185 $this->doQuery("SET search_path = $safeschema, $wgDBts2schema, public");
191 function makeConnectionString( $vars ) {
193 foreach ( $vars as $name => $value ) {
194 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
200 function initial_setup($password, $dbName) {
201 // If this is the initial connection, setup the schema stuff and possibly create the user
202 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
204 print "<li>Checking the version of Postgres...";
205 $version = $this->getServerVersion();
207 if ($version < $PGMINVER) {
208 print "<b>FAILED</b>. Required version is $PGMINVER. You have $version</li>\n";
211 print "version $this->numeric_version is OK.</li>\n";
213 $safeuser = $this->quote_ident($wgDBuser);
214 // Are we connecting as a superuser for the first time?
215 if ($wgDBsuperuser) {
216 // Are we really a superuser? Check out our rights
218 CASE WHEN usesuper IS TRUE THEN
219 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
220 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
222 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
223 $rows = $this->numRows($res = $this->doQuery($SQL));
225 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
228 $perms = pg_fetch_result($res, 0, 0);
230 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
231 $rows = $this->numRows($this->doQuery($SQL));
233 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
236 if ($perms != 1 and $perms != 3) {
237 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
238 print 'Please use a different Postgres user.</li>';
241 print "<li>Creating user <b>$wgDBuser</b>...";
242 $safepass = $this->addQuotes($wgDBpassword);
243 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
244 $this->doQuery($SQL);
247 // User now exists, check out the database
248 if ($dbName != $wgDBname) {
249 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
250 $rows = $this->numRows($this->doQuery($SQL));
252 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
256 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
257 print 'Please use a different Postgres user.</li>';
260 print "<li>Creating database <b>$wgDBname</b>...";
261 $safename = $this->quote_ident($wgDBname);
262 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
263 $this->doQuery($SQL);
265 // Hopefully tsearch2 and plpgsql are in template1...
268 // Reconnect to check out tsearch2 rights for this user
269 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
272 if ($this->mServer
!=false && $this->mServer
!="") {
273 $hstring="host=$this->mServer ";
275 if ($this->mPort
!=false && $this->mPort
!="") {
276 $hstring .= "port=$this->mPort ";
279 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$wgDBsuperuser password=$password");
280 if ( $this->mConn
== false ) {
281 print "<b>FAILED TO CONNECT!</b></li>";
287 if ($this->numeric_version
< 8.3) {
289 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
290 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
291 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
292 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
293 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
297 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
298 foreach (array('cfg','cfgmap','dict','parser') as $table) {
299 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
300 $this->doQuery($SQL);
305 // Setup the schema for this user if needed
306 $result = $this->schemaExists($wgDBmwschema);
307 $safeschema = $this->quote_ident($wgDBmwschema);
309 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
310 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
312 print "<b>FAILED</b>.</li>\n";
318 print "<li>Schema already exists, explicitly granting rights...\n";
319 $safeschema2 = $this->addQuotes($wgDBmwschema);
320 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
321 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
322 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
323 "AND p.relkind IN ('r','S','v')\n";
325 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
326 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
327 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
328 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
329 $res = $this->doQuery($SQL);
331 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
334 $this->doQuery("SET search_path = $safeschema");
335 $rows = $this->numRows($res);
338 $this->doQuery(pg_fetch_result($res, $rows, 0));
343 // Install plpgsql if needed
344 $this->setup_plpgsql();
347 return true; // Reconnect as regular user
351 if (!defined('POSTGRES_SEARCHPATH')) {
353 if ($this->numeric_version
< 8.3) {
354 // Do we have the basic tsearch2 table?
355 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
356 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
357 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
358 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
359 print " for instructions.</li>\n";
364 // Does this user have the rights to the tsearch2 tables?
365 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
366 print "<li>Checking tsearch2 permissions...";
367 // Let's check all four, just to be safe
368 error_reporting( 0 );
369 $ts2tables = array('cfg','cfgmap','dict','parser');
370 $safetsschema = $this->quote_ident($wgDBts2schema);
371 foreach ( $ts2tables AS $tname ) {
372 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
373 $res = $this->doQuery($SQL);
375 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
376 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
380 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = '$ctype'";
381 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
382 $res = $this->doQuery($SQL);
383 error_reporting( E_ALL
);
385 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
390 // Will the current locale work? Can we force it to?
391 print "<li>Verifying tsearch2 locale with $ctype...";
392 $rows = $this->numRows($res);
395 print "<b>not found</b></li>\n";
396 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
400 $tsname = pg_fetch_result($res, 0, 0);
401 if ($tsname != 'default') {
402 print "<b>not set to default ($tsname)</b>";
403 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
408 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
409 $res = $this->doQuery($SQL);
411 print "<b>FAILED</b>. ";
412 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
418 // Final test: try out a simple tsearch2 query
419 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
420 $res = $this->doQuery($SQL);
422 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
428 // Install plpgsql if needed
429 $this->setup_plpgsql();
431 // Does the schema already exist? Who owns it?
432 $result = $this->schemaExists($wgDBmwschema);
434 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
435 error_reporting( 0 );
436 $safeschema = $this->quote_ident($wgDBmwschema);
437 $result = $this->doQuery("CREATE SCHEMA $safeschema");
438 error_reporting( E_ALL
);
440 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
441 "You can try making them the owner of the database, or try creating the schema with a ".
442 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
447 else if ($result != $wgDBuser) {
448 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$wgDBuser\". Not ideal.</li>\n";
451 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$wgDBuser\". Excellent.</li>\n";
454 // Always return GMT time to accomodate the existing integer-based timestamp assumption
455 print "<li>Setting the timezone to GMT for user \"$wgDBuser\" ...";
456 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
457 $result = pg_query($this->mConn
, $SQL);
459 print "<b>FAILED</b>.</li>\n";
463 // Set for the rest of this session
464 $SQL = "SET timezone = 'GMT'";
465 $result = pg_query($this->mConn
, $SQL);
467 print "<li>Failed to set timezone</li>\n";
471 print "<li>Setting the datestyle to ISO, YMD for user \"$wgDBuser\" ...";
472 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
473 $result = pg_query($this->mConn
, $SQL);
475 print "<b>FAILED</b>.</li>\n";
479 // Set for the rest of this session
480 $SQL = "SET datestyle = 'ISO, YMD'";
481 $result = pg_query($this->mConn
, $SQL);
483 print "<li>Failed to set datestyle</li>\n";
487 // Fix up the search paths if needed
488 print "<li>Setting the search path for user \"$wgDBuser\" ...";
489 $path = $this->quote_ident($wgDBmwschema);
490 if ($wgDBts2schema !== $wgDBmwschema)
491 $path .= ", ". $this->quote_ident($wgDBts2schema);
492 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
494 $SQL = "ALTER USER $safeuser SET search_path = $path";
495 $result = pg_query($this->mConn
, $SQL);
497 print "<b>FAILED</b>.</li>\n";
501 // Set for the rest of this session
502 $SQL = "SET search_path = $path";
503 $result = pg_query($this->mConn
, $SQL);
505 print "<li>Failed to set search_path</li>\n";
508 define( "POSTGRES_SEARCHPATH", $path );
513 function setup_plpgsql() {
514 print "<li>Checking for Pl/Pgsql ...";
515 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
516 $rows = $this->numRows($this->doQuery($SQL));
518 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
519 print "not installed. Attempting to install Pl/Pgsql ...";
520 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
521 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
522 $rows = $this->numRows($this->doQuery($SQL));
524 $olde = error_reporting(0);
525 error_reporting($olde - E_WARNING
);
526 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
527 error_reporting($olde);
529 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
534 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
543 * Closes a database connection, if it is open
544 * Returns success, true if already closed
547 $this->mOpened
= false;
548 if ( $this->mConn
) {
549 return pg_close( $this->mConn
);
555 function doQuery( $sql ) {
556 if (function_exists('mb_convert_encoding')) {
557 $sql = mb_convert_encoding($sql,'UTF-8');
559 $this->mLastResult
= pg_query( $this->mConn
, $sql);
560 $this->mAffectedRows
= NULL; // use pg_affected_rows(mLastResult)
561 return $this->mLastResult
;
564 function queryIgnore( $sql, $fname = '' ) {
565 return $this->query( $sql, $fname, true );
568 function freeResult( $res ) {
569 if ( $res instanceof ResultWrapper
) {
572 if ( !@pg_free_result
( $res ) ) {
573 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
577 function fetchObject( $res ) {
578 if ( $res instanceof ResultWrapper
) {
581 @$row = pg_fetch_object( $res );
582 # FIXME: HACK HACK HACK HACK debug
585 # hashar : not sure if the following test really trigger if the object
587 if( pg_last_error($this->mConn
) ) {
588 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
593 function fetchRow( $res ) {
594 if ( $res instanceof ResultWrapper
) {
597 @$row = pg_fetch_array( $res );
598 if( pg_last_error($this->mConn
) ) {
599 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
604 function numRows( $res ) {
605 if ( $res instanceof ResultWrapper
) {
608 @$n = pg_num_rows( $res );
609 if( pg_last_error($this->mConn
) ) {
610 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
614 function numFields( $res ) {
615 if ( $res instanceof ResultWrapper
) {
618 return pg_num_fields( $res );
620 function fieldName( $res, $n ) {
621 if ( $res instanceof ResultWrapper
) {
624 return pg_field_name( $res, $n );
628 * This must be called after nextSequenceVal
630 function insertId() {
631 return $this->mInsertId
;
634 function dataSeek( $res, $row ) {
635 if ( $res instanceof ResultWrapper
) {
638 return pg_result_seek( $res, $row );
641 function lastError() {
642 if ( $this->mConn
) {
643 return pg_last_error();
646 return "No database connection";
649 function lastErrno() {
650 return pg_last_error() ?
1 : 0;
653 function affectedRows() {
654 if ( !is_null( $this->mAffectedRows
) ) {
655 // Forced result for simulated queries
656 return $this->mAffectedRows
;
658 if( empty( $this->mLastResult
) )
660 return pg_affected_rows( $this->mLastResult
);
664 * Estimate rows in dataset
665 * Returns estimated count, based on EXPLAIN output
666 * This is not necessarily an accurate estimate, so use sparingly
667 * Returns -1 if count cannot be found
668 * Takes same arguments as Database::select()
671 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
672 $options['EXPLAIN'] = true;
673 $res = $this->select( $table, $vars, $conds, $fname, $options );
676 $row = $this->fetchRow( $res );
678 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
681 $this->freeResult($res);
688 * Returns information about an index
689 * If errors are explicitly ignored, returns NULL on failure
691 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
692 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
693 $res = $this->query( $sql, $fname );
697 while ( $row = $this->fetchObject( $res ) ) {
698 if ( $row->indexname
== $index ) {
705 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
706 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
707 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
708 $res = $this->query( $sql, $fname );
711 while ($row = $this->fetchObject( $res ))
718 * INSERT wrapper, inserts an array into a table
720 * $args may be a single associative array, or an array of these with numeric keys,
721 * for multi-row insert (Postgres version 8.2 and above only).
723 * @param array $table String: Name of the table to insert to.
724 * @param array $args Array: Items to insert into the table.
725 * @param array $fname String: Name of the function, for profiling
726 * @param mixed $options String or Array. Valid options: IGNORE
728 * @return bool Success of insert operation. IGNORE always returns true.
730 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
733 if ( !count( $args ) ) {
737 $table = $this->tableName( $table );
738 if (! isset( $wgDBversion ) ) {
739 $wgDBversion = $this->getServerVersion();
742 if ( !is_array( $options ) )
743 $options = array( $options );
745 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
747 $keys = array_keys( $args[0] );
751 $keys = array_keys( $args );
754 // If IGNORE is set, we use savepoints to emulate mysql's behavior
755 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
757 // If we are not in a transaction, we need to be for savepoint trickery
760 if (! $this->mTrxLevel
) {
764 $olde = error_reporting( 0 );
765 // For future use, we may want to track the number of actual inserts
766 // Right now, insert (all writes) simply return true/false
767 $numrowsinserted = 0;
770 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
773 if ( $wgDBversion >= 8.2 && !$ignore ) {
775 foreach ( $args as $row ) {
781 $sql .= '(' . $this->makeList( $row ) . ')';
783 $res = (bool)$this->query( $sql, $fname, $ignore );
788 foreach ( $args as $row ) {
790 $tempsql .= '(' . $this->makeList( $row ) . ')';
793 pg_query($this->mConn
, "SAVEPOINT $ignore");
796 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
799 $bar = pg_last_error();
801 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
804 pg_query( $this->mConn
, "RELEASE $ignore" );
809 // If any of them fail, we fail overall for this function call
810 // Note that this will be ignored if IGNORE is set
817 // Not multi, just a lone insert
819 pg_query($this->mConn
, "SAVEPOINT $ignore");
822 $sql .= '(' . $this->makeList( $args ) . ')';
823 $res = (bool)$this->query( $sql, $fname, $ignore );
825 $bar = pg_last_error();
827 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
830 pg_query( $this->mConn
, "RELEASE $ignore" );
836 $olde = error_reporting( $olde );
841 // Set the affected row count for the whole operation
842 $this->mAffectedRows
= $numrowsinserted;
844 // IGNORE always returns true
853 function tableName( $name ) {
854 # Replace reserved words with better ones
859 return 'pagecontent';
866 * Return the next in a sequence, save the value for retrieval via insertId()
868 function nextSequenceValue( $seqName ) {
869 $safeseq = preg_replace( "/'/", "''", $seqName );
870 $res = $this->query( "SELECT nextval('$safeseq')" );
871 $row = $this->fetchRow( $res );
872 $this->mInsertId
= $row[0];
873 $this->freeResult( $res );
874 return $this->mInsertId
;
878 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
880 function currentSequenceValue( $seqName ) {
881 $safeseq = preg_replace( "/'/", "''", $seqName );
882 $res = $this->query( "SELECT currval('$safeseq')" );
883 $row = $this->fetchRow( $res );
885 $this->freeResult( $res );
890 * Postgres does not have a "USE INDEX" clause, so return an empty string
892 function useIndexClause( $index ) {
896 # REPLACE query wrapper
897 # Postgres simulates this with a DELETE followed by INSERT
898 # $row is the row to insert, an associative array
899 # $uniqueIndexes is an array of indexes. Each element may be either a
900 # field name or an array of field names
902 # It may be more efficient to leave off unique indexes which are unlikely to collide.
903 # However if you do this, you run the risk of encountering errors which wouldn't have
905 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
906 $table = $this->tableName( $table );
908 if (count($rows)==0) {
913 if ( !is_array( reset( $rows ) ) ) {
914 $rows = array( $rows );
917 foreach( $rows as $row ) {
918 # Delete rows which collide
919 if ( $uniqueIndexes ) {
920 $sql = "DELETE FROM $table WHERE ";
922 foreach ( $uniqueIndexes as $index ) {
929 if ( is_array( $index ) ) {
931 foreach ( $index as $col ) {
937 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
940 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
944 $this->query( $sql, $fname );
948 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
949 $this->makeList( $row, LIST_COMMA
) . ')';
950 $this->query( $sql, $fname );
954 # DELETE where the condition is a join
955 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
957 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
960 $delTable = $this->tableName( $delTable );
961 $joinTable = $this->tableName( $joinTable );
962 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
963 if ( $conds != '*' ) {
964 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
968 $this->query( $sql, $fname );
971 # Returns the size of a text field, or -1 for "unlimited"
972 function textFieldSize( $table, $field ) {
973 $table = $this->tableName( $table );
974 $sql = "SELECT t.typname as ftype,a.atttypmod as size
975 FROM pg_class c, pg_attribute a, pg_type t
976 WHERE relname='$table' AND a.attrelid=c.oid AND
977 a.atttypid=t.oid and a.attname='$field'";
978 $res =$this->query($sql);
979 $row=$this->fetchObject($res);
980 if ($row->ftype
=="varchar") {
985 $this->freeResult( $res );
989 function lowPriorityOption() {
993 function limitResult($sql, $limit, $offset=false) {
994 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
998 * Returns an SQL expression for a simple conditional.
999 * Uses CASE on Postgres
1001 * @param string $cond SQL expression which will result in a boolean value
1002 * @param string $trueVal SQL expression to return if true
1003 * @param string $falseVal SQL expression to return if false
1004 * @return string SQL fragment
1006 function conditional( $cond, $trueVal, $falseVal ) {
1007 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1010 function wasDeadlock() {
1011 return $this->lastErrno() == '40P01';
1014 function timestamp( $ts=0 ) {
1015 return wfTimestamp(TS_POSTGRES
,$ts);
1019 * Return aggregated value function call
1021 function aggregateValue ($valuedata,$valuename='value') {
1026 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1027 // Ignore errors during error handling to avoid infinite recursion
1028 $ignore = $this->ignoreErrors( true );
1029 $this->mErrorCount++
;
1031 if ($ignore ||
$tempIgnore) {
1032 wfDebug("SQL ERROR (ignored): $error\n");
1033 $this->ignoreErrors( $ignore );
1036 $message = "A database error has occurred\n" .
1038 "Function: $fname\n" .
1039 "Error: $errno $error\n";
1040 throw new DBUnexpectedError($this, $message);
1045 * @return string wikitext of a link to the server software's web site
1047 function getSoftwareLink() {
1048 return "[http://www.postgresql.org/ PostgreSQL]";
1052 * @return string Version information from the database
1054 function getServerVersion() {
1055 $versionInfo = pg_version( $this->mConn
);
1056 return $versionInfo['server'];
1060 * Query whether a given relation exists (in the given schema, or the
1061 * default mw one if not given)
1063 function relationExists( $table, $types, $schema = false ) {
1064 global $wgDBmwschema;
1065 if (!is_array($types))
1066 $types = array($types);
1068 $schema = $wgDBmwschema;
1069 $etable = $this->addQuotes($table);
1070 $eschema = $this->addQuotes($schema);
1071 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1072 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1073 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1074 $res = $this->query( $SQL );
1075 $count = $res ?
$res->numRows() : 0;
1077 $this->freeResult( $res );
1078 return $count ?
true : false;
1082 * For backward compatibility, this function checks both tables and
1085 function tableExists ($table, $schema = false) {
1086 return $this->relationExists($table, array('r', 'v'), $schema);
1089 function sequenceExists ($sequence, $schema = false) {
1090 return $this->relationExists($sequence, 'S', $schema);
1093 function triggerExists($table, $trigger) {
1094 global $wgDBmwschema;
1097 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1098 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1099 AND tgrelid=pg_class.oid
1100 AND nspname=%s AND relname=%s AND tgname=%s
1102 $res = $this->query(sprintf($q,
1103 $this->addQuotes($wgDBmwschema),
1104 $this->addQuotes($table),
1105 $this->addQuotes($trigger)));
1108 $rows = $res->numRows();
1109 $this->freeResult($res);
1113 function ruleExists($table, $rule) {
1114 global $wgDBmwschema;
1115 $exists = $this->selectField("pg_rules", "rulename",
1116 array( "rulename" => $rule,
1117 "tablename" => $table,
1118 "schemaname" => $wgDBmwschema));
1119 return $exists === $rule;
1122 function constraintExists($table, $constraint) {
1123 global $wgDBmwschema;
1124 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1125 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1126 $this->addQuotes($wgDBmwschema),
1127 $this->addQuotes($table),
1128 $this->addQuotes($constraint));
1129 $res = $this->query($SQL);
1132 $rows = $res->numRows();
1133 $this->freeResult($res);
1138 * Query whether a given schema exists. Returns the name of the owner
1140 function schemaExists( $schema ) {
1141 $eschema = preg_replace("/'/", "''", $schema);
1142 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1143 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1144 $res = $this->query( $SQL );
1145 if ( $res && $res->numRows() ) {
1146 $row = $res->fetchObject();
1147 $owner = $row->rolname
;
1152 $this->freeResult($res);
1157 * Query whether a given column exists in the mediawiki schema
1159 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1160 global $wgDBmwschema;
1161 $etable = preg_replace("/'/", "''", $table);
1162 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1163 $ecol = preg_replace("/'/", "''", $field);
1164 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1165 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1166 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1167 $res = $this->query( $SQL, $fname );
1168 $count = $res ?
$res->numRows() : 0;
1170 $this->freeResult( $res );
1174 function fieldInfo( $table, $field ) {
1175 return PostgresField
::fromText($this, $table, $field);
1179 * pg_field_type() wrapper
1181 function fieldType( $res, $index ) {
1182 if ( $res instanceof ResultWrapper
) {
1183 $res = $res->result
;
1185 return pg_field_type( $res, $index );
1188 function begin( $fname = 'DatabasePostgres::begin' ) {
1189 $this->query( 'BEGIN', $fname );
1190 $this->mTrxLevel
= 1;
1192 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1195 function commit( $fname = 'DatabasePostgres::commit' ) {
1196 $this->query( 'COMMIT', $fname );
1197 $this->mTrxLevel
= 0;
1200 /* Not even sure why this is used in the main codebase... */
1201 function limitResultForUpdate($sql, $num) {
1205 function setup_database() {
1206 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1208 // Make sure that we can write to the correct schema
1209 // If not, Postgres will happily and silently go to the next search_path item
1210 $ctest = "mediawiki_test_table";
1211 $safeschema = $this->quote_ident($wgDBmwschema);
1212 if ($this->tableExists($ctest, $wgDBmwschema)) {
1213 $this->doQuery("DROP TABLE $safeschema.$ctest");
1215 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1216 $olde = error_reporting( 0 );
1217 $res = $this->doQuery($SQL);
1218 error_reporting( $olde );
1220 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
1223 $this->doQuery("DROP TABLE $safeschema.$ctest");
1225 $res = dbsource( "../maintenance/postgres/tables.sql", $this);
1227 ## Update version information
1228 $mwv = $this->addQuotes($wgVersion);
1229 $pgv = $this->addQuotes($this->getServerVersion());
1230 $pgu = $this->addQuotes($this->mUser
);
1231 $mws = $this->addQuotes($wgDBmwschema);
1232 $tss = $this->addQuotes($wgDBts2schema);
1233 $pgp = $this->addQuotes($wgDBport);
1234 $dbn = $this->addQuotes($this->mDBname
);
1235 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1237 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1238 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1239 "ctype = '$ctype' ".
1240 "WHERE type = 'Creation'";
1243 ## Avoid the non-standard "REPLACE INTO" syntax
1244 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1246 dieout( "<li>Could not find the interwiki.sql file");
1248 ## We simply assume it is already empty as we have just created it
1249 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1250 while ( ! feof( $f ) ) {
1251 $line = fgets($f,1024);
1253 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1256 $this->query("$SQL $matches[1],$matches[2])");
1258 print " (table interwiki successfully populated)...\n";
1260 $this->doQuery("COMMIT");
1263 function encodeBlob( $b ) {
1264 return new Blob ( pg_escape_bytea( $b ) ) ;
1267 function decodeBlob( $b ) {
1268 if ($b instanceof Blob
) {
1271 return pg_unescape_bytea( $b );
1274 function strencode( $s ) { ## Should not be called by us
1275 return pg_escape_string( $s );
1278 function addQuotes( $s ) {
1279 if ( is_null( $s ) ) {
1281 } else if ( is_bool( $s ) ) {
1282 return intval( $s );
1283 } else if ($s instanceof Blob
) {
1284 return "'".$s->fetch($s)."'";
1286 return "'" . pg_escape_string($s) . "'";
1289 function quote_ident( $s ) {
1290 return '"' . preg_replace( '/"/', '""', $s) . '"';
1293 /* For now, does nothing */
1294 function selectDB( $db ) {
1299 * Postgres specific version of replaceVars.
1300 * Calls the parent version in Database.php
1304 * @param string $com SQL string, read from a stream (usually tables.sql)
1306 * @return string SQL string
1308 protected function replaceVars( $ins ) {
1310 $ins = parent
::replaceVars( $ins );
1312 if ($this->numeric_version
>= 8.3) {
1313 // Thanks for not providing backwards-compatibility, 8.3
1314 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1317 if ($this->numeric_version
<= 8.1) { // Our minimum version
1318 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1325 * Various select options
1329 * @param array $options an associative array of options to be turned into
1330 * an SQL query, valid keys are listed in the function.
1333 function makeSelectOptions( $options ) {
1334 $preLimitTail = $postLimitTail = '';
1335 $startOpts = $useIndex = '';
1337 $noKeyOptions = array();
1338 foreach ( $options as $key => $option ) {
1339 if ( is_numeric( $key ) ) {
1340 $noKeyOptions[$option] = true;
1344 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1345 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1346 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1348 //if (isset($options['LIMIT'])) {
1349 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1350 // isset($options['OFFSET']) ? $options['OFFSET']
1354 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1355 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1356 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1358 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1361 public function setTimeout( $timeout ) {
1362 // @todo fixme no-op
1366 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1371 * How lagged is this slave?
1374 public function getLag() {
1375 # Not implemented for PostgreSQL
1379 function setFakeSlaveLag( $lag ) {}
1380 function setFakeMaster( $enabled = true ) {}
1382 function getDBname() {
1383 return $this->mDBname
;
1386 function getServer() {
1387 return $this->mServer
;
1390 function buildConcat( $stringList ) {
1391 return implode( ' || ', $stringList );
1394 /* These are not used yet, but we know we don't want the default version */
1396 public function lock( $lockName, $method ) {
1399 public function unlock( $lockName, $method ) {
1403 public function getSearchEngine() {
1404 return "SearchPostgres";
1407 } // end DatabasePostgres class