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