5 * This is the Postgres database abstraction layer.
9 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
11 static function fromText($db, $table, $field) {
16 attnotnull, attlen, COALESCE(conname, '') AS conname,
17 COALESCE(condeferred, 'f') AS deferred,
18 COALESCE(condeferrable, 'f') AS deferrable,
19 CASE WHEN typname = 'int2' THEN 'smallint'
20 WHEN typname = 'int4' THEN 'integer'
21 WHEN typname = 'int8' THEN 'bigint'
22 WHEN typname = 'bpchar' THEN 'char'
23 ELSE typname END AS typname
25 JOIN pg_namespace n ON (n.oid = c.relnamespace)
26 JOIN pg_attribute a ON (a.attrelid = c.oid)
27 JOIN pg_type t ON (t.oid = a.atttypid)
28 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
34 $res = $db->query(sprintf($q,
35 $db->addQuotes($wgDBmwschema),
36 $db->addQuotes($table),
37 $db->addQuotes($field)));
38 $row = $db->fetchObject($res);
41 $n = new PostgresField
;
42 $n->type
= $row->typname
;
43 $n->nullable
= ($row->attnotnull
== 'f');
45 $n->tablename
= $table;
46 $n->max_length
= $row->attlen
;
47 $n->deferrable
= ($row->deferrable
== 't');
48 $n->deferred
= ($row->deferred
== 't');
49 $n->conname
= $row->conname
;
57 function tableName() {
58 return $this->tablename
;
66 return $this->nullable
;
69 function maxLength() {
70 return $this->max_length
;
73 function is_deferrable() {
74 return $this->deferrable
;
77 function is_deferred() {
78 return $this->deferred
;
82 return $this->conname
;
90 class DatabasePostgres
extends DatabaseBase
{
91 var $mInsertId = null;
92 var $mLastResult = null;
93 var $numeric_version = null;
94 var $mAffectedRows = null;
96 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
97 $failFunction = false, $flags = 0 )
100 $this->mFailFunction
= $failFunction;
101 $this->mFlags
= $flags;
102 $this->open( $server, $user, $password, $dbName);
110 function cascadingDeletes() {
113 function cleanupTriggers() {
116 function strictIPs() {
119 function realTimestamps() {
122 function implicitGroupby() {
125 function implicitOrderby() {
128 function searchableIPs() {
131 function functionalIndexes() {
135 function hasConstraint( $name ) {
136 global $wgDBmwschema;
137 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" . pg_escape_string( $name ) . "' AND n.nspname = '" . pg_escape_string($wgDBmwschema) ."'";
138 return $this->numRows($res = $this->doQuery($SQL));
141 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
143 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
147 * Usually aborts on failure
148 * If the failFunction is set to a non-zero integer, returns success
150 function open( $server, $user, $password, $dbName ) {
151 # Test for Postgres support, to avoid suppressed fatal error
152 if ( !function_exists( 'pg_connect' ) ) {
153 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" );
158 if (!strlen($user)) { ## e.g. the class is being loaded
162 $this->mServer
= $server;
163 $this->mPort
= $port = $wgDBport;
164 $this->mUser
= $user;
165 $this->mPassword
= $password;
166 $this->mDBname
= $dbName;
168 $connectVars = array(
171 'password' => $password );
172 if ($server!=false && $server!="") {
173 $connectVars['host'] = $server;
175 if ($port!=false && $port!="") {
176 $connectVars['port'] = $port;
178 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
180 $this->installErrorHandler();
181 $this->mConn
= pg_connect( $connectString );
182 $phpError = $this->restoreErrorHandler();
184 if ( !$this->mConn
) {
185 wfDebug( "DB connection error\n" );
186 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
187 wfDebug( $this->lastError()."\n" );
188 if ( !$this->mFailFunction
) {
189 throw new DBConnectionError( $this, $phpError );
195 $this->mOpened
= true;
197 global $wgCommandLineMode;
198 ## If called from the command-line (e.g. importDump), only show errors
199 if ($wgCommandLineMode) {
200 $this->doQuery( "SET client_min_messages = 'ERROR'" );
203 $this->doQuery( "SET client_encoding='UTF8'" );
205 global $wgDBmwschema, $wgDBts2schema;
206 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
207 && $wgDBmwschema !== 'mediawiki'
208 && preg_match( '/^\w+$/', $wgDBmwschema )
209 && preg_match( '/^\w+$/', $wgDBts2schema )
211 $safeschema = $this->quote_ident($wgDBmwschema);
212 $safeschema2 = $this->quote_ident($wgDBts2schema);
213 $this->doQuery( "SET search_path = $safeschema, $wgDBts2schema, public" );
219 function makeConnectionString( $vars ) {
221 foreach ( $vars as $name => $value ) {
222 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
228 function initial_setup($password, $dbName) {
229 // If this is the initial connection, setup the schema stuff and possibly create the user
230 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
232 print "<li>Checking the version of Postgres...";
233 $version = $this->getServerVersion();
235 if ($version < $PGMINVER) {
236 print "<b>FAILED</b>. Required version is $PGMINVER. You have " . htmlspecialchars( $version ) . "</li>\n";
239 print "version " . htmlspecialchars( $this->numeric_version
) . " is OK.</li>\n";
241 $safeuser = $this->quote_ident($wgDBuser);
242 // Are we connecting as a superuser for the first time?
243 if ($wgDBsuperuser) {
244 // Are we really a superuser? Check out our rights
246 CASE WHEN usesuper IS TRUE THEN
247 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
248 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
250 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
251 $rows = $this->numRows($res = $this->doQuery($SQL));
253 print "<li>ERROR: Could not read permissions for user \"" . htmlspecialchars( $wgDBsuperuser ) . "\"</li>\n";
256 $perms = pg_fetch_result($res, 0, 0);
258 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
259 $rows = $this->numRows($this->doQuery($SQL));
261 print "<li>User \"" . htmlspecialchars( $wgDBuser ) . "\" already exists, skipping account creation.</li>";
264 if ($perms != 1 and $perms != 3) {
265 print "<li>ERROR: the user \"" . htmlspecialchars( $wgDBsuperuser ) . "\" cannot create other users. ";
266 print 'Please use a different Postgres user.</li>';
269 print "<li>Creating user <b>" . htmlspecialchars( $wgDBuser ) . "</b>...";
270 $safepass = $this->addQuotes($wgDBpassword);
271 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
272 $this->doQuery($SQL);
275 // User now exists, check out the database
276 if ($dbName != $wgDBname) {
277 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
278 $rows = $this->numRows($this->doQuery($SQL));
280 print "<li>Database \"" . htmlspecialchars( $wgDBname ) . "\" already exists, skipping database creation.</li>";
284 print "<li>ERROR: the user \"" . htmlspecialchars( $wgDBsuperuser ) . "\" cannot create databases. ";
285 print 'Please use a different Postgres user.</li>';
288 print "<li>Creating database <b>" . htmlspecialchars( $wgDBname ) . "</b>...";
289 $safename = $this->quote_ident($wgDBname);
290 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
291 $this->doQuery($SQL);
293 // Hopefully tsearch2 and plpgsql are in template1...
296 // Reconnect to check out tsearch2 rights for this user
297 print "<li>Connecting to \"" . htmlspecialchars( $wgDBname ) . "\" as superuser \"" .
298 htmlspecialchars( $wgDBsuperuser ) . "\" to check rights...";
300 $connectVars = array();
301 if ($this->mServer
!=false && $this->mServer
!="") {
302 $connectVars['host'] = $this->mServer
;
304 if ($this->mPort
!=false && $this->mPort
!="") {
305 $connectVars['port'] = $this->mPort
;
307 $connectVars['dbname'] = $wgDBname;
308 $connectVars['user'] = $wgDBsuperuser;
309 $connectVars['password'] = $password;
311 @$this->mConn
= pg_connect( $this->makeConnectionString( $connectVars ) );
312 if ( $this->mConn
) {
313 print "<b>FAILED TO CONNECT!</b></li>";
319 if ($this->numeric_version
< 8.3) {
321 print "<li>Checking that tsearch2 is installed in the database \"" .
322 htmlspecialchars( $wgDBname ) . "\"...";
323 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
324 print "<b>FAILED</b>. tsearch2 must be installed in the database \"" .
325 htmlspecialchars( $wgDBname ) . "\".";
326 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
327 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
331 print "<li>Ensuring that user \"" . htmlspecialchars( $wgDBuser ) .
332 "\" has select rights on the tsearch2 tables...";
333 foreach (array('cfg','cfgmap','dict','parser') as $table) {
334 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
335 $this->doQuery($SQL);
340 // Setup the schema for this user if needed
341 $result = $this->schemaExists($wgDBmwschema);
342 $safeschema = $this->quote_ident($wgDBmwschema);
344 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
345 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
347 print "<b>FAILED</b>.</li>\n";
353 print "<li>Schema already exists, explicitly granting rights...\n";
354 $safeschema2 = $this->addQuotes($wgDBmwschema);
355 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
356 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
357 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
358 "AND p.relkind IN ('r','S','v')\n";
360 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
361 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
362 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
363 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
364 $res = $this->doQuery($SQL);
366 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
369 $this->doQuery("SET search_path = $safeschema");
370 $rows = $this->numRows($res);
373 $this->doQuery(pg_fetch_result($res, $rows, 0));
378 // Install plpgsql if needed
379 $this->setup_plpgsql();
382 return true; // Reconnect as regular user
386 if (!defined('POSTGRES_SEARCHPATH')) {
388 if ($this->numeric_version
< 8.3) {
389 // Do we have the basic tsearch2 table?
390 print "<li>Checking for tsearch2 in the schema \"" . htmlspecialchars( $wgDBts2schema ) . "\"...";
391 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
392 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
393 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
394 print " for instructions.</li>\n";
399 // Does this user have the rights to the tsearch2 tables?
400 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
401 print "<li>Checking tsearch2 permissions...";
402 // Let's check all four, just to be safe
403 error_reporting( 0 );
404 $ts2tables = array('cfg','cfgmap','dict','parser');
405 $safetsschema = $this->quote_ident($wgDBts2schema);
406 foreach ( $ts2tables AS $tname ) {
407 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
408 $res = $this->doQuery($SQL);
410 print "<b>FAILED</b> to access " . htmlspecialchars( "pg_ts_$tname" ) .
411 ". Make sure that the user \"". htmlspecialchars( $wgDBuser ) .
412 "\" has SELECT access to all four tsearch2 tables</li>\n";
416 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = " . $this->addQuotes( $ctype ) ;
417 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
418 $res = $this->doQuery($SQL);
419 error_reporting( E_ALL
);
421 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
426 // Will the current locale work? Can we force it to?
427 print "<li>Verifying tsearch2 locale with " . htmlspecialchars( $ctype ) . "...";
428 $rows = $this->numRows($res);
431 print "<b>not found</b></li>\n";
432 print "<li>Attempting to set default tsearch2 locale to \"" . htmlspecialchars( $ctype ) . "\"...";
436 $tsname = pg_fetch_result($res, 0, 0);
437 if ($tsname != 'default') {
438 print "<b>not set to default (" . htmlspecialchars( $tsname ) . ")</b>";
439 print "<li>Attempting to change tsearch2 default locale to \"" .
440 htmlspecialchars( $ctype ) . "\"...";
445 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = " . $this->addQuotes( $ctype ) . " WHERE ts_name = 'default'";
446 $res = $this->doQuery($SQL);
448 print "<b>FAILED</b>. ";
449 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"" .
450 htmlspecialchars( $ctype ) . "\"</li>\n";
456 // Final test: try out a simple tsearch2 query
457 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
458 $res = $this->doQuery($SQL);
460 print "<b>FAILED</b>. Specifically, \"" . htmlspecialchars( $SQL ) . "\" did not work.</li>";
466 // Install plpgsql if needed
467 $this->setup_plpgsql();
469 // Does the schema already exist? Who owns it?
470 $result = $this->schemaExists($wgDBmwschema);
472 print "<li>Creating schema <b>" . htmlspecialchars( $wgDBmwschema ) . "</b> ...";
473 error_reporting( 0 );
474 $safeschema = $this->quote_ident($wgDBmwschema);
475 $result = $this->doQuery("CREATE SCHEMA $safeschema");
476 error_reporting( E_ALL
);
478 print "<b>FAILED</b>. The user \"" . htmlspecialchars( $wgDBuser ) .
479 "\" must be able to access the schema. ".
480 "You can try making them the owner of the database, or try creating the schema with a ".
481 "different user, and then grant access to the \"" .
482 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
487 else if ($result != $wgDBuser) {
488 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists but is not owned by \"" .
489 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
492 print "<li>Schema \"" . htmlspecialchars( $wgDBmwschema ) . "\" exists and is owned by \"" .
493 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
496 // Always return GMT time to accomodate the existing integer-based timestamp assumption
497 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
498 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
499 $result = pg_query($this->mConn
, $SQL);
501 print "<b>FAILED</b>.</li>\n";
505 // Set for the rest of this session
506 $SQL = "SET timezone = 'GMT'";
507 $result = pg_query($this->mConn
, $SQL);
509 print "<li>Failed to set timezone</li>\n";
513 print "<li>Setting the datestyle to ISO, YMD for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
514 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
515 $result = pg_query($this->mConn
, $SQL);
517 print "<b>FAILED</b>.</li>\n";
521 // Set for the rest of this session
522 $SQL = "SET datestyle = 'ISO, YMD'";
523 $result = pg_query($this->mConn
, $SQL);
525 print "<li>Failed to set datestyle</li>\n";
529 // Fix up the search paths if needed
530 print "<li>Setting the search path for user \"" . htmlspecialchars( $wgDBuser ) . "\" ...";
531 $path = $this->quote_ident($wgDBmwschema);
532 if ($wgDBts2schema !== $wgDBmwschema)
533 $path .= ", ". $this->quote_ident($wgDBts2schema);
534 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
536 $SQL = "ALTER USER $safeuser SET search_path = $path";
537 $result = pg_query($this->mConn
, $SQL);
539 print "<b>FAILED</b>.</li>\n";
543 // Set for the rest of this session
544 $SQL = "SET search_path = $path";
545 $result = pg_query($this->mConn
, $SQL);
547 print "<li>Failed to set search_path</li>\n";
550 define( "POSTGRES_SEARCHPATH", $path );
555 function setup_plpgsql() {
556 print "<li>Checking for Pl/Pgsql ...";
557 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
558 $rows = $this->numRows($this->doQuery($SQL));
560 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
561 print "not installed. Attempting to install Pl/Pgsql ...";
562 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
563 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
564 $rows = $this->numRows($this->doQuery($SQL));
566 $olde = error_reporting(0);
567 error_reporting($olde - E_WARNING
);
568 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
569 error_reporting($olde);
571 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
572 htmlspecialchars( $wgDBname ) . "</tt></li>";
577 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>" .
578 htmlspecialchars( $wgDBname ) . "</tt></li>";
587 * Closes a database connection, if it is open
588 * Returns success, true if already closed
591 $this->mOpened
= false;
592 if ( $this->mConn
) {
593 return pg_close( $this->mConn
);
599 function doQuery( $sql ) {
600 if (function_exists('mb_convert_encoding')) {
601 $sql = mb_convert_encoding($sql,'UTF-8');
603 $this->mLastResult
= pg_query( $this->mConn
, $sql);
604 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
605 return $this->mLastResult
;
608 function queryIgnore( $sql, $fname = '' ) {
609 return $this->query( $sql, $fname, true );
612 function freeResult( $res ) {
613 if ( $res instanceof ResultWrapper
) {
616 if ( !@pg_free_result
( $res ) ) {
617 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
621 function fetchObject( $res ) {
622 if ( $res instanceof ResultWrapper
) {
625 @$row = pg_fetch_object( $res );
626 # FIXME: HACK HACK HACK HACK debug
629 # hashar : not sure if the following test really trigger if the object
631 if( pg_last_error($this->mConn
) ) {
632 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
637 function fetchRow( $res ) {
638 if ( $res instanceof ResultWrapper
) {
641 @$row = pg_fetch_array( $res );
642 if( pg_last_error($this->mConn
) ) {
643 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
648 function numRows( $res ) {
649 if ( $res instanceof ResultWrapper
) {
652 @$n = pg_num_rows( $res );
653 if( pg_last_error($this->mConn
) ) {
654 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn
) ) );
658 function numFields( $res ) {
659 if ( $res instanceof ResultWrapper
) {
662 return pg_num_fields( $res );
664 function fieldName( $res, $n ) {
665 if ( $res instanceof ResultWrapper
) {
668 return pg_field_name( $res, $n );
672 * This must be called after nextSequenceVal
674 function insertId() {
675 return $this->mInsertId
;
678 function dataSeek( $res, $row ) {
679 if ( $res instanceof ResultWrapper
) {
682 return pg_result_seek( $res, $row );
685 function lastError() {
686 if ( $this->mConn
) {
687 return pg_last_error();
690 return "No database connection";
693 function lastErrno() {
694 return pg_last_error() ?
1 : 0;
697 function affectedRows() {
698 if ( !is_null( $this->mAffectedRows
) ) {
699 // Forced result for simulated queries
700 return $this->mAffectedRows
;
702 if( empty( $this->mLastResult
) )
704 return pg_affected_rows( $this->mLastResult
);
708 * Estimate rows in dataset
709 * Returns estimated count, based on EXPLAIN output
710 * This is not necessarily an accurate estimate, so use sparingly
711 * Returns -1 if count cannot be found
712 * Takes same arguments as Database::select()
715 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
716 $options['EXPLAIN'] = true;
717 $res = $this->select( $table, $vars, $conds, $fname, $options );
720 $row = $this->fetchRow( $res );
722 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
725 $this->freeResult($res);
732 * Returns information about an index
733 * If errors are explicitly ignored, returns NULL on failure
735 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
736 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
737 $res = $this->query( $sql, $fname );
741 while ( $row = $this->fetchObject( $res ) ) {
742 if ( $row->indexname
== $this->indexName( $index ) ) {
749 function indexUnique ($table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
750 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
751 " AND indexdef LIKE 'CREATE UNIQUE%(" .
752 $this->strencode( $this->indexName( $index ) ) .
754 $res = $this->query( $sql, $fname );
757 while ($row = $this->fetchObject( $res ))
764 * INSERT wrapper, inserts an array into a table
766 * $args may be a single associative array, or an array of these with numeric keys,
767 * for multi-row insert (Postgres version 8.2 and above only).
769 * @param $table String: Name of the table to insert to.
770 * @param $args Array: Items to insert into the table.
771 * @param $fname String: Name of the function, for profiling
772 * @param $options String or Array. Valid options: IGNORE
774 * @return bool Success of insert operation. IGNORE always returns true.
776 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
779 if ( !count( $args ) ) {
783 $table = $this->tableName( $table );
784 if (! isset( $wgDBversion ) ) {
785 $wgDBversion = $this->getServerVersion();
788 if ( !is_array( $options ) )
789 $options = array( $options );
791 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
793 $keys = array_keys( $args[0] );
797 $keys = array_keys( $args );
800 // If IGNORE is set, we use savepoints to emulate mysql's behavior
801 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
803 // If we are not in a transaction, we need to be for savepoint trickery
806 if (! $this->mTrxLevel
) {
810 $olde = error_reporting( 0 );
811 // For future use, we may want to track the number of actual inserts
812 // Right now, insert (all writes) simply return true/false
813 $numrowsinserted = 0;
816 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
819 if ( $wgDBversion >= 8.2 && !$ignore ) {
821 foreach ( $args as $row ) {
827 $sql .= '(' . $this->makeList( $row ) . ')';
829 $res = (bool)$this->query( $sql, $fname, $ignore );
834 foreach ( $args as $row ) {
836 $tempsql .= '(' . $this->makeList( $row ) . ')';
839 pg_query($this->mConn
, "SAVEPOINT $ignore");
842 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
845 $bar = pg_last_error();
847 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
850 pg_query( $this->mConn
, "RELEASE $ignore" );
855 // If any of them fail, we fail overall for this function call
856 // Note that this will be ignored if IGNORE is set
863 // Not multi, just a lone insert
865 pg_query($this->mConn
, "SAVEPOINT $ignore");
868 $sql .= '(' . $this->makeList( $args ) . ')';
869 $res = (bool)$this->query( $sql, $fname, $ignore );
871 $bar = pg_last_error();
873 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
876 pg_query( $this->mConn
, "RELEASE $ignore" );
882 $olde = error_reporting( $olde );
887 // Set the affected row count for the whole operation
888 $this->mAffectedRows
= $numrowsinserted;
890 // IGNORE always returns true
900 * INSERT SELECT wrapper
901 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
902 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
903 * $conds may be "*" to copy the whole table
904 * srcTable may be an array of tables.
905 * @todo FIXME: implement this a little better (seperate select/insert)?
907 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
908 $insertOptions = array(), $selectOptions = array() )
910 $destTable = $this->tableName( $destTable );
912 // If IGNORE is set, we use savepoints to emulate mysql's behavior
913 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
915 if( is_array( $insertOptions ) ) {
916 $insertOptions = implode( ' ', $insertOptions );
918 if( !is_array( $selectOptions ) ) {
919 $selectOptions = array( $selectOptions );
921 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
922 if( is_array( $srcTable ) ) {
923 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
925 $srcTable = $this->tableName( $srcTable );
928 // If we are not in a transaction, we need to be for savepoint trickery
931 if( !$this->mTrxLevel
) {
935 $olde = error_reporting( 0 );
936 $numrowsinserted = 0;
937 pg_query( $this->mConn
, "SAVEPOINT $ignore");
940 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
941 " SELECT $startOpts " . implode( ',', $varMap ) .
942 " FROM $srcTable $useIndex";
944 if ( $conds != '*') {
945 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
948 $sql .= " $tailOpts";
950 $res = (bool)$this->query( $sql, $fname, $ignore );
952 $bar = pg_last_error();
953 if( $bar != false ) {
954 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
956 pg_query( $this->mConn
, "RELEASE $ignore" );
959 $olde = error_reporting( $olde );
964 // Set the affected row count for the whole operation
965 $this->mAffectedRows
= $numrowsinserted;
967 // IGNORE always returns true
974 function tableName( $name ) {
975 # Replace reserved words with better ones
980 return 'pagecontent';
987 * Return the next in a sequence, save the value for retrieval via insertId()
989 function nextSequenceValue( $seqName ) {
990 $safeseq = preg_replace( "/'/", "''", $seqName );
991 $res = $this->query( "SELECT nextval('$safeseq')" );
992 $row = $this->fetchRow( $res );
993 $this->mInsertId
= $row[0];
994 $this->freeResult( $res );
995 return $this->mInsertId
;
999 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1001 function currentSequenceValue( $seqName ) {
1002 $safeseq = preg_replace( "/'/", "''", $seqName );
1003 $res = $this->query( "SELECT currval('$safeseq')" );
1004 $row = $this->fetchRow( $res );
1006 $this->freeResult( $res );
1010 # REPLACE query wrapper
1011 # Postgres simulates this with a DELETE followed by INSERT
1012 # $row is the row to insert, an associative array
1013 # $uniqueIndexes is an array of indexes. Each element may be either a
1014 # field name or an array of field names
1016 # It may be more efficient to leave off unique indexes which are unlikely to collide.
1017 # However if you do this, you run the risk of encountering errors which wouldn't have
1019 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
1020 $table = $this->tableName( $table );
1022 if (count($rows)==0) {
1027 if ( !is_array( reset( $rows ) ) ) {
1028 $rows = array( $rows );
1031 foreach( $rows as $row ) {
1032 # Delete rows which collide
1033 if ( $uniqueIndexes ) {
1034 $sql = "DELETE FROM $table WHERE ";
1036 foreach ( $uniqueIndexes as $index ) {
1043 if ( is_array( $index ) ) {
1045 foreach ( $index as $col ) {
1051 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
1054 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
1058 $this->query( $sql, $fname );
1061 # Now insert the row
1062 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
1063 $this->makeList( $row, LIST_COMMA
) . ')';
1064 $this->query( $sql, $fname );
1068 # DELETE where the condition is a join
1069 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
1071 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
1074 $delTable = $this->tableName( $delTable );
1075 $joinTable = $this->tableName( $joinTable );
1076 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
1077 if ( $conds != '*' ) {
1078 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
1082 $this->query( $sql, $fname );
1085 # Returns the size of a text field, or -1 for "unlimited"
1086 function textFieldSize( $table, $field ) {
1087 $table = $this->tableName( $table );
1088 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1089 FROM pg_class c, pg_attribute a, pg_type t
1090 WHERE relname='$table' AND a.attrelid=c.oid AND
1091 a.atttypid=t.oid and a.attname='$field'";
1092 $res =$this->query($sql);
1093 $row=$this->fetchObject($res);
1094 if ($row->ftype
=="varchar") {
1099 $this->freeResult( $res );
1103 function limitResult($sql, $limit, $offset=false) {
1104 return "$sql LIMIT $limit ".(is_numeric($offset)?
" OFFSET {$offset} ":"");
1107 function wasDeadlock() {
1108 return $this->lastErrno() == '40P01';
1111 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
1112 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
1115 function timestamp( $ts=0 ) {
1116 return wfTimestamp(TS_POSTGRES
,$ts);
1120 * Return aggregated value function call
1122 function aggregateValue ($valuedata,$valuename='value') {
1127 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1128 // Ignore errors during error handling to avoid infinite recursion
1129 $ignore = $this->ignoreErrors( true );
1130 $this->mErrorCount++
;
1132 if ($ignore ||
$tempIgnore) {
1133 wfDebug("SQL ERROR (ignored): $error\n");
1134 $this->ignoreErrors( $ignore );
1137 $message = "A database error has occurred\n" .
1139 "Function: $fname\n" .
1140 "Error: $errno $error\n";
1141 throw new DBUnexpectedError($this, $message);
1146 * @return string wikitext of a link to the server software's web site
1148 function getSoftwareLink() {
1149 return "[http://www.postgresql.org/ PostgreSQL]";
1153 * @return string Version information from the database
1155 function getServerVersion() {
1156 $versionInfo = pg_version( $this->mConn
);
1157 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1158 // Old client, abort install
1159 $this->numeric_version
= '7.3 or earlier';
1160 } elseif ( isset( $versionInfo['server'] ) ) {
1162 $this->numeric_version
= $versionInfo['server'];
1164 // Bug 16937: broken pgsql extension from PHP<5.3
1165 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
1167 return $this->numeric_version
;
1171 * Query whether a given relation exists (in the given schema, or the
1172 * default mw one if not given)
1174 function relationExists( $table, $types, $schema = false ) {
1175 global $wgDBmwschema;
1176 if ( !is_array( $types ) )
1177 $types = array( $types );
1179 $schema = $wgDBmwschema;
1180 $etable = $this->addQuotes( $table );
1181 $eschema = $this->addQuotes( $schema );
1182 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1183 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1184 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1185 $res = $this->query( $SQL );
1186 $count = $res ?
$res->numRows() : 0;
1188 $this->freeResult( $res );
1189 return $count ?
true : false;
1193 * For backward compatibility, this function checks both tables and
1196 function tableExists( $table, $schema = false ) {
1197 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1200 function sequenceExists( $sequence, $schema = false ) {
1201 return $this->relationExists( $sequence, 'S', $schema );
1204 function triggerExists( $table, $trigger ) {
1205 global $wgDBmwschema;
1208 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1209 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1210 AND tgrelid=pg_class.oid
1211 AND nspname=%s AND relname=%s AND tgname=%s
1213 $res = $this->query(sprintf($q,
1214 $this->addQuotes($wgDBmwschema),
1215 $this->addQuotes($table),
1216 $this->addQuotes($trigger)));
1219 $rows = $res->numRows();
1220 $this->freeResult( $res );
1224 function ruleExists( $table, $rule ) {
1225 global $wgDBmwschema;
1226 $exists = $this->selectField("pg_rules", "rulename",
1227 array( "rulename" => $rule,
1228 "tablename" => $table,
1229 "schemaname" => $wgDBmwschema ) );
1230 return $exists === $rule;
1233 function constraintExists( $table, $constraint ) {
1234 global $wgDBmwschema;
1235 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1236 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1237 $this->addQuotes($wgDBmwschema),
1238 $this->addQuotes($table),
1239 $this->addQuotes($constraint));
1240 $res = $this->query($SQL);
1243 $rows = $res->numRows();
1244 $this->freeResult($res);
1249 * Query whether a given schema exists. Returns the name of the owner
1251 function schemaExists( $schema ) {
1252 $eschema = preg_replace("/'/", "''", $schema);
1253 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1254 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1255 $res = $this->query( $SQL );
1256 if ( $res && $res->numRows() ) {
1257 $row = $res->fetchObject();
1258 $owner = $row->rolname
;
1263 $this->freeResult($res);
1268 * Query whether a given column exists in the mediawiki schema
1270 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1271 global $wgDBmwschema;
1272 $etable = preg_replace("/'/", "''", $table);
1273 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1274 $ecol = preg_replace("/'/", "''", $field);
1275 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1276 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1277 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1278 $res = $this->query( $SQL, $fname );
1279 $count = $res ?
$res->numRows() : 0;
1281 $this->freeResult( $res );
1285 function fieldInfo( $table, $field ) {
1286 return PostgresField
::fromText($this, $table, $field);
1290 * pg_field_type() wrapper
1292 function fieldType( $res, $index ) {
1293 if ( $res instanceof ResultWrapper
) {
1294 $res = $res->result
;
1296 return pg_field_type( $res, $index );
1299 function begin( $fname = 'DatabasePostgres::begin' ) {
1300 $this->query( 'BEGIN', $fname );
1301 $this->mTrxLevel
= 1;
1303 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1306 function commit( $fname = 'DatabasePostgres::commit' ) {
1307 $this->query( 'COMMIT', $fname );
1308 $this->mTrxLevel
= 0;
1311 /* Not even sure why this is used in the main codebase... */
1312 function limitResultForUpdate( $sql, $num ) {
1316 function setup_database() {
1317 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1319 // Make sure that we can write to the correct schema
1320 // If not, Postgres will happily and silently go to the next search_path item
1321 $ctest = "mediawiki_test_table";
1322 $safeschema = $this->quote_ident($wgDBmwschema);
1323 if ($this->tableExists($ctest, $wgDBmwschema)) {
1324 $this->doQuery("DROP TABLE $safeschema.$ctest");
1326 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1327 $olde = error_reporting( 0 );
1328 $res = $this->doQuery($SQL);
1329 error_reporting( $olde );
1331 print "<b>FAILED</b>. Make sure that the user \"" . htmlspecialchars( $wgDBuser ) .
1332 "\" can write to the schema \"" . htmlspecialchars( $wgDBmwschema ) . "\"</li>\n";
1333 dieout(""); # Will close the main list <ul> and finish the page.
1335 $this->doQuery("DROP TABLE $safeschema.$ctest");
1337 $res = $this->sourceFile( "../maintenance/postgres/tables.sql" );
1338 if ($res === true) {
1339 print " done.</li>\n";
1341 print " <b>FAILED</b></li>\n";
1342 dieout( htmlspecialchars( $res ) );
1345 ## Update version information
1346 $mwv = $this->addQuotes($wgVersion);
1347 $pgv = $this->addQuotes($this->getServerVersion());
1348 $pgu = $this->addQuotes($this->mUser
);
1349 $mws = $this->addQuotes($wgDBmwschema);
1350 $tss = $this->addQuotes($wgDBts2schema);
1351 $pgp = $this->addQuotes($wgDBport);
1352 $dbn = $this->addQuotes($this->mDBname
);
1353 $ctype = $this->addQuotes( pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0) );
1355 echo "<li>Populating interwiki table... ";
1356 ## Avoid the non-standard "REPLACE INTO" syntax
1357 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1359 print "<b>FAILED</b></li>";
1360 dieout( "Could not find the interwiki.sql file" );
1362 ## We simply assume it is already empty as we have just created it
1363 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1364 while ( ! feof( $f ) ) {
1365 $line = fgets($f,1024);
1367 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1370 $this->query("$SQL $matches[1],$matches[2])");
1372 print " successfully populated.</li>\n";
1374 $this->doQuery("COMMIT");
1377 function encodeBlob( $b ) {
1378 return new Blob ( pg_escape_bytea( $b ) ) ;
1381 function decodeBlob( $b ) {
1382 if ($b instanceof Blob
) {
1385 return pg_unescape_bytea( $b );
1388 function strencode( $s ) { ## Should not be called by us
1389 return pg_escape_string( $s );
1392 function addQuotes( $s ) {
1393 if ( is_null( $s ) ) {
1395 } else if ( is_bool( $s ) ) {
1396 return intval( $s );
1397 } else if ($s instanceof Blob
) {
1398 return "'".$s->fetch($s)."'";
1400 return "'" . pg_escape_string($s) . "'";
1403 function quote_ident( $s ) {
1404 return '"' . preg_replace( '/"/', '""', $s) . '"';
1408 * Postgres specific version of replaceVars.
1409 * Calls the parent version in Database.php
1413 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1415 * @return string SQL string
1417 protected function replaceVars( $ins ) {
1419 $ins = parent
::replaceVars( $ins );
1421 if ($this->numeric_version
>= 8.3) {
1422 // Thanks for not providing backwards-compatibility, 8.3
1423 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1426 if ($this->numeric_version
<= 8.1) { // Our minimum version
1427 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1434 * Various select options
1438 * @param $options Array: an associative array of options to be turned into
1439 * an SQL query, valid keys are listed in the function.
1442 function makeSelectOptions( $options ) {
1443 $preLimitTail = $postLimitTail = '';
1444 $startOpts = $useIndex = '';
1446 $noKeyOptions = array();
1447 foreach ( $options as $key => $option ) {
1448 if ( is_numeric( $key ) ) {
1449 $noKeyOptions[$option] = true;
1453 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1454 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1455 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1457 //if (isset($options['LIMIT'])) {
1458 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1459 // isset($options['OFFSET']) ? $options['OFFSET']
1463 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1464 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1465 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1467 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1471 * How lagged is this slave?
1474 public function getLag() {
1475 # Not implemented for PostgreSQL
1479 function setFakeSlaveLag( $lag ) {}
1480 function setFakeMaster( $enabled = true ) {}
1482 function getDBname() {
1483 return $this->mDBname
;
1486 function getServer() {
1487 return $this->mServer
;
1490 function buildConcat( $stringList ) {
1491 return implode( ' || ', $stringList );
1494 public function getSearchEngine() {
1495 return "SearchPostgres";
1497 } // end DatabasePostgres class