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