(bug 7589) Update to Indonesian localisation (id) #38; updating the release notes
[mediawiki.git] / includes / DatabasePostgres.php
bloba5e02e77f2b1cad2e2a0998b51e6d4925a16b559
1 <?php
3 /**
4 * This is 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
8 * Database class.
10 * @package MediaWiki
13 class DatabasePostgres extends Database {
14 var $mInsertId = NULL;
15 var $mLastResult = NULL;
17 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
18 $failFunction = false, $flags = 0 )
21 global $wgOut, $wgDBprefix, $wgCommandLineMode;
22 # Can't get a reference if it hasn't been set yet
23 if ( !isset( $wgOut ) ) {
24 $wgOut = NULL;
26 $this->mOut =& $wgOut;
27 $this->mFailFunction = $failFunction;
28 $this->mCascadingDeletes = true;
29 $this->mCleanupTriggers = true;
30 $this->mStrictIPs = true;
31 $this->mFlags = $flags;
32 $this->open( $server, $user, $password, $dbName);
36 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
37 $failFunction = false, $flags = 0)
39 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
42 /**
43 * Usually aborts on failure
44 * If the failFunction is set to a non-zero integer, returns success
46 function open( $server, $user, $password, $dbName ) {
47 # Test for Postgres support, to avoid suppressed fatal error
48 if ( !function_exists( 'pg_connect' ) ) {
49 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" );
53 global $wgDBport;
55 $this->close();
56 $this->mServer = $server;
57 $port = $wgDBport;
58 $this->mUser = $user;
59 $this->mPassword = $password;
60 $this->mDBname = $dbName;
62 $success = false;
63 $hstring="";
64 if ($server!=false && $server!="") {
65 $hstring="host=$server ";
67 if ($port!=false && $port!="") {
68 $hstring .= "port=$port ";
71 if (!strlen($user)) { ## e.g. the class is being loaded
72 return;
75 error_reporting( E_ALL );
76 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
78 if ( $this->mConn == false ) {
79 wfDebug( "DB connection error\n" );
80 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
81 wfDebug( $this->lastError()."\n" );
82 return false;
85 $this->mOpened = true;
86 ## If this is the initial connection, setup the schema stuff and possibly create the user
87 if (defined('MEDIAWIKI_INSTALL')) {
88 global $wgDBname, $wgDBuser, $wgDBpass, $wgDBsuperuser, $wgDBmwschema,
89 $wgDBts2schema, $wgDBts2locale;
90 print "OK</li>\n";
92 print "<li>Checking the version of Postgres...";
93 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
94 if (!preg_match("/PostgreSQL (\d+\.\d+)(\S+)/", $version, $thisver)) {
95 print "<b>FAILED</b> (could not determine the version)</li>\n";
96 dieout("</ul>");
98 $PGMINVER = "8.1";
99 if ($thisver[1] < $PGMINVER) {
100 print "<b>FAILED</b>. Required version is $PGMINVER. You have $thisver[1]$thisver[2]</li>\n";
101 dieout("</ul>");
103 print "version $thisver[1]$thisver[2] is OK.</li>\n";
105 $safeuser = $this->quote_ident($wgDBuser);
106 ## Are we connecting as a superuser for the first time?
107 if ($wgDBsuperuser) {
108 ## Are we really a superuser? Check out our rights
109 $SQL = "SELECT
110 CASE WHEN usesuper IS TRUE THEN
111 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
112 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
113 END AS rights
114 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
115 $rows = $this->numRows($res = $this->doQuery($SQL));
116 if (!$rows) {
117 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
118 dieout('</ul>');
120 $perms = pg_fetch_result($res, 0, 0);
122 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
123 $rows = $this->numRows($this->doQuery($SQL));
124 if ($rows) {
125 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
127 else {
128 if ($perms != 1 and $perms != 3) {
129 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
130 print 'Please use a different Postgres user.</li>';
131 dieout('</ul>');
133 print "<li>Creating user <b>$wgDBuser</b>...";
134 $safepass = $this->addQuotes($wgDBpass);
135 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
136 $this->doQuery($SQL);
137 print "OK</li>\n";
139 ## User now exists, check out the database
140 if ($dbName != $wgDBname) {
141 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
142 $rows = $this->numRows($this->doQuery($SQL));
143 if ($rows) {
144 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
146 else {
147 if ($perms < 2) {
148 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
149 print 'Please use a different Postgres user.</li>';
150 dieout('</ul>');
152 print "<li>Creating database <b>$wgDBname</b>...";
153 $safename = $this->quote_ident($wgDBname);
154 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
155 $this->doQuery($SQL);
156 print "OK</li>\n";
157 ## Hopefully tsearch2 and plpgsql are in template1...
160 ## Reconnect to check out tsearch2 rights for this user
161 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
162 @$this->mConn = pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
163 if ( $this->mConn == false ) {
164 print "<b>FAILED TO CONNECT!</b></li>";
165 dieout("</ul>");
167 print "OK</li>\n";
170 ## Tsearch2 checks
171 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
172 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
173 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
174 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
175 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
176 dieout("</ul>");
178 print "OK</li>\n";
179 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
180 foreach (array('cfg','cfgmap','dict','parser') as $table) {
181 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
182 $this->doQuery($SQL);
184 print "OK</li>\n";
187 ## Setup the schema for this user if needed
188 $result = $this->schemaExists($wgDBmwschema);
189 $safeschema = $this->quote_ident($wgDBmwschema);
190 if (!$result) {
191 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
192 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
193 if (!$result) {
194 print "<b>FAILED</b>.</li>\n";
195 dieout("</ul>");
197 print "OK</li>\n";
199 else {
200 print "<li>Schema already exists, explicitly granting rights...\n";
201 $safeschema2 = $this->addQuotes($wgDBmwschema);
202 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
203 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
204 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
205 "AND p.relkind IN ('r','S','v')\n";
206 $SQL .= "UNION\n";
207 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
208 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
209 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
210 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
211 $res = $this->doQuery($SQL);
212 if (!$res) {
213 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
214 dieout("</ul>");
216 $this->doQuery("SET search_path = $safeschema");
217 $rows = $this->numRows($res);
218 while ($rows) {
219 $rows--;
220 $this->doQuery(pg_fetch_result($res, $rows, 0));
222 print "OK</li>";
225 $wgDBsuperuser = '';
226 return true; ## Reconnect as regular user
229 if (!defined('POSTGRES_SEARCHPATH')) {
231 ## Do we have the basic tsearch2 table?
232 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
233 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
234 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
235 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
236 print " for instructions.</li>\n";
237 dieout("</ul>");
239 print "OK</li>\n";
241 ## Does this user have the rights to the tsearch2 tables?
242 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
243 print "<li>Checking tsearch2 permissions...";
244 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
245 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
246 error_reporting( 0 );
247 $res = $this->doQuery($SQL);
248 error_reporting( E_ALL );
249 if (!$res) {
250 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
251 dieout("</ul>");
253 print "OK</li>";
255 ## Will the current locale work? Can we force it to?
256 print "<li>Verifying tsearch2 locale with $ctype...";
257 $rows = $this->numRows($res);
258 $resetlocale = 0;
259 if (!$rows) {
260 print "<b>not found</b></li>\n";
261 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
262 $resetlocale = 1;
264 else {
265 $tsname = pg_fetch_result($res, 0, 0);
266 if ($tsname != 'default') {
267 print "<b>not set to default ($tsname)</b>";
268 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
269 $resetlocale = 1;
272 if ($resetlocale) {
273 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
274 $res = $this->doQuery($SQL);
275 if (!$res) {
276 print "<b>FAILED</b>. ";
277 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"ctype\"</li>\n";
278 dieout("</ul>");
280 print "OK</li>";
283 ## Final test: try out a simple tsearch2 query
284 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
285 $res = $this->doQuery($SQL);
286 if (!$res) {
287 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
288 dieout("</ul>");
290 print "OK</li>";
292 ## Do we have plpgsql installed?
293 print "<li>Checking for Pl/Pgsql ...";
294 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
295 $rows = $this->numRows($this->doQuery($SQL));
296 if ($rows < 1) {
297 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
298 print "not installed. Attempting to install Pl/Pgsql ...";
299 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
300 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
301 $rows = $this->numRows($this->doQuery($SQL));
302 if ($rows >= 1) {
303 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
304 if (!$result) {
305 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
306 dieout("</ul>");
309 else {
310 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
311 dieout("</ul>");
314 print "OK</li>\n";
316 ## Does the schema already exist? Who owns it?
317 $result = $this->schemaExists($wgDBmwschema);
318 if (!$result) {
319 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
320 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
321 if (!$result) {
322 print "<b>FAILED</b>.</li>\n";
323 dieout("</ul>");
325 print "OK</li>\n";
327 else if ($result != $user) {
328 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
330 else {
331 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
334 ## Fix up the search paths if needed
335 print "<li>Setting the search path for user \"$user\" ...";
336 $path = $this->quote_ident($wgDBmwschema);
337 if ($wgDBts2schema !== $wgDBmwschema)
338 $path .= ", ". $this->quote_ident($wgDBts2schema);
339 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
340 $path .= ", public";
341 $SQL = "ALTER USER $safeuser SET search_path = $path";
342 $result = pg_query($this->mConn, $SQL);
343 if (!$result) {
344 print "<b>FAILED</b>.</li>\n";
345 dieout("</ul>");
347 print "OK</li>\n";
348 ## Set for the rest of this session
349 $SQL = "SET search_path = $path";
350 $result = pg_query($this->mConn, $SQL);
351 if (!$result) {
352 print "<li>Failed to set search_path</li>\n";
353 dieout("</ul>");
355 define( "POSTGRES_SEARCHPATH", $path );
358 global $wgCommandLineMode;
359 ## If called from the command-line (e.g. importDump), only show errors
360 if ($wgCommandLineMode) {
361 $this->doQuery("SET client_min_messages = 'ERROR'");
364 return $this->mConn;
368 * Closes a database connection, if it is open
369 * Returns success, true if already closed
371 function close() {
372 $this->mOpened = false;
373 if ( $this->mConn ) {
374 return pg_close( $this->mConn );
375 } else {
376 return true;
380 function doQuery( $sql ) {
381 return $this->mLastResult=pg_query( $this->mConn , $sql);
384 function queryIgnore( $sql, $fname = '' ) {
385 return $this->query( $sql, $fname, true );
388 function freeResult( $res ) {
389 if ( !@pg_free_result( $res ) ) {
390 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
394 function fetchObject( $res ) {
395 @$row = pg_fetch_object( $res );
396 # FIXME: HACK HACK HACK HACK debug
398 # TODO:
399 # hashar : not sure if the following test really trigger if the object
400 # fetching failled.
401 if( pg_last_error($this->mConn) ) {
402 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
404 return $row;
407 function fetchRow( $res ) {
408 @$row = pg_fetch_array( $res );
409 if( pg_last_error($this->mConn) ) {
410 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
412 return $row;
415 function numRows( $res ) {
416 @$n = pg_num_rows( $res );
417 if( pg_last_error($this->mConn) ) {
418 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
420 return $n;
422 function numFields( $res ) { return pg_num_fields( $res ); }
423 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
426 * This must be called after nextSequenceVal
428 function insertId() {
429 return $this->mInsertId;
432 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
433 function lastError() {
434 if ( $this->mConn ) {
435 return pg_last_error();
437 else {
438 return "No database connection";
441 function lastErrno() {
442 return pg_last_error() ? 1 : 0;
445 function affectedRows() {
446 return pg_affected_rows( $this->mLastResult );
450 * Returns information about an index
451 * If errors are explicitly ignored, returns NULL on failure
453 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
454 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
455 $res = $this->query( $sql, $fname );
456 if ( !$res ) {
457 return NULL;
460 while ( $row = $this->fetchObject( $res ) ) {
461 if ( $row->indexname == $index ) {
462 return $row;
465 return false;
468 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
469 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
470 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
471 $res = $this->query( $sql, $fname );
472 if ( !$res )
473 return NULL;
474 while ($row = $this->fetchObject( $res ))
475 return true;
476 return false;
480 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
481 # Postgres doesn't support options
482 # We have a go at faking one of them
483 # TODO: DELAYED, LOW_PRIORITY
485 if ( !is_array($options))
486 $options = array($options);
488 if ( in_array( 'IGNORE', $options ) )
489 $oldIgnore = $this->ignoreErrors( true );
491 # IGNORE is performed using single-row inserts, ignoring errors in each
492 # FIXME: need some way to distiguish between key collision and other types of error
493 $oldIgnore = $this->ignoreErrors( true );
494 if ( !is_array( reset( $a ) ) ) {
495 $a = array( $a );
497 foreach ( $a as $row ) {
498 parent::insert( $table, $row, $fname, array() );
500 $this->ignoreErrors( $oldIgnore );
501 $retVal = true;
503 if ( in_array( 'IGNORE', $options ) )
504 $this->ignoreErrors( $oldIgnore );
506 return $retVal;
509 function tableName( $name ) {
510 # Replace reserved words with better ones
511 switch( $name ) {
512 case 'user':
513 return 'mwuser';
514 case 'text':
515 return 'pagecontent';
516 default:
517 return $name;
522 * Return the next in a sequence, save the value for retrieval via insertId()
524 function nextSequenceValue( $seqName ) {
525 $safeseq = preg_replace( "/'/", "''", $seqName );
526 $res = $this->query( "SELECT nextval('$safeseq')" );
527 $row = $this->fetchRow( $res );
528 $this->mInsertId = $row[0];
529 $this->freeResult( $res );
530 return $this->mInsertId;
534 * Postgres does not have a "USE INDEX" clause, so return an empty string
536 function useIndexClause( $index ) {
537 return '';
540 # REPLACE query wrapper
541 # Postgres simulates this with a DELETE followed by INSERT
542 # $row is the row to insert, an associative array
543 # $uniqueIndexes is an array of indexes. Each element may be either a
544 # field name or an array of field names
546 # It may be more efficient to leave off unique indexes which are unlikely to collide.
547 # However if you do this, you run the risk of encountering errors which wouldn't have
548 # occurred in MySQL
549 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
550 $table = $this->tableName( $table );
552 if (count($rows)==0) {
553 return;
556 # Single row case
557 if ( !is_array( reset( $rows ) ) ) {
558 $rows = array( $rows );
561 foreach( $rows as $row ) {
562 # Delete rows which collide
563 if ( $uniqueIndexes ) {
564 $sql = "DELETE FROM $table WHERE ";
565 $first = true;
566 foreach ( $uniqueIndexes as $index ) {
567 if ( $first ) {
568 $first = false;
569 $sql .= "(";
570 } else {
571 $sql .= ') OR (';
573 if ( is_array( $index ) ) {
574 $first2 = true;
575 foreach ( $index as $col ) {
576 if ( $first2 ) {
577 $first2 = false;
578 } else {
579 $sql .= ' AND ';
581 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
583 } else {
584 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
587 $sql .= ')';
588 $this->query( $sql, $fname );
591 # Now insert the row
592 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
593 $this->makeList( $row, LIST_COMMA ) . ')';
594 $this->query( $sql, $fname );
598 # DELETE where the condition is a join
599 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
600 if ( !$conds ) {
601 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
604 $delTable = $this->tableName( $delTable );
605 $joinTable = $this->tableName( $joinTable );
606 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
607 if ( $conds != '*' ) {
608 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
610 $sql .= ')';
612 $this->query( $sql, $fname );
615 # Returns the size of a text field, or -1 for "unlimited"
616 function textFieldSize( $table, $field ) {
617 $table = $this->tableName( $table );
618 $sql = "SELECT t.typname as ftype,a.atttypmod as size
619 FROM pg_class c, pg_attribute a, pg_type t
620 WHERE relname='$table' AND a.attrelid=c.oid AND
621 a.atttypid=t.oid and a.attname='$field'";
622 $res =$this->query($sql);
623 $row=$this->fetchObject($res);
624 if ($row->ftype=="varchar") {
625 $size=$row->size-4;
626 } else {
627 $size=$row->size;
629 $this->freeResult( $res );
630 return $size;
633 function lowPriorityOption() {
634 return '';
637 function limitResult($sql, $limit,$offset) {
638 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
642 * Returns an SQL expression for a simple conditional.
643 * Uses CASE on Postgres
645 * @param string $cond SQL expression which will result in a boolean value
646 * @param string $trueVal SQL expression to return if true
647 * @param string $falseVal SQL expression to return if false
648 * @return string SQL fragment
650 function conditional( $cond, $trueVal, $falseVal ) {
651 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
654 # FIXME: actually detecting deadlocks might be nice
655 function wasDeadlock() {
656 return false;
659 function timestamp( $ts=0 ) {
660 return wfTimestamp(TS_POSTGRES,$ts);
664 * Return aggregated value function call
666 function aggregateValue ($valuedata,$valuename='value') {
667 return $valuedata;
671 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
672 $message = "A database error has occurred\n" .
673 "Query: $sql\n" .
674 "Function: $fname\n" .
675 "Error: $errno $error\n";
676 throw new DBUnexpectedError($this, $message);
680 * @return string wikitext of a link to the server software's web site
682 function getSoftwareLink() {
683 return "[http://www.postgresql.org/ PostgreSQL]";
687 * @return string Version information from the database
689 function getServerVersion() {
690 $res = $this->query( "SELECT version()" );
691 $row = $this->fetchRow( $res );
692 $version = $row[0];
693 $this->freeResult( $res );
694 return $version;
699 * Query whether a given table exists (in the given schema, or the default mw one if not given)
701 function tableExists( $table, $schema = false ) {
702 global $wgDBmwschema;
703 if (! $schema )
704 $schema = $wgDBmwschema;
705 $etable = preg_replace("/'/", "''", $table);
706 $eschema = preg_replace("/'/", "''", $schema);
707 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
708 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
709 . "AND c.relkind IN ('r','v')";
710 $res = $this->query( $SQL );
711 $count = $res ? pg_num_rows($res) : 0;
712 if ($res)
713 $this->freeResult( $res );
714 return $count;
719 * Query whether a given schema exists. Returns the name of the owner
721 function schemaExists( $schema ) {
722 $eschema = preg_replace("/'/", "''", $schema);
723 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
724 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
725 $res = $this->query( $SQL );
726 $owner = $res ? pg_num_rows($res) ? pg_fetch_result($res, 0, 0) : false : false;
727 if ($res)
728 $this->freeResult($res);
729 return $owner;
733 * Query whether a given column exists in the mediawiki schema
735 function fieldExists( $table, $field ) {
736 global $wgDBmwschema;
737 $etable = preg_replace("/'/", "''", $table);
738 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
739 $ecol = preg_replace("/'/", "''", $field);
740 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
741 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
742 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
743 $res = $this->query( $SQL );
744 $count = $res ? pg_num_rows($res) : 0;
745 if ($res)
746 $this->freeResult( $res );
747 return $count;
750 function fieldInfo( $table, $field ) {
751 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
752 $type = pg_field_type( $res, 0 );
753 return $type;
756 function begin( $fname = 'DatabasePostgrs::begin' ) {
757 $this->query( 'BEGIN', $fname );
758 $this->mTrxLevel = 1;
760 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
761 return true;
763 function commit( $fname = 'DatabasePostgres::commit' ) {
764 $this->query( 'COMMIT', $fname );
765 $this->mTrxLevel = 0;
768 /* Not even sure why this is used in the main codebase... */
769 function limitResultForUpdate($sql, $num) {
770 return $sql;
773 function setup_database() {
774 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
776 dbsource( "../maintenance/postgres/tables.sql", $this);
778 ## Update version information
779 $mwv = $this->addQuotes($wgVersion);
780 $pgv = $this->addQuotes($this->getServerVersion());
781 $pgu = $this->addQuotes($this->mUser);
782 $mws = $this->addQuotes($wgDBmwschema);
783 $tss = $this->addQuotes($wgDBts2schema);
784 $pgp = $this->addQuotes($wgDBport);
785 $dbn = $this->addQuotes($this->mDBname);
786 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
788 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
789 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
790 "ctype = '$ctype' ".
791 "WHERE type = 'Creation'";
792 $this->query($SQL);
794 ## Avoid the non-standard "REPLACE INTO" syntax
795 $f = fopen( "../maintenance/interwiki.sql", 'r' );
796 if ($f == false ) {
797 dieout( "<li>Could not find the interwiki.sql file");
799 ## We simply assume it is already empty as we have just created it
800 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
801 while ( ! feof( $f ) ) {
802 $line = fgets($f,1024);
803 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
804 continue;
806 $yesno = $matches[2]; ## ? "'true'" : "'false'";
807 $this->query("$SQL $matches[1],$matches[2])");
809 print " (table interwiki successfully populated)...\n";
812 function encodeBlob($b) {
813 return array('bytea',pg_escape_bytea($b));
815 function decodeBlob($b) {
816 return pg_unescape_bytea( $b );
819 function strencode( $s ) { ## Should not be called by us
820 return pg_escape_string( $s );
823 function addQuotes( $s ) {
824 if ( is_null( $s ) ) {
825 return 'NULL';
826 } else if (is_array( $s )) { ## Assume it is bytea data
827 return "E'$s[1]'";
829 return "'" . pg_escape_string($s) . "'";
830 return "E'" . pg_escape_string($s) . "'";
833 function quote_ident( $s ) {
834 return '"' . preg_replace( '/"/', '""', $s) . '"';