4 * This is the Postgres database abstraction layer.
6 * As it includes more generic version for DB functions,
7 * than MySQL ones, some of them should be moved to parent
12 class DatabasePostgres
extends Database
{
13 var $mInsertId = NULL;
14 var $mLastResult = NULL;
15 var $numeric_version = NULL;
17 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
18 $failFunction = false, $flags = 0 )
22 # Can't get a reference if it hasn't been set yet
23 if ( !isset( $wgOut ) ) {
26 $this->mOut
=& $wgOut;
27 $this->mFailFunction
= $failFunction;
28 $this->mCascadingDeletes
= true;
29 $this->mCleanupTriggers
= true;
30 $this->mStrictIPs
= true;
31 $this->mFlags
= $flags;
32 $this->open( $server, $user, $password, $dbName);
36 function realTimestamps() {
40 function implicitGroupby() {
44 function searchableIPs() {
48 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
49 $failFunction = false, $flags = 0)
51 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
55 * Usually aborts on failure
56 * If the failFunction is set to a non-zero integer, returns success
58 function open( $server, $user, $password, $dbName ) {
59 # Test for Postgres support, to avoid suppressed fatal error
60 if ( !function_exists( 'pg_connect' ) ) {
61 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" );
68 $this->mServer
= $server;
71 $this->mPassword
= $password;
72 $this->mDBname
= $dbName;
75 if ($server!=false && $server!="") {
76 $hstring="host=$server ";
78 if ($port!=false && $port!="") {
79 $hstring .= "port=$port ";
82 if (!strlen($user)) { ## e.g. the class is being loaded
86 error_reporting( E_ALL
);
87 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
89 if ( $this->mConn
== false ) {
90 wfDebug( "DB connection error\n" );
91 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
92 wfDebug( $this->lastError()."\n" );
96 $this->mOpened
= true;
97 ## If this is the initial connection, setup the schema stuff and possibly create the user
98 if (defined('MEDIAWIKI_INSTALL')) {
99 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
102 print "<li>Checking the version of Postgres...";
103 $version = $this->getServerVersion();
105 if ($this->numeric_version
< $PGMINVER) {
106 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
109 print "version $this->numeric_version is OK.</li>\n";
111 $safeuser = $this->quote_ident($wgDBuser);
112 ## Are we connecting as a superuser for the first time?
113 if ($wgDBsuperuser) {
114 ## Are we really a superuser? Check out our rights
116 CASE WHEN usesuper IS TRUE THEN
117 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
118 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
120 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
121 $rows = $this->numRows($res = $this->doQuery($SQL));
123 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
126 $perms = pg_fetch_result($res, 0, 0);
128 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
129 $rows = $this->numRows($this->doQuery($SQL));
131 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
134 if ($perms != 1 and $perms != 3) {
135 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
136 print 'Please use a different Postgres user.</li>';
139 print "<li>Creating user <b>$wgDBuser</b>...";
140 $safepass = $this->addQuotes($wgDBpassword);
141 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
142 $this->doQuery($SQL);
145 ## User now exists, check out the database
146 if ($dbName != $wgDBname) {
147 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
148 $rows = $this->numRows($this->doQuery($SQL));
150 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
154 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
155 print 'Please use a different Postgres user.</li>';
158 print "<li>Creating database <b>$wgDBname</b>...";
159 $safename = $this->quote_ident($wgDBname);
160 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
161 $this->doQuery($SQL);
163 ## Hopefully tsearch2 and plpgsql are in template1...
166 ## Reconnect to check out tsearch2 rights for this user
167 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
168 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
169 if ( $this->mConn
== false ) {
170 print "<b>FAILED TO CONNECT!</b></li>";
177 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
178 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
179 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
180 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
181 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
185 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
186 foreach (array('cfg','cfgmap','dict','parser') as $table) {
187 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
188 $this->doQuery($SQL);
193 ## Setup the schema for this user if needed
194 $result = $this->schemaExists($wgDBmwschema);
195 $safeschema = $this->quote_ident($wgDBmwschema);
197 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
198 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
200 print "<b>FAILED</b>.</li>\n";
206 print "<li>Schema already exists, explicitly granting rights...\n";
207 $safeschema2 = $this->addQuotes($wgDBmwschema);
208 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
209 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
210 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
211 "AND p.relkind IN ('r','S','v')\n";
213 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
214 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
215 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
216 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
217 $res = $this->doQuery($SQL);
219 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
222 $this->doQuery("SET search_path = $safeschema");
223 $rows = $this->numRows($res);
226 $this->doQuery(pg_fetch_result($res, $rows, 0));
232 return true; ## Reconnect as regular user
235 if (!defined('POSTGRES_SEARCHPATH')) {
237 ## Do we have the basic tsearch2 table?
238 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
239 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
240 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
241 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
242 print " for instructions.</li>\n";
247 ## Does this user have the rights to the tsearch2 tables?
248 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
249 print "<li>Checking tsearch2 permissions...";
250 ## Let's check all four, just to be safe
251 error_reporting( 0 );
252 $ts2tables = array('cfg','cfgmap','dict','parser');
253 foreach ( $ts2tables AS $tname ) {
254 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
255 $res = $this->doQuery($SQL);
257 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
258 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
262 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
263 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
264 $res = $this->doQuery($SQL);
265 error_reporting( E_ALL
);
267 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
272 ## Will the current locale work? Can we force it to?
273 print "<li>Verifying tsearch2 locale with $ctype...";
274 $rows = $this->numRows($res);
277 print "<b>not found</b></li>\n";
278 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
282 $tsname = pg_fetch_result($res, 0, 0);
283 if ($tsname != 'default') {
284 print "<b>not set to default ($tsname)</b>";
285 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
290 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
291 $res = $this->doQuery($SQL);
293 print "<b>FAILED</b>. ";
294 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
300 ## Final test: try out a simple tsearch2 query
301 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
302 $res = $this->doQuery($SQL);
304 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
309 ## Do we have plpgsql installed?
310 print "<li>Checking for Pl/Pgsql ...";
311 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
312 $rows = $this->numRows($this->doQuery($SQL));
314 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
315 print "not installed. Attempting to install Pl/Pgsql ...";
316 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
317 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
318 $rows = $this->numRows($this->doQuery($SQL));
320 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
322 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
327 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
333 ## Does the schema already exist? Who owns it?
334 $result = $this->schemaExists($wgDBmwschema);
336 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
337 error_reporting( 0 );
338 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
339 error_reporting( E_ALL
);
341 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
342 "You can try making them the owner of the database, or try creating the schema with a ".
343 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
348 else if ($result != $user) {
349 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
352 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
355 ## Fix up the search paths if needed
356 print "<li>Setting the search path for user \"$user\" ...";
357 $path = $this->quote_ident($wgDBmwschema);
358 if ($wgDBts2schema !== $wgDBmwschema)
359 $path .= ", ". $this->quote_ident($wgDBts2schema);
360 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
362 $SQL = "ALTER USER $safeuser SET search_path = $path";
363 $result = pg_query($this->mConn
, $SQL);
365 print "<b>FAILED</b>.</li>\n";
369 ## Set for the rest of this session
370 $SQL = "SET search_path = $path";
371 $result = pg_query($this->mConn
, $SQL);
373 print "<li>Failed to set search_path</li>\n";
376 define( "POSTGRES_SEARCHPATH", $path );
379 global $wgCommandLineMode;
380 ## If called from the command-line (e.g. importDump), only show errors
381 if ($wgCommandLineMode) {
382 $this->doQuery("SET client_min_messages = 'ERROR'");
389 * Closes a database connection, if it is open
390 * Returns success, true if already closed
393 $this->mOpened
= false;
394 if ( $this->mConn
) {
395 return pg_close( $this->mConn
);
401 function doQuery( $sql ) {
402 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
405 function queryIgnore( $sql, $fname = '' ) {
406 return $this->query( $sql, $fname, true );
409 function freeResult( $res ) {
410 if ( !@pg_free_result
( $res ) ) {
411 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
415 function fetchObject( $res ) {
416 @$row = pg_fetch_object( $res );
417 # FIXME: HACK HACK HACK HACK debug
420 # hashar : not sure if the following test really trigger if the object
422 if( pg_last_error($this->mConn
) ) {
423 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
428 function fetchRow( $res ) {
429 @$row = pg_fetch_array( $res );
430 if( pg_last_error($this->mConn
) ) {
431 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
436 function numRows( $res ) {
437 @$n = pg_num_rows( $res );
438 if( pg_last_error($this->mConn
) ) {
439 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
443 function numFields( $res ) { return pg_num_fields( $res ); }
444 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
447 * This must be called after nextSequenceVal
449 function insertId() {
450 return $this->mInsertId
;
453 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
454 function lastError() {
455 if ( $this->mConn
) {
456 return pg_last_error();
459 return "No database connection";
462 function lastErrno() {
463 return pg_last_error() ?
1 : 0;
466 function affectedRows() {
467 return pg_affected_rows( $this->mLastResult
);
471 * Returns information about an index
472 * If errors are explicitly ignored, returns NULL on failure
474 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
475 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
476 $res = $this->query( $sql, $fname );
481 while ( $row = $this->fetchObject( $res ) ) {
482 if ( $row->indexname
== $index ) {
485 // BUG: !!!! This code needs to be synced up with database.php
492 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
493 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
494 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
495 $res = $this->query( $sql, $fname );
498 while ($row = $this->fetchObject( $res ))
504 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
505 # Postgres doesn't support options
506 # We have a go at faking one of them
507 # TODO: DELAYED, LOW_PRIORITY
509 if ( !is_array($options))
510 $options = array($options);
512 if ( in_array( 'IGNORE', $options ) )
513 $oldIgnore = $this->ignoreErrors( true );
515 # IGNORE is performed using single-row inserts, ignoring errors in each
516 # FIXME: need some way to distiguish between key collision and other types of error
517 $oldIgnore = $this->ignoreErrors( true );
518 if ( !is_array( reset( $a ) ) ) {
521 foreach ( $a as $row ) {
522 parent
::insert( $table, $row, $fname, array() );
524 $this->ignoreErrors( $oldIgnore );
527 if ( in_array( 'IGNORE', $options ) )
528 $this->ignoreErrors( $oldIgnore );
533 function tableName( $name ) {
534 # Replace reserved words with better ones
539 return 'pagecontent';
546 * Return the next in a sequence, save the value for retrieval via insertId()
548 function nextSequenceValue( $seqName ) {
549 $safeseq = preg_replace( "/'/", "''", $seqName );
550 $res = $this->query( "SELECT nextval('$safeseq')" );
551 $row = $this->fetchRow( $res );
552 $this->mInsertId
= $row[0];
553 $this->freeResult( $res );
554 return $this->mInsertId
;
558 * Postgres does not have a "USE INDEX" clause, so return an empty string
560 function useIndexClause( $index ) {
564 # REPLACE query wrapper
565 # Postgres simulates this with a DELETE followed by INSERT
566 # $row is the row to insert, an associative array
567 # $uniqueIndexes is an array of indexes. Each element may be either a
568 # field name or an array of field names
570 # It may be more efficient to leave off unique indexes which are unlikely to collide.
571 # However if you do this, you run the risk of encountering errors which wouldn't have
573 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
574 $table = $this->tableName( $table );
576 if (count($rows)==0) {
581 if ( !is_array( reset( $rows ) ) ) {
582 $rows = array( $rows );
585 foreach( $rows as $row ) {
586 # Delete rows which collide
587 if ( $uniqueIndexes ) {
588 $sql = "DELETE FROM $table WHERE ";
590 foreach ( $uniqueIndexes as $index ) {
597 if ( is_array( $index ) ) {
599 foreach ( $index as $col ) {
605 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
608 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
612 $this->query( $sql, $fname );
616 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
617 $this->makeList( $row, LIST_COMMA
) . ')';
618 $this->query( $sql, $fname );
622 # DELETE where the condition is a join
623 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
625 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
628 $delTable = $this->tableName( $delTable );
629 $joinTable = $this->tableName( $joinTable );
630 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
631 if ( $conds != '*' ) {
632 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
636 $this->query( $sql, $fname );
639 # Returns the size of a text field, or -1 for "unlimited"
640 function textFieldSize( $table, $field ) {
641 $table = $this->tableName( $table );
642 $sql = "SELECT t.typname as ftype,a.atttypmod as size
643 FROM pg_class c, pg_attribute a, pg_type t
644 WHERE relname='$table' AND a.attrelid=c.oid AND
645 a.atttypid=t.oid and a.attname='$field'";
646 $res =$this->query($sql);
647 $row=$this->fetchObject($res);
648 if ($row->ftype
=="varchar") {
653 $this->freeResult( $res );
657 function lowPriorityOption() {
661 function limitResult($sql, $limit,$offset) {
662 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
666 * Returns an SQL expression for a simple conditional.
667 * Uses CASE on Postgres
669 * @param string $cond SQL expression which will result in a boolean value
670 * @param string $trueVal SQL expression to return if true
671 * @param string $falseVal SQL expression to return if false
672 * @return string SQL fragment
674 function conditional( $cond, $trueVal, $falseVal ) {
675 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
678 function wasDeadlock() {
679 return $this->lastErrno() == '40P01';
682 function timestamp( $ts=0 ) {
683 return wfTimestamp(TS_POSTGRES
,$ts);
687 * Return aggregated value function call
689 function aggregateValue ($valuedata,$valuename='value') {
694 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
695 # Ignore errors during error handling to avoid infinite recursion
696 $ignore = $this->ignoreErrors( true );
697 ++
$this->mErrorCount
;
699 if ($ignore ||
$tempIgnore) {
700 wfDebug("SQL ERROR (ignored): $error\n");
701 $this->ignoreErrors( $ignore );
704 $message = "A database error has occurred\n" .
706 "Function: $fname\n" .
707 "Error: $errno $error\n";
708 throw new DBUnexpectedError($this, $message);
713 * @return string wikitext of a link to the server software's web site
715 function getSoftwareLink() {
716 return "[http://www.postgresql.org/ PostgreSQL]";
720 * @return string Version information from the database
722 function getServerVersion() {
723 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
725 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
726 die("Could not determine the numeric version from $version!");
728 $this->numeric_version
= $thisver[1];
734 * Query whether a given table exists (in the given schema, or the default mw one if not given)
736 function tableExists( $table, $schema = false ) {
737 global $wgDBmwschema;
739 $schema = $wgDBmwschema;
740 $etable = preg_replace("/'/", "''", $table);
741 $eschema = preg_replace("/'/", "''", $schema);
742 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
743 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
744 . "AND c.relkind IN ('r','v')";
745 $res = $this->query( $SQL );
746 $count = $res ?
pg_num_rows($res) : 0;
748 $this->freeResult( $res );
754 * Query whether a given schema exists. Returns the name of the owner
756 function schemaExists( $schema ) {
757 $eschema = preg_replace("/'/", "''", $schema);
758 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
759 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
760 $res = $this->query( $SQL );
761 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
763 $this->freeResult($res);
768 * Query whether a given column exists in the mediawiki schema
770 function fieldExists( $table, $field ) {
771 global $wgDBmwschema;
772 $etable = preg_replace("/'/", "''", $table);
773 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
774 $ecol = preg_replace("/'/", "''", $field);
775 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
776 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
777 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
778 $res = $this->query( $SQL );
779 $count = $res ?
pg_num_rows($res) : 0;
781 $this->freeResult( $res );
785 function fieldInfo( $table, $field ) {
786 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
787 $type = pg_field_type( $res, 0 );
791 function begin( $fname = 'DatabasePostgrs::begin' ) {
792 $this->query( 'BEGIN', $fname );
793 $this->mTrxLevel
= 1;
795 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
798 function commit( $fname = 'DatabasePostgres::commit' ) {
799 $this->query( 'COMMIT', $fname );
800 $this->mTrxLevel
= 0;
803 /* Not even sure why this is used in the main codebase... */
804 function limitResultForUpdate($sql, $num) {
808 function setup_database() {
809 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
811 ## Make sure that we can write to the correct schema
812 ## If not, Postgres will happily and silently go to the next search_path item
813 $SQL = "CREATE TABLE $wgDBmwschema.mw_test_table(a int)";
814 error_reporting( 0 );
815 $res = $this->doQuery($SQL);
816 error_reporting( E_ALL
);
818 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"wgDBmwschema\"</li>\n";
822 dbsource( "../maintenance/postgres/tables.sql", $this);
824 ## Version-specific stuff
825 if ($this->numeric_version
== 8.1) {
826 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
827 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
830 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
831 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
834 ## Update version information
835 $mwv = $this->addQuotes($wgVersion);
836 $pgv = $this->addQuotes($this->getServerVersion());
837 $pgu = $this->addQuotes($this->mUser
);
838 $mws = $this->addQuotes($wgDBmwschema);
839 $tss = $this->addQuotes($wgDBts2schema);
840 $pgp = $this->addQuotes($wgDBport);
841 $dbn = $this->addQuotes($this->mDBname
);
842 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
844 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
845 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
847 "WHERE type = 'Creation'";
850 ## Avoid the non-standard "REPLACE INTO" syntax
851 $f = fopen( "../maintenance/interwiki.sql", 'r' );
853 dieout( "<li>Could not find the interwiki.sql file");
855 ## We simply assume it is already empty as we have just created it
856 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
857 while ( ! feof( $f ) ) {
858 $line = fgets($f,1024);
860 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
863 $this->query("$SQL $matches[1],$matches[2])");
865 print " (table interwiki successfully populated)...\n";
868 function encodeBlob($b) {
869 return array('bytea',pg_escape_bytea($b));
871 function decodeBlob($b) {
872 return pg_unescape_bytea( $b );
875 function strencode( $s ) { ## Should not be called by us
876 return pg_escape_string( $s );
879 function addQuotes( $s ) {
880 if ( is_null( $s ) ) {
882 } else if (is_array( $s )) { ## Assume it is bytea data
885 return "'" . pg_escape_string($s) . "'";
886 // Unreachable: return "E'" . pg_escape_string($s) . "'";
889 function quote_ident( $s ) {
890 return '"' . preg_replace( '/"/', '""', $s) . '"';
893 /* For now, does nothing */
894 function selectDB( $db ) {
899 * Returns an optional USE INDEX clause to go after the table, and a
900 * string to go at the end of the query
904 * @param array $options an associative array of options to be turned into
905 * an SQL query, valid keys are listed in the function.
908 function makeSelectOptions( $options ) {
909 $preLimitTail = $postLimitTail = '';
912 $noKeyOptions = array();
913 foreach ( $options as $key => $option ) {
914 if ( is_numeric( $key ) ) {
915 $noKeyOptions[$option] = true;
919 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
920 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
922 //if (isset($options['LIMIT'])) {
923 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
924 // isset($options['OFFSET']) ? $options['OFFSET']
928 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
929 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
930 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
932 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
933 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
938 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
941 public function setTimeout( $timeout ) {
946 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
951 } // end DatabasePostgres class