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 )
82 # Can't get a reference if it hasn't been set yet
83 if ( !isset( $wgOut ) ) {
86 $this->mOut
=& $wgOut;
87 $this->mFailFunction
= $failFunction;
88 $this->mFlags
= $flags;
89 $this->open( $server, $user, $password, $dbName);
93 function cascadingDeletes() {
96 function cleanupTriggers() {
99 function strictIPs() {
102 function realTimestamps() {
105 function implicitGroupby() {
108 function implicitOrderby() {
111 function searchableIPs() {
114 function functionalIndexes() {
118 function hasConstraint( $name ) {
119 global $wgDBmwschema;
120 $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) ."'";
121 return $this->numRows($res = $this->doQuery($SQL));
124 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
126 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
130 * Usually aborts on failure
131 * If the failFunction is set to a non-zero integer, returns success
133 function open( $server, $user, $password, $dbName ) {
134 # Test for Postgres support, to avoid suppressed fatal error
135 if ( !function_exists( 'pg_connect' ) ) {
136 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" );
141 if (!strlen($user)) { ## e.g. the class is being loaded
146 $this->mServer
= $server;
147 $this->mPort
= $port = $wgDBport;
148 $this->mUser
= $user;
149 $this->mPassword
= $password;
150 $this->mDBname
= $dbName;
153 if ($server!=false && $server!="") {
154 $hstring="host=$server ";
156 if ($port!=false && $port!="") {
157 $hstring .= "port=$port ";
160 error_reporting( E_ALL
);
161 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
163 if ( $this->mConn
== false ) {
164 wfDebug( "DB connection error\n" );
165 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
166 wfDebug( $this->lastError()."\n" );
170 $this->mOpened
= true;
172 global $wgCommandLineMode;
173 ## If called from the command-line (e.g. importDump), only show errors
174 if ($wgCommandLineMode) {
175 $this->doQuery("SET client_min_messages = 'ERROR'");
178 global $wgDBmwschema, $wgDBts2schema;
179 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
180 && $wgDBmwschema !== 'mediawiki'
181 && preg_match( '/^\w+$/', $wgDBmwschema )
182 && preg_match( '/^\w+$/', $wgDBts2schema )
184 $safeschema = $this->quote_ident($wgDBmwschema);
185 $safeschema2 = $this->quote_ident($wgDBts2schema);
186 $this->doQuery("SET search_path = $safeschema, $wgDBts2schema, public");
193 function initial_setup($password, $dbName) {
194 // If this is the initial connection, setup the schema stuff and possibly create the user
195 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
197 print "<li>Checking the version of Postgres...";
198 $version = $this->getServerVersion();
200 if ($this->numeric_version
< $PGMINVER) {
201 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
204 print "version $this->numeric_version is OK.</li>\n";
206 $safeuser = $this->quote_ident($wgDBuser);
207 // Are we connecting as a superuser for the first time?
208 if ($wgDBsuperuser) {
209 // Are we really a superuser? Check out our rights
211 CASE WHEN usesuper IS TRUE THEN
212 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
213 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
215 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
216 $rows = $this->numRows($res = $this->doQuery($SQL));
218 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
221 $perms = pg_fetch_result($res, 0, 0);
223 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
224 $rows = $this->numRows($this->doQuery($SQL));
226 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
229 if ($perms != 1 and $perms != 3) {
230 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
231 print 'Please use a different Postgres user.</li>';
234 print "<li>Creating user <b>$wgDBuser</b>...";
235 $safepass = $this->addQuotes($wgDBpassword);
236 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
237 $this->doQuery($SQL);
240 // User now exists, check out the database
241 if ($dbName != $wgDBname) {
242 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
243 $rows = $this->numRows($this->doQuery($SQL));
245 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
249 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
250 print 'Please use a different Postgres user.</li>';
253 print "<li>Creating database <b>$wgDBname</b>...";
254 $safename = $this->quote_ident($wgDBname);
255 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
256 $this->doQuery($SQL);
258 // Hopefully tsearch2 and plpgsql are in template1...
261 // Reconnect to check out tsearch2 rights for this user
262 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
265 if ($this->mServer
!=false && $this->mServer
!="") {
266 $hstring="host=$this->mServer ";
268 if ($this->mPort
!=false && $this->mPort
!="") {
269 $hstring .= "port=$this->mPort ";
272 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$wgDBsuperuser password=$password");
273 if ( $this->mConn
== false ) {
274 print "<b>FAILED TO CONNECT!</b></li>";
280 if ($this->numeric_version
< 8.3) {
282 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
283 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
284 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
285 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
286 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
290 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
291 foreach (array('cfg','cfgmap','dict','parser') as $table) {
292 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
293 $this->doQuery($SQL);
298 // Setup the schema for this user if needed
299 $result = $this->schemaExists($wgDBmwschema);
300 $safeschema = $this->quote_ident($wgDBmwschema);
302 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
303 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
305 print "<b>FAILED</b>.</li>\n";
311 print "<li>Schema already exists, explicitly granting rights...\n";
312 $safeschema2 = $this->addQuotes($wgDBmwschema);
313 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
314 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
315 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
316 "AND p.relkind IN ('r','S','v')\n";
318 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
319 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
320 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
321 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
322 $res = $this->doQuery($SQL);
324 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
327 $this->doQuery("SET search_path = $safeschema");
328 $rows = $this->numRows($res);
331 $this->doQuery(pg_fetch_result($res, $rows, 0));
336 // Install plpgsql if needed
337 $this->setup_plpgsql();
340 return true; // Reconnect as regular user
344 if (!defined('POSTGRES_SEARCHPATH')) {
346 if ($this->numeric_version
< 8.3) {
347 // Do we have the basic tsearch2 table?
348 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
349 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
350 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
351 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
352 print " for instructions.</li>\n";
357 // Does this user have the rights to the tsearch2 tables?
358 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
359 print "<li>Checking tsearch2 permissions...";
360 // Let's check all four, just to be safe
361 error_reporting( 0 );
362 $ts2tables = array('cfg','cfgmap','dict','parser');
363 $safetsschema = $this->quote_ident($wgDBts2schema);
364 foreach ( $ts2tables AS $tname ) {
365 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
366 $res = $this->doQuery($SQL);
368 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
369 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
373 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = '$ctype'";
374 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
375 $res = $this->doQuery($SQL);
376 error_reporting( E_ALL
);
378 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
383 // Will the current locale work? Can we force it to?
384 print "<li>Verifying tsearch2 locale with $ctype...";
385 $rows = $this->numRows($res);
388 print "<b>not found</b></li>\n";
389 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
393 $tsname = pg_fetch_result($res, 0, 0);
394 if ($tsname != 'default') {
395 print "<b>not set to default ($tsname)</b>";
396 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
401 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
402 $res = $this->doQuery($SQL);
404 print "<b>FAILED</b>. ";
405 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
411 // Final test: try out a simple tsearch2 query
412 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
413 $res = $this->doQuery($SQL);
415 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
421 // Install plpgsql if needed
422 $this->setup_plpgsql();
424 // Does the schema already exist? Who owns it?
425 $result = $this->schemaExists($wgDBmwschema);
427 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
428 error_reporting( 0 );
429 $safeschema = $this->quote_ident($wgDBmwschema);
430 $result = $this->doQuery("CREATE SCHEMA $safeschema");
431 error_reporting( E_ALL
);
433 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
434 "You can try making them the owner of the database, or try creating the schema with a ".
435 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
440 else if ($result != $wgDBuser) {
441 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$wgDBuser\". Not ideal.</li>\n";
444 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$wgDBuser\". Excellent.</li>\n";
447 // Always return GMT time to accomodate the existing integer-based timestamp assumption
448 print "<li>Setting the timezone to GMT for user \"$wgDBuser\" ...";
449 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
450 $result = pg_query($this->mConn
, $SQL);
452 print "<b>FAILED</b>.</li>\n";
456 // Set for the rest of this session
457 $SQL = "SET timezone = 'GMT'";
458 $result = pg_query($this->mConn
, $SQL);
460 print "<li>Failed to set timezone</li>\n";
464 print "<li>Setting the datestyle to ISO, YMD for user \"$wgDBuser\" ...";
465 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
466 $result = pg_query($this->mConn
, $SQL);
468 print "<b>FAILED</b>.</li>\n";
472 // Set for the rest of this session
473 $SQL = "SET datestyle = 'ISO, YMD'";
474 $result = pg_query($this->mConn
, $SQL);
476 print "<li>Failed to set datestyle</li>\n";
480 // Fix up the search paths if needed
481 print "<li>Setting the search path for user \"$wgDBuser\" ...";
482 $path = $this->quote_ident($wgDBmwschema);
483 if ($wgDBts2schema !== $wgDBmwschema)
484 $path .= ", ". $this->quote_ident($wgDBts2schema);
485 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
487 $SQL = "ALTER USER $safeuser SET search_path = $path";
488 $result = pg_query($this->mConn
, $SQL);
490 print "<b>FAILED</b>.</li>\n";
494 // Set for the rest of this session
495 $SQL = "SET search_path = $path";
496 $result = pg_query($this->mConn
, $SQL);
498 print "<li>Failed to set search_path</li>\n";
501 define( "POSTGRES_SEARCHPATH", $path );
506 function setup_plpgsql() {
507 print "<li>Checking for Pl/Pgsql ...";
508 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
509 $rows = $this->numRows($this->doQuery($SQL));
511 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
512 print "not installed. Attempting to install Pl/Pgsql ...";
513 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
514 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
515 $rows = $this->numRows($this->doQuery($SQL));
517 $olde = error_reporting(0);
518 error_reporting($olde - E_WARNING
);
519 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
520 error_reporting($olde);
522 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
527 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
536 * Closes a database connection, if it is open
537 * Returns success, true if already closed
540 $this->mOpened
= false;
541 if ( $this->mConn
) {
542 return pg_close( $this->mConn
);
548 function doQuery( $sql ) {
549 if (function_exists('mb_convert_encoding')) {
550 $sql = mb_convert_encoding($sql,'UTF-8');
552 $this->mLastResult
= pg_query( $this->mConn
, $sql);
553 $this->mAffectedRows
= NULL; // use pg_affected_rows(mLastResult)
554 return $this->mLastResult
;
557 function queryIgnore( $sql, $fname = '' ) {
558 return $this->query( $sql, $fname, true );
561 function freeResult( $res ) {
562 if ( $res instanceof ResultWrapper
) {
565 if ( !@pg_free_result
( $res ) ) {
566 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
570 function fetchObject( $res ) {
571 if ( $res instanceof ResultWrapper
) {
574 @$row = pg_fetch_object( $res );
575 # FIXME: HACK HACK HACK HACK debug
578 # hashar : not sure if the following test really trigger if the object
580 if( pg_last_error($this->mConn
) ) {
581 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
586 function fetchRow( $res ) {
587 if ( $res instanceof ResultWrapper
) {
590 @$row = pg_fetch_array( $res );
591 if( pg_last_error($this->mConn
) ) {
592 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
597 function numRows( $res ) {
598 if ( $res instanceof ResultWrapper
) {
601 @$n = pg_num_rows( $res );
602 if( pg_last_error($this->mConn
) ) {
603 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
607 function numFields( $res ) {
608 if ( $res instanceof ResultWrapper
) {
611 return pg_num_fields( $res );
613 function fieldName( $res, $n ) {
614 if ( $res instanceof ResultWrapper
) {
617 return pg_field_name( $res, $n );
621 * This must be called after nextSequenceVal
623 function insertId() {
624 return $this->mInsertId
;
627 function dataSeek( $res, $row ) {
628 if ( $res instanceof ResultWrapper
) {
631 return pg_result_seek( $res, $row );
634 function lastError() {
635 if ( $this->mConn
) {
636 return pg_last_error();
639 return "No database connection";
642 function lastErrno() {
643 return pg_last_error() ?
1 : 0;
646 function affectedRows() {
647 if ( !is_null( $this->mAffectedRows
) ) {
648 // Forced result for simulated queries
649 return $this->mAffectedRows
;
651 if( empty( $this->mLastResult
) )
653 return pg_affected_rows( $this->mLastResult
);
657 * Estimate rows in dataset
658 * Returns estimated count, based on EXPLAIN output
659 * This is not necessarily an accurate estimate, so use sparingly
660 * Returns -1 if count cannot be found
661 * Takes same arguments as Database::select()
664 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
665 $options['EXPLAIN'] = true;
666 $res = $this->select( $table, $vars, $conds, $fname, $options );
669 $row = $this->fetchRow( $res );
671 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
674 $this->freeResult($res);
681 * Returns information about an index
682 * If errors are explicitly ignored, returns NULL on failure
684 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
685 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
686 $res = $this->query( $sql, $fname );
690 while ( $row = $this->fetchObject( $res ) ) {
691 if ( $row->indexname
== $index ) {
698 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
699 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
700 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
701 $res = $this->query( $sql, $fname );
704 while ($row = $this->fetchObject( $res ))
711 * INSERT wrapper, inserts an array into a table
713 * $args may be a single associative array, or an array of these with numeric keys,
714 * for multi-row insert (Postgres version 8.2 and above only).
716 * @param array $table String: Name of the table to insert to.
717 * @param array $args Array: Items to insert into the table.
718 * @param array $fname String: Name of the function, for profiling
719 * @param mixed $options String or Array. Valid options: IGNORE
721 * @return bool Success of insert operation. IGNORE always returns true.
723 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
726 if ( !count( $args ) ) {
730 $table = $this->tableName( $table );
731 if (! isset( $wgDBversion ) ) {
732 $this->getServerVersion();
733 $wgDBversion = $this->numeric_version
;
736 if ( !is_array( $options ) )
737 $options = array( $options );
739 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
741 $keys = array_keys( $args[0] );
745 $keys = array_keys( $args );
748 // If IGNORE is set, we use savepoints to emulate mysql's behavior
749 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
751 // If we are not in a transaction, we need to be for savepoint trickery
754 if (! $this->mTrxLevel
) {
758 $olde = error_reporting( 0 );
759 // For future use, we may want to track the number of actual inserts
760 // Right now, insert (all writes) simply return true/false
761 $numrowsinserted = 0;
764 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
767 if ( $wgDBversion >= 8.2 && !$ignore ) {
769 foreach ( $args as $row ) {
775 $sql .= '(' . $this->makeList( $row ) . ')';
777 $res = (bool)$this->query( $sql, $fname, $ignore );
782 foreach ( $args as $row ) {
784 $tempsql .= '(' . $this->makeList( $row ) . ')';
787 pg_query($this->mConn
, "SAVEPOINT $ignore");
790 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
793 $bar = pg_last_error();
795 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
798 pg_query( $this->mConn
, "RELEASE $ignore" );
803 // If any of them fail, we fail overall for this function call
804 // Note that this will be ignored if IGNORE is set
811 // Not multi, just a lone insert
813 pg_query($this->mConn
, "SAVEPOINT $ignore");
816 $sql .= '(' . $this->makeList( $args ) . ')';
817 $res = (bool)$this->query( $sql, $fname, $ignore );
819 $bar = pg_last_error();
821 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
824 pg_query( $this->mConn
, "RELEASE $ignore" );
830 $olde = error_reporting( $olde );
835 // Set the affected row count for the whole operation
836 $this->mAffectedRows
= $numrowsinserted;
838 // IGNORE always returns true
847 function tableName( $name ) {
848 # Replace reserved words with better ones
853 return 'pagecontent';
860 * Return the next in a sequence, save the value for retrieval via insertId()
862 function nextSequenceValue( $seqName ) {
863 $safeseq = preg_replace( "/'/", "''", $seqName );
864 $res = $this->query( "SELECT nextval('$safeseq')" );
865 $row = $this->fetchRow( $res );
866 $this->mInsertId
= $row[0];
867 $this->freeResult( $res );
868 return $this->mInsertId
;
872 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
874 function currentSequenceValue( $seqName ) {
875 $safeseq = preg_replace( "/'/", "''", $seqName );
876 $res = $this->query( "SELECT currval('$safeseq')" );
877 $row = $this->fetchRow( $res );
879 $this->freeResult( $res );
884 * Postgres does not have a "USE INDEX" clause, so return an empty string
886 function useIndexClause( $index ) {
890 # REPLACE query wrapper
891 # Postgres simulates this with a DELETE followed by INSERT
892 # $row is the row to insert, an associative array
893 # $uniqueIndexes is an array of indexes. Each element may be either a
894 # field name or an array of field names
896 # It may be more efficient to leave off unique indexes which are unlikely to collide.
897 # However if you do this, you run the risk of encountering errors which wouldn't have
899 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
900 $table = $this->tableName( $table );
902 if (count($rows)==0) {
907 if ( !is_array( reset( $rows ) ) ) {
908 $rows = array( $rows );
911 foreach( $rows as $row ) {
912 # Delete rows which collide
913 if ( $uniqueIndexes ) {
914 $sql = "DELETE FROM $table WHERE ";
916 foreach ( $uniqueIndexes as $index ) {
923 if ( is_array( $index ) ) {
925 foreach ( $index as $col ) {
931 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
934 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
938 $this->query( $sql, $fname );
942 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
943 $this->makeList( $row, LIST_COMMA
) . ')';
944 $this->query( $sql, $fname );
948 # DELETE where the condition is a join
949 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
951 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
954 $delTable = $this->tableName( $delTable );
955 $joinTable = $this->tableName( $joinTable );
956 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
957 if ( $conds != '*' ) {
958 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
962 $this->query( $sql, $fname );
965 # Returns the size of a text field, or -1 for "unlimited"
966 function textFieldSize( $table, $field ) {
967 $table = $this->tableName( $table );
968 $sql = "SELECT t.typname as ftype,a.atttypmod as size
969 FROM pg_class c, pg_attribute a, pg_type t
970 WHERE relname='$table' AND a.attrelid=c.oid AND
971 a.atttypid=t.oid and a.attname='$field'";
972 $res =$this->query($sql);
973 $row=$this->fetchObject($res);
974 if ($row->ftype
=="varchar") {
979 $this->freeResult( $res );
983 function lowPriorityOption() {
987 function limitResult($sql, $limit, $offset=false) {
988 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
992 * Returns an SQL expression for a simple conditional.
993 * Uses CASE on Postgres
995 * @param string $cond SQL expression which will result in a boolean value
996 * @param string $trueVal SQL expression to return if true
997 * @param string $falseVal SQL expression to return if false
998 * @return string SQL fragment
1000 function conditional( $cond, $trueVal, $falseVal ) {
1001 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1004 function wasDeadlock() {
1005 return $this->lastErrno() == '40P01';
1008 function timestamp( $ts=0 ) {
1009 return wfTimestamp(TS_POSTGRES
,$ts);
1013 * Return aggregated value function call
1015 function aggregateValue ($valuedata,$valuename='value') {
1020 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1021 // Ignore errors during error handling to avoid infinite recursion
1022 $ignore = $this->ignoreErrors( true );
1023 $this->mErrorCount++
;
1025 if ($ignore ||
$tempIgnore) {
1026 wfDebug("SQL ERROR (ignored): $error\n");
1027 $this->ignoreErrors( $ignore );
1030 $message = "A database error has occurred\n" .
1032 "Function: $fname\n" .
1033 "Error: $errno $error\n";
1034 throw new DBUnexpectedError($this, $message);
1039 * @return string wikitext of a link to the server software's web site
1041 function getSoftwareLink() {
1042 return "[http://www.postgresql.org/ PostgreSQL]";
1046 * @return string Version information from the database
1048 function getServerVersion() {
1049 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
1051 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
1052 die("Could not determine the numeric version from $version!");
1054 $version = $thisver[1].$thisver[2];
1055 $this->numeric_version
= $thisver[1];
1061 * Query whether a given relation exists (in the given schema, or the
1062 * default mw one if not given)
1064 function relationExists( $table, $types, $schema = false ) {
1065 global $wgDBmwschema;
1066 if (!is_array($types))
1067 $types = array($types);
1069 $schema = $wgDBmwschema;
1070 $etable = $this->addQuotes($table);
1071 $eschema = $this->addQuotes($schema);
1072 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1073 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1074 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1075 $res = $this->query( $SQL );
1076 $count = $res ?
$res->numRows() : 0;
1078 $this->freeResult( $res );
1079 return $count ?
true : false;
1083 * For backward compatibility, this function checks both tables and
1086 function tableExists ($table, $schema = false) {
1087 return $this->relationExists($table, array('r', 'v'), $schema);
1090 function sequenceExists ($sequence, $schema = false) {
1091 return $this->relationExists($sequence, 'S', $schema);
1094 function triggerExists($table, $trigger) {
1095 global $wgDBmwschema;
1098 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1099 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1100 AND tgrelid=pg_class.oid
1101 AND nspname=%s AND relname=%s AND tgname=%s
1103 $res = $this->query(sprintf($q,
1104 $this->addQuotes($wgDBmwschema),
1105 $this->addQuotes($table),
1106 $this->addQuotes($trigger)));
1109 $rows = $res->numRows();
1110 $this->freeResult($res);
1114 function ruleExists($table, $rule) {
1115 global $wgDBmwschema;
1116 $exists = $this->selectField("pg_rules", "rulename",
1117 array( "rulename" => $rule,
1118 "tablename" => $table,
1119 "schemaname" => $wgDBmwschema));
1120 return $exists === $rule;
1123 function constraintExists($table, $constraint) {
1124 global $wgDBmwschema;
1125 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1126 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1127 $this->addQuotes($wgDBmwschema),
1128 $this->addQuotes($table),
1129 $this->addQuotes($constraint));
1130 $res = $this->query($SQL);
1133 $rows = $res->numRows();
1134 $this->freeResult($res);
1139 * Query whether a given schema exists. Returns the name of the owner
1141 function schemaExists( $schema ) {
1142 $eschema = preg_replace("/'/", "''", $schema);
1143 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1144 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1145 $res = $this->query( $SQL );
1146 if ( $res && $res->numRows() ) {
1147 $row = $res->fetchObject();
1148 $owner = $row->rolname
;
1153 $this->freeResult($res);
1158 * Query whether a given column exists in the mediawiki schema
1160 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1161 global $wgDBmwschema;
1162 $etable = preg_replace("/'/", "''", $table);
1163 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1164 $ecol = preg_replace("/'/", "''", $field);
1165 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1166 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1167 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1168 $res = $this->query( $SQL, $fname );
1169 $count = $res ?
$res->numRows() : 0;
1171 $this->freeResult( $res );
1175 function fieldInfo( $table, $field ) {
1176 return PostgresField
::fromText($this, $table, $field);
1180 * pg_field_type() wrapper
1182 function fieldType( $res, $index ) {
1183 if ( $res instanceof ResultWrapper
) {
1184 $res = $res->result
;
1186 return pg_field_type( $res, $index );
1189 function begin( $fname = 'DatabasePostgres::begin' ) {
1190 $this->query( 'BEGIN', $fname );
1191 $this->mTrxLevel
= 1;
1193 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1196 function commit( $fname = 'DatabasePostgres::commit' ) {
1197 $this->query( 'COMMIT', $fname );
1198 $this->mTrxLevel
= 0;
1201 /* Not even sure why this is used in the main codebase... */
1202 function limitResultForUpdate($sql, $num) {
1206 function setup_database() {
1207 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1209 // Make sure that we can write to the correct schema
1210 // If not, Postgres will happily and silently go to the next search_path item
1211 $ctest = "mediawiki_test_table";
1212 $safeschema = $this->quote_ident($wgDBmwschema);
1213 if ($this->tableExists($ctest, $wgDBmwschema)) {
1214 $this->doQuery("DROP TABLE $safeschema.$ctest");
1216 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1217 $olde = error_reporting( 0 );
1218 $res = $this->doQuery($SQL);
1219 error_reporting( $olde );
1221 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
1224 $this->doQuery("DROP TABLE $safeschema.$ctest");
1226 $res = dbsource( "../maintenance/postgres/tables.sql", $this);
1228 ## Update version information
1229 $mwv = $this->addQuotes($wgVersion);
1230 $pgv = $this->addQuotes($this->getServerVersion());
1231 $pgu = $this->addQuotes($this->mUser
);
1232 $mws = $this->addQuotes($wgDBmwschema);
1233 $tss = $this->addQuotes($wgDBts2schema);
1234 $pgp = $this->addQuotes($wgDBport);
1235 $dbn = $this->addQuotes($this->mDBname
);
1236 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1238 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1239 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1240 "ctype = '$ctype' ".
1241 "WHERE type = 'Creation'";
1244 ## Avoid the non-standard "REPLACE INTO" syntax
1245 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1247 dieout( "<li>Could not find the interwiki.sql file");
1249 ## We simply assume it is already empty as we have just created it
1250 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1251 while ( ! feof( $f ) ) {
1252 $line = fgets($f,1024);
1254 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1257 $this->query("$SQL $matches[1],$matches[2])");
1259 print " (table interwiki successfully populated)...\n";
1261 $this->doQuery("COMMIT");
1264 function encodeBlob( $b ) {
1265 return new Blob ( pg_escape_bytea( $b ) ) ;
1268 function decodeBlob( $b ) {
1269 if ($b instanceof Blob
) {
1272 return pg_unescape_bytea( $b );
1275 function strencode( $s ) { ## Should not be called by us
1276 return pg_escape_string( $s );
1279 function addQuotes( $s ) {
1280 if ( is_null( $s ) ) {
1282 } else if ( is_bool( $s ) ) {
1283 return intval( $s );
1284 } else if ($s instanceof Blob
) {
1285 return "'".$s->fetch($s)."'";
1287 return "'" . pg_escape_string($s) . "'";
1290 function quote_ident( $s ) {
1291 return '"' . preg_replace( '/"/', '""', $s) . '"';
1294 /* For now, does nothing */
1295 function selectDB( $db ) {
1300 * Postgres specific version of replaceVars.
1301 * Calls the parent version in Database.php
1305 * @param string $com SQL string, read from a stream (usually tables.sql)
1307 * @return string SQL string
1309 protected function replaceVars( $ins ) {
1311 $ins = parent
::replaceVars( $ins );
1313 if ($this->numeric_version
>= 8.3) {
1314 // Thanks for not providing backwards-compatibility, 8.3
1315 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1318 if ($this->numeric_version
<= 8.1) { // Our minimum version
1319 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1326 * Various select options
1330 * @param array $options an associative array of options to be turned into
1331 * an SQL query, valid keys are listed in the function.
1334 function makeSelectOptions( $options ) {
1335 $preLimitTail = $postLimitTail = '';
1336 $startOpts = $useIndex = '';
1338 $noKeyOptions = array();
1339 foreach ( $options as $key => $option ) {
1340 if ( is_numeric( $key ) ) {
1341 $noKeyOptions[$option] = true;
1345 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1346 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1347 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1349 //if (isset($options['LIMIT'])) {
1350 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1351 // isset($options['OFFSET']) ? $options['OFFSET']
1355 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1356 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1357 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1359 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1362 public function setTimeout( $timeout ) {
1363 // @todo fixme no-op
1367 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1372 * How lagged is this slave?
1375 public function getLag() {
1376 # Not implemented for PostgreSQL
1380 function setFakeSlaveLag( $lag ) {}
1381 function setFakeMaster( $enabled = true ) {}
1383 function getDBname() {
1384 return $this->mDBname
;
1387 function getServer() {
1388 return $this->mServer
;
1391 function buildConcat( $stringList ) {
1392 return implode( ' || ', $stringList );
1395 /* These are not used yet, but we know we don't want the default version */
1397 public function lock( $lockName, $method ) {
1400 public function unlock( $lockName, $method ) {
1404 public function getSearchEngine() {
1405 return "SearchPostgres";
1408 } // end DatabasePostgres class