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" );
66 if (!strlen($user)) { ## e.g. the class is being loaded
71 $this->mServer
= $server;
74 $this->mPassword
= $password;
75 $this->mDBname
= $dbName;
78 if ($server!=false && $server!="") {
79 $hstring="host=$server ";
81 if ($port!=false && $port!="") {
82 $hstring .= "port=$port ";
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
236 if (!defined('POSTGRES_SEARCHPATH')) {
238 ## Do we have the basic tsearch2 table?
239 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
240 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
241 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
242 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
243 print " for instructions.</li>\n";
248 ## Does this user have the rights to the tsearch2 tables?
249 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
250 print "<li>Checking tsearch2 permissions...";
251 ## Let's check all four, just to be safe
252 error_reporting( 0 );
253 $ts2tables = array('cfg','cfgmap','dict','parser');
254 foreach ( $ts2tables AS $tname ) {
255 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
256 $res = $this->doQuery($SQL);
258 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
259 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
263 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
264 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
265 $res = $this->doQuery($SQL);
266 error_reporting( E_ALL
);
268 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
273 ## Will the current locale work? Can we force it to?
274 print "<li>Verifying tsearch2 locale with $ctype...";
275 $rows = $this->numRows($res);
278 print "<b>not found</b></li>\n";
279 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
283 $tsname = pg_fetch_result($res, 0, 0);
284 if ($tsname != 'default') {
285 print "<b>not set to default ($tsname)</b>";
286 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
291 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
292 $res = $this->doQuery($SQL);
294 print "<b>FAILED</b>. ";
295 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
301 ## Final test: try out a simple tsearch2 query
302 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
303 $res = $this->doQuery($SQL);
305 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
310 ## Do we have plpgsql installed?
311 print "<li>Checking for Pl/Pgsql ...";
312 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
313 $rows = $this->numRows($this->doQuery($SQL));
315 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
316 print "not installed. Attempting to install Pl/Pgsql ...";
317 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
318 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
319 $rows = $this->numRows($this->doQuery($SQL));
321 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
323 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
328 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
334 ## Does the schema already exist? Who owns it?
335 $result = $this->schemaExists($wgDBmwschema);
337 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
338 error_reporting( 0 );
339 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
340 error_reporting( E_ALL
);
342 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
343 "You can try making them the owner of the database, or try creating the schema with a ".
344 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
349 else if ($result != $user) {
350 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
353 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
356 ## Fix up the search paths if needed
357 print "<li>Setting the search path for user \"$user\" ...";
358 $path = $this->quote_ident($wgDBmwschema);
359 if ($wgDBts2schema !== $wgDBmwschema)
360 $path .= ", ". $this->quote_ident($wgDBts2schema);
361 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
363 $SQL = "ALTER USER $safeuser SET search_path = $path";
364 $result = pg_query($this->mConn
, $SQL);
366 print "<b>FAILED</b>.</li>\n";
370 ## Set for the rest of this session
371 $SQL = "SET search_path = $path";
372 $result = pg_query($this->mConn
, $SQL);
374 print "<li>Failed to set search_path</li>\n";
377 define( "POSTGRES_SEARCHPATH", $path );
380 global $wgCommandLineMode;
381 ## If called from the command-line (e.g. importDump), only show errors
382 if ($wgCommandLineMode) {
383 $this->doQuery("SET client_min_messages = 'ERROR'");
390 * Closes a database connection, if it is open
391 * Returns success, true if already closed
394 $this->mOpened
= false;
395 if ( $this->mConn
) {
396 return pg_close( $this->mConn
);
402 function doQuery( $sql ) {
403 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
406 function queryIgnore( $sql, $fname = '' ) {
407 return $this->query( $sql, $fname, true );
410 function freeResult( $res ) {
411 if ( !@pg_free_result
( $res ) ) {
412 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
416 function fetchObject( $res ) {
417 @$row = pg_fetch_object( $res );
418 # FIXME: HACK HACK HACK HACK debug
421 # hashar : not sure if the following test really trigger if the object
423 if( pg_last_error($this->mConn
) ) {
424 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
429 function fetchRow( $res ) {
430 @$row = pg_fetch_array( $res );
431 if( pg_last_error($this->mConn
) ) {
432 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
437 function numRows( $res ) {
438 @$n = pg_num_rows( $res );
439 if( pg_last_error($this->mConn
) ) {
440 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
444 function numFields( $res ) { return pg_num_fields( $res ); }
445 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
448 * This must be called after nextSequenceVal
450 function insertId() {
451 return $this->mInsertId
;
454 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
455 function lastError() {
456 if ( $this->mConn
) {
457 return pg_last_error();
460 return "No database connection";
463 function lastErrno() {
464 return pg_last_error() ?
1 : 0;
467 function affectedRows() {
468 return pg_affected_rows( $this->mLastResult
);
472 * Returns information about an index
473 * If errors are explicitly ignored, returns NULL on failure
475 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
476 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
477 $res = $this->query( $sql, $fname );
482 while ( $row = $this->fetchObject( $res ) ) {
483 if ( $row->indexname
== $index ) {
486 // BUG: !!!! This code needs to be synced up with database.php
493 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
494 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
495 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
496 $res = $this->query( $sql, $fname );
499 while ($row = $this->fetchObject( $res ))
505 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
506 # Postgres doesn't support options
507 # We have a go at faking one of them
508 # TODO: DELAYED, LOW_PRIORITY
510 if ( !is_array($options))
511 $options = array($options);
513 if ( in_array( 'IGNORE', $options ) )
514 $oldIgnore = $this->ignoreErrors( true );
516 # IGNORE is performed using single-row inserts, ignoring errors in each
517 # FIXME: need some way to distiguish between key collision and other types of error
518 $oldIgnore = $this->ignoreErrors( true );
519 if ( !is_array( reset( $a ) ) ) {
522 foreach ( $a as $row ) {
523 parent
::insert( $table, $row, $fname, array() );
525 $this->ignoreErrors( $oldIgnore );
528 if ( in_array( 'IGNORE', $options ) )
529 $this->ignoreErrors( $oldIgnore );
534 function tableName( $name ) {
535 # Replace reserved words with better ones
540 return 'pagecontent';
547 * Return the next in a sequence, save the value for retrieval via insertId()
549 function nextSequenceValue( $seqName ) {
550 $safeseq = preg_replace( "/'/", "''", $seqName );
551 $res = $this->query( "SELECT nextval('$safeseq')" );
552 $row = $this->fetchRow( $res );
553 $this->mInsertId
= $row[0];
554 $this->freeResult( $res );
555 return $this->mInsertId
;
559 * Postgres does not have a "USE INDEX" clause, so return an empty string
561 function useIndexClause( $index ) {
565 # REPLACE query wrapper
566 # Postgres simulates this with a DELETE followed by INSERT
567 # $row is the row to insert, an associative array
568 # $uniqueIndexes is an array of indexes. Each element may be either a
569 # field name or an array of field names
571 # It may be more efficient to leave off unique indexes which are unlikely to collide.
572 # However if you do this, you run the risk of encountering errors which wouldn't have
574 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
575 $table = $this->tableName( $table );
577 if (count($rows)==0) {
582 if ( !is_array( reset( $rows ) ) ) {
583 $rows = array( $rows );
586 foreach( $rows as $row ) {
587 # Delete rows which collide
588 if ( $uniqueIndexes ) {
589 $sql = "DELETE FROM $table WHERE ";
591 foreach ( $uniqueIndexes as $index ) {
598 if ( is_array( $index ) ) {
600 foreach ( $index as $col ) {
606 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
609 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
613 $this->query( $sql, $fname );
617 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
618 $this->makeList( $row, LIST_COMMA
) . ')';
619 $this->query( $sql, $fname );
623 # DELETE where the condition is a join
624 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
626 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
629 $delTable = $this->tableName( $delTable );
630 $joinTable = $this->tableName( $joinTable );
631 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
632 if ( $conds != '*' ) {
633 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
637 $this->query( $sql, $fname );
640 # Returns the size of a text field, or -1 for "unlimited"
641 function textFieldSize( $table, $field ) {
642 $table = $this->tableName( $table );
643 $sql = "SELECT t.typname as ftype,a.atttypmod as size
644 FROM pg_class c, pg_attribute a, pg_type t
645 WHERE relname='$table' AND a.attrelid=c.oid AND
646 a.atttypid=t.oid and a.attname='$field'";
647 $res =$this->query($sql);
648 $row=$this->fetchObject($res);
649 if ($row->ftype
=="varchar") {
654 $this->freeResult( $res );
658 function lowPriorityOption() {
662 function limitResult($sql, $limit,$offset) {
663 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
667 * Returns an SQL expression for a simple conditional.
668 * Uses CASE on Postgres
670 * @param string $cond SQL expression which will result in a boolean value
671 * @param string $trueVal SQL expression to return if true
672 * @param string $falseVal SQL expression to return if false
673 * @return string SQL fragment
675 function conditional( $cond, $trueVal, $falseVal ) {
676 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
679 function wasDeadlock() {
680 return $this->lastErrno() == '40P01';
683 function timestamp( $ts=0 ) {
684 return wfTimestamp(TS_POSTGRES
,$ts);
688 * Return aggregated value function call
690 function aggregateValue ($valuedata,$valuename='value') {
695 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
696 # Ignore errors during error handling to avoid infinite recursion
697 $ignore = $this->ignoreErrors( true );
698 ++
$this->mErrorCount
;
700 if ($ignore ||
$tempIgnore) {
701 wfDebug("SQL ERROR (ignored): $error\n");
702 $this->ignoreErrors( $ignore );
705 $message = "A database error has occurred\n" .
707 "Function: $fname\n" .
708 "Error: $errno $error\n";
709 throw new DBUnexpectedError($this, $message);
714 * @return string wikitext of a link to the server software's web site
716 function getSoftwareLink() {
717 return "[http://www.postgresql.org/ PostgreSQL]";
721 * @return string Version information from the database
723 function getServerVersion() {
724 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
726 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
727 die("Could not determine the numeric version from $version!");
729 $this->numeric_version
= $thisver[1];
735 * Query whether a given table exists (in the given schema, or the default mw one if not given)
737 function tableExists( $table, $schema = false ) {
738 global $wgDBmwschema;
740 $schema = $wgDBmwschema;
741 $etable = preg_replace("/'/", "''", $table);
742 $eschema = preg_replace("/'/", "''", $schema);
743 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
744 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
745 . "AND c.relkind IN ('r','v')";
746 $res = $this->query( $SQL );
747 $count = $res ?
pg_num_rows($res) : 0;
749 $this->freeResult( $res );
755 * Query whether a given schema exists. Returns the name of the owner
757 function schemaExists( $schema ) {
758 $eschema = preg_replace("/'/", "''", $schema);
759 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
760 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
761 $res = $this->query( $SQL );
762 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
764 $this->freeResult($res);
769 * Query whether a given column exists in the mediawiki schema
771 function fieldExists( $table, $field ) {
772 global $wgDBmwschema;
773 $etable = preg_replace("/'/", "''", $table);
774 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
775 $ecol = preg_replace("/'/", "''", $field);
776 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
777 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
778 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
779 $res = $this->query( $SQL );
780 $count = $res ?
pg_num_rows($res) : 0;
782 $this->freeResult( $res );
786 function fieldInfo( $table, $field ) {
787 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
788 $type = pg_field_type( $res, 0 );
792 function begin( $fname = 'DatabasePostgres::begin' ) {
793 $this->query( 'BEGIN', $fname );
794 $this->mTrxLevel
= 1;
796 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
799 function commit( $fname = 'DatabasePostgres::commit' ) {
800 $this->query( 'COMMIT', $fname );
801 $this->mTrxLevel
= 0;
804 /* Not even sure why this is used in the main codebase... */
805 function limitResultForUpdate($sql, $num) {
809 function setup_database() {
810 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
812 ## Make sure that we can write to the correct schema
813 ## If not, Postgres will happily and silently go to the next search_path item
814 $SQL = "CREATE TABLE $wgDBmwschema.mw_test_table(a int)";
815 error_reporting( 0 );
816 $res = $this->doQuery($SQL);
817 error_reporting( E_ALL
);
819 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"wgDBmwschema\"</li>\n";
823 dbsource( "../maintenance/postgres/tables.sql", $this);
825 ## Version-specific stuff
826 if ($this->numeric_version
== 8.1) {
827 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
828 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
831 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
832 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
835 ## Update version information
836 $mwv = $this->addQuotes($wgVersion);
837 $pgv = $this->addQuotes($this->getServerVersion());
838 $pgu = $this->addQuotes($this->mUser
);
839 $mws = $this->addQuotes($wgDBmwschema);
840 $tss = $this->addQuotes($wgDBts2schema);
841 $pgp = $this->addQuotes($wgDBport);
842 $dbn = $this->addQuotes($this->mDBname
);
843 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
845 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
846 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
848 "WHERE type = 'Creation'";
851 ## Avoid the non-standard "REPLACE INTO" syntax
852 $f = fopen( "../maintenance/interwiki.sql", 'r' );
854 dieout( "<li>Could not find the interwiki.sql file");
856 ## We simply assume it is already empty as we have just created it
857 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
858 while ( ! feof( $f ) ) {
859 $line = fgets($f,1024);
861 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
864 $this->query("$SQL $matches[1],$matches[2])");
866 print " (table interwiki successfully populated)...\n";
869 function encodeBlob($b) {
870 return array('bytea',pg_escape_bytea($b));
872 function decodeBlob($b) {
873 return pg_unescape_bytea( $b );
876 function strencode( $s ) { ## Should not be called by us
877 return pg_escape_string( $s );
880 function addQuotes( $s ) {
881 if ( is_null( $s ) ) {
883 } else if (is_array( $s )) { ## Assume it is bytea data
886 return "'" . pg_escape_string($s) . "'";
887 // Unreachable: return "E'" . pg_escape_string($s) . "'";
890 function quote_ident( $s ) {
891 return '"' . preg_replace( '/"/', '""', $s) . '"';
894 /* For now, does nothing */
895 function selectDB( $db ) {
900 * Returns an optional USE INDEX clause to go after the table, and a
901 * string to go at the end of the query
905 * @param array $options an associative array of options to be turned into
906 * an SQL query, valid keys are listed in the function.
909 function makeSelectOptions( $options ) {
910 $preLimitTail = $postLimitTail = '';
913 $noKeyOptions = array();
914 foreach ( $options as $key => $option ) {
915 if ( is_numeric( $key ) ) {
916 $noKeyOptions[$option] = true;
920 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
921 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
923 //if (isset($options['LIMIT'])) {
924 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
925 // isset($options['OFFSET']) ? $options['OFFSET']
929 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
930 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
931 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
933 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
934 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
939 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
942 public function setTimeout( $timeout ) {
947 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
952 } // end DatabasePostgres class