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