9e7d8c63b587b5905c50787b3c10eccfbec14572
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
13 private $name, $tablename, $type, $nullable, $max_length;
15 static function fromText($db, $table, $field) {
19 SELECT typname, attnotnull, attlen
20 FROM pg_class, pg_namespace, pg_attribute, pg_type
21 WHERE relnamespace=pg_namespace.oid
23 AND attrelid=pg_class.oid
24 AND atttypid=pg_type.oid
29 $res = $db->query(sprintf($q,
30 $db->addQuotes($wgDBmwschema),
31 $db->addQuotes($table),
32 $db->addQuotes($field)));
33 $row = $db->fetchObject($res);
36 $n = new PostgresField
;
37 $n->type
= $row->typname
;
38 $n->nullable
= ($row->attnotnull
== 'f');
40 $n->tablename
= $table;
41 $n->max_length
= $row->attlen
;
49 function tableName() {
50 return $this->tablename
;
58 return $this->nullable
;
61 function maxLength() {
62 return $this->max_length
;
66 class DatabasePostgres
extends Database
{
67 var $mInsertId = NULL;
68 var $mLastResult = NULL;
69 var $numeric_version = NULL;
71 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
72 $failFunction = false, $flags = 0 )
76 # Can't get a reference if it hasn't been set yet
77 if ( !isset( $wgOut ) ) {
80 $this->mOut
=& $wgOut;
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 searchableIPs() {
106 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
108 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
112 * Usually aborts on failure
113 * If the failFunction is set to a non-zero integer, returns success
115 function open( $server, $user, $password, $dbName ) {
116 # Test for Postgres support, to avoid suppressed fatal error
117 if ( !function_exists( 'pg_connect' ) ) {
118 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" );
123 if (!strlen($user)) { ## e.g. the class is being loaded
128 $this->mServer
= $server;
130 $this->mUser
= $user;
131 $this->mPassword
= $password;
132 $this->mDBname
= $dbName;
135 if ($server!=false && $server!="") {
136 $hstring="host=$server ";
138 if ($port!=false && $port!="") {
139 $hstring .= "port=$port ";
143 error_reporting( E_ALL
);
144 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
146 if ( $this->mConn
== false ) {
147 wfDebug( "DB connection error\n" );
148 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
149 wfDebug( $this->lastError()."\n" );
153 $this->mOpened
= true;
154 ## If this is the initial connection, setup the schema stuff and possibly create the user
155 if (defined('MEDIAWIKI_INSTALL')) {
156 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
157 $wgDBts2schema, $wgDBtimezone;
159 print "<li>Checking the version of Postgres...";
160 $version = $this->getServerVersion();
162 if ($this->numeric_version
< $PGMINVER) {
163 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
166 print "version $this->numeric_version is OK.</li>\n";
168 print "<li>Figuring out timezone the database is using...";
169 ## Figure out what the local timezone is for this database
171 if ($this->doQuery("SET datestyle TO ISO")) {
172 $res = $this->doQuery("SELECT substring(now() FROM E'-?\\\d\\\d\$')::int");
174 $wgDBtimezone = pg_fetch_result($res,0,0);
175 print "timezone is '$wgDBtimezone'</li>\n";
178 if ($wgDBtimezone === 99) {
179 print "<b>UNKNOWN</b>. Defaulting to '0'</li>\n";
182 $safeuser = $this->quote_ident($wgDBuser);
183 ## Are we connecting as a superuser for the first time?
184 if ($wgDBsuperuser) {
185 ## Are we really a superuser? Check out our rights
187 CASE WHEN usesuper IS TRUE THEN
188 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
189 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
191 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
192 $rows = $this->numRows($res = $this->doQuery($SQL));
194 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
197 $perms = pg_fetch_result($res, 0, 0);
199 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
200 $rows = $this->numRows($this->doQuery($SQL));
202 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
205 if ($perms != 1 and $perms != 3) {
206 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
207 print 'Please use a different Postgres user.</li>';
210 print "<li>Creating user <b>$wgDBuser</b>...";
211 $safepass = $this->addQuotes($wgDBpassword);
212 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
213 $this->doQuery($SQL);
216 ## User now exists, check out the database
217 if ($dbName != $wgDBname) {
218 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
219 $rows = $this->numRows($this->doQuery($SQL));
221 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
225 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
226 print 'Please use a different Postgres user.</li>';
229 print "<li>Creating database <b>$wgDBname</b>...";
230 $safename = $this->quote_ident($wgDBname);
231 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
232 $this->doQuery($SQL);
234 ## Hopefully tsearch2 and plpgsql are in template1...
237 ## Reconnect to check out tsearch2 rights for this user
238 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
239 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
240 if ( $this->mConn
== false ) {
241 print "<b>FAILED TO CONNECT!</b></li>";
248 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
249 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
250 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
251 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
252 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
256 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
257 foreach (array('cfg','cfgmap','dict','parser') as $table) {
258 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
259 $this->doQuery($SQL);
264 ## Setup the schema for this user if needed
265 $result = $this->schemaExists($wgDBmwschema);
266 $safeschema = $this->quote_ident($wgDBmwschema);
268 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
269 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
271 print "<b>FAILED</b>.</li>\n";
277 print "<li>Schema already exists, explicitly granting rights...\n";
278 $safeschema2 = $this->addQuotes($wgDBmwschema);
279 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
280 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
281 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
282 "AND p.relkind IN ('r','S','v')\n";
284 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
285 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
286 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
287 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
288 $res = $this->doQuery($SQL);
290 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
293 $this->doQuery("SET search_path = $safeschema");
294 $rows = $this->numRows($res);
297 $this->doQuery(pg_fetch_result($res, $rows, 0));
303 return true; ## Reconnect as regular user
307 if (!defined('POSTGRES_SEARCHPATH')) {
309 ## Do we have the basic tsearch2 table?
310 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
311 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
312 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
313 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
314 print " for instructions.</li>\n";
319 ## Does this user have the rights to the tsearch2 tables?
320 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
321 print "<li>Checking tsearch2 permissions...";
322 ## Let's check all four, just to be safe
323 error_reporting( 0 );
324 $ts2tables = array('cfg','cfgmap','dict','parser');
325 foreach ( $ts2tables AS $tname ) {
326 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
327 $res = $this->doQuery($SQL);
329 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
330 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
334 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
335 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
336 $res = $this->doQuery($SQL);
337 error_reporting( E_ALL
);
339 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
344 ## Will the current locale work? Can we force it to?
345 print "<li>Verifying tsearch2 locale with $ctype...";
346 $rows = $this->numRows($res);
349 print "<b>not found</b></li>\n";
350 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
354 $tsname = pg_fetch_result($res, 0, 0);
355 if ($tsname != 'default') {
356 print "<b>not set to default ($tsname)</b>";
357 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
362 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
363 $res = $this->doQuery($SQL);
365 print "<b>FAILED</b>. ";
366 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
372 ## Final test: try out a simple tsearch2 query
373 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
374 $res = $this->doQuery($SQL);
376 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
381 ## Do we have plpgsql installed?
382 print "<li>Checking for Pl/Pgsql ...";
383 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
384 $rows = $this->numRows($this->doQuery($SQL));
386 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
387 print "not installed. Attempting to install Pl/Pgsql ...";
388 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
389 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
390 $rows = $this->numRows($this->doQuery($SQL));
392 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
394 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
399 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
405 ## Does the schema already exist? Who owns it?
406 $result = $this->schemaExists($wgDBmwschema);
408 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
409 error_reporting( 0 );
410 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
411 error_reporting( E_ALL
);
413 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
414 "You can try making them the owner of the database, or try creating the schema with a ".
415 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
420 else if ($result != $user) {
421 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
424 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
427 ## Fix up the search paths if needed
428 print "<li>Setting the search path for user \"$user\" ...";
429 $path = $this->quote_ident($wgDBmwschema);
430 if ($wgDBts2schema !== $wgDBmwschema)
431 $path .= ", ". $this->quote_ident($wgDBts2schema);
432 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
434 $SQL = "ALTER USER $safeuser SET search_path = $path";
435 $result = pg_query($this->mConn
, $SQL);
437 print "<b>FAILED</b>.</li>\n";
441 ## Set for the rest of this session
442 $SQL = "SET search_path = $path";
443 $result = pg_query($this->mConn
, $SQL);
445 print "<li>Failed to set search_path</li>\n";
448 define( "POSTGRES_SEARCHPATH", $path );
451 global $wgCommandLineMode;
452 ## If called from the command-line (e.g. importDump), only show errors
453 if ($wgCommandLineMode) {
454 $this->doQuery("SET client_min_messages = 'ERROR'");
461 * Closes a database connection, if it is open
462 * Returns success, true if already closed
465 $this->mOpened
= false;
466 if ( $this->mConn
) {
467 return pg_close( $this->mConn
);
473 function doQuery( $sql ) {
474 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
477 function queryIgnore( $sql, $fname = '' ) {
478 return $this->query( $sql, $fname, true );
481 function freeResult( $res ) {
482 if ( !@pg_free_result
( $res ) ) {
483 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
487 function fetchObject( $res ) {
488 @$row = pg_fetch_object( $res );
489 # FIXME: HACK HACK HACK HACK debug
492 # hashar : not sure if the following test really trigger if the object
494 if( pg_last_error($this->mConn
) ) {
495 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
500 function fetchRow( $res ) {
501 @$row = pg_fetch_array( $res );
502 if( pg_last_error($this->mConn
) ) {
503 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
508 function numRows( $res ) {
509 @$n = pg_num_rows( $res );
510 if( pg_last_error($this->mConn
) ) {
511 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
515 function numFields( $res ) { return pg_num_fields( $res ); }
516 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
519 * This must be called after nextSequenceVal
521 function insertId() {
522 return $this->mInsertId
;
525 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
526 function lastError() {
527 if ( $this->mConn
) {
528 return pg_last_error();
531 return "No database connection";
534 function lastErrno() {
535 return pg_last_error() ?
1 : 0;
538 function affectedRows() {
539 return pg_affected_rows( $this->mLastResult
);
543 * Returns information about an index
544 * If errors are explicitly ignored, returns NULL on failure
546 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
547 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
548 $res = $this->query( $sql, $fname );
553 while ( $row = $this->fetchObject( $res ) ) {
554 if ( $row->indexname
== $index ) {
557 // BUG: !!!! This code needs to be synced up with database.php
564 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
565 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
566 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
567 $res = $this->query( $sql, $fname );
570 while ($row = $this->fetchObject( $res ))
576 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
577 # Postgres doesn't support options
578 # We have a go at faking one of them
579 # TODO: DELAYED, LOW_PRIORITY
581 if ( !is_array($options))
582 $options = array($options);
584 if ( in_array( 'IGNORE', $options ) )
585 $oldIgnore = $this->ignoreErrors( true );
587 # IGNORE is performed using single-row inserts, ignoring errors in each
588 # FIXME: need some way to distiguish between key collision and other types of error
589 $oldIgnore = $this->ignoreErrors( true );
590 if ( !is_array( reset( $a ) ) ) {
593 foreach ( $a as $row ) {
594 parent
::insert( $table, $row, $fname, array() );
596 $this->ignoreErrors( $oldIgnore );
599 if ( in_array( 'IGNORE', $options ) )
600 $this->ignoreErrors( $oldIgnore );
605 function tableName( $name ) {
606 # Replace reserved words with better ones
611 return 'pagecontent';
618 * Return the next in a sequence, save the value for retrieval via insertId()
620 function nextSequenceValue( $seqName ) {
621 $safeseq = preg_replace( "/'/", "''", $seqName );
622 $res = $this->query( "SELECT nextval('$safeseq')" );
623 $row = $this->fetchRow( $res );
624 $this->mInsertId
= $row[0];
625 $this->freeResult( $res );
626 return $this->mInsertId
;
630 * Postgres does not have a "USE INDEX" clause, so return an empty string
632 function useIndexClause( $index ) {
636 # REPLACE query wrapper
637 # Postgres simulates this with a DELETE followed by INSERT
638 # $row is the row to insert, an associative array
639 # $uniqueIndexes is an array of indexes. Each element may be either a
640 # field name or an array of field names
642 # It may be more efficient to leave off unique indexes which are unlikely to collide.
643 # However if you do this, you run the risk of encountering errors which wouldn't have
645 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
646 $table = $this->tableName( $table );
648 if (count($rows)==0) {
653 if ( !is_array( reset( $rows ) ) ) {
654 $rows = array( $rows );
657 foreach( $rows as $row ) {
658 # Delete rows which collide
659 if ( $uniqueIndexes ) {
660 $sql = "DELETE FROM $table WHERE ";
662 foreach ( $uniqueIndexes as $index ) {
669 if ( is_array( $index ) ) {
671 foreach ( $index as $col ) {
677 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
680 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
684 $this->query( $sql, $fname );
688 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
689 $this->makeList( $row, LIST_COMMA
) . ')';
690 $this->query( $sql, $fname );
694 # DELETE where the condition is a join
695 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
697 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
700 $delTable = $this->tableName( $delTable );
701 $joinTable = $this->tableName( $joinTable );
702 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
703 if ( $conds != '*' ) {
704 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
708 $this->query( $sql, $fname );
711 # Returns the size of a text field, or -1 for "unlimited"
712 function textFieldSize( $table, $field ) {
713 $table = $this->tableName( $table );
714 $sql = "SELECT t.typname as ftype,a.atttypmod as size
715 FROM pg_class c, pg_attribute a, pg_type t
716 WHERE relname='$table' AND a.attrelid=c.oid AND
717 a.atttypid=t.oid and a.attname='$field'";
718 $res =$this->query($sql);
719 $row=$this->fetchObject($res);
720 if ($row->ftype
=="varchar") {
725 $this->freeResult( $res );
729 function lowPriorityOption() {
733 function limitResult($sql, $limit,$offset=false) {
734 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
738 * Returns an SQL expression for a simple conditional.
739 * Uses CASE on Postgres
741 * @param string $cond SQL expression which will result in a boolean value
742 * @param string $trueVal SQL expression to return if true
743 * @param string $falseVal SQL expression to return if false
744 * @return string SQL fragment
746 function conditional( $cond, $trueVal, $falseVal ) {
747 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
750 function wasDeadlock() {
751 return $this->lastErrno() == '40P01';
754 function timestamp( $ts=0 ) {
755 return wfTimestamp(TS_POSTGRES
,$ts);
759 * Return aggregated value function call
761 function aggregateValue ($valuedata,$valuename='value') {
766 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
767 # Ignore errors during error handling to avoid infinite recursion
768 $ignore = $this->ignoreErrors( true );
769 ++
$this->mErrorCount
;
771 if ($ignore ||
$tempIgnore) {
772 wfDebug("SQL ERROR (ignored): $error\n");
773 $this->ignoreErrors( $ignore );
776 $message = "A database error has occurred\n" .
778 "Function: $fname\n" .
779 "Error: $errno $error\n";
780 throw new DBUnexpectedError($this, $message);
785 * @return string wikitext of a link to the server software's web site
787 function getSoftwareLink() {
788 return "[http://www.postgresql.org/ PostgreSQL]";
792 * @return string Version information from the database
794 function getServerVersion() {
795 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
797 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
798 die("Could not determine the numeric version from $version!");
800 $this->numeric_version
= $thisver[1];
806 * Query whether a given relation exists (in the given schema, or the
807 * default mw one if not given)
809 function relationExists( $table, $types, $schema = false ) {
810 global $wgDBmwschema;
811 if (!is_array($types))
812 $types = array($types);
814 $schema = $wgDBmwschema;
815 $etable = $this->addQuotes($table);
816 $eschema = $this->addQuotes($schema);
817 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
818 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
819 . "AND c.relkind IN ('" . implode("','", $types) . "')";
820 $res = $this->query( $SQL );
821 $count = $res ?
pg_num_rows($res) : 0;
823 $this->freeResult( $res );
828 * For backward compatibility, this function checks both tables and
831 function tableExists ($table, $schema = false) {
832 return $this->relationExists($table, array('r', 'v'), $schema);
835 function sequenceExists ($sequence, $schema = false) {
836 return $this->relationExists($sequence, 'S', $schema);
839 function triggerExists($table, $trigger) {
840 global $wgDBmwschema;
843 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
844 WHERE relnamespace=pg_namespace.oid AND relkind='r'
845 AND tgrelid=pg_class.oid
846 AND nspname=%s AND relname=%s AND tgname=%s
848 $res = $this->query(sprintf($q,
849 $this->addQuotes($wgDBmwschema),
850 $this->addQuotes($table),
851 $this->addQuotes($trigger)));
852 $row = $this->fetchRow($res);
854 $this->freeResult($res);
858 function ruleExists($table, $rule) {
859 global $wgDBmwschema;
860 $exists = $this->selectField("pg_rules", "rulename",
861 array( "rulename" => $rule,
862 "tablename" => $table,
863 "schemaname" => $wgDBmwschema));
864 return $exists === $rule;
868 * Query whether a given schema exists. Returns the name of the owner
870 function schemaExists( $schema ) {
871 $eschema = preg_replace("/'/", "''", $schema);
872 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
873 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
874 $res = $this->query( $SQL );
875 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
877 $this->freeResult($res);
882 * Query whether a given column exists in the mediawiki schema
884 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
885 global $wgDBmwschema;
886 $etable = preg_replace("/'/", "''", $table);
887 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
888 $ecol = preg_replace("/'/", "''", $field);
889 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
890 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
891 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
892 $res = $this->query( $SQL, $fname );
893 $count = $res ?
pg_num_rows($res) : 0;
895 $this->freeResult( $res );
899 function fieldInfo( $table, $field ) {
900 return PostgresField
::fromText($this, $table, $field);
903 function begin( $fname = 'DatabasePostgres::begin' ) {
904 $this->query( 'BEGIN', $fname );
905 $this->mTrxLevel
= 1;
907 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
910 function commit( $fname = 'DatabasePostgres::commit' ) {
911 $this->query( 'COMMIT', $fname );
912 $this->mTrxLevel
= 0;
915 /* Not even sure why this is used in the main codebase... */
916 function limitResultForUpdate($sql, $num) {
920 function setup_database() {
921 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
923 ## Make sure that we can write to the correct schema
924 ## If not, Postgres will happily and silently go to the next search_path item
925 $ctest = "mw_test_table";
926 if ($this->tableExists($ctest, $wgDBmwschema)) {
927 $this->doQuery("DROP TABLE $wgDBmwschema.$ctest");
929 $SQL = "CREATE TABLE $wgDBmwschema.$ctest(a int)";
930 error_reporting( 0 );
931 $res = $this->doQuery($SQL);
932 error_reporting( E_ALL
);
934 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
937 $this->doQuery("DROP TABLE $wgDBmwschema.mw_test_table");
939 dbsource( "../maintenance/postgres/tables.sql", $this);
941 ## Version-specific stuff
942 if ($this->numeric_version
== 8.1) {
943 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
944 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
947 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
948 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
951 ## Update version information
952 $mwv = $this->addQuotes($wgVersion);
953 $pgv = $this->addQuotes($this->getServerVersion());
954 $pgu = $this->addQuotes($this->mUser
);
955 $mws = $this->addQuotes($wgDBmwschema);
956 $tss = $this->addQuotes($wgDBts2schema);
957 $pgp = $this->addQuotes($wgDBport);
958 $dbn = $this->addQuotes($this->mDBname
);
959 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
961 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
962 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
964 "WHERE type = 'Creation'";
967 ## Avoid the non-standard "REPLACE INTO" syntax
968 $f = fopen( "../maintenance/interwiki.sql", 'r' );
970 dieout( "<li>Could not find the interwiki.sql file");
972 ## We simply assume it is already empty as we have just created it
973 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
974 while ( ! feof( $f ) ) {
975 $line = fgets($f,1024);
977 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
980 $this->query("$SQL $matches[1],$matches[2])");
982 print " (table interwiki successfully populated)...\n";
984 $this->doQuery("COMMIT");
987 function encodeBlob($b) {
988 return array('bytea',pg_escape_bytea($b));
990 function decodeBlob($b) {
991 return pg_unescape_bytea( $b );
994 function strencode( $s ) { ## Should not be called by us
995 return pg_escape_string( $s );
998 function addQuotes( $s ) {
999 if ( is_null( $s ) ) {
1001 } else if (is_array( $s )) { ## Assume it is bytea data
1004 return "'" . pg_escape_string($s) . "'";
1005 // Unreachable: return "E'" . pg_escape_string($s) . "'";
1008 function quote_ident( $s ) {
1009 return '"' . preg_replace( '/"/', '""', $s) . '"';
1012 /* For now, does nothing */
1013 function selectDB( $db ) {
1018 * Returns an optional USE INDEX clause to go after the table, and a
1019 * string to go at the end of the query
1023 * @param array $options an associative array of options to be turned into
1024 * an SQL query, valid keys are listed in the function.
1027 function makeSelectOptions( $options ) {
1028 $preLimitTail = $postLimitTail = '';
1031 $noKeyOptions = array();
1032 foreach ( $options as $key => $option ) {
1033 if ( is_numeric( $key ) ) {
1034 $noKeyOptions[$option] = true;
1038 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1039 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1041 //if (isset($options['LIMIT'])) {
1042 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1043 // isset($options['OFFSET']) ? $options['OFFSET']
1047 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1048 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1049 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1051 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1052 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1057 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1060 public function setTimeout( $timeout ) {
1065 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1070 } // end DatabasePostgres class