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