* (bug 8437) Make Title::loadRestrictions() initialise $mRestrictions properly
[lhc/web/wiklou.git] / includes / DatabasePostgres.php
1 <?php
2
3 /**
4 * This is the Postgres database abstraction layer.
5 *
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.
9 *
10 * @package MediaWiki
11 */
12
13 class DatabasePostgres extends Database {
14 var $mInsertId = NULL;
15 var $mLastResult = NULL;
16
17 function DatabasePostgres($server = false, $user = false, $password = false, $dbName = false,
18 $failFunction = false, $flags = 0 )
19 {
20
21 global $wgOut;
22 # Can't get a reference if it hasn't been set yet
23 if ( !isset( $wgOut ) ) {
24 $wgOut = NULL;
25 }
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);
33
34 }
35
36 function realTimestamps() {
37 return true;
38 }
39
40 static function newFromParams( $server = false, $user = false, $password = false, $dbName = false,
41 $failFunction = false, $flags = 0)
42 {
43 return new DatabasePostgres( $server, $user, $password, $dbName, $failFunction, $flags );
44 }
45
46 /**
47 * Usually aborts on failure
48 * If the failFunction is set to a non-zero integer, returns success
49 */
50 function open( $server, $user, $password, $dbName ) {
51 # Test for Postgres support, to avoid suppressed fatal error
52 if ( !function_exists( 'pg_connect' ) ) {
53 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" );
54 }
55
56
57 global $wgDBport;
58
59 $this->close();
60 $this->mServer = $server;
61 $port = $wgDBport;
62 $this->mUser = $user;
63 $this->mPassword = $password;
64 $this->mDBname = $dbName;
65
66 $hstring="";
67 if ($server!=false && $server!="") {
68 $hstring="host=$server ";
69 }
70 if ($port!=false && $port!="") {
71 $hstring .= "port=$port ";
72 }
73
74 if (!strlen($user)) { ## e.g. the class is being loaded
75 return;
76 }
77
78 error_reporting( E_ALL );
79 @$this->mConn = pg_connect("$hstring dbname=$dbName user=$user password=$password");
80
81 if ( $this->mConn == false ) {
82 wfDebug( "DB connection error\n" );
83 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
84 wfDebug( $this->lastError()."\n" );
85 return false;
86 }
87
88 $this->mOpened = true;
89 ## If this is the initial connection, setup the schema stuff and possibly create the user
90 if (defined('MEDIAWIKI_INSTALL')) {
91 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBsuperuser, $wgDBmwschema,
92 $wgDBts2schema;
93 print "OK</li>\n";
94
95 print "<li>Checking the version of Postgres...";
96 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
97 $thisver = array();
98 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
99 print "<b>FAILED</b> (could not determine the version)</li>\n";
100 dieout("</ul>");
101 }
102 $PGMINVER = "8.1";
103 if ($thisver[1] < $PGMINVER) {
104 print "<b>FAILED</b>. Required version is $PGMINVER. You have $thisver[1]$thisver[2]</li>\n";
105 dieout("</ul>");
106 }
107 print "version $thisver[1]$thisver[2] is OK.</li>\n";
108
109 $safeuser = $this->quote_ident($wgDBuser);
110 ## Are we connecting as a superuser for the first time?
111 if ($wgDBsuperuser) {
112 ## Are we really a superuser? Check out our rights
113 $SQL = "SELECT
114 CASE WHEN usesuper IS TRUE THEN
115 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
116 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
117 END AS rights
118 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBsuperuser);
119 $rows = $this->numRows($res = $this->doQuery($SQL));
120 if (!$rows) {
121 print "<li>ERROR: Could not read permissions for user \"$wgDBsuperuser\"</li>\n";
122 dieout('</ul>');
123 }
124 $perms = pg_fetch_result($res, 0, 0);
125
126 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes($wgDBuser);
127 $rows = $this->numRows($this->doQuery($SQL));
128 if ($rows) {
129 print "<li>User \"$wgDBuser\" already exists, skipping account creation.</li>";
130 }
131 else {
132 if ($perms != 1 and $perms != 3) {
133 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create other users. ";
134 print 'Please use a different Postgres user.</li>';
135 dieout('</ul>');
136 }
137 print "<li>Creating user <b>$wgDBuser</b>...";
138 $safepass = $this->addQuotes($wgDBpassword);
139 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
140 $this->doQuery($SQL);
141 print "OK</li>\n";
142 }
143 ## User now exists, check out the database
144 if ($dbName != $wgDBname) {
145 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes($wgDBname);
146 $rows = $this->numRows($this->doQuery($SQL));
147 if ($rows) {
148 print "<li>Database \"$wgDBname\" already exists, skipping database creation.</li>";
149 }
150 else {
151 if ($perms < 2) {
152 print "<li>ERROR: the user \"$wgDBsuperuser\" cannot create databases. ";
153 print 'Please use a different Postgres user.</li>';
154 dieout('</ul>');
155 }
156 print "<li>Creating database <b>$wgDBname</b>...";
157 $safename = $this->quote_ident($wgDBname);
158 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
159 $this->doQuery($SQL);
160 print "OK</li>\n";
161 ## Hopefully tsearch2 and plpgsql are in template1...
162 }
163
164 ## Reconnect to check out tsearch2 rights for this user
165 print "<li>Connecting to \"$wgDBname\" as superuser \"$wgDBsuperuser\" to check rights...";
166 @$this->mConn = pg_connect("$hstring dbname=$wgDBname user=$user password=$password");
167 if ( $this->mConn == false ) {
168 print "<b>FAILED TO CONNECT!</b></li>";
169 dieout("</ul>");
170 }
171 print "OK</li>\n";
172 }
173
174 ## Tsearch2 checks
175 print "<li>Checking that tsearch2 is installed in the database \"$wgDBname\"...";
176 if (! $this->tableExists("pg_ts_cfg", $wgDBts2schema)) {
177 print "<b>FAILED</b>. tsearch2 must be installed in the database \"$wgDBname\".";
178 print "Please see <a href='http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
179 print " for instructions or ask on #postgresql on irc.freenode.net</li>\n";
180 dieout("</ul>");
181 }
182 print "OK</li>\n";
183 print "<li>Ensuring that user \"$wgDBuser\" has select rights on the tsearch2 tables...";
184 foreach (array('cfg','cfgmap','dict','parser') as $table) {
185 $SQL = "GRANT SELECT ON pg_ts_$table TO $safeuser";
186 $this->doQuery($SQL);
187 }
188 print "OK</li>\n";
189
190
191 ## Setup the schema for this user if needed
192 $result = $this->schemaExists($wgDBmwschema);
193 $safeschema = $this->quote_ident($wgDBmwschema);
194 if (!$result) {
195 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
196 $result = $this->doQuery("CREATE SCHEMA $safeschema AUTHORIZATION $safeuser");
197 if (!$result) {
198 print "<b>FAILED</b>.</li>\n";
199 dieout("</ul>");
200 }
201 print "OK</li>\n";
202 }
203 else {
204 print "<li>Schema already exists, explicitly granting rights...\n";
205 $safeschema2 = $this->addQuotes($wgDBmwschema);
206 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
207 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
208 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
209 "AND p.relkind IN ('r','S','v')\n";
210 $SQL .= "UNION\n";
211 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
212 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
213 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
214 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
215 $res = $this->doQuery($SQL);
216 if (!$res) {
217 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
218 dieout("</ul>");
219 }
220 $this->doQuery("SET search_path = $safeschema");
221 $rows = $this->numRows($res);
222 while ($rows) {
223 $rows--;
224 $this->doQuery(pg_fetch_result($res, $rows, 0));
225 }
226 print "OK</li>";
227 }
228
229 $wgDBsuperuser = '';
230 return true; ## Reconnect as regular user
231 }
232
233 if (!defined('POSTGRES_SEARCHPATH')) {
234
235 ## Do we have the basic tsearch2 table?
236 print "<li>Checking for tsearch2 in the schema \"$wgDBts2schema\"...";
237 if (! $this->tableExists("pg_ts_dict", $wgDBts2schema)) {
238 print "<b>FAILED</b>. Make sure tsearch2 is installed. See <a href=";
239 print "'http://www.devx.com/opensource/Article/21674/0/page/2'>this article</a>";
240 print " for instructions.</li>\n";
241 dieout("</ul>");
242 }
243 print "OK</li>\n";
244
245 ## Does this user have the rights to the tsearch2 tables?
246 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
247 print "<li>Checking tsearch2 permissions...";
248 $SQL = "SELECT ts_name FROM $wgDBts2schema.pg_ts_cfg WHERE locale = '$ctype'";
249 $SQL .= " ORDER BY CASE WHEN ts_name <> 'default' THEN 1 ELSE 0 END";
250 error_reporting( 0 );
251 $res = $this->doQuery($SQL);
252 error_reporting( E_ALL );
253 if (!$res) {
254 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" has SELECT access to the tsearch2 tables</li>\n";
255 dieout("</ul>");
256 }
257 print "OK</li>";
258
259 ## Will the current locale work? Can we force it to?
260 print "<li>Verifying tsearch2 locale with $ctype...";
261 $rows = $this->numRows($res);
262 $resetlocale = 0;
263 if (!$rows) {
264 print "<b>not found</b></li>\n";
265 print "<li>Attempting to set default tsearch2 locale to \"$ctype\"...";
266 $resetlocale = 1;
267 }
268 else {
269 $tsname = pg_fetch_result($res, 0, 0);
270 if ($tsname != 'default') {
271 print "<b>not set to default ($tsname)</b>";
272 print "<li>Attempting to change tsearch2 default locale to \"$ctype\"...";
273 $resetlocale = 1;
274 }
275 }
276 if ($resetlocale) {
277 $SQL = "UPDATE $wgDBts2schema.pg_ts_cfg SET locale = '$ctype' WHERE ts_name = 'default'";
278 $res = $this->doQuery($SQL);
279 if (!$res) {
280 print "<b>FAILED</b>. ";
281 print "Please make sure that the locale in pg_ts_cfg for \"default\" is set to \"ctype\"</li>\n";
282 dieout("</ul>");
283 }
284 print "OK</li>";
285 }
286
287 ## Final test: try out a simple tsearch2 query
288 $SQL = "SELECT $wgDBts2schema.to_tsvector('default','MediaWiki tsearch2 testing')";
289 $res = $this->doQuery($SQL);
290 if (!$res) {
291 print "<b>FAILED</b>. Specifically, \"$SQL\" did not work.</li>";
292 dieout("</ul>");
293 }
294 print "OK</li>";
295
296 ## Do we have plpgsql installed?
297 print "<li>Checking for Pl/Pgsql ...";
298 $SQL = "SELECT 1 FROM pg_catalog.pg_language WHERE lanname = 'plpgsql'";
299 $rows = $this->numRows($this->doQuery($SQL));
300 if ($rows < 1) {
301 // plpgsql is not installed, but if we have a pg_pltemplate table, we should be able to create it
302 print "not installed. Attempting to install Pl/Pgsql ...";
303 $SQL = "SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace) ".
304 "WHERE relname = 'pg_pltemplate' AND nspname='pg_catalog'";
305 $rows = $this->numRows($this->doQuery($SQL));
306 if ($rows >= 1) {
307 $result = $this->doQuery("CREATE LANGUAGE plpgsql");
308 if (!$result) {
309 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
310 dieout("</ul>");
311 }
312 }
313 else {
314 print "<b>FAILED</b>. You need to install the language plpgsql in the database <tt>$wgDBname</tt></li>";
315 dieout("</ul>");
316 }
317 }
318 print "OK</li>\n";
319
320 ## Does the schema already exist? Who owns it?
321 $result = $this->schemaExists($wgDBmwschema);
322 if (!$result) {
323 print "<li>Creating schema <b>$wgDBmwschema</b> ...";
324 $result = $this->doQuery("CREATE SCHEMA $wgDBmwschema");
325 if (!$result) {
326 print "<b>FAILED</b>.</li>\n";
327 dieout("</ul>");
328 }
329 print "OK</li>\n";
330 }
331 else if ($result != $user) {
332 print "<li>Schema \"$wgDBmwschema\" exists but is not owned by \"$user\". Not ideal.</li>\n";
333 }
334 else {
335 print "<li>Schema \"$wgDBmwschema\" exists and is owned by \"$user\". Excellent.</li>\n";
336 }
337
338 ## Fix up the search paths if needed
339 print "<li>Setting the search path for user \"$user\" ...";
340 $path = $this->quote_ident($wgDBmwschema);
341 if ($wgDBts2schema !== $wgDBmwschema)
342 $path .= ", ". $this->quote_ident($wgDBts2schema);
343 if ($wgDBmwschema !== 'public' and $wgDBts2schema !== 'public')
344 $path .= ", public";
345 $SQL = "ALTER USER $safeuser SET search_path = $path";
346 $result = pg_query($this->mConn, $SQL);
347 if (!$result) {
348 print "<b>FAILED</b>.</li>\n";
349 dieout("</ul>");
350 }
351 print "OK</li>\n";
352 ## Set for the rest of this session
353 $SQL = "SET search_path = $path";
354 $result = pg_query($this->mConn, $SQL);
355 if (!$result) {
356 print "<li>Failed to set search_path</li>\n";
357 dieout("</ul>");
358 }
359 define( "POSTGRES_SEARCHPATH", $path );
360 }}
361
362 global $wgCommandLineMode;
363 ## If called from the command-line (e.g. importDump), only show errors
364 if ($wgCommandLineMode) {
365 $this->doQuery("SET client_min_messages = 'ERROR'");
366 }
367
368 return $this->mConn;
369 }
370
371 /**
372 * Closes a database connection, if it is open
373 * Returns success, true if already closed
374 */
375 function close() {
376 $this->mOpened = false;
377 if ( $this->mConn ) {
378 return pg_close( $this->mConn );
379 } else {
380 return true;
381 }
382 }
383
384 function doQuery( $sql ) {
385 return $this->mLastResult=pg_query( $this->mConn , $sql);
386 }
387
388 function queryIgnore( $sql, $fname = '' ) {
389 return $this->query( $sql, $fname, true );
390 }
391
392 function freeResult( $res ) {
393 if ( !@pg_free_result( $res ) ) {
394 throw new DBUnexpectedError($this, "Unable to free Postgres result\n" );
395 }
396 }
397
398 function fetchObject( $res ) {
399 @$row = pg_fetch_object( $res );
400 # FIXME: HACK HACK HACK HACK debug
401
402 # TODO:
403 # hashar : not sure if the following test really trigger if the object
404 # fetching failled.
405 if( pg_last_error($this->mConn) ) {
406 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
407 }
408 return $row;
409 }
410
411 function fetchRow( $res ) {
412 @$row = pg_fetch_array( $res );
413 if( pg_last_error($this->mConn) ) {
414 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
415 }
416 return $row;
417 }
418
419 function numRows( $res ) {
420 @$n = pg_num_rows( $res );
421 if( pg_last_error($this->mConn) ) {
422 throw new DBUnexpectedError($this, 'SQL error: ' . htmlspecialchars( pg_last_error($this->mConn) ) );
423 }
424 return $n;
425 }
426 function numFields( $res ) { return pg_num_fields( $res ); }
427 function fieldName( $res, $n ) { return pg_field_name( $res, $n ); }
428
429 /**
430 * This must be called after nextSequenceVal
431 */
432 function insertId() {
433 return $this->mInsertId;
434 }
435
436 function dataSeek( $res, $row ) { return pg_result_seek( $res, $row ); }
437 function lastError() {
438 if ( $this->mConn ) {
439 return pg_last_error();
440 }
441 else {
442 return "No database connection";
443 }
444 }
445 function lastErrno() {
446 return pg_last_error() ? 1 : 0;
447 }
448
449 function affectedRows() {
450 return pg_affected_rows( $this->mLastResult );
451 }
452
453 /**
454 * Returns information about an index
455 * If errors are explicitly ignored, returns NULL on failure
456 */
457 function indexInfo( $table, $index, $fname = 'Database::indexExists' ) {
458 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
459 $res = $this->query( $sql, $fname );
460 if ( !$res ) {
461 return NULL;
462 }
463
464 while ( $row = $this->fetchObject( $res ) ) {
465 if ( $row->indexname == $index ) {
466 return $row;
467
468 // BUG: !!!! This code needs to be synced up with database.php
469
470 }
471 }
472 return false;
473 }
474
475 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
476 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
477 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
478 $res = $this->query( $sql, $fname );
479 if ( !$res )
480 return NULL;
481 while ($row = $this->fetchObject( $res ))
482 return true;
483 return false;
484
485 }
486
487 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
488 # Postgres doesn't support options
489 # We have a go at faking one of them
490 # TODO: DELAYED, LOW_PRIORITY
491
492 if ( !is_array($options))
493 $options = array($options);
494
495 if ( in_array( 'IGNORE', $options ) )
496 $oldIgnore = $this->ignoreErrors( true );
497
498 # IGNORE is performed using single-row inserts, ignoring errors in each
499 # FIXME: need some way to distiguish between key collision and other types of error
500 $oldIgnore = $this->ignoreErrors( true );
501 if ( !is_array( reset( $a ) ) ) {
502 $a = array( $a );
503 }
504 foreach ( $a as $row ) {
505 parent::insert( $table, $row, $fname, array() );
506 }
507 $this->ignoreErrors( $oldIgnore );
508 $retVal = true;
509
510 if ( in_array( 'IGNORE', $options ) )
511 $this->ignoreErrors( $oldIgnore );
512
513 return $retVal;
514 }
515
516 function tableName( $name ) {
517 # Replace reserved words with better ones
518 switch( $name ) {
519 case 'user':
520 return 'mwuser';
521 case 'text':
522 return 'pagecontent';
523 default:
524 return $name;
525 }
526 }
527
528 /**
529 * Return the next in a sequence, save the value for retrieval via insertId()
530 */
531 function nextSequenceValue( $seqName ) {
532 $safeseq = preg_replace( "/'/", "''", $seqName );
533 $res = $this->query( "SELECT nextval('$safeseq')" );
534 $row = $this->fetchRow( $res );
535 $this->mInsertId = $row[0];
536 $this->freeResult( $res );
537 return $this->mInsertId;
538 }
539
540 /**
541 * Postgres does not have a "USE INDEX" clause, so return an empty string
542 */
543 function useIndexClause( $index ) {
544 return '';
545 }
546
547 # REPLACE query wrapper
548 # Postgres simulates this with a DELETE followed by INSERT
549 # $row is the row to insert, an associative array
550 # $uniqueIndexes is an array of indexes. Each element may be either a
551 # field name or an array of field names
552 #
553 # It may be more efficient to leave off unique indexes which are unlikely to collide.
554 # However if you do this, you run the risk of encountering errors which wouldn't have
555 # occurred in MySQL
556 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
557 $table = $this->tableName( $table );
558
559 if (count($rows)==0) {
560 return;
561 }
562
563 # Single row case
564 if ( !is_array( reset( $rows ) ) ) {
565 $rows = array( $rows );
566 }
567
568 foreach( $rows as $row ) {
569 # Delete rows which collide
570 if ( $uniqueIndexes ) {
571 $sql = "DELETE FROM $table WHERE ";
572 $first = true;
573 foreach ( $uniqueIndexes as $index ) {
574 if ( $first ) {
575 $first = false;
576 $sql .= "(";
577 } else {
578 $sql .= ') OR (';
579 }
580 if ( is_array( $index ) ) {
581 $first2 = true;
582 foreach ( $index as $col ) {
583 if ( $first2 ) {
584 $first2 = false;
585 } else {
586 $sql .= ' AND ';
587 }
588 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
589 }
590 } else {
591 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
592 }
593 }
594 $sql .= ')';
595 $this->query( $sql, $fname );
596 }
597
598 # Now insert the row
599 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
600 $this->makeList( $row, LIST_COMMA ) . ')';
601 $this->query( $sql, $fname );
602 }
603 }
604
605 # DELETE where the condition is a join
606 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
607 if ( !$conds ) {
608 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
609 }
610
611 $delTable = $this->tableName( $delTable );
612 $joinTable = $this->tableName( $joinTable );
613 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
614 if ( $conds != '*' ) {
615 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
616 }
617 $sql .= ')';
618
619 $this->query( $sql, $fname );
620 }
621
622 # Returns the size of a text field, or -1 for "unlimited"
623 function textFieldSize( $table, $field ) {
624 $table = $this->tableName( $table );
625 $sql = "SELECT t.typname as ftype,a.atttypmod as size
626 FROM pg_class c, pg_attribute a, pg_type t
627 WHERE relname='$table' AND a.attrelid=c.oid AND
628 a.atttypid=t.oid and a.attname='$field'";
629 $res =$this->query($sql);
630 $row=$this->fetchObject($res);
631 if ($row->ftype=="varchar") {
632 $size=$row->size-4;
633 } else {
634 $size=$row->size;
635 }
636 $this->freeResult( $res );
637 return $size;
638 }
639
640 function lowPriorityOption() {
641 return '';
642 }
643
644 function limitResult($sql, $limit,$offset) {
645 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
646 }
647
648 /**
649 * Returns an SQL expression for a simple conditional.
650 * Uses CASE on Postgres
651 *
652 * @param string $cond SQL expression which will result in a boolean value
653 * @param string $trueVal SQL expression to return if true
654 * @param string $falseVal SQL expression to return if false
655 * @return string SQL fragment
656 */
657 function conditional( $cond, $trueVal, $falseVal ) {
658 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
659 }
660
661 function wasDeadlock() {
662 return $this->lastErrno() == '40P01';
663 }
664
665 function timestamp( $ts=0 ) {
666 return wfTimestamp(TS_POSTGRES,$ts);
667 }
668
669 /**
670 * Return aggregated value function call
671 */
672 function aggregateValue ($valuedata,$valuename='value') {
673 return $valuedata;
674 }
675
676
677 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
678 # Ignore errors during error handling to avoid infinite recursion
679 $ignore = $this->ignoreErrors( true );
680 ++$this->mErrorCount;
681
682 if ($ignore || $tempIgnore) {
683 wfDebug("SQL ERROR (ignored): $error\n");
684 $this->ignoreErrors( $ignore );
685 }
686 else {
687 $message = "A database error has occurred\n" .
688 "Query: $sql\n" .
689 "Function: $fname\n" .
690 "Error: $errno $error\n";
691 throw new DBUnexpectedError($this, $message);
692 }
693 }
694
695 /**
696 * @return string wikitext of a link to the server software's web site
697 */
698 function getSoftwareLink() {
699 return "[http://www.postgresql.org/ PostgreSQL]";
700 }
701
702 /**
703 * @return string Version information from the database
704 */
705 function getServerVersion() {
706 $res = $this->query( "SELECT version()" );
707 $row = $this->fetchRow( $res );
708 $version = $row[0];
709 $this->freeResult( $res );
710 return $version;
711 }
712
713
714 /**
715 * Query whether a given table exists (in the given schema, or the default mw one if not given)
716 */
717 function tableExists( $table, $schema = false ) {
718 global $wgDBmwschema;
719 if (! $schema )
720 $schema = $wgDBmwschema;
721 $etable = preg_replace("/'/", "''", $table);
722 $eschema = preg_replace("/'/", "''", $schema);
723 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
724 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
725 . "AND c.relkind IN ('r','v')";
726 $res = $this->query( $SQL );
727 $count = $res ? pg_num_rows($res) : 0;
728 if ($res)
729 $this->freeResult( $res );
730 return $count;
731 }
732
733
734 /**
735 * Query whether a given schema exists. Returns the name of the owner
736 */
737 function schemaExists( $schema ) {
738 $eschema = preg_replace("/'/", "''", $schema);
739 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
740 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
741 $res = $this->query( $SQL );
742 $owner = $res ? pg_num_rows($res) ? pg_fetch_result($res, 0, 0) : false : false;
743 if ($res)
744 $this->freeResult($res);
745 return $owner;
746 }
747
748 /**
749 * Query whether a given column exists in the mediawiki schema
750 */
751 function fieldExists( $table, $field ) {
752 global $wgDBmwschema;
753 $etable = preg_replace("/'/", "''", $table);
754 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
755 $ecol = preg_replace("/'/", "''", $field);
756 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
757 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
758 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
759 $res = $this->query( $SQL );
760 $count = $res ? pg_num_rows($res) : 0;
761 if ($res)
762 $this->freeResult( $res );
763 return $count;
764 }
765
766 function fieldInfo( $table, $field ) {
767 $res = $this->query( "SELECT $field FROM $table LIMIT 1" );
768 $type = pg_field_type( $res, 0 );
769 return $type;
770 }
771
772 function begin( $fname = 'DatabasePostgrs::begin' ) {
773 $this->query( 'BEGIN', $fname );
774 $this->mTrxLevel = 1;
775 }
776 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
777 return true;
778 }
779 function commit( $fname = 'DatabasePostgres::commit' ) {
780 $this->query( 'COMMIT', $fname );
781 $this->mTrxLevel = 0;
782 }
783
784 /* Not even sure why this is used in the main codebase... */
785 function limitResultForUpdate($sql, $num) {
786 return $sql;
787 }
788
789 function setup_database() {
790 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport;
791
792 dbsource( "../maintenance/postgres/tables.sql", $this);
793
794 ## Update version information
795 $mwv = $this->addQuotes($wgVersion);
796 $pgv = $this->addQuotes($this->getServerVersion());
797 $pgu = $this->addQuotes($this->mUser);
798 $mws = $this->addQuotes($wgDBmwschema);
799 $tss = $this->addQuotes($wgDBts2schema);
800 $pgp = $this->addQuotes($wgDBport);
801 $dbn = $this->addQuotes($this->mDBname);
802 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
803
804 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
805 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
806 "ctype = '$ctype' ".
807 "WHERE type = 'Creation'";
808 $this->query($SQL);
809
810 ## Avoid the non-standard "REPLACE INTO" syntax
811 $f = fopen( "../maintenance/interwiki.sql", 'r' );
812 if ($f == false ) {
813 dieout( "<li>Could not find the interwiki.sql file");
814 }
815 ## We simply assume it is already empty as we have just created it
816 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
817 while ( ! feof( $f ) ) {
818 $line = fgets($f,1024);
819 $matches = array();
820 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
821 continue;
822 }
823 $this->query("$SQL $matches[1],$matches[2])");
824 }
825 print " (table interwiki successfully populated)...\n";
826 }
827
828 function encodeBlob($b) {
829 return array('bytea',pg_escape_bytea($b));
830 }
831 function decodeBlob($b) {
832 return pg_unescape_bytea( $b );
833 }
834
835 function strencode( $s ) { ## Should not be called by us
836 return pg_escape_string( $s );
837 }
838
839 function addQuotes( $s ) {
840 if ( is_null( $s ) ) {
841 return 'NULL';
842 } else if (is_array( $s )) { ## Assume it is bytea data
843 return "E'$s[1]'";
844 }
845 return "'" . pg_escape_string($s) . "'";
846 // Unreachable: return "E'" . pg_escape_string($s) . "'";
847 }
848
849 function quote_ident( $s ) {
850 return '"' . preg_replace( '/"/', '""', $s) . '"';
851 }
852
853 /* For now, does nothing */
854 function selectDB( $db ) {
855 return true;
856 }
857
858 /**
859 * Returns an optional USE INDEX clause to go after the table, and a
860 * string to go at the end of the query
861 *
862 * @private
863 *
864 * @param array $options an associative array of options to be turned into
865 * an SQL query, valid keys are listed in the function.
866 * @return array
867 */
868 function makeSelectOptions( $options ) {
869 $tailOpts = '';
870 $startOpts = '';
871
872 $noKeyOptions = array();
873 foreach ( $options as $key => $option ) {
874 if ( is_numeric( $key ) ) {
875 $noKeyOptions[$option] = true;
876 }
877 }
878
879 if ( isset( $options['GROUP BY'] ) ) $tailOpts .= " GROUP BY {$options['GROUP BY']}";
880 if ( isset( $options['ORDER BY'] ) ) $tailOpts .= " ORDER BY {$options['ORDER BY']}";
881
882 if (isset($options['LIMIT'])) {
883 $tailOpts .= $this->limitResult('', $options['LIMIT'],
884 isset($options['OFFSET']) ? $options['OFFSET'] : false);
885 }
886
887 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $tailOpts .= ' FOR UPDATE';
888 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $tailOpts .= ' LOCK IN SHARE MODE';
889 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
890
891 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
892 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
893 } else {
894 $useIndex = '';
895 }
896
897 return array( $startOpts, $useIndex, $tailOpts );
898 }
899
900 function ping() {
901 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
902 return true;
903 }
904
905
906 } // end DatabasePostgres class
907
908 ?>