aaaand one more
[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
605 while ( $row = $this->fetchObject( $res ) ) {
606 if ( $row->indexname == $index ) {
607 return $row;
608
609 // BUG: !!!! This code needs to be synced up with database.php
610
611 }
612 }
613 return false;
614 }
615
616 function indexUnique ($table, $index, $fname = 'Database::indexUnique' ) {
617 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
618 " AND indexdef LIKE 'CREATE UNIQUE%({$index})'";
619 $res = $this->query( $sql, $fname );
620 if ( !$res )
621 return NULL;
622 while ($row = $this->fetchObject( $res ))
623 return true;
624 return false;
625
626 }
627
628 /**
629 * INSERT wrapper, inserts an array into a table
630 *
631 * $args may be a single associative array, or an array of these with numeric keys,
632 * for multi-row insert (Postgres version 8.2 and above only).
633 *
634 * @param array $table String: Name of the table to insert to.
635 * @param array $args Array: Items to insert into the table.
636 * @param array $fname String: Name of the function, for profiling
637 * @param mixed $options String or Array. Valid options: IGNORE
638 *
639 * @return bool Success of insert operation. IGNORE always returns true.
640 */
641 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
642 global $wgDBversion;
643
644 $table = $this->tableName( $table );
645 if (! isset( $wgDBversion ) ) {
646 $this->getServerVersion();
647 $wgDBversion = $this->numeric_version;
648 }
649
650 if ( !is_array( $options ) )
651 $options = array( $options );
652
653 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
654 $multi = true;
655 $keys = array_keys( $args[0] );
656 }
657 else {
658 $multi = false;
659 $keys = array_keys( $args );
660 }
661
662 $ignore = in_array( 'IGNORE', $options ) ? 1 : 0;
663 if ( $ignore )
664 $olde = error_reporting( 0 );
665
666 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
667
668 if ( $multi ) {
669 if ( $wgDBversion >= 8.1 ) {
670 $first = true;
671 foreach ( $args as $row ) {
672 if ( $first ) {
673 $first = false;
674 } else {
675 $sql .= ',';
676 }
677 $sql .= '(' . $this->makeList( $row ) . ')';
678 }
679 $res = (bool)$this->query( $sql, $fname, $ignore );
680 }
681 else {
682 $res = true;
683 $origsql = $sql;
684 foreach ( $args as $row ) {
685 $tempsql = $origsql;
686 $tempsql .= '(' . $this->makeList( $row ) . ')';
687 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
688 if (! $tempres)
689 $res = false;
690 }
691 }
692 }
693 else {
694 $sql .= '(' . $this->makeList( $args ) . ')';
695 $res = (bool)$this->query( $sql, $fname, $ignore );
696 }
697
698 if ( $ignore ) {
699 $olde = error_reporting( $olde );
700 return true;
701 }
702
703 return $res;
704
705 }
706
707 function tableName( $name ) {
708 # Replace reserved words with better ones
709 switch( $name ) {
710 case 'user':
711 return 'mwuser';
712 case 'text':
713 return 'pagecontent';
714 default:
715 return $name;
716 }
717 }
718
719 /**
720 * Return the next in a sequence, save the value for retrieval via insertId()
721 */
722 function nextSequenceValue( $seqName ) {
723 $safeseq = preg_replace( "/'/", "''", $seqName );
724 $res = $this->query( "SELECT nextval('$safeseq')" );
725 $row = $this->fetchRow( $res );
726 $this->mInsertId = $row[0];
727 $this->freeResult( $res );
728 return $this->mInsertId;
729 }
730
731 /**
732 * Postgres does not have a "USE INDEX" clause, so return an empty string
733 */
734 function useIndexClause( $index ) {
735 return '';
736 }
737
738 # REPLACE query wrapper
739 # Postgres simulates this with a DELETE followed by INSERT
740 # $row is the row to insert, an associative array
741 # $uniqueIndexes is an array of indexes. Each element may be either a
742 # field name or an array of field names
743 #
744 # It may be more efficient to leave off unique indexes which are unlikely to collide.
745 # However if you do this, you run the risk of encountering errors which wouldn't have
746 # occurred in MySQL
747 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
748 $table = $this->tableName( $table );
749
750 if (count($rows)==0) {
751 return;
752 }
753
754 # Single row case
755 if ( !is_array( reset( $rows ) ) ) {
756 $rows = array( $rows );
757 }
758
759 foreach( $rows as $row ) {
760 # Delete rows which collide
761 if ( $uniqueIndexes ) {
762 $sql = "DELETE FROM $table WHERE ";
763 $first = true;
764 foreach ( $uniqueIndexes as $index ) {
765 if ( $first ) {
766 $first = false;
767 $sql .= "(";
768 } else {
769 $sql .= ') OR (';
770 }
771 if ( is_array( $index ) ) {
772 $first2 = true;
773 foreach ( $index as $col ) {
774 if ( $first2 ) {
775 $first2 = false;
776 } else {
777 $sql .= ' AND ';
778 }
779 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
780 }
781 } else {
782 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
783 }
784 }
785 $sql .= ')';
786 $this->query( $sql, $fname );
787 }
788
789 # Now insert the row
790 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
791 $this->makeList( $row, LIST_COMMA ) . ')';
792 $this->query( $sql, $fname );
793 }
794 }
795
796 # DELETE where the condition is a join
797 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = "Database::deleteJoin" ) {
798 if ( !$conds ) {
799 throw new DBUnexpectedError($this, 'Database::deleteJoin() called with empty $conds' );
800 }
801
802 $delTable = $this->tableName( $delTable );
803 $joinTable = $this->tableName( $joinTable );
804 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
805 if ( $conds != '*' ) {
806 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
807 }
808 $sql .= ')';
809
810 $this->query( $sql, $fname );
811 }
812
813 # Returns the size of a text field, or -1 for "unlimited"
814 function textFieldSize( $table, $field ) {
815 $table = $this->tableName( $table );
816 $sql = "SELECT t.typname as ftype,a.atttypmod as size
817 FROM pg_class c, pg_attribute a, pg_type t
818 WHERE relname='$table' AND a.attrelid=c.oid AND
819 a.atttypid=t.oid and a.attname='$field'";
820 $res =$this->query($sql);
821 $row=$this->fetchObject($res);
822 if ($row->ftype=="varchar") {
823 $size=$row->size-4;
824 } else {
825 $size=$row->size;
826 }
827 $this->freeResult( $res );
828 return $size;
829 }
830
831 function lowPriorityOption() {
832 return '';
833 }
834
835 function limitResult($sql, $limit,$offset=false) {
836 return "$sql LIMIT $limit ".(is_numeric($offset)?" OFFSET {$offset} ":"");
837 }
838
839 /**
840 * Returns an SQL expression for a simple conditional.
841 * Uses CASE on Postgres
842 *
843 * @param string $cond SQL expression which will result in a boolean value
844 * @param string $trueVal SQL expression to return if true
845 * @param string $falseVal SQL expression to return if false
846 * @return string SQL fragment
847 */
848 function conditional( $cond, $trueVal, $falseVal ) {
849 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
850 }
851
852 function wasDeadlock() {
853 return $this->lastErrno() == '40P01';
854 }
855
856 function timestamp( $ts=0 ) {
857 return wfTimestamp(TS_POSTGRES,$ts);
858 }
859
860 /**
861 * Return aggregated value function call
862 */
863 function aggregateValue ($valuedata,$valuename='value') {
864 return $valuedata;
865 }
866
867
868 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
869 # Ignore errors during error handling to avoid infinite recursion
870 $ignore = $this->ignoreErrors( true );
871 ++$this->mErrorCount;
872
873 if ($ignore || $tempIgnore) {
874 wfDebug("SQL ERROR (ignored): $error\n");
875 $this->ignoreErrors( $ignore );
876 }
877 else {
878 $message = "A database error has occurred\n" .
879 "Query: $sql\n" .
880 "Function: $fname\n" .
881 "Error: $errno $error\n";
882 throw new DBUnexpectedError($this, $message);
883 }
884 }
885
886 /**
887 * @return string wikitext of a link to the server software's web site
888 */
889 function getSoftwareLink() {
890 return "[http://www.postgresql.org/ PostgreSQL]";
891 }
892
893 /**
894 * @return string Version information from the database
895 */
896 function getServerVersion() {
897 $version = pg_fetch_result($this->doQuery("SELECT version()"),0,0);
898 $thisver = array();
899 if (!preg_match('/PostgreSQL (\d+\.\d+)(\S+)/', $version, $thisver)) {
900 die("Could not determine the numeric version from $version!");
901 }
902 $this->numeric_version = $thisver[1];
903 return $version;
904 }
905
906
907 /**
908 * Query whether a given relation exists (in the given schema, or the
909 * default mw one if not given)
910 */
911 function relationExists( $table, $types, $schema = false ) {
912 global $wgDBmwschema;
913 if (!is_array($types))
914 $types = array($types);
915 if (! $schema )
916 $schema = $wgDBmwschema;
917 $etable = $this->addQuotes($table);
918 $eschema = $this->addQuotes($schema);
919 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
920 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
921 . "AND c.relkind IN ('" . implode("','", $types) . "')";
922 $res = $this->query( $SQL );
923 $count = $res ? pg_num_rows($res) : 0;
924 if ($res)
925 $this->freeResult( $res );
926 return $count;
927 }
928
929 /*
930 * For backward compatibility, this function checks both tables and
931 * views.
932 */
933 function tableExists ($table, $schema = false) {
934 return $this->relationExists($table, array('r', 'v'), $schema);
935 }
936
937 function sequenceExists ($sequence, $schema = false) {
938 return $this->relationExists($sequence, 'S', $schema);
939 }
940
941 function triggerExists($table, $trigger) {
942 global $wgDBmwschema;
943
944 $q = <<<END
945 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
946 WHERE relnamespace=pg_namespace.oid AND relkind='r'
947 AND tgrelid=pg_class.oid
948 AND nspname=%s AND relname=%s AND tgname=%s
949 END;
950 $res = $this->query(sprintf($q,
951 $this->addQuotes($wgDBmwschema),
952 $this->addQuotes($table),
953 $this->addQuotes($trigger)));
954 if (!$res)
955 return NULL;
956 $rows = pg_num_rows($res);
957 $this->freeResult($res);
958 return $rows;
959 }
960
961 function ruleExists($table, $rule) {
962 global $wgDBmwschema;
963 $exists = $this->selectField("pg_rules", "rulename",
964 array( "rulename" => $rule,
965 "tablename" => $table,
966 "schemaname" => $wgDBmwschema));
967 return $exists === $rule;
968 }
969
970 function constraintExists($table, $constraint) {
971 global $wgDBmwschema;
972 $SQL = sprintf("SELECT 1 FROM information_schema.table_constraints ".
973 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
974 $this->addQuotes($wgDBmwschema),
975 $this->addQuotes($table),
976 $this->addQuotes($constraint));
977 $res = $this->query($SQL);
978 if (!$res)
979 return NULL;
980 $rows = pg_num_rows($res);
981 $this->freeResult($res);
982 return $rows;
983 }
984
985 /**
986 * Query whether a given schema exists. Returns the name of the owner
987 */
988 function schemaExists( $schema ) {
989 $eschema = preg_replace("/'/", "''", $schema);
990 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
991 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
992 $res = $this->query( $SQL );
993 $owner = $res ? pg_num_rows($res) ? pg_fetch_result($res, 0, 0) : false : false;
994 if ($res)
995 $this->freeResult($res);
996 return $owner;
997 }
998
999 /**
1000 * Query whether a given column exists in the mediawiki schema
1001 */
1002 function fieldExists( $table, $field, $fname = 'DatabasePostgres::fieldExists' ) {
1003 global $wgDBmwschema;
1004 $etable = preg_replace("/'/", "''", $table);
1005 $eschema = preg_replace("/'/", "''", $wgDBmwschema);
1006 $ecol = preg_replace("/'/", "''", $field);
1007 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n, pg_catalog.pg_attribute a "
1008 . "WHERE c.relnamespace = n.oid AND c.relname = '$etable' AND n.nspname = '$eschema' "
1009 . "AND a.attrelid = c.oid AND a.attname = '$ecol'";
1010 $res = $this->query( $SQL, $fname );
1011 $count = $res ? pg_num_rows($res) : 0;
1012 if ($res)
1013 $this->freeResult( $res );
1014 return $count;
1015 }
1016
1017 function fieldInfo( $table, $field ) {
1018 return PostgresField::fromText($this, $table, $field);
1019 }
1020
1021 function begin( $fname = 'DatabasePostgres::begin' ) {
1022 $this->query( 'BEGIN', $fname );
1023 $this->mTrxLevel = 1;
1024 }
1025 function immediateCommit( $fname = 'DatabasePostgres::immediateCommit' ) {
1026 return true;
1027 }
1028 function commit( $fname = 'DatabasePostgres::commit' ) {
1029 $this->query( 'COMMIT', $fname );
1030 $this->mTrxLevel = 0;
1031 }
1032
1033 /* Not even sure why this is used in the main codebase... */
1034 function limitResultForUpdate($sql, $num) {
1035 return $sql;
1036 }
1037
1038 function setup_database() {
1039 global $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgDBport, $wgDBuser;
1040
1041 ## Make sure that we can write to the correct schema
1042 ## If not, Postgres will happily and silently go to the next search_path item
1043 $ctest = "mw_test_table";
1044 if ($this->tableExists($ctest, $wgDBmwschema)) {
1045 $this->doQuery("DROP TABLE $wgDBmwschema.$ctest");
1046 }
1047 $SQL = "CREATE TABLE $wgDBmwschema.$ctest(a int)";
1048 $olde = error_reporting( 0 );
1049 $res = $this->doQuery($SQL);
1050 error_reporting( $olde );
1051 if (!$res) {
1052 print "<b>FAILED</b>. Make sure that the user \"$wgDBuser\" can write to the schema \"$wgDBmwschema\"</li>\n";
1053 dieout("</ul>");
1054 }
1055 $this->doQuery("DROP TABLE $wgDBmwschema.mw_test_table");
1056
1057 dbsource( "../maintenance/postgres/tables.sql", $this);
1058
1059 ## Version-specific stuff
1060 if ($this->numeric_version == 8.1) {
1061 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gist(textvector)");
1062 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gist(titlevector)");
1063 }
1064 else {
1065 $this->doQuery("CREATE INDEX ts2_page_text ON pagecontent USING gin(textvector)");
1066 $this->doQuery("CREATE INDEX ts2_page_title ON page USING gin(titlevector)");
1067 }
1068
1069 ## Update version information
1070 $mwv = $this->addQuotes($wgVersion);
1071 $pgv = $this->addQuotes($this->getServerVersion());
1072 $pgu = $this->addQuotes($this->mUser);
1073 $mws = $this->addQuotes($wgDBmwschema);
1074 $tss = $this->addQuotes($wgDBts2schema);
1075 $pgp = $this->addQuotes($wgDBport);
1076 $dbn = $this->addQuotes($this->mDBname);
1077 $ctype = pg_fetch_result($this->doQuery("SHOW lc_ctype"),0,0);
1078
1079 $SQL = "UPDATE mediawiki_version SET mw_version=$mwv, pg_version=$pgv, pg_user=$pgu, ".
1080 "mw_schema = $mws, ts2_schema = $tss, pg_port=$pgp, pg_dbname=$dbn, ".
1081 "ctype = '$ctype' ".
1082 "WHERE type = 'Creation'";
1083 $this->query($SQL);
1084
1085 ## Avoid the non-standard "REPLACE INTO" syntax
1086 $f = fopen( "../maintenance/interwiki.sql", 'r' );
1087 if ($f == false ) {
1088 dieout( "<li>Could not find the interwiki.sql file");
1089 }
1090 ## We simply assume it is already empty as we have just created it
1091 $SQL = "INSERT INTO interwiki(iw_prefix,iw_url,iw_local) VALUES ";
1092 while ( ! feof( $f ) ) {
1093 $line = fgets($f,1024);
1094 $matches = array();
1095 if (!preg_match('/^\s*(\(.+?),(\d)\)/', $line, $matches)) {
1096 continue;
1097 }
1098 $this->query("$SQL $matches[1],$matches[2])");
1099 }
1100 print " (table interwiki successfully populated)...\n";
1101
1102 $this->doQuery("COMMIT");
1103 }
1104
1105 function encodeBlob($b) {
1106 return array('bytea',pg_escape_bytea($b));
1107 }
1108 function decodeBlob($b) {
1109 return pg_unescape_bytea( $b );
1110 }
1111
1112 function strencode( $s ) { ## Should not be called by us
1113 return pg_escape_string( $s );
1114 }
1115
1116 function addQuotes( $s ) {
1117 if ( is_null( $s ) ) {
1118 return 'NULL';
1119 } else if (is_array( $s )) { ## Assume it is bytea data
1120 return "E'$s[1]'";
1121 }
1122 return "'" . pg_escape_string($s) . "'";
1123 // Unreachable: return "E'" . pg_escape_string($s) . "'";
1124 }
1125
1126 function quote_ident( $s ) {
1127 return '"' . preg_replace( '/"/', '""', $s) . '"';
1128 }
1129
1130 /* For now, does nothing */
1131 function selectDB( $db ) {
1132 return true;
1133 }
1134
1135 /**
1136 * Various select options
1137 *
1138 * @private
1139 *
1140 * @param array $options an associative array of options to be turned into
1141 * an SQL query, valid keys are listed in the function.
1142 * @return array
1143 */
1144 function makeSelectOptions( $options ) {
1145 $preLimitTail = $postLimitTail = '';
1146 $startOpts = $useIndex = '';
1147
1148 $noKeyOptions = array();
1149 foreach ( $options as $key => $option ) {
1150 if ( is_numeric( $key ) ) {
1151 $noKeyOptions[$option] = true;
1152 }
1153 }
1154
1155 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY " . $options['GROUP BY'];
1156 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
1157 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY " . $options['ORDER BY'];
1158
1159 //if (isset($options['LIMIT'])) {
1160 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1161 // isset($options['OFFSET']) ? $options['OFFSET']
1162 // : false);
1163 //}
1164
1165 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
1166 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
1167 if ( isset( $noKeyOptions['DISTINCT'] ) && isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
1168
1169 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1170 }
1171
1172 public function setTimeout( $timeout ) {
1173 // @todo fixme no-op
1174 }
1175
1176 function ping() {
1177 wfDebug( "Function ping() not written for DatabasePostgres.php yet");
1178 return true;
1179 }
1180
1181
1182 } // end DatabasePostgres class
1183
1184 ?>