* (bug 6976) Add namespace and direction classes to classic skins
[mediawiki.git] / includes / DatabasePostgres.php
blobf96d931c532e200c1f073c5e72ee7cde6ff2f0ae
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 /**
14 * Depends on database
16 require_once( 'Database.php' );
18 class DatabasePostgres extends Database {
19 var $mInsertId = NULL;
20 var $mLastResult = NULL;
22 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
23 $failFunction = false, $flags = 0 )
26 global $wgOut, $wgDBprefix, $wgCommandLineMode;
27 # Can't get a reference if it hasn't been set yet
28 if ( !isset( $wgOut ) ) {
29 $wgOut = NULL;
31 $this->mOut =& $wgOut;
32 $this->mFailFunction = $failFunction;
33 $this->mCascadingDeletes = true;
34 $this->mCleanupTriggers = true;
35 $this->mStrictIPs = true;
36 $this->mFlags = $flags;
37 $this->open( $server, $user, $password, $dbName);
41 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
42 $failFunction = false, $flags = 0)
44 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
47 /**
48 * Usually aborts on failure
49 * If the failFunction is set to a non-zero integer, returns success
51 function open( $server, $user, $password, $dbName ) {
52 # Test for Postgres support, to avoid suppressed fatal error
53 if ( !function_exists( 'pg_connect' ) ) {
54 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" );
58 global $wgDBport;
60 $this->close();
61 $this->mServer = $server;
62 $port = $wgDBport;
63 $this->mUser = $user;
64 $this->mPassword = $password;
65 $this->mDBname = $dbName;
67 $success = false;
68 $hstring="";
69 if ($server!=false && $server!="") {
70 $hstring="host=$server ";
72 if ($port!=false && $port!="") {
73 $hstring .= "port=$port ";
76 if (!strlen($user)) { ## e.g. the class is being loaded
77 return;
80 error_reporting( E_ALL );
81 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
83 if ( $this->mConn == false ) {
84 wfDebug( "DB connection error\n" );
85 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
86 wfDebug( $this->lastError()."\n" );
87 return false;
90 $this->mOpened = true;
91 ## If this is the initial connection, setup the schema stuff and possibly create the user
92 if (defined('MEDIAWIKI_INSTALL')) {
93 global $wgDBname, $wgDBuser, $wgDBpass, $wgDBsuperuser, $wgDBmwschema, $wgDBts2schema;
94 print "OK</li>\n";
96 $safeuser = $this->quote_ident($wgDBuser);
97 ## Are we connecting as a superuser for the first time?
98 if ($wgDBsuperuser) {
99 ## Are we really a superuser? Check out our rights
100 $SQL = "SELECT
101 CASE WHEN usesuper IS TRUE THEN
102 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
103 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
104 END AS rights
105 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
106 $rows = $this->numRows($res = $this->doQuery($SQL));
107 if (!$rows) {
108 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
109 dieout('</ul>');
111 $perms = pg_fetch_result($res, 0, 0);
113 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
114 $rows = $this->numRows($this->doQuery($SQL));
115 if ($rows) {
116 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
118 else {
119 if ($perms != 1 and $perms != 3) {
120 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
121 print 'Please use a different Postgres user.</li>';
122 dieout('</ul>');
124 print "<li>Creating user <b>$wgDBuser</b>...";
125 $safepass = $this->addQuotes($wgDBpass);
126 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
127 $this->doQuery($SQL);
128 print "OK</li>\n";
130 ## User now exists, check out the database
131 if ($dbName != $wgDBname) {
132 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
133 $rows = $this->numRows($this->doQuery($SQL));
134 if ($rows) {
135 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
137 else {
138 if ($perms < 2) {
139 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
140 print 'Please use a different Postgres user.</li>';
141 dieout('</ul>');
143 print "<li>Creating database <b>$wgDBname</b>...";
144 $safename = $this->quote_ident($wgDBname);
145 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
146 $this->doQuery($SQL);
147 print "OK</li>\n";
148 ## Hopefully tsearch2 and plpgsql are in template1...
151 ## Reconnect to check out tsearch2 rights for this user
152 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
153 @$this->mConn = pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
154 if ( $this->mConn == false ) {
155 print "<b>FAILED TO CONNECT!</b></li>";
156 dieout("</ul>");
158 print "OK</li>\n";
161 ## Tsearch2 checks
162 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
163 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
164 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
165 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
166 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
167 dieout("</ul>");
169 print "OK</li>\n";
170 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
171 foreach (array('cfg','cfgmap','dict','parser') as $table) {
172 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
173 $this->doQuery($SQL);
175 print "OK</li>\n";
178 ## Setup the schema for this user if needed
179 $result = $this->schemaExists($wgDBmwschema);
180 $safeschema = $this->quote_ident($wgDBmwschema);
181 if (!$result) {
182 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
183 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
184 if (!$result) {
185 print "<b>FAILED</b>.</li>\n";
186 dieout("</ul>");
188 print "OK</li>\n";
190 else {
191 print "<li>Schema already exists, explicitly granting rights...\n";
192 $safeschema2 = $this->addQuotes($wgDBmwschema);
193 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
194 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
195 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
196 "AND p.relkind IN ('r','S','v')\n";
197 $SQL .= "UNION\n";
198 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
199 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
200 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
201 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
202 $res = $this->doQuery($SQL);
203 if (!$res) {
204 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
205 dieout("</ul>");
207 $this->doQuery("SET search_path = $safeschema");
208 $rows = $this->numRows($res);
209 while ($rows) {
210 $rows--;
211 $this->doQuery(pg_fetch_result($res, $rows, 0));
213 print "OK</li>";
216 $wgDBsuperuser = '';
217 return true; ## Reconnect as regular user
220 if (!defined('POSTGRES_SEARCHPATH')) {
222 ## Do we have the basic tsearch2 table?
223 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
224 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
225 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
226 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
227 print " for instructions.</li>\n";
228 dieout("</ul>");
230 print "OK</li>\n";
232 ## Does this user have the rights to the tsearch2 tables?
233 print "<li>Checking tsearch2 permissions...";
234 $SQL = "SELECT 1 FROM $wgDBts2schema.pg_ts_cfg";
235 error_reporting( 0 );
236 $res = $this->doQuery($SQL);
237 error_reporting( E_ALL );
238 if (!$res) {
239 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
240 dieout("</ul>");
242 print "OK</li>";
244 ## Do we have plpgsql installed?
245 print "<li>Checking for Pl/Pgsql ...";
246 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
247 $rows = $this->numRows($this->doQuery($SQL));
248 if ($rows < 1) {
249 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
250 print "not installed. Attempting to install Pl/Pgsql ...";
251 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
252 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
253 $rows = $this->numRows($this->doQuery($SQL));
254 if ($rows >= 1) {
255 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
256 if (!$result) {
257 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
258 dieout("</ul>");
261 else {
262 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
263 dieout("</ul>");
266 print "OK</li>\n";
268 ## Does the schema already exist? Who owns it?
269 $result = $this->schemaExists($wgDBmwschema);
270 if (!$result) {
271 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
272 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
273 if (!$result) {
274 print "<b>FAILED</b>.</li>\n";
275 dieout("</ul>");
277 print "OK</li>\n";
279 else if ($result != $user) {
280 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
282 else {
283 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
286 ## Fix up the search paths if needed
287 print "<li>Setting the search path for user \"$user\" ...";
288 $path = $this->quote_ident($wgDBmwschema);
289 if ($wgDBts2schema !== $wgDBmwschema)
290 $path .= ", ". $this->quote_ident($wgDBts2schema);
291 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
292 $path .= ", public";
293 $SQL = "ALTER USER $safeuser SET search_path = $path";
294 $result = pg_query($this->mConn, $SQL);
295 if (!$result) {
296 print "<b>FAILED</b>.</li>\n";
297 dieout("</ul>");
299 print "OK</li>\n";
300 ## Set for the rest of this session
301 $SQL = "SET search_path = $path";
302 $result = pg_query($this->mConn, $SQL);
303 if (!$result) {
304 print "<li>Failed to set search_path</li>\n";
305 dieout("</ul>");
307 define( "POSTGRES_SEARCHPATH", $path );
310 global $wgCommandLineMode;
311 ## If called from the command-line (e.g. importDump), only show errors
312 if ($wgCommandLineMode) {
313 $this->doQuery("SET client_min_messages = 'ERROR'");
316 return $this->mConn;
320 * Closes a database connection, if it is open
321 * Returns success, true if already closed
323 function close() {
324 $this->mOpened = false;
325 if ( $this->mConn ) {
326 return pg_close( $this->mConn );
327 } else {
328 return true;
332 function doQuery( $sql ) {
333 return $this->mLastResult=pg_query( $this->mConn , $sql);
336 function queryIgnore( $sql, $fname = '' ) {
337 return $this->query( $sql, $fname, true );
340 function freeResult( $res ) {
341 if ( !@pg_free_result( $res ) ) {
342 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
346 function fetchObject( $res ) {
347 @$row = pg_fetch_object( $res );
348 # FIXME: HACK HACK HACK HACK debug
350 # TODO:
351 # hashar : not sure if the following test really trigger if the object
352 # fetching failled.
353 if( pg_last_error($this->mConn) ) {
354 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
356 return $row;
359 function fetchRow( $res ) {
360 @$row = pg_fetch_array( $res );
361 if( pg_last_error($this->mConn) ) {
362 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
364 return $row;
367 function numRows( $res ) {
368 @$n = pg_num_rows( $res );
369 if( pg_last_error($this->mConn) ) {
370 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
372 return $n;
374 function numFields( $res ) { return pg_num_fields( $res ); }
375 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
378 * This must be called after nextSequenceVal
380 function insertId() {
381 return $this->mInsertId;
384 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
385 function lastError() {
386 if ( $this->mConn ) {
387 return pg_last_error();
389 else {
390 return "No database connection";
393 function lastErrno() {
394 return pg_last_error() ? 1 : 0;
397 function affectedRows() {
398 return pg_affected_rows( $this->mLastResult );
402 * Returns information about an index
403 * If errors are explicitly ignored, returns NULL on failure
405 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
406 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
407 $res = $this->query( $sql, $fname );
408 if ( !$res ) {
409 return NULL;
412 while ( $row = $this->fetchObject( $res ) ) {
413 if ( $row->indexname == $index ) {
414 return $row;
417 return false;
420 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
421 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
422 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
423 $res = $this->query( $sql, $fname );
424 if ( !$res )
425 return NULL;
426 while ($row = $this->fetchObject( $res ))
427 return true;
428 return false;
432 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
433 # Postgres doesn't support options
434 # We have a go at faking one of them
435 # TODO: DELAYED, LOW_PRIORITY
437 if ( !is_array($options))
438 $options = array($options);
440 if ( in_array( 'IGNORE', $options ) )
441 $oldIgnore = $this->ignoreErrors( true );
443 # IGNORE is performed using single-row inserts, ignoring errors in each
444 # FIXME: need some way to distiguish between key collision and other types of error
445 $oldIgnore = $this->ignoreErrors( true );
446 if ( !is_array( reset( $a ) ) ) {
447 $a = array( $a );
449 foreach ( $a as $row ) {
450 parent::insert( $table, $row, $fname, array() );
452 $this->ignoreErrors( $oldIgnore );
453 $retVal = true;
455 if ( in_array( 'IGNORE', $options ) )
456 $this->ignoreErrors( $oldIgnore );
458 return $retVal;
461 function tableName( $name ) {
462 # Replace reserved words with better ones
463 switch( $name ) {
464 case 'user':
465 return 'mwuser';
466 case 'text':
467 return 'pagecontent';
468 default:
469 return $name;
474 * Return the next in a sequence, save the value for retrieval via insertId()
476 function nextSequenceValue( $seqName ) {
477 $safeseq = preg_replace( "/'/", "''", $seqName );
478 $res = $this->query( "SELECT nextval('$safeseq')" );
479 $row = $this->fetchRow( $res );
480 $this->mInsertId = $row[0];
481 $this->freeResult( $res );
482 return $this->mInsertId;
486 * Postgres does not have a "USE INDEX" clause, so return an empty string
488 function useIndexClause( $index ) {
489 return '';
492 # REPLACE query wrapper
493 # Postgres simulates this with a DELETE followed by INSERT
494 # $row is the row to insert, an associative array
495 # $uniqueIndexes is an array of indexes. Each element may be either a
496 # field name or an array of field names
498 # It may be more efficient to leave off unique indexes which are unlikely to collide.
499 # However if you do this, you run the risk of encountering errors which wouldn't have
500 # occurred in MySQL
501 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
502 $table = $this->tableName( $table );
504 if (count($rows)==0) {
505 return;
508 # Single row case
509 if ( !is_array( reset( $rows ) ) ) {
510 $rows = array( $rows );
513 foreach( $rows as $row ) {
514 # Delete rows which collide
515 if ( $uniqueIndexes ) {
516 $sql = "DELETE FROM $table WHERE ";
517 $first = true;
518 foreach ( $uniqueIndexes as $index ) {
519 if ( $first ) {
520 $first = false;
521 $sql .= "(";
522 } else {
523 $sql .= ') OR (';
525 if ( is_array( $index ) ) {
526 $first2 = true;
527 foreach ( $index as $col ) {
528 if ( $first2 ) {
529 $first2 = false;
530 } else {
531 $sql .= ' AND ';
533 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
535 } else {
536 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
539 $sql .= ')';
540 $this->query( $sql, $fname );
543 # Now insert the row
544 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
545 $this->makeList( $row, LIST_COMMA ) . ')';
546 $this->query( $sql, $fname );
550 # DELETE where the condition is a join
551 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
552 if ( !$conds ) {
553 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
556 $delTable = $this->tableName( $delTable );
557 $joinTable = $this->tableName( $joinTable );
558 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
559 if ( $conds != '*' ) {
560 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
562 $sql .= ')';
564 $this->query( $sql, $fname );
567 # Returns the size of a text field, or -1 for "unlimited"
568 function textFieldSize( $table, $field ) {
569 $table = $this->tableName( $table );
570 $sql = "SELECT t.typname as ftype,a.atttypmod as size
571 FROM pg_class c, pg_attribute a, pg_type t
572 WHERE relname='$table' AND a.attrelid=c.oid AND
573 a.atttypid=t.oid and a.attname='$field'";
574 $res =$this->query($sql);
575 $row=$this->fetchObject($res);
576 if ($row->ftype=="varchar") {
577 $size=$row->size-4;
578 } else {
579 $size=$row->size;
581 $this->freeResult( $res );
582 return $size;
585 function lowPriorityOption() {
586 return '';
589 function limitResult($sql, $limit,$offset) {
590 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
594 * Returns an SQL expression for a simple conditional.
595 * Uses CASE on Postgres
597 * @param string $cond SQL expression which will result in a boolean value
598 * @param string $trueVal SQL expression to return if true
599 * @param string $falseVal SQL expression to return if false
600 * @return string SQL fragment
602 function conditional( $cond, $trueVal, $falseVal ) {
603 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
606 # FIXME: actually detecting deadlocks might be nice
607 function wasDeadlock() {
608 return false;
611 function timestamp( $ts=0 ) {
612 return wfTimestamp(TS_POSTGRES,$ts);
616 * Return aggregated value function call
618 function aggregateValue ($valuedata,$valuename='value') {
619 return $valuedata;
623 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
624 $message = "A database error has occurred\n" .
625 "Query: $sql\n" .
626 "Function: $fname\n" .
627 "Error: $errno $error\n";
628 throw new DBUnexpectedError($this, $message);
632 * @return string wikitext of a link to the server software's web site
634 function getSoftwareLink() {
635 return "[http://www.postgresql.org/ PostgreSQL]";
639 * @return string Version information from the database
641 function getServerVersion() {
642 $res = $this->query( "SELECT version()" );
643 $row = $this->fetchRow( $res );
644 $version = $row[0];
645 $this->freeResult( $res );
646 return $version;
651 * Query whether a given table exists (in the given schema, or the default mw one if not given)
653 function tableExists( $table, $schema = false ) {
654 global $wgDBmwschema;
655 if (! $schema )
656 $schema = $wgDBmwschema;
657 $etable = preg_replace("/'/", "''", $table);
658 $eschema = preg_replace("/'/", "''", $schema);
659 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
660 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
661 . "AND c.relkind IN ('r','v')";
662 $res = $this->query( $SQL );
663 $count = $res ? pg_num_rows($res) : 0;
664 if ($res)
665 $this->freeResult( $res );
666 return $count;
671 * Query whether a given schema exists. Returns the name of the owner
673 function schemaExists( $schema ) {
674 $eschema = preg_replace("/'/", "''", $schema);
675 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
676 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
677 $res = $this->query( $SQL );
678 $owner = $res ? pg_num_rows($res) ? pg_fetch_result($res, 0, 0) : false : false;
679 if ($res)
680 $this->freeResult($res);
681 return $owner;
685 * Query whether a given column exists in the mediawiki schema
687 function fieldExists( $table, $field ) {
688 global $wgDBmwschema;
689 $etable = preg_replace("/'/", "''", $table);
690 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
691 $ecol = preg_replace("/'/", "''", $field);
692 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
693 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
694 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
695 $res = $this->query( $SQL );
696 $count = $res ? pg_num_rows($res) : 0;
697 if ($res)
698 $this->freeResult( $res );
699 return $count;
702 function fieldInfo( $table, $field ) {
703 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
704 $type = pg_field_type( $res, 0 );
705 return $type;
708 function begin( $fname = 'DatabasePostgrs::begin' ) {
709 $this->query( 'BEGIN', $fname );
710 $this->mTrxLevel = 1;
712 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
713 return true;
715 function commit( $fname = 'DatabasePostgres::commit' ) {
716 $this->query( 'COMMIT', $fname );
717 $this->mTrxLevel = 0;
720 /* Not even sure why this is used in the main codebase... */
721 function limitResultForUpdate($sql, $num) {
722 return $sql;
725 function setup_database() {
726 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
728 dbsource( "../maintenance/postgres/tables.sql", $this);
730 ## Update version information
731 $mwv = $this->addQuotes($wgVersion);
732 $pgv = $this->addQuotes($this->getServerVersion());
733 $pgu = $this->addQuotes($this->mUser);
734 $mws = $this->addQuotes($wgDBmwschema);
735 $tss = $this->addQuotes($wgDBts2schema);
736 $pgp = $this->addQuotes($wgDBport);
737 $dbn = $this->addQuotes($this->mDBname);
739 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
740 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn ".
741 "WHERE type = 'Creation'";
742 $this->query($SQL);
744 ## Avoid the non-standard "REPLACE INTO" syntax
745 $f = fopen( "../maintenance/interwiki.sql", 'r' );
746 if ($f == false ) {
747 dieout( "<li>Could not find the interwiki.sql file");
749 ## We simply assume it is already empty as we have just created it
750 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
751 while ( ! feof( $f ) ) {
752 $line = fgets($f,1024);
753 if (!preg_match("/^\s*(\(.+?),(\d)\)/", $line, $matches)) {
754 continue;
756 $yesno = $matches[2]; ## ? "'true'" : "'false'";
757 $this->query("$SQL $matches[1],$matches[2])");
759 print " (table interwiki successfully populated)...\n";
762 function encodeBlob($b) {
763 return array('bytea',pg_escape_bytea($b));
765 function decodeBlob($b) {
766 return pg_unescape_bytea( $b );
769 function strencode( $s ) { ## Should not be called by us
770 return pg_escape_string( $s );
773 function addQuotes( $s ) {
774 if ( is_null( $s ) ) {
775 return 'NULL';
776 } else if (is_array( $s )) { ## Assume it is bytea data
777 return "E'$s[1]'";
779 return "'" . pg_escape_string($s) . "'";
780 return "E'" . pg_escape_string($s) . "'";
783 function quote_ident( $s ) {
784 return '"' . preg_replace( '/"/', '""', $s) . '"';