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