70f60ad65d280a237c50234fcd8cc5116af9aac5
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 class DatabasePostgres
extends Database
{
14 var $mInsertId = NULL;
15 var $mLastResult = NULL;
16 var $numeric_version = NULL;
18 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
19 $failFunction = false, $flags = 0 )
23 # Can't get a reference if it hasn't been set yet
24 if ( !isset( $wgOut ) ) {
27 $this->mOut
=& $wgOut;
28 $this->mFailFunction
= $failFunction;
29 $this->mCascadingDeletes
= true;
30 $this->mCleanupTriggers
= true;
31 $this->mStrictIPs
= true;
32 $this->mFlags
= $flags;
33 $this->open( $server, $user, $password, $dbName);
37 function realTimestamps() {
41 function implicitGroupby() {
45 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
46 $failFunction = false, $flags = 0)
48 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
52 * Usually aborts on failure
53 * If the failFunction is set to a non-zero integer, returns success
55 function open( $server, $user, $password, $dbName ) {
56 # Test for Postgres support, to avoid suppressed fatal error
57 if ( !function_exists( 'pg_connect' ) ) {
58 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" );
65 $this->mServer
= $server;
68 $this->mPassword
= $password;
69 $this->mDBname
= $dbName;
72 if ($server!=false && $server!="") {
73 $hstring="host=$server ";
75 if ($port!=false && $port!="") {
76 $hstring .= "port=$port ";
79 if (!strlen($user)) { ## e.g. the class is being loaded
83 error_reporting( E_ALL
);
84 @$this->mConn
= pg_connect("$hstring dbname=$dbName user=$user password=$password");
86 if ( $this->mConn
== false ) {
87 wfDebug( "DB connection error\n" );
88 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
89 wfDebug( $this->lastError()."\n" );
93 $this->mOpened
= true;
94 ## If this is the initial connection, setup the schema stuff and possibly create the user
95 if (defined('MEDIAWIKI_INSTALL')) {
96 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
99 print "<li>Checking the version of Postgres...";
100 $version = $this->getServerVersion();
102 if ($this->numeric_version
< $PGMINVER) {
103 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
106 print "version $this->numeric_version is OK.</li>\n";
108 $safeuser = $this->quote_ident($wgDBuser);
109 ## Are we connecting as a superuser for the first time?
110 if ($wgDBsuperuser) {
111 ## Are we really a superuser? Check out our rights
113 CASE WHEN usesuper IS TRUE THEN
114 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
115 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
117 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
118 $rows = $this->numRows($res = $this->doQuery($SQL));
120 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
123 $perms = pg_fetch_result($res, 0, 0);
125 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
126 $rows = $this->numRows($this->doQuery($SQL));
128 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
131 if ($perms != 1 and $perms != 3) {
132 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
133 print 'Please use a different Postgres user.</li>';
136 print "<li>Creating user <b>$wgDBuser</b>...";
137 $safepass = $this->addQuotes($wgDBpassword);
138 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
139 $this->doQuery($SQL);
142 ## User now exists, check out the database
143 if ($dbName != $wgDBname) {
144 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
145 $rows = $this->numRows($this->doQuery($SQL));
147 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
151 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
152 print 'Please use a different Postgres user.</li>';
155 print "<li>Creating database <b>$wgDBname</b>...";
156 $safename = $this->quote_ident($wgDBname);
157 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
158 $this->doQuery($SQL);
160 ## Hopefully tsearch2 and plpgsql are in template1...
163 ## Reconnect to check out tsearch2 rights for this user
164 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
165 @$this->mConn
= pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
166 if ( $this->mConn
== false ) {
167 print "<b>FAILED TO CONNECT!</b></li>";
174 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
175 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
176 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
177 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
178 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
182 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
183 foreach (array('cfg','cfgmap','dict','parser') as $table) {
184 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
185 $this->doQuery($SQL);
190 ## Setup the schema for this user if needed
191 $result = $this->schemaExists($wgDBmwschema);
192 $safeschema = $this->quote_ident($wgDBmwschema);
194 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
195 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
197 print "<b>FAILED</b>.</li>\n";
203 print "<li>Schema already exists, explicitly granting rights...\n";
204 $safeschema2 = $this->addQuotes($wgDBmwschema);
205 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
206 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
207 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
208 "AND p.relkind IN ('r','S','v')\n";
210 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
211 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
212 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
213 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
214 $res = $this->doQuery($SQL);
216 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
219 $this->doQuery("SET search_path = $safeschema");
220 $rows = $this->numRows($res);
223 $this->doQuery(pg_fetch_result($res, $rows, 0));
229 return true; ## Reconnect as regular user
232 if (!defined('POSTGRES_SEARCHPATH')) {
234 ## Do we have the basic tsearch2 table?
235 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
236 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
237 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
238 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
239 print " for instructions.</li>\n";
244 ## Does this user have the rights to the tsearch2 tables?
245 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
246 print "<li>Checking tsearch2 permissions...";
247 ## Let's check all four, just to be safe
248 error_reporting( 0 );
249 $ts2tables = array('cfg','cfgmap','dict','parser');
250 foreach ( $ts2tables AS $tname ) {
251 $SQL = "SELECT count(*) FROM $wgDBts2schema.pg_ts_$tname";
252 $res = $this->doQuery($SQL);
254 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
255 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
259 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
260 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
261 $res = $this->doQuery($SQL);
262 error_reporting( E_ALL
);
264 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
269 ## Will the current locale work? Can we force it to?
270 print "<li>Verifying tsearch2 locale with $ctype...";
271 $rows = $this->numRows($res);
274 print "<b>not found</b></li>\n";
275 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
279 $tsname = pg_fetch_result($res, 0, 0);
280 if ($tsname != 'default') {
281 print "<b>not set to default ($tsname)</b>";
282 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
287 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
288 $res = $this->doQuery($SQL);
290 print "<b>FAILED</b>. ";
291 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"ctype\"</li>\n";
297 ## Final test: try out a simple tsearch2 query
298 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
299 $res = $this->doQuery($SQL);
301 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
306 ## Do we have plpgsql installed?
307 print "<li>Checking for Pl/Pgsql ...";
308 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
309 $rows = $this->numRows($this->doQuery($SQL));
311 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
312 print "not installed. Attempting to install Pl/Pgsql ...";
313 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
314 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
315 $rows = $this->numRows($this->doQuery($SQL));
317 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
319 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
324 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
330 ## Does the schema already exist? Who owns it?
331 $result = $this->schemaExists($wgDBmwschema);
333 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
334 error_reporting( 0 );
335 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
336 error_reporting( E_ALL
);
338 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
339 "You can try making them the owner of the database, or try creating the schema with a ".
340 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
345 else if ($result != $user) {
346 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
349 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
352 ## Fix up the search paths if needed
353 print "<li>Setting the search path for user \"$user\" ...";
354 $path = $this->quote_ident($wgDBmwschema);
355 if ($wgDBts2schema !== $wgDBmwschema)
356 $path .= ", ". $this->quote_ident($wgDBts2schema);
357 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
359 $SQL = "ALTER USER $safeuser SET search_path = $path";
360 $result = pg_query($this->mConn
, $SQL);
362 print "<b>FAILED</b>.</li>\n";
366 ## Set for the rest of this session
367 $SQL = "SET search_path = $path";
368 $result = pg_query($this->mConn
, $SQL);
370 print "<li>Failed to set search_path</li>\n";
373 define( "POSTGRES_SEARCHPATH", $path );
376 global $wgCommandLineMode;
377 ## If called from the command-line (e.g. importDump), only show errors
378 if ($wgCommandLineMode) {
379 $this->doQuery("SET client_min_messages = 'ERROR'");
386 * Closes a database connection, if it is open
387 * Returns success, true if already closed
390 $this->mOpened
= false;
391 if ( $this->mConn
) {
392 return pg_close( $this->mConn
);
398 function doQuery( $sql ) {
399 return $this->mLastResult
=pg_query( $this->mConn
, $sql);
402 function queryIgnore( $sql, $fname = '' ) {
403 return $this->query( $sql, $fname, true );
406 function freeResult( $res ) {
407 if ( !@pg_free_result
( $res ) ) {
408 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
412 function fetchObject( $res ) {
413 @$row = pg_fetch_object( $res );
414 # FIXME: HACK HACK HACK HACK debug
417 # hashar : not sure if the following test really trigger if the object
419 if( pg_last_error($this->mConn
) ) {
420 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
425 function fetchRow( $res ) {
426 @$row = pg_fetch_array( $res );
427 if( pg_last_error($this->mConn
) ) {
428 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
433 function numRows( $res ) {
434 @$n = pg_num_rows( $res );
435 if( pg_last_error($this->mConn
) ) {
436 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
440 function numFields( $res ) { return pg_num_fields( $res ); }
441 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
444 * This must be called after nextSequenceVal
446 function insertId() {
447 return $this->mInsertId
;
450 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
451 function lastError() {
452 if ( $this->mConn
) {
453 return pg_last_error();
456 return "No database connection";
459 function lastErrno() {
460 return pg_last_error() ?
1 : 0;
463 function affectedRows() {
464 return pg_affected_rows( $this->mLastResult
);
468 * Returns information about an index
469 * If errors are explicitly ignored, returns NULL on failure
471 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
472 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
473 $res = $this->query( $sql, $fname );
478 while ( $row = $this->fetchObject( $res ) ) {
479 if ( $row->indexname
== $index ) {
482 // BUG: !!!! This code needs to be synced up with database.php
489 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
490 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
491 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
492 $res = $this->query( $sql, $fname );
495 while ($row = $this->fetchObject( $res ))
501 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
502 # Postgres doesn't support options
503 # We have a go at faking one of them
504 # TODO: DELAYED, LOW_PRIORITY
506 if ( !is_array($options))
507 $options = array($options);
509 if ( in_array( 'IGNORE', $options ) )
510 $oldIgnore = $this->ignoreErrors( true );
512 # IGNORE is performed using single-row inserts, ignoring errors in each
513 # FIXME: need some way to distiguish between key collision and other types of error
514 $oldIgnore = $this->ignoreErrors( true );
515 if ( !is_array( reset( $a ) ) ) {
518 foreach ( $a as $row ) {
519 parent
::insert( $table, $row, $fname, array() );
521 $this->ignoreErrors( $oldIgnore );
524 if ( in_array( 'IGNORE', $options ) )
525 $this->ignoreErrors( $oldIgnore );
530 function tableName( $name ) {
531 # Replace reserved words with better ones
536 return 'pagecontent';
543 * Return the next in a sequence, save the value for retrieval via insertId()
545 function nextSequenceValue( $seqName ) {
546 $safeseq = preg_replace( "/'/", "''", $seqName );
547 $res = $this->query( "SELECT nextval('$safeseq')" );
548 $row = $this->fetchRow( $res );
549 $this->mInsertId
= $row[0];
550 $this->freeResult( $res );
551 return $this->mInsertId
;
555 * Postgres does not have a "USE INDEX" clause, so return an empty string
557 function useIndexClause( $index ) {
561 # REPLACE query wrapper
562 # Postgres simulates this with a DELETE followed by INSERT
563 # $row is the row to insert, an associative array
564 # $uniqueIndexes is an array of indexes. Each element may be either a
565 # field name or an array of field names
567 # It may be more efficient to leave off unique indexes which are unlikely to collide.
568 # However if you do this, you run the risk of encountering errors which wouldn't have
570 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
571 $table = $this->tableName( $table );
573 if (count($rows)==0) {
578 if ( !is_array( reset( $rows ) ) ) {
579 $rows = array( $rows );
582 foreach( $rows as $row ) {
583 # Delete rows which collide
584 if ( $uniqueIndexes ) {
585 $sql = "DELETE FROM $table WHERE ";
587 foreach ( $uniqueIndexes as $index ) {
594 if ( is_array( $index ) ) {
596 foreach ( $index as $col ) {
602 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
605 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
609 $this->query( $sql, $fname );
613 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
614 $this->makeList( $row, LIST_COMMA
) . ')';
615 $this->query( $sql, $fname );
619 # DELETE where the condition is a join
620 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
622 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
625 $delTable = $this->tableName( $delTable );
626 $joinTable = $this->tableName( $joinTable );
627 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
628 if ( $conds != '*' ) {
629 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
633 $this->query( $sql, $fname );
636 # Returns the size of a text field, or -1 for "unlimited"
637 function textFieldSize( $table, $field ) {
638 $table = $this->tableName( $table );
639 $sql = "SELECT t.typname as ftype,a.atttypmod as size
640 FROM pg_class c, pg_attribute a, pg_type t
641 WHERE relname='$table' AND a.attrelid=c.oid AND
642 a.atttypid=t.oid and a.attname='$field'";
643 $res =$this->query($sql);
644 $row=$this->fetchObject($res);
645 if ($row->ftype
=="varchar") {
650 $this->freeResult( $res );
654 function lowPriorityOption() {
658 function limitResult($sql, $limit,$offset) {
659 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
663 * Returns an SQL expression for a simple conditional.
664 * Uses CASE on Postgres
666 * @param string $cond SQL expression which will result in a boolean value
667 * @param string $trueVal SQL expression to return if true
668 * @param string $falseVal SQL expression to return if false
669 * @return string SQL fragment
671 function conditional( $cond, $trueVal, $falseVal ) {
672 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
675 function wasDeadlock() {
676 return $this->lastErrno() == '40P01';
679 function timestamp( $ts=0 ) {
680 return wfTimestamp(TS_POSTGRES
,$ts);
684 * Return aggregated value function call
686 function aggregateValue ($valuedata,$valuename='value') {
691 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
692 # Ignore errors during error handling to avoid infinite recursion
693 $ignore = $this->ignoreErrors( true );
694 ++
$this->mErrorCount
;
696 if ($ignore ||
$tempIgnore) {
697 wfDebug("SQL ERROR (ignored): $error\n");
698 $this->ignoreErrors( $ignore );
701 $message = "A database error has occurred\n" .
703 "Function: $fname\n" .
704 "Error: $errno $error\n";
705 throw new DBUnexpectedError($this, $message);
710 * @return string wikitext of a link to the server software's web site
712 function getSoftwareLink() {
713 return "[http://www.postgresql.org/ PostgreSQL]";
717 * @return string Version information from the database
719 function getServerVersion() {
720 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
722 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
723 die("Could not determine the numeric version from $version!");
725 $this->numeric_version
= $thisver[1];
731 * Query whether a given table exists (in the given schema, or the default mw one if not given)
733 function tableExists( $table, $schema = false ) {
734 global $wgDBmwschema;
736 $schema = $wgDBmwschema;
737 $etable = preg_replace("/'/", "''", $table);
738 $eschema = preg_replace("/'/", "''", $schema);
739 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
740 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
741 . "AND c.relkind IN ('r','v')";
742 $res = $this->query( $SQL );
743 $count = $res ?
pg_num_rows($res) : 0;
745 $this->freeResult( $res );
751 * Query whether a given schema exists. Returns the name of the owner
753 function schemaExists( $schema ) {
754 $eschema = preg_replace("/'/", "''", $schema);
755 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
756 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
757 $res = $this->query( $SQL );
758 $owner = $res ?
pg_num_rows($res) ?
pg_fetch_result($res, 0, 0) : false : false;
760 $this->freeResult($res);
765 * Query whether a given column exists in the mediawiki schema
767 function fieldExists( $table, $field ) {
768 global $wgDBmwschema;
769 $etable = preg_replace("/'/", "''", $table);
770 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
771 $ecol = preg_replace("/'/", "''", $field);
772 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
773 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
774 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
775 $res = $this->query( $SQL );
776 $count = $res ?
pg_num_rows($res) : 0;
778 $this->freeResult( $res );
782 function fieldInfo( $table, $field ) {
783 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
784 $type = pg_field_type( $res, 0 );
788 function begin( $fname = 'DatabasePostgrs::begin' ) {
789 $this->query( 'BEGIN', $fname );
790 $this->mTrxLevel
= 1;
792 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
795 function commit( $fname = 'DatabasePostgres::commit' ) {
796 $this->query( 'COMMIT', $fname );
797 $this->mTrxLevel
= 0;
800 /* Not even sure why this is used in the main codebase... */
801 function limitResultForUpdate($sql, $num) {
805 function setup_database() {
806 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
808 ## Make sure that we can write to the correct schema
809 ## If not, Postgres will happily and silently go to the next search_path item
810 $SQL = "CREATE TABLE $wgDBmwschema.mw_test_table(a int)";
811 error_reporting( 0 );
812 $res = $this->doQuery($SQL);
813 error_reporting( E_ALL
);
815 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"wgDBmwschema\"</li>\n";
819 dbsource( "../maintenance/postgres/tables.sql", $this);
821 ## Version-specific stuff
822 if ($this->numeric_version
== 8.1) {
823 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
824 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
827 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
828 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
831 ## Update version information
832 $mwv = $this->addQuotes($wgVersion);
833 $pgv = $this->addQuotes($this->getServerVersion());
834 $pgu = $this->addQuotes($this->mUser
);
835 $mws = $this->addQuotes($wgDBmwschema);
836 $tss = $this->addQuotes($wgDBts2schema);
837 $pgp = $this->addQuotes($wgDBport);
838 $dbn = $this->addQuotes($this->mDBname
);
839 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
841 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
842 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
844 "WHERE type = 'Creation'";
847 ## Avoid the non-standard "REPLACE INTO" syntax
848 $f = fopen( "../maintenance/interwiki.sql", 'r' );
850 dieout( "<li>Could not find the interwiki.sql file");
852 ## We simply assume it is already empty as we have just created it
853 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
854 while ( ! feof( $f ) ) {
855 $line = fgets($f,1024);
857 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
860 $this->query("$SQL $matches[1],$matches[2])");
862 print " (table interwiki successfully populated)...\n";
865 function encodeBlob($b) {
866 return array('bytea',pg_escape_bytea($b));
868 function decodeBlob($b) {
869 return pg_unescape_bytea( $b );
872 function strencode( $s ) { ## Should not be called by us
873 return pg_escape_string( $s );
876 function addQuotes( $s ) {
877 if ( is_null( $s ) ) {
879 } else if (is_array( $s )) { ## Assume it is bytea data
882 return "'" . pg_escape_string($s) . "'";
883 // Unreachable: return "E'" . pg_escape_string($s) . "'";
886 function quote_ident( $s ) {
887 return '"' . preg_replace( '/"/', '""', $s) . '"';
890 /* For now, does nothing */
891 function selectDB( $db ) {
896 * Returns an optional USE INDEX clause to go after the table, and a
897 * string to go at the end of the query
901 * @param array $options an associative array of options to be turned into
902 * an SQL query, valid keys are listed in the function.
905 function makeSelectOptions( $options ) {
909 $noKeyOptions = array();
910 foreach ( $options as $key => $option ) {
911 if ( is_numeric( $key ) ) {
912 $noKeyOptions[$option] = true;
916 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
917 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
919 if (isset($options['LIMIT'])) {
920 $tailOpts .= $this->limitResult('', $options['LIMIT'],
921 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
924 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
925 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
926 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
928 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
929 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
934 return array( $startOpts, $useIndex, $tailOpts );
938 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
943 } // end DatabasePostgres class