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