(bug 10323) Special:Undelete should have "inverse selection" button
[mediawiki.git] / includes / db / DatabasePostgres.php
blob590c682d2a27f886d5dfc6bba6297a8a0e5717cb
1 <?php
2 /**
3 * @ingroup Database
4 * @file
5 * This is the Postgres database abstraction layer.
7 */
8 class PostgresField {
9 private $name, $tablename, $type, $nullable, $max_length;
11 static function fromText($db, $table, $field) {
12 global $wgDBmwschema;
14 $q = <<<END
15 SELECT
16 CASE WHEN typname = 'int2' THEN 'smallint'
17 WHEN typname = 'int4' THEN 'integer'
18 WHEN typname = 'int8' THEN 'bigint'
19 WHEN typname = 'bpchar' THEN 'char'
20 ELSE typname END AS typname,
21 attnotnull, attlen
22 FROM pg_class, pg_namespace, pg_attribute, pg_type
23 WHERE relnamespace=pg_namespace.oid
24 AND relkind='r'
25 AND attrelid=pg_class.oid
26 AND atttypid=pg_type.oid
27 AND nspname=%s
28 AND relname=%s
29 AND attname=%s;
30 END;
31 $res = $db->query(sprintf($q,
32 $db->addQuotes($wgDBmwschema),
33 $db->addQuotes($table),
34 $db->addQuotes($field)));
35 $row = $db->fetchObject($res);
36 if (!$row)
37 return null;
38 $n = new PostgresField;
39 $n->type = $row->typname;
40 $n->nullable = ($row->attnotnull == 'f');
41 $n->name = $field;
42 $n->tablename = $table;
43 $n->max_length = $row->attlen;
44 return $n;
47 function name() {
48 return $this->name;
51 function tableName() {
52 return $this->tablename;
55 function type() {
56 return $this->type;
59 function nullable() {
60 return $this->nullable;
63 function maxLength() {
64 return $this->max_length;
68 /**
69 * @ingroup Database
71 class DatabasePostgres extends Database {
72 var $mInsertId = NULL;
73 var $mLastResult = NULL;
74 var $numeric_version = NULL;
75 var $mAffectedRows = NULL;
77 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
78 $failFunction = false, $flags = 0 )
81 global $wgOut;
82 # Can't get a reference if it hasn't been set yet
83 if ( !isset( $wgOut ) ) {
84 $wgOut = NULL;
86 $this->mOut =& $wgOut;
87 $this->mFailFunction = $failFunction;
88 $this->mFlags = $flags;
89 $this->open( $server, $user, $password, $dbName);
93 function cascadingDeletes() {
94 return true;
96 function cleanupTriggers() {
97 return true;
99 function strictIPs() {
100 return true;
102 function realTimestamps() {
103 return true;
105 function implicitGroupby() {
106 return false;
108 function implicitOrderby() {
109 return false;
111 function searchableIPs() {
112 return true;
114 function functionalIndexes() {
115 return true;
118 function hasConstraint( $name ) {
119 global $wgDBmwschema;
120 $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) ."'";
121 return $this->numRows($res = $this->doQuery($SQL));
124 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0)
126 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
130 * Usually aborts on failure
131 * If the failFunction is set to a non-zero integer, returns success
133 function open( $server, $user, $password, $dbName ) {
134 # Test for Postgres support, to avoid suppressed fatal error
135 if ( !function_exists( 'pg_connect' ) ) {
136 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" );
139 global $wgDBport;
141 if (!strlen($user)) { ## e.g. the class is being loaded
142 return;
145 $this->close();
146 $this->mServer = $server;
147 $this->mPort = $port = $wgDBport;
148 $this->mUser = $user;
149 $this->mPassword = $password;
150 $this->mDBname = $dbName;
152 $hstring="";
153 if ($server!=false && $server!="") {
154 $hstring="host=$server ";
156 if ($port!=false && $port!="") {
157 $hstring .= "port=$port ";
160 error_reporting( E_ALL );
161 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
163 if ( $this->mConn == false ) {
164 wfDebug( "DB connection error\n" );
165 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
166 wfDebug( $this->lastError()."\n" );
167 return false;
170 $this->mOpened = true;
172 global $wgCommandLineMode;
173 ## If called from the command-line (e.g. importDump), only show errors
174 if ($wgCommandLineMode) {
175 $this->doQuery("SET client_min_messages = 'ERROR'");
178 global $wgDBmwschema, $wgDBts2schema;
179 if (isset( $wgDBmwschema ) && isset( $wgDBts2schema )
180 && $wgDBmwschema !== 'mediawiki'
181 && preg_match( '/^\w+$/', $wgDBmwschema )
182 && preg_match( '/^\w+$/', $wgDBts2schema )
184 $safeschema = $this->quote_ident($wgDBmwschema);
185 $safeschema2 = $this->quote_ident($wgDBts2schema);
186 $this->doQuery("SET search_path = $safeschema, $wgDBts2schema, public");
189 return $this->mConn;
193 function initial_setup($password, $dbName) {
194 // If this is the initial connection, setup the schema stuff and possibly create the user
195 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
197 print "<li>Checking the version of Postgres...";
198 $version = $this->getServerVersion();
199 $PGMINVER = '8.1';
200 if ($this->numeric_version < $PGMINVER) {
201 print "<b>FAILED</b>. Required version is $PGMINVER. You have $this->numeric_version ($version)</li>\n";
202 dieout("</ul>");
204 print "version $this->numeric_version is OK.</li>\n";
206 $safeuser = $this->quote_ident($wgDBuser);
207 // Are we connecting as a superuser for the first time?
208 if ($wgDBsuperuser) {
209 // Are we really a superuser? Check out our rights
210 $SQL = "SELECT
211 CASE WHEN usesuper IS TRUE THEN
212 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
213 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
214 END AS rights
215 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
216 $rows = $this->numRows($res = $this->doQuery($SQL));
217 if (!$rows) {
218 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
219 dieout('</ul>');
221 $perms = pg_fetch_result($res, 0, 0);
223 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
224 $rows = $this->numRows($this->doQuery($SQL));
225 if ($rows) {
226 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
228 else {
229 if ($perms != 1 and $perms != 3) {
230 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
231 print 'Please use a different Postgres user.</li>';
232 dieout('</ul>');
234 print "<li>Creating user <b>$wgDBuser</b>...";
235 $safepass = $this->addQuotes($wgDBpassword);
236 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
237 $this->doQuery($SQL);
238 print "OK</li>\n";
240 // User now exists, check out the database
241 if ($dbName != $wgDBname) {
242 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
243 $rows = $this->numRows($this->doQuery($SQL));
244 if ($rows) {
245 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
247 else {
248 if ($perms < 2) {
249 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
250 print 'Please use a different Postgres user.</li>';
251 dieout('</ul>');
253 print "<li>Creating database <b>$wgDBname</b>...";
254 $safename = $this->quote_ident($wgDBname);
255 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
256 $this->doQuery($SQL);
257 print "OK</li>\n";
258 // Hopefully tsearch2 and plpgsql are in template1...
261 // Reconnect to check out tsearch2 rights for this user
262 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
264 $hstring="";
265 if ($this->mServer!=false && $this->mServer!="") {
266 $hstring="host=$this->mServer ";
268 if ($this->mPort!=false && $this->mPort!="") {
269 $hstring .= "port=$this->mPort ";
272 @$this->mConn = pg_connect("$hstring dbname=$wgDBname user=$wgDBsuperuser password=$password");
273 if ( $this->mConn == false ) {
274 print "<b>FAILED TO CONNECT!</b></li>";
275 dieout("</ul>");
277 print "OK</li>\n";
280 if ($this->numeric_version < 8.3) {
281 // Tsearch2 checks
282 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
283 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
284 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
285 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
286 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
287 dieout("</ul>");
289 print "OK</li>\n";
290 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
291 foreach (array('cfg','cfgmap','dict','parser') as $table) {
292 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
293 $this->doQuery($SQL);
295 print "OK</li>\n";
298 // Setup the schema for this user if needed
299 $result = $this->schemaExists($wgDBmwschema);
300 $safeschema = $this->quote_ident($wgDBmwschema);
301 if (!$result) {
302 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
303 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
304 if (!$result) {
305 print "<b>FAILED</b>.</li>\n";
306 dieout("</ul>");
308 print "OK</li>\n";
310 else {
311 print "<li>Schema already exists, explicitly granting rights...\n";
312 $safeschema2 = $this->addQuotes($wgDBmwschema);
313 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
314 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
315 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
316 "AND p.relkind IN ('r','S','v')\n";
317 $SQL .= "UNION\n";
318 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
319 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
320 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
321 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
322 $res = $this->doQuery($SQL);
323 if (!$res) {
324 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
325 dieout("</ul>");
327 $this->doQuery("SET search_path = $safeschema");
328 $rows = $this->numRows($res);
329 while ($rows) {
330 $rows--;
331 $this->doQuery(pg_fetch_result($res, $rows, 0));
333 print "OK</li>";
336 // Install plpgsql if needed
337 $this->setup_plpgsql();
339 $wgDBsuperuser = '';
340 return true; // Reconnect as regular user
342 } // end superuser
344 if (!defined('POSTGRES_SEARCHPATH')) {
346 if ($this->numeric_version < 8.3) {
347 // Do we have the basic tsearch2 table?
348 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
349 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
350 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
351 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
352 print " for instructions.</li>\n";
353 dieout("</ul>");
355 print "OK</li>\n";
357 // Does this user have the rights to the tsearch2 tables?
358 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
359 print "<li>Checking tsearch2 permissions...";
360 // Let's check all four, just to be safe
361 error_reporting( 0 );
362 $ts2tables = array('cfg','cfgmap','dict','parser');
363 $safetsschema = $this->quote_ident($wgDBts2schema);
364 foreach ( $ts2tables AS $tname ) {
365 $SQL = "SELECT count(*) FROM $safetsschema.pg_ts_$tname";
366 $res = $this->doQuery($SQL);
367 if (!$res) {
368 print "<b>FAILED</b> to access pg_ts_$tname. Make sure that the user ".
369 "\"$wgDBuser\" has SELECT access to all four tsearch2 tables</li>\n";
370 dieout("</ul>");
373 $SQL = "SELECT ts_name FROM $safetsschema.pg_ts_cfg WHERE locale = '$ctype'";
374 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
375 $res = $this->doQuery($SQL);
376 error_reporting( E_ALL );
377 if (!$res) {
378 print "<b>FAILED</b>. Could not determine the tsearch2 locale information</li>\n";
379 dieout("</ul>");
381 print "OK</li>";
383 // Will the current locale work? Can we force it to?
384 print "<li>Verifying tsearch2 locale with $ctype...";
385 $rows = $this->numRows($res);
386 $resetlocale = 0;
387 if (!$rows) {
388 print "<b>not found</b></li>\n";
389 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
390 $resetlocale = 1;
392 else {
393 $tsname = pg_fetch_result($res, 0, 0);
394 if ($tsname != 'default') {
395 print "<b>not set to default ($tsname)</b>";
396 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
397 $resetlocale = 1;
400 if ($resetlocale) {
401 $SQL = "UPDATE $safetsschema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
402 $res = $this->doQuery($SQL);
403 if (!$res) {
404 print "<b>FAILED</b>. ";
405 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"$ctype\"</li>\n";
406 dieout("</ul>");
408 print "OK</li>";
411 // Final test: try out a simple tsearch2 query
412 $SQL = "SELECT $safetsschema.to_tsvector('default','MediaWiki tsearch2 testing')";
413 $res = $this->doQuery($SQL);
414 if (!$res) {
415 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
416 dieout("</ul>");
418 print "OK</li>";
421 // Install plpgsql if needed
422 $this->setup_plpgsql();
424 // Does the schema already exist? Who owns it?
425 $result = $this->schemaExists($wgDBmwschema);
426 if (!$result) {
427 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
428 error_reporting( 0 );
429 $safeschema = $this->quote_ident($wgDBmwschema);
430 $result = $this->doQuery("CREATE SCHEMA $safeschema");
431 error_reporting( E_ALL );
432 if (!$result) {
433 print "<b>FAILED</b>. The user \"$wgDBuser\" must be able to access the schema. ".
434 "You can try making them the owner of the database, or try creating the schema with a ".
435 "different user, and then grant access to the \"$wgDBuser\" user.</li>\n";
436 dieout("</ul>");
438 print "OK</li>\n";
440 else if ($result != $wgDBuser) {
441 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$wgDBuser\". Not ideal.</li>\n";
443 else {
444 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$wgDBuser\". Excellent.</li>\n";
447 // Always return GMT time to accomodate the existing integer-based timestamp assumption
448 print "<li>Setting the timezone to GMT for user \"$wgDBuser\" ...";
449 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
450 $result = pg_query($this->mConn, $SQL);
451 if (!$result) {
452 print "<b>FAILED</b>.</li>\n";
453 dieout("</ul>");
455 print "OK</li>\n";
456 // Set for the rest of this session
457 $SQL = "SET timezone = 'GMT'";
458 $result = pg_query($this->mConn, $SQL);
459 if (!$result) {
460 print "<li>Failed to set timezone</li>\n";
461 dieout("</ul>");
464 print "<li>Setting the datestyle to ISO, YMD for user \"$wgDBuser\" ...";
465 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
466 $result = pg_query($this->mConn, $SQL);
467 if (!$result) {
468 print "<b>FAILED</b>.</li>\n";
469 dieout("</ul>");
471 print "OK</li>\n";
472 // Set for the rest of this session
473 $SQL = "SET datestyle = 'ISO, YMD'";
474 $result = pg_query($this->mConn, $SQL);
475 if (!$result) {
476 print "<li>Failed to set datestyle</li>\n";
477 dieout("</ul>");
480 // Fix up the search paths if needed
481 print "<li>Setting the search path for user \"$wgDBuser\" ...";
482 $path = $this->quote_ident($wgDBmwschema);
483 if ($wgDBts2schema !== $wgDBmwschema)
484 $path .= ", ". $this->quote_ident($wgDBts2schema);
485 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
486 $path .= ", public";
487 $SQL = "ALTER USER $safeuser SET search_path = $path";
488 $result = pg_query($this->mConn, $SQL);
489 if (!$result) {
490 print "<b>FAILED</b>.</li>\n";
491 dieout("</ul>");
493 print "OK</li>\n";
494 // Set for the rest of this session
495 $SQL = "SET search_path = $path";
496 $result = pg_query($this->mConn, $SQL);
497 if (!$result) {
498 print "<li>Failed to set search_path</li>\n";
499 dieout("</ul>");
501 define( "POSTGRES_SEARCHPATH", $path );
506 function setup_plpgsql() {
507 print "<li>Checking for Pl/Pgsql ...";
508 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
509 $rows = $this->numRows($this->doQuery($SQL));
510 if ($rows < 1) {
511 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
512 print "not installed. Attempting to install Pl/Pgsql ...";
513 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
514 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
515 $rows = $this->numRows($this->doQuery($SQL));
516 if ($rows >= 1) {
517 $olde = error_reporting(0);
518 error_reporting($olde - E_WARNING);
519 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
520 error_reporting($olde);
521 if (!$result) {
522 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
523 dieout("</ul>");
526 else {
527 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
528 dieout("</ul>");
531 print "OK</li>\n";
536 * Closes a database connection, if it is open
537 * Returns success, true if already closed
539 function close() {
540 $this->mOpened = false;
541 if ( $this->mConn ) {
542 return pg_close( $this->mConn );
543 } else {
544 return true;
548 function doQuery( $sql ) {
549 if (function_exists('mb_convert_encoding')) {
550 $sql = mb_convert_encoding($sql,'UTF-8');
552 $this->mLastResult = pg_query( $this->mConn, $sql);
553 $this->mAffectedRows = NULL; // use pg_affected_rows(mLastResult)
554 return $this->mLastResult;
557 function queryIgnore( $sql, $fname = '' ) {
558 return $this->query( $sql, $fname, true );
561 function freeResult( $res ) {
562 if ( $res instanceof ResultWrapper ) {
563 $res = $res->result;
565 if ( !@pg_free_result( $res ) ) {
566 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
570 function fetchObject( $res ) {
571 if ( $res instanceof ResultWrapper ) {
572 $res = $res->result;
574 @$row = pg_fetch_object( $res );
575 # FIXME: HACK HACK HACK HACK debug
577 # TODO:
578 # hashar : not sure if the following test really trigger if the object
579 # fetching failed.
580 if( pg_last_error($this->mConn) ) {
581 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
583 return $row;
586 function fetchRow( $res ) {
587 if ( $res instanceof ResultWrapper ) {
588 $res = $res->result;
590 @$row = pg_fetch_array( $res );
591 if( pg_last_error($this->mConn) ) {
592 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
594 return $row;
597 function numRows( $res ) {
598 if ( $res instanceof ResultWrapper ) {
599 $res = $res->result;
601 @$n = pg_num_rows( $res );
602 if( pg_last_error($this->mConn) ) {
603 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
605 return $n;
607 function numFields( $res ) {
608 if ( $res instanceof ResultWrapper ) {
609 $res = $res->result;
611 return pg_num_fields( $res );
613 function fieldName( $res, $n ) {
614 if ( $res instanceof ResultWrapper ) {
615 $res = $res->result;
617 return pg_field_name( $res, $n );
621 * This must be called after nextSequenceVal
623 function insertId() {
624 return $this->mInsertId;
627 function dataSeek( $res, $row ) {
628 if ( $res instanceof ResultWrapper ) {
629 $res = $res->result;
631 return pg_result_seek( $res, $row );
634 function lastError() {
635 if ( $this->mConn ) {
636 return pg_last_error();
638 else {
639 return "No database connection";
642 function lastErrno() {
643 return pg_last_error() ? 1 : 0;
646 function affectedRows() {
647 if ( !is_null( $this->mAffectedRows ) ) {
648 // Forced result for simulated queries
649 return $this->mAffectedRows;
651 if( empty( $this->mLastResult ) )
652 return 0;
653 return pg_affected_rows( $this->mLastResult );
657 * Estimate rows in dataset
658 * Returns estimated count, based on EXPLAIN output
659 * This is not necessarily an accurate estimate, so use sparingly
660 * Returns -1 if count cannot be found
661 * Takes same arguments as Database::select()
664 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
665 $options['EXPLAIN'] = true;
666 $res = $this->select( $table, $vars, $conds, $fname, $options );
667 $rows = -1;
668 if ( $res ) {
669 $row = $this->fetchRow( $res );
670 $count = array();
671 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
672 $rows = $count[1];
674 $this->freeResult($res);
676 return $rows;
681 * Returns information about an index
682 * If errors are explicitly ignored, returns NULL on failure
684 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
685 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
686 $res = $this->query( $sql, $fname );
687 if ( !$res ) {
688 return NULL;
690 while ( $row = $this->fetchObject( $res ) ) {
691 if ( $row->indexname == $index ) {
692 return $row;
695 return false;
698 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
699 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
700 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
701 $res = $this->query( $sql, $fname );
702 if ( !$res )
703 return NULL;
704 while ($row = $this->fetchObject( $res ))
705 return true;
706 return false;
711 * INSERT wrapper, inserts an array into a table
713 * $args may be a single associative array, or an array of these with numeric keys,
714 * for multi-row insert (Postgres version 8.2 and above only).
716 * @param array $table String: Name of the table to insert to.
717 * @param array $args Array: Items to insert into the table.
718 * @param array $fname String: Name of the function, for profiling
719 * @param mixed $options String or Array. Valid options: IGNORE
721 * @return bool Success of insert operation. IGNORE always returns true.
723 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
724 global $wgDBversion;
726 if ( !count( $args ) ) {
727 return true;
730 $table = $this->tableName( $table );
731 if (! isset( $wgDBversion ) ) {
732 $this->getServerVersion();
733 $wgDBversion = $this->numeric_version;
736 if ( !is_array( $options ) )
737 $options = array( $options );
739 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
740 $multi = true;
741 $keys = array_keys( $args[0] );
743 else {
744 $multi = false;
745 $keys = array_keys( $args );
748 // If IGNORE is set, we use savepoints to emulate mysql's behavior
749 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
751 // If we are not in a transaction, we need to be for savepoint trickery
752 $didbegin = 0;
753 if ( $ignore ) {
754 if (! $this->mTrxLevel) {
755 $this->begin();
756 $didbegin = 1;
758 $olde = error_reporting( 0 );
759 // For future use, we may want to track the number of actual inserts
760 // Right now, insert (all writes) simply return true/false
761 $numrowsinserted = 0;
764 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
766 if ( $multi ) {
767 if ( $wgDBversion >= 8.2 && !$ignore ) {
768 $first = true;
769 foreach ( $args as $row ) {
770 if ( $first ) {
771 $first = false;
772 } else {
773 $sql .= ',';
775 $sql .= '(' . $this->makeList( $row ) . ')';
777 $res = (bool)$this->query( $sql, $fname, $ignore );
779 else {
780 $res = true;
781 $origsql = $sql;
782 foreach ( $args as $row ) {
783 $tempsql = $origsql;
784 $tempsql .= '(' . $this->makeList( $row ) . ')';
786 if ( $ignore ) {
787 pg_query($this->mConn, "SAVEPOINT $ignore");
790 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
792 if ( $ignore ) {
793 $bar = pg_last_error();
794 if ($bar != false) {
795 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
797 else {
798 pg_query( $this->mConn, "RELEASE $ignore" );
799 $numrowsinserted++;
803 // If any of them fail, we fail overall for this function call
804 // Note that this will be ignored if IGNORE is set
805 if (! $tempres)
806 $res = false;
810 else {
811 // Not multi, just a lone insert
812 if ( $ignore ) {
813 pg_query($this->mConn, "SAVEPOINT $ignore");
816 $sql .= '(' . $this->makeList( $args ) . ')';
817 $res = (bool)$this->query( $sql, $fname, $ignore );
818 if ( $ignore ) {
819 $bar = pg_last_error();
820 if ($bar != false) {
821 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
823 else {
824 pg_query( $this->mConn, "RELEASE $ignore" );
825 $numrowsinserted++;
829 if ( $ignore ) {
830 $olde = error_reporting( $olde );
831 if ($didbegin) {
832 $this->commit();
835 // Set the affected row count for the whole operation
836 $this->mAffectedRows = $numrowsinserted;
838 // IGNORE always returns true
839 return true;
843 return $res;
847 function tableName( $name ) {
848 # Replace reserved words with better ones
849 switch( $name ) {
850 case 'user':
851 return 'mwuser';
852 case 'text':
853 return 'pagecontent';
854 default:
855 return $name;
860 * Return the next in a sequence, save the value for retrieval via insertId()
862 function nextSequenceValue( $seqName ) {
863 $safeseq = preg_replace( "/'/", "''", $seqName );
864 $res = $this->query( "SELECT nextval('$safeseq')" );
865 $row = $this->fetchRow( $res );
866 $this->mInsertId = $row[0];
867 $this->freeResult( $res );
868 return $this->mInsertId;
872 * Return the current value of a sequence. Assumes it has ben nextval'ed in this session.
874 function currentSequenceValue( $seqName ) {
875 $safeseq = preg_replace( "/'/", "''", $seqName );
876 $res = $this->query( "SELECT currval('$safeseq')" );
877 $row = $this->fetchRow( $res );
878 $currval = $row[0];
879 $this->freeResult( $res );
880 return $currval;
884 * Postgres does not have a "USE INDEX" clause, so return an empty string
886 function useIndexClause( $index ) {
887 return '';
890 # REPLACE query wrapper
891 # Postgres simulates this with a DELETE followed by INSERT
892 # $row is the row to insert, an associative array
893 # $uniqueIndexes is an array of indexes. Each element may be either a
894 # field name or an array of field names
896 # It may be more efficient to leave off unique indexes which are unlikely to collide.
897 # However if you do this, you run the risk of encountering errors which wouldn't have
898 # occurred in MySQL
899 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
900 $table = $this->tableName( $table );
902 if (count($rows)==0) {
903 return;
906 # Single row case
907 if ( !is_array( reset( $rows ) ) ) {
908 $rows = array( $rows );
911 foreach( $rows as $row ) {
912 # Delete rows which collide
913 if ( $uniqueIndexes ) {
914 $sql = "DELETE FROM $table WHERE ";
915 $first = true;
916 foreach ( $uniqueIndexes as $index ) {
917 if ( $first ) {
918 $first = false;
919 $sql .= "(";
920 } else {
921 $sql .= ') OR (';
923 if ( is_array( $index ) ) {
924 $first2 = true;
925 foreach ( $index as $col ) {
926 if ( $first2 ) {
927 $first2 = false;
928 } else {
929 $sql .= ' AND ';
931 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
933 } else {
934 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
937 $sql .= ')';
938 $this->query( $sql, $fname );
941 # Now insert the row
942 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
943 $this->makeList( $row, LIST_COMMA ) . ')';
944 $this->query( $sql, $fname );
948 # DELETE where the condition is a join
949 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
950 if ( !$conds ) {
951 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
954 $delTable = $this->tableName( $delTable );
955 $joinTable = $this->tableName( $joinTable );
956 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
957 if ( $conds != '*' ) {
958 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
960 $sql .= ')';
962 $this->query( $sql, $fname );
965 # Returns the size of a text field, or -1 for "unlimited"
966 function textFieldSize( $table, $field ) {
967 $table = $this->tableName( $table );
968 $sql = "SELECT t.typname as ftype,a.atttypmod as size
969 FROM pg_class c, pg_attribute a, pg_type t
970 WHERE relname='$table' AND a.attrelid=c.oid AND
971 a.atttypid=t.oid and a.attname='$field'";
972 $res =$this->query($sql);
973 $row=$this->fetchObject($res);
974 if ($row->ftype=="varchar") {
975 $size=$row->size-4;
976 } else {
977 $size=$row->size;
979 $this->freeResult( $res );
980 return $size;
983 function lowPriorityOption() {
984 return '';
987 function limitResult($sql, $limit, $offset=false) {
988 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
992 * Returns an SQL expression for a simple conditional.
993 * Uses CASE on Postgres
995 * @param string $cond SQL expression which will result in a boolean value
996 * @param string $trueVal SQL expression to return if true
997 * @param string $falseVal SQL expression to return if false
998 * @return string SQL fragment
1000 function conditional( $cond, $trueVal, $falseVal ) {
1001 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1004 function wasDeadlock() {
1005 return $this->lastErrno() == '40P01';
1008 function timestamp( $ts=0 ) {
1009 return wfTimestamp(TS_POSTGRES,$ts);
1013 * Return aggregated value function call
1015 function aggregateValue ($valuedata,$valuename='value') {
1016 return $valuedata;
1020 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1021 // Ignore errors during error handling to avoid infinite recursion
1022 $ignore = $this->ignoreErrors( true );
1023 $this->mErrorCount++;
1025 if ($ignore || $tempIgnore) {
1026 wfDebug("SQL ERROR (ignored): $error\n");
1027 $this->ignoreErrors( $ignore );
1029 else {
1030 $message = "A database error has occurred\n" .
1031 "Query: $sql\n" .
1032 "Function: $fname\n" .
1033 "Error: $errno $error\n";
1034 throw new DBUnexpectedError($this, $message);
1039 * @return string wikitext of a link to the server software's web site
1041 function getSoftwareLink() {
1042 return "[http://www.postgresql.org/ PostgreSQL]";
1046 * @return string Version information from the database
1048 function getServerVersion() {
1049 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
1050 $thisver = array();
1051 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
1052 die("Could not determine the numeric version from $version!");
1054 $version = $thisver[1].$thisver[2];
1055 $this->numeric_version = $thisver[1];
1056 return $version;
1061 * Query whether a given relation exists (in the given schema, or the
1062 * default mw one if not given)
1064 function relationExists( $table, $types, $schema = false ) {
1065 global $wgDBmwschema;
1066 if (!is_array($types))
1067 $types = array($types);
1068 if (! $schema )
1069 $schema = $wgDBmwschema;
1070 $etable = $this->addQuotes($table);
1071 $eschema = $this->addQuotes($schema);
1072 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1073 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1074 . "AND c.relkind IN ('" . implode("','", $types) . "')";
1075 $res = $this->query( $SQL );
1076 $count = $res ? $res->numRows() : 0;
1077 if ($res)
1078 $this->freeResult( $res );
1079 return $count ? true : false;
1083 * For backward compatibility, this function checks both tables and
1084 * views.
1086 function tableExists ($table, $schema = false) {
1087 return $this->relationExists($table, array('r', 'v'), $schema);
1090 function sequenceExists ($sequence, $schema = false) {
1091 return $this->relationExists($sequence, 'S', $schema);
1094 function triggerExists($table, $trigger) {
1095 global $wgDBmwschema;
1097 $q = <<<END
1098 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1099 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1100 AND tgrelid=pg_class.oid
1101 AND nspname=%s AND relname=%s AND tgname=%s
1102 END;
1103 $res = $this->query(sprintf($q,
1104 $this->addQuotes($wgDBmwschema),
1105 $this->addQuotes($table),
1106 $this->addQuotes($trigger)));
1107 if (!$res)
1108 return NULL;
1109 $rows = $res->numRows();
1110 $this->freeResult($res);
1111 return $rows;
1114 function ruleExists($table, $rule) {
1115 global $wgDBmwschema;
1116 $exists = $this->selectField("pg_rules", "rulename",
1117 array( "rulename" => $rule,
1118 "tablename" => $table,
1119 "schemaname" => $wgDBmwschema));
1120 return $exists === $rule;
1123 function constraintExists($table, $constraint) {
1124 global $wgDBmwschema;
1125 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
1126 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1127 $this->addQuotes($wgDBmwschema),
1128 $this->addQuotes($table),
1129 $this->addQuotes($constraint));
1130 $res = $this->query($SQL);
1131 if (!$res)
1132 return NULL;
1133 $rows = $res->numRows();
1134 $this->freeResult($res);
1135 return $rows;
1139 * Query whether a given schema exists. Returns the name of the owner
1141 function schemaExists( $schema ) {
1142 $eschema = preg_replace("/'/", "''", $schema);
1143 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1144 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1145 $res = $this->query( $SQL );
1146 if ( $res && $res->numRows() ) {
1147 $row = $res->fetchObject();
1148 $owner = $row->rolname;
1149 } else {
1150 $owner = false;
1152 if ($res)
1153 $this->freeResult($res);
1154 return $owner;
1158 * Query whether a given column exists in the mediawiki schema
1160 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1161 global $wgDBmwschema;
1162 $etable = preg_replace("/'/", "''", $table);
1163 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1164 $ecol = preg_replace("/'/", "''", $field);
1165 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1166 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1167 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1168 $res = $this->query( $SQL, $fname );
1169 $count = $res ? $res->numRows() : 0;
1170 if ($res)
1171 $this->freeResult( $res );
1172 return $count;
1175 function fieldInfo( $table, $field ) {
1176 return PostgresField::fromText($this, $table, $field);
1180 * pg_field_type() wrapper
1182 function fieldType( $res, $index ) {
1183 if ( $res instanceof ResultWrapper ) {
1184 $res = $res->result;
1186 return pg_field_type( $res, $index );
1189 function begin( $fname = 'DatabasePostgres::begin' ) {
1190 $this->query( 'BEGIN', $fname );
1191 $this->mTrxLevel = 1;
1193 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1194 return true;
1196 function commit( $fname = 'DatabasePostgres::commit' ) {
1197 $this->query( 'COMMIT', $fname );
1198 $this->mTrxLevel = 0;
1201 /* Not even sure why this is used in the main codebase... */
1202 function limitResultForUpdate($sql, $num) {
1203 return $sql;
1206 function setup_database() {
1207 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1209 // Make sure that we can write to the correct schema
1210 // If not, Postgres will happily and silently go to the next search_path item
1211 $ctest = "mediawiki_test_table";
1212 $safeschema = $this->quote_ident($wgDBmwschema);
1213 if ($this->tableExists($ctest, $wgDBmwschema)) {
1214 $this->doQuery("DROP TABLE $safeschema.$ctest");
1216 $SQL = "CREATE TABLE $safeschema.$ctest(a int)";
1217 $olde = error_reporting( 0 );
1218 $res = $this->doQuery($SQL);
1219 error_reporting( $olde );
1220 if (!$res) {
1221 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
1222 dieout("</ul>");
1224 $this->doQuery("DROP TABLE $safeschema.$ctest");
1226 $res = dbsource( "../maintenance/postgres/tables.sql", $this);
1228 ## Update version information
1229 $mwv = $this->addQuotes($wgVersion);
1230 $pgv = $this->addQuotes($this->getServerVersion());
1231 $pgu = $this->addQuotes($this->mUser);
1232 $mws = $this->addQuotes($wgDBmwschema);
1233 $tss = $this->addQuotes($wgDBts2schema);
1234 $pgp = $this->addQuotes($wgDBport);
1235 $dbn = $this->addQuotes($this->mDBname);
1236 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1238 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1239 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1240 "ctype = '$ctype' ".
1241 "WHERE type = 'Creation'";
1242 $this->query($SQL);
1244 ## Avoid the non-standard "REPLACE INTO" syntax
1245 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1246 if ($f == false ) {
1247 dieout( "<li>Could not find the interwiki.sql file");
1249 ## We simply assume it is already empty as we have just created it
1250 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1251 while ( ! feof( $f ) ) {
1252 $line = fgets($f,1024);
1253 $matches = array();
1254 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1255 continue;
1257 $this->query("$SQL $matches[1],$matches[2])");
1259 print " (table interwiki successfully populated)...\n";
1261 $this->doQuery("COMMIT");
1264 function encodeBlob( $b ) {
1265 return new Blob ( pg_escape_bytea( $b ) ) ;
1268 function decodeBlob( $b ) {
1269 if ($b instanceof Blob) {
1270 $b = $b->fetch();
1272 return pg_unescape_bytea( $b );
1275 function strencode( $s ) { ## Should not be called by us
1276 return pg_escape_string( $s );
1279 function addQuotes( $s ) {
1280 if ( is_null( $s ) ) {
1281 return 'NULL';
1282 } else if ( is_bool( $s ) ) {
1283 return intval( $s );
1284 } else if ($s instanceof Blob) {
1285 return "'".$s->fetch($s)."'";
1287 return "'" . pg_escape_string($s) . "'";
1290 function quote_ident( $s ) {
1291 return '"' . preg_replace( '/"/', '""', $s) . '"';
1294 /* For now, does nothing */
1295 function selectDB( $db ) {
1296 return true;
1300 * Postgres specific version of replaceVars.
1301 * Calls the parent version in Database.php
1303 * @private
1305 * @param string $com SQL string, read from a stream (usually tables.sql)
1307 * @return string SQL string
1309 protected function replaceVars( $ins ) {
1311 $ins = parent::replaceVars( $ins );
1313 if ($this->numeric_version >= 8.3) {
1314 // Thanks for not providing backwards-compatibility, 8.3
1315 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1318 if ($this->numeric_version <= 8.1) { // Our minimum version
1319 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1322 return $ins;
1326 * Various select options
1328 * @private
1330 * @param array $options an associative array of options to be turned into
1331 * an SQL query, valid keys are listed in the function.
1332 * @return array
1334 function makeSelectOptions( $options ) {
1335 $preLimitTail = $postLimitTail = '';
1336 $startOpts = $useIndex = '';
1338 $noKeyOptions = array();
1339 foreach ( $options as $key => $option ) {
1340 if ( is_numeric( $key ) ) {
1341 $noKeyOptions[$option] = true;
1345 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1346 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1347 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1349 //if (isset($options['LIMIT'])) {
1350 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1351 // isset($options['OFFSET']) ? $options['OFFSET']
1352 // : false);
1355 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1356 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1357 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1359 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1362 public function setTimeout( $timeout ) {
1363 // @todo fixme no-op
1366 function ping() {
1367 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1368 return true;
1372 * How lagged is this slave?
1375 public function getLag() {
1376 # Not implemented for PostgreSQL
1377 return false;
1380 function setFakeSlaveLag( $lag ) {}
1381 function setFakeMaster( $enabled = true ) {}
1383 function getDBname() {
1384 return $this->mDBname;
1387 function getServer() {
1388 return $this->mServer;
1391 function buildConcat( $stringList ) {
1392 return implode( ' || ', $stringList );
1395 /* These are not used yet, but we know we don't want the default version */
1397 public function lock( $lockName, $method ) {
1398 return true;
1400 public function unlock( $lockName, $method ) {
1401 return true;
1404 public function getSearchEngine() {
1405 return "SearchPostgres";
1408 } // end DatabasePostgres class