Remove now unused enableBackend()
[lhc/web/wiklou.git] / includes / db / DatabasePostgres.php
1 <?php
2 /**
3 * This is the Postgres database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 class PostgresField implements Field {
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
11
12 static function fromText($db, $table, $field) {
13 global $wgDBmwschema;
14
15 $q = <<<SQL
16 SELECT
17 attnotnull, attlen, COALESCE(conname, '') AS conname,
18 COALESCE(condeferred, 'f') AS deferred,
19 COALESCE(condeferrable, 'f') AS deferrable,
20 CASE WHEN typname = 'int2' THEN 'smallint'
21 WHEN typname = 'int4' THEN 'integer'
22 WHEN typname = 'int8' THEN 'bigint'
23 WHEN typname = 'bpchar' THEN 'char'
24 ELSE typname END AS typname
25 FROM pg_class c
26 JOIN pg_namespace n ON (n.oid = c.relnamespace)
27 JOIN pg_attribute a ON (a.attrelid = c.oid)
28 JOIN pg_type t ON (t.oid = a.atttypid)
29 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
30 WHERE relkind = 'r'
31 AND nspname=%s
32 AND relname=%s
33 AND attname=%s;
34 SQL;
35
36 $table = $db->tableName( $table );
37 $res = $db->query(
38 sprintf( $q,
39 $db->addQuotes( $wgDBmwschema ),
40 $db->addQuotes( $table ),
41 $db->addQuotes( $field )
42 )
43 );
44 $row = $db->fetchObject( $res );
45 if ( !$row ) {
46 return null;
47 }
48 $n = new PostgresField;
49 $n->type = $row->typname;
50 $n->nullable = ( $row->attnotnull == 'f' );
51 $n->name = $field;
52 $n->tablename = $table;
53 $n->max_length = $row->attlen;
54 $n->deferrable = ( $row->deferrable == 't' );
55 $n->deferred = ( $row->deferred == 't' );
56 $n->conname = $row->conname;
57 return $n;
58 }
59
60 function name() {
61 return $this->name;
62 }
63
64 function tableName() {
65 return $this->tablename;
66 }
67
68 function type() {
69 return $this->type;
70 }
71
72 function isNullable() {
73 return $this->nullable;
74 }
75
76 function maxLength() {
77 return $this->max_length;
78 }
79
80 function is_deferrable() {
81 return $this->deferrable;
82 }
83
84 function is_deferred() {
85 return $this->deferred;
86 }
87
88 function conname() {
89 return $this->conname;
90 }
91
92 }
93
94 /**
95 * @ingroup Database
96 */
97 class DatabasePostgres extends DatabaseBase {
98 var $mInsertId = null;
99 var $mLastResult = null;
100 var $numeric_version = null;
101 var $mAffectedRows = null;
102
103 function getType() {
104 return 'postgres';
105 }
106
107 function cascadingDeletes() {
108 return true;
109 }
110 function cleanupTriggers() {
111 return true;
112 }
113 function strictIPs() {
114 return true;
115 }
116 function realTimestamps() {
117 return true;
118 }
119 function implicitGroupby() {
120 return false;
121 }
122 function implicitOrderby() {
123 return false;
124 }
125 function searchableIPs() {
126 return true;
127 }
128 function functionalIndexes() {
129 return true;
130 }
131
132 function hasConstraint( $name ) {
133 global $wgDBmwschema;
134 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
135 pg_escape_string( $this->mConn, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn, $wgDBmwschema ) ."'";
136 $res = $this->doQuery( $SQL );
137 return $this->numRows( $res );
138 }
139
140 /**
141 * Usually aborts on failure
142 */
143 function open( $server, $user, $password, $dbName ) {
144 # Test for Postgres support, to avoid suppressed fatal error
145 if ( !function_exists( 'pg_connect' ) ) {
146 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" );
147 }
148
149 global $wgDBport;
150
151 if ( !strlen( $user ) ) { # e.g. the class is being loaded
152 return;
153 }
154
155 $this->close();
156 $this->mServer = $server;
157 $this->mPort = $port = $wgDBport;
158 $this->mUser = $user;
159 $this->mPassword = $password;
160 $this->mDBname = $dbName;
161
162 $connectVars = array(
163 'dbname' => $dbName,
164 'user' => $user,
165 'password' => $password
166 );
167 if ( $server != false && $server != '' ) {
168 $connectVars['host'] = $server;
169 }
170 if ( $port != false && $port != '' ) {
171 $connectVars['port'] = $port;
172 }
173 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW );
174
175 $this->installErrorHandler();
176 $this->mConn = pg_connect( $connectString );
177 $phpError = $this->restoreErrorHandler();
178
179 if ( !$this->mConn ) {
180 wfDebug( "DB connection error\n" );
181 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
182 wfDebug( $this->lastError() . "\n" );
183 throw new DBConnectionError( $this, $phpError );
184 }
185
186 $this->mOpened = true;
187
188 global $wgCommandLineMode;
189 # If called from the command-line (e.g. importDump), only show errors
190 if ( $wgCommandLineMode ) {
191 $this->doQuery( "SET client_min_messages = 'ERROR'" );
192 }
193
194 $this->doQuery( "SET client_encoding='UTF8'" );
195 $this->doQuery( "SET datestyle = 'ISO, YMD'" );
196 $this->doQuery( "SET timezone = 'GMT'" );
197
198 global $wgDBmwschema;
199 if ( isset( $wgDBmwschema )
200 && $wgDBmwschema !== 'mediawiki'
201 && preg_match( '/^\w+$/', $wgDBmwschema )
202 ) {
203 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
204 $this->doQuery( "SET search_path = $safeschema, public" );
205 }
206
207 return $this->mConn;
208 }
209
210 function makeConnectionString( $vars ) {
211 $s = '';
212 foreach ( $vars as $name => $value ) {
213 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
214 }
215 return $s;
216 }
217
218
219 function initial_setup( $superuser, $password, $dbName ) {
220 // If this is the initial connection, setup the schema stuff and possibly create the user
221 global $wgDBname, $wgDBuser, $wgDBpassword, $wgDBmwschema, $wgDBts2schema;
222
223 $safeuser = $this->addIdentifierQuotes( $wgDBuser );
224 // Are we connecting as a superuser for the first time?
225 if ( $superuser ) {
226 // Are we really a superuser? Check out our rights
227 $SQL = "SELECT
228 CASE WHEN usesuper IS TRUE THEN
229 CASE WHEN usecreatedb IS TRUE THEN 3 ELSE 1 END
230 ELSE CASE WHEN usecreatedb IS TRUE THEN 2 ELSE 0 END
231 END AS rights
232 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $superuser );
233 $rows = $this->numRows( $res = $this->doQuery( $SQL ) );
234 if ( !$rows ) {
235 print '<li>ERROR: Could not read permissions for user "' . htmlspecialchars( $superuser ) . "\"</li>\n";
236 dieout( );
237 }
238 $perms = pg_fetch_result( $res, 0, 0 );
239
240 $SQL = "SELECT 1 FROM pg_catalog.pg_user WHERE usename = " . $this->addQuotes( $wgDBuser );
241 $rows = $this->numRows( $this->doQuery( $SQL ) );
242 if ( $rows ) {
243 print '<li>User "' . htmlspecialchars( $wgDBuser ) . '" already exists, skipping account creation.</li>';
244 } else {
245 if ( $perms != 1 && $perms != 3 ) {
246 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create other users. ';
247 print 'Please use a different Postgres user.</li>';
248 dieout( );
249 }
250 print '<li>Creating user <b>' . htmlspecialchars( $wgDBuser ) . '</b>...';
251 $safepass = $this->addQuotes( $wgDBpassword );
252 $SQL = "CREATE USER $safeuser NOCREATEDB PASSWORD $safepass";
253 $this->doQuery( $SQL );
254 print "OK</li>\n";
255 }
256 // User now exists, check out the database
257 if ( $dbName != $wgDBname ) {
258 $SQL = "SELECT 1 FROM pg_catalog.pg_database WHERE datname = " . $this->addQuotes( $wgDBname );
259 $rows = $this->numRows( $this->doQuery( $SQL ) );
260 if ( $rows ) {
261 print '<li>Database "' . htmlspecialchars( $wgDBname ) . '" already exists, skipping database creation.</li>';
262 } else {
263 if ( $perms < 1 ) {
264 print '<li>ERROR: the user "' . htmlspecialchars( $superuser ) . '" cannot create databases. ';
265 print 'Please use a different Postgres user.</li>';
266 dieout( );
267 }
268 print '<li>Creating database <b>' . htmlspecialchars( $wgDBname ) . '</b>...';
269 $safename = $this->addIdentifierQuotes( $wgDBname );
270 $SQL = "CREATE DATABASE $safename OWNER $safeuser ";
271 $this->doQuery( $SQL );
272 print "OK</li>\n";
273 // Hopefully tsearch2 and plpgsql are in template1...
274 }
275
276 // Reconnect to check out tsearch2 rights for this user
277 print '<li>Connecting to "' . htmlspecialchars( $wgDBname ) . '" as superuser "' .
278 htmlspecialchars( $superuser ) . '" to check rights...';
279
280 $connectVars = array();
281 if ( $this->mServer != false && $this->mServer != '' ) {
282 $connectVars['host'] = $this->mServer;
283 }
284 if ( $this->mPort != false && $this->mPort != '' ) {
285 $connectVars['port'] = $this->mPort;
286 }
287 $connectVars['dbname'] = $wgDBname;
288 $connectVars['user'] = $superuser;
289 $connectVars['password'] = $password;
290
291 @$this->mConn = pg_connect( $this->makeConnectionString( $connectVars ) );
292 if ( !$this->mConn ) {
293 print "<b>FAILED TO CONNECT!</b></li>";
294 dieout( );
295 }
296 print "OK</li>\n";
297 }
298
299 // Setup the schema for this user if needed
300 $result = $this->schemaExists( $wgDBmwschema );
301 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
302 if ( !$result ) {
303 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
304 $result = $this->doQuery( "CREATE SCHEMA $safeschema AUTHORIZATION $safeuser" );
305 if ( !$result ) {
306 print "<b>FAILED</b>.</li>\n";
307 dieout( );
308 }
309 print "OK</li>\n";
310 } else {
311 print "<li>Schema already exists, explicitly granting rights...\n";
312 $safeschema2 = $this->addQuotes( $wgDBmwschema );
313 $SQL = "SELECT 'GRANT ALL ON '||pg_catalog.quote_ident(relname)||' TO $safeuser;'\n".
314 "FROM pg_catalog.pg_class p, pg_catalog.pg_namespace n\n".
315 "WHERE relnamespace = n.oid AND n.nspname = $safeschema2\n".
316 "AND p.relkind IN ('r','S','v')\n";
317 $SQL .= "UNION\n";
318 $SQL .= "SELECT 'GRANT ALL ON FUNCTION '||pg_catalog.quote_ident(proname)||'('||\n".
319 "pg_catalog.oidvectortypes(p.proargtypes)||') TO $safeuser;'\n".
320 "FROM pg_catalog.pg_proc p, pg_catalog.pg_namespace n\n".
321 "WHERE p.pronamespace = n.oid AND n.nspname = $safeschema2";
322 $res = $this->doQuery( $SQL );
323 if ( !$res ) {
324 print "<b>FAILED</b>. Could not set rights for the user.</li>\n";
325 dieout( );
326 }
327 $this->doQuery( "SET search_path = $safeschema" );
328 $rows = $this->numRows( $res );
329 while ( $rows ) {
330 $rows--;
331 $this->doQuery( pg_fetch_result( $res, $rows, 0 ) );
332 }
333 print "OK</li>";
334 }
335
336 // Install plpgsql if needed
337 $this->setup_plpgsql();
338
339 return true; // Reconnect as regular user
340
341 } // end superuser
342
343 if ( !defined( 'POSTGRES_SEARCHPATH' ) ) {
344 // Install plpgsql if needed
345 $this->setup_plpgsql();
346
347 // Does the schema already exist? Who owns it?
348 $result = $this->schemaExists( $wgDBmwschema );
349 if ( !$result ) {
350 print '<li>Creating schema <b>' . htmlspecialchars( $wgDBmwschema ) . '</b> ...';
351 error_reporting( 0 );
352 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
353 $result = $this->doQuery( "CREATE SCHEMA $safeschema" );
354 error_reporting( E_ALL );
355 if ( !$result ) {
356 print '<b>FAILED</b>. The user "' . htmlspecialchars( $wgDBuser ) .
357 '" must be able to access the schema. '.
358 'You can try making them the owner of the database, or try creating the schema with a '.
359 'different user, and then grant access to the "' .
360 htmlspecialchars( $wgDBuser ) . "\" user.</li>\n";
361 dieout( );
362 }
363 print "OK</li>\n";
364 } elseif ( $result != $wgDBuser ) {
365 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists but is not owned by "' .
366 htmlspecialchars( $wgDBuser ) . "\". Not ideal.</li>\n";
367 } else {
368 print '<li>Schema "' . htmlspecialchars( $wgDBmwschema ) . '" exists and is owned by "' .
369 htmlspecialchars( $wgDBuser ) . "\". Excellent.</li>\n";
370 }
371
372 // Always return GMT time to accomodate the existing integer-based timestamp assumption
373 print "<li>Setting the timezone to GMT for user \"" . htmlspecialchars( $wgDBuser ) . '" ...';
374 $SQL = "ALTER USER $safeuser SET timezone = 'GMT'";
375 $result = pg_query( $this->mConn, $SQL );
376 if ( !$result ) {
377 print "<b>FAILED</b>.</li>\n";
378 dieout( );
379 }
380 print "OK</li>\n";
381 // Set for the rest of this session
382 $SQL = "SET timezone = 'GMT'";
383 $result = pg_query( $this->mConn, $SQL );
384 if ( !$result ) {
385 print "<li>Failed to set timezone</li>\n";
386 dieout( );
387 }
388
389 print '<li>Setting the datestyle to ISO, YMD for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
390 $SQL = "ALTER USER $safeuser SET datestyle = 'ISO, YMD'";
391 $result = pg_query( $this->mConn, $SQL );
392 if ( !$result ) {
393 print "<b>FAILED</b>.</li>\n";
394 dieout( );
395 }
396 print "OK</li>\n";
397 // Set for the rest of this session
398 $SQL = "SET datestyle = 'ISO, YMD'";
399 $result = pg_query( $this->mConn, $SQL );
400 if ( !$result ) {
401 print "<li>Failed to set datestyle</li>\n";
402 dieout( );
403 }
404
405 // Fix up the search paths if needed
406 print '<li>Setting the search path for user "' . htmlspecialchars( $wgDBuser ) . '" ...';
407 $path = $this->addIdentifierQuotes( $wgDBmwschema );
408 if ( $wgDBts2schema !== $wgDBmwschema ) {
409 $path .= ', '. $this->addIdentifierQuotes( $wgDBts2schema );
410 }
411 if ( $wgDBmwschema !== 'public' && $wgDBts2schema !== 'public' ) {
412 $path .= ', public';
413 }
414 $SQL = "ALTER USER $safeuser SET search_path = $path";
415 $result = pg_query( $this->mConn, $SQL );
416 if ( !$result ) {
417 print "<b>FAILED</b>.</li>\n";
418 dieout( );
419 }
420 print "OK</li>\n";
421 // Set for the rest of this session
422 $SQL = "SET search_path = $path";
423 $result = pg_query( $this->mConn, $SQL );
424 if ( !$result ) {
425 print "<li>Failed to set search_path</li>\n";
426 dieout( );
427 }
428 define( 'POSTGRES_SEARCHPATH', $path );
429 }
430 }
431
432 /**
433 * Closes a database connection, if it is open
434 * Returns success, true if already closed
435 */
436 function close() {
437 $this->mOpened = false;
438 if ( $this->mConn ) {
439 return pg_close( $this->mConn );
440 } else {
441 return true;
442 }
443 }
444
445 function doQuery( $sql ) {
446 if ( function_exists( 'mb_convert_encoding' ) ) {
447 $sql = mb_convert_encoding( $sql, 'UTF-8' );
448 }
449 $this->mLastResult = pg_query( $this->mConn, $sql );
450 $this->mAffectedRows = null; // use pg_affected_rows(mLastResult)
451 return $this->mLastResult;
452 }
453
454 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
455 return $this->query( $sql, $fname, true );
456 }
457
458 function freeResult( $res ) {
459 if ( $res instanceof ResultWrapper ) {
460 $res = $res->result;
461 }
462 if ( !@pg_free_result( $res ) ) {
463 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
464 }
465 }
466
467 function fetchObject( $res ) {
468 if ( $res instanceof ResultWrapper ) {
469 $res = $res->result;
470 }
471 @$row = pg_fetch_object( $res );
472 # FIXME: HACK HACK HACK HACK debug
473
474 # TODO:
475 # hashar : not sure if the following test really trigger if the object
476 # fetching failed.
477 if( pg_last_error( $this->mConn ) ) {
478 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
479 }
480 return $row;
481 }
482
483 function fetchRow( $res ) {
484 if ( $res instanceof ResultWrapper ) {
485 $res = $res->result;
486 }
487 @$row = pg_fetch_array( $res );
488 if( pg_last_error( $this->mConn ) ) {
489 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
490 }
491 return $row;
492 }
493
494 function numRows( $res ) {
495 if ( $res instanceof ResultWrapper ) {
496 $res = $res->result;
497 }
498 @$n = pg_num_rows( $res );
499 if( pg_last_error( $this->mConn ) ) {
500 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
501 }
502 return $n;
503 }
504
505 function numFields( $res ) {
506 if ( $res instanceof ResultWrapper ) {
507 $res = $res->result;
508 }
509 return pg_num_fields( $res );
510 }
511
512 function fieldName( $res, $n ) {
513 if ( $res instanceof ResultWrapper ) {
514 $res = $res->result;
515 }
516 return pg_field_name( $res, $n );
517 }
518
519 /**
520 * This must be called after nextSequenceVal
521 */
522 function insertId() {
523 return $this->mInsertId;
524 }
525
526 function dataSeek( $res, $row ) {
527 if ( $res instanceof ResultWrapper ) {
528 $res = $res->result;
529 }
530 return pg_result_seek( $res, $row );
531 }
532
533 function lastError() {
534 if ( $this->mConn ) {
535 return pg_last_error();
536 } else {
537 return 'No database connection';
538 }
539 }
540 function lastErrno() {
541 return pg_last_error() ? 1 : 0;
542 }
543
544 function affectedRows() {
545 if ( !is_null( $this->mAffectedRows ) ) {
546 // Forced result for simulated queries
547 return $this->mAffectedRows;
548 }
549 if( empty( $this->mLastResult ) ) {
550 return 0;
551 }
552 return pg_affected_rows( $this->mLastResult );
553 }
554
555 /**
556 * Estimate rows in dataset
557 * Returns estimated count, based on EXPLAIN output
558 * This is not necessarily an accurate estimate, so use sparingly
559 * Returns -1 if count cannot be found
560 * Takes same arguments as Database::select()
561 */
562 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
563 $options['EXPLAIN'] = true;
564 $res = $this->select( $table, $vars, $conds, $fname, $options );
565 $rows = -1;
566 if ( $res ) {
567 $row = $this->fetchRow( $res );
568 $count = array();
569 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
570 $rows = $count[1];
571 }
572 }
573 return $rows;
574 }
575
576 /**
577 * Returns information about an index
578 * If errors are explicitly ignored, returns NULL on failure
579 */
580 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
581 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
582 $res = $this->query( $sql, $fname );
583 if ( !$res ) {
584 return null;
585 }
586 foreach ( $res as $row ) {
587 if ( $row->indexname == $this->indexName( $index ) ) {
588 return $row;
589 }
590 }
591 return false;
592 }
593
594 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
595 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
596 " AND indexdef LIKE 'CREATE UNIQUE%(" .
597 $this->strencode( $this->indexName( $index ) ) .
598 ")'";
599 $res = $this->query( $sql, $fname );
600 if ( !$res ) {
601 return null;
602 }
603 foreach ( $res as $row ) {
604 return true;
605 }
606 return false;
607 }
608
609 /**
610 * INSERT wrapper, inserts an array into a table
611 *
612 * $args may be a single associative array, or an array of these with numeric keys,
613 * for multi-row insert (Postgres version 8.2 and above only).
614 *
615 * @param $table String: Name of the table to insert to.
616 * @param $args Array: Items to insert into the table.
617 * @param $fname String: Name of the function, for profiling
618 * @param $options String or Array. Valid options: IGNORE
619 *
620 * @return bool Success of insert operation. IGNORE always returns true.
621 */
622 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
623 if ( !count( $args ) ) {
624 return true;
625 }
626
627 $table = $this->tableName( $table );
628 if (! isset( $this->numeric_version ) ) {
629 $this->getServerVersion();
630 }
631
632 if ( !is_array( $options ) ) {
633 $options = array( $options );
634 }
635
636 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
637 $multi = true;
638 $keys = array_keys( $args[0] );
639 } else {
640 $multi = false;
641 $keys = array_keys( $args );
642 }
643
644 // If IGNORE is set, we use savepoints to emulate mysql's behavior
645 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
646
647 // If we are not in a transaction, we need to be for savepoint trickery
648 $didbegin = 0;
649 if ( $ignore ) {
650 if ( !$this->mTrxLevel ) {
651 $this->begin();
652 $didbegin = 1;
653 }
654 $olde = error_reporting( 0 );
655 // For future use, we may want to track the number of actual inserts
656 // Right now, insert (all writes) simply return true/false
657 $numrowsinserted = 0;
658 }
659
660 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
661
662 if ( $multi ) {
663 if ( $this->numeric_version >= 8.2 && !$ignore ) {
664 $first = true;
665 foreach ( $args as $row ) {
666 if ( $first ) {
667 $first = false;
668 } else {
669 $sql .= ',';
670 }
671 $sql .= '(' . $this->makeList( $row ) . ')';
672 }
673 $res = (bool)$this->query( $sql, $fname, $ignore );
674 } else {
675 $res = true;
676 $origsql = $sql;
677 foreach ( $args as $row ) {
678 $tempsql = $origsql;
679 $tempsql .= '(' . $this->makeList( $row ) . ')';
680
681 if ( $ignore ) {
682 pg_query( $this->mConn, "SAVEPOINT $ignore" );
683 }
684
685 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
686
687 if ( $ignore ) {
688 $bar = pg_last_error();
689 if ( $bar != false ) {
690 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
691 } else {
692 pg_query( $this->mConn, "RELEASE $ignore" );
693 $numrowsinserted++;
694 }
695 }
696
697 // If any of them fail, we fail overall for this function call
698 // Note that this will be ignored if IGNORE is set
699 if ( !$tempres ) {
700 $res = false;
701 }
702 }
703 }
704 } else {
705 // Not multi, just a lone insert
706 if ( $ignore ) {
707 pg_query($this->mConn, "SAVEPOINT $ignore");
708 }
709
710 $sql .= '(' . $this->makeList( $args ) . ')';
711 $res = (bool)$this->query( $sql, $fname, $ignore );
712 if ( $ignore ) {
713 $bar = pg_last_error();
714 if ( $bar != false ) {
715 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
716 } else {
717 pg_query( $this->mConn, "RELEASE $ignore" );
718 $numrowsinserted++;
719 }
720 }
721 }
722 if ( $ignore ) {
723 $olde = error_reporting( $olde );
724 if ( $didbegin ) {
725 $this->commit();
726 }
727
728 // Set the affected row count for the whole operation
729 $this->mAffectedRows = $numrowsinserted;
730
731 // IGNORE always returns true
732 return true;
733 }
734
735 return $res;
736 }
737
738 /**
739 * INSERT SELECT wrapper
740 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
741 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
742 * $conds may be "*" to copy the whole table
743 * srcTable may be an array of tables.
744 * @todo FIXME: implement this a little better (seperate select/insert)?
745 */
746 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
747 $insertOptions = array(), $selectOptions = array() )
748 {
749 $destTable = $this->tableName( $destTable );
750
751 // If IGNORE is set, we use savepoints to emulate mysql's behavior
752 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
753
754 if( is_array( $insertOptions ) ) {
755 $insertOptions = implode( ' ', $insertOptions );
756 }
757 if( !is_array( $selectOptions ) ) {
758 $selectOptions = array( $selectOptions );
759 }
760 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
761 if( is_array( $srcTable ) ) {
762 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
763 } else {
764 $srcTable = $this->tableName( $srcTable );
765 }
766
767 // If we are not in a transaction, we need to be for savepoint trickery
768 $didbegin = 0;
769 if ( $ignore ) {
770 if( !$this->mTrxLevel ) {
771 $this->begin();
772 $didbegin = 1;
773 }
774 $olde = error_reporting( 0 );
775 $numrowsinserted = 0;
776 pg_query( $this->mConn, "SAVEPOINT $ignore");
777 }
778
779 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
780 " SELECT $startOpts " . implode( ',', $varMap ) .
781 " FROM $srcTable $useIndex";
782
783 if ( $conds != '*' ) {
784 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
785 }
786
787 $sql .= " $tailOpts";
788
789 $res = (bool)$this->query( $sql, $fname, $ignore );
790 if( $ignore ) {
791 $bar = pg_last_error();
792 if( $bar != false ) {
793 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
794 } else {
795 pg_query( $this->mConn, "RELEASE $ignore" );
796 $numrowsinserted++;
797 }
798 $olde = error_reporting( $olde );
799 if( $didbegin ) {
800 $this->commit();
801 }
802
803 // Set the affected row count for the whole operation
804 $this->mAffectedRows = $numrowsinserted;
805
806 // IGNORE always returns true
807 return true;
808 }
809
810 return $res;
811 }
812
813 function tableName( $name ) {
814 # Replace reserved words with better ones
815 switch( $name ) {
816 case 'user':
817 return 'mwuser';
818 case 'text':
819 return 'pagecontent';
820 default:
821 return $name;
822 }
823 }
824
825 /**
826 * Return the next in a sequence, save the value for retrieval via insertId()
827 */
828 function nextSequenceValue( $seqName ) {
829 $safeseq = str_replace( "'", "''", $seqName );
830 $res = $this->query( "SELECT nextval('$safeseq')" );
831 $row = $this->fetchRow( $res );
832 $this->mInsertId = $row[0];
833 return $this->mInsertId;
834 }
835
836 /**
837 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
838 */
839 function currentSequenceValue( $seqName ) {
840 $safeseq = str_replace( "'", "''", $seqName );
841 $res = $this->query( "SELECT currval('$safeseq')" );
842 $row = $this->fetchRow( $res );
843 $currval = $row[0];
844 return $currval;
845 }
846
847 /**
848 * REPLACE query wrapper
849 * Postgres simulates this with a DELETE followed by INSERT
850 * $row is the row to insert, an associative array
851 * $uniqueIndexes is an array of indexes. Each element may be either a
852 * field name or an array of field names
853 *
854 * It may be more efficient to leave off unique indexes which are unlikely to collide.
855 * However if you do this, you run the risk of encountering errors which wouldn't have
856 * occurred in MySQL
857 */
858 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
859 $table = $this->tableName( $table );
860
861 if ( count( $rows ) == 0 ) {
862 return;
863 }
864
865 # Single row case
866 if ( !is_array( reset( $rows ) ) ) {
867 $rows = array( $rows );
868 }
869
870 foreach( $rows as $row ) {
871 # Delete rows which collide
872 if ( $uniqueIndexes ) {
873 $sql = "DELETE FROM $table WHERE ";
874 $first = true;
875 foreach ( $uniqueIndexes as $index ) {
876 if ( $first ) {
877 $first = false;
878 $sql .= '(';
879 } else {
880 $sql .= ') OR (';
881 }
882 if ( is_array( $index ) ) {
883 $first2 = true;
884 foreach ( $index as $col ) {
885 if ( $first2 ) {
886 $first2 = false;
887 } else {
888 $sql .= ' AND ';
889 }
890 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
891 }
892 } else {
893 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
894 }
895 }
896 $sql .= ')';
897 $this->query( $sql, $fname );
898 }
899
900 # Now insert the row
901 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
902 $this->makeList( $row, LIST_COMMA ) . ')';
903 $this->query( $sql, $fname );
904 }
905 }
906
907 # DELETE where the condition is a join
908 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
909 if ( !$conds ) {
910 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
911 }
912
913 $delTable = $this->tableName( $delTable );
914 $joinTable = $this->tableName( $joinTable );
915 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
916 if ( $conds != '*' ) {
917 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
918 }
919 $sql .= ')';
920
921 $this->query( $sql, $fname );
922 }
923
924 # Returns the size of a text field, or -1 for "unlimited"
925 function textFieldSize( $table, $field ) {
926 $table = $this->tableName( $table );
927 $sql = "SELECT t.typname as ftype,a.atttypmod as size
928 FROM pg_class c, pg_attribute a, pg_type t
929 WHERE relname='$table' AND a.attrelid=c.oid AND
930 a.atttypid=t.oid and a.attname='$field'";
931 $res =$this->query( $sql );
932 $row = $this->fetchObject( $res );
933 if ( $row->ftype == 'varchar' ) {
934 $size = $row->size - 4;
935 } else {
936 $size = $row->size;
937 }
938 return $size;
939 }
940
941 function limitResult( $sql, $limit, $offset = false ) {
942 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
943 }
944
945 function wasDeadlock() {
946 return $this->lastErrno() == '40P01';
947 }
948
949 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
950 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
951 }
952
953 function timestamp( $ts = 0 ) {
954 return wfTimestamp( TS_POSTGRES, $ts );
955 }
956
957 /**
958 * Return aggregated value function call
959 */
960 function aggregateValue( $valuedata, $valuename = 'value' ) {
961 return $valuedata;
962 }
963
964 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
965 // Ignore errors during error handling to avoid infinite recursion
966 $ignore = $this->ignoreErrors( true );
967 $this->mErrorCount++;
968
969 if ( $ignore || $tempIgnore ) {
970 wfDebug( "SQL ERROR (ignored): $error\n" );
971 $this->ignoreErrors( $ignore );
972 } else {
973 $message = "A database error has occurred. Did you forget to run maintenance/update.php after upgrading? See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
974 "Query: $sql\n" .
975 "Function: $fname\n" .
976 "Error: $errno $error\n";
977 throw new DBUnexpectedError( $this, $message );
978 }
979 }
980
981 /**
982 * @return string wikitext of a link to the server software's web site
983 */
984 public static function getSoftwareLink() {
985 return '[http://www.postgresql.org/ PostgreSQL]';
986 }
987
988 /**
989 * @return string Version information from the database
990 */
991 function getServerVersion() {
992 if ( !isset( $this->numeric_version ) ) {
993 $versionInfo = pg_version( $this->mConn );
994 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
995 // Old client, abort install
996 $this->numeric_version = '7.3 or earlier';
997 } elseif ( isset( $versionInfo['server'] ) ) {
998 // Normal client
999 $this->numeric_version = $versionInfo['server'];
1000 } else {
1001 // Bug 16937: broken pgsql extension from PHP<5.3
1002 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1003 }
1004 }
1005 return $this->numeric_version;
1006 }
1007
1008 /**
1009 * Query whether a given relation exists (in the given schema, or the
1010 * default mw one if not given)
1011 */
1012 function relationExists( $table, $types, $schema = false ) {
1013 global $wgDBmwschema;
1014 if ( !is_array( $types ) ) {
1015 $types = array( $types );
1016 }
1017 if ( !$schema ) {
1018 $schema = $wgDBmwschema;
1019 }
1020 $table = $this->tableName( $table );
1021 $etable = $this->addQuotes( $table );
1022 $eschema = $this->addQuotes( $schema );
1023 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1024 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1025 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1026 $res = $this->query( $SQL );
1027 $count = $res ? $res->numRows() : 0;
1028 return (bool)$count;
1029 }
1030
1031 /**
1032 * For backward compatibility, this function checks both tables and
1033 * views.
1034 */
1035 function tableExists( $table, $schema = false ) {
1036 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1037 }
1038
1039 function sequenceExists( $sequence, $schema = false ) {
1040 return $this->relationExists( $sequence, 'S', $schema );
1041 }
1042
1043 function triggerExists( $table, $trigger ) {
1044 global $wgDBmwschema;
1045
1046 $q = <<<SQL
1047 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1048 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1049 AND tgrelid=pg_class.oid
1050 AND nspname=%s AND relname=%s AND tgname=%s
1051 SQL;
1052 $res = $this->query(
1053 sprintf(
1054 $q,
1055 $this->addQuotes( $wgDBmwschema ),
1056 $this->addQuotes( $table ),
1057 $this->addQuotes( $trigger )
1058 )
1059 );
1060 if ( !$res ) {
1061 return null;
1062 }
1063 $rows = $res->numRows();
1064 return $rows;
1065 }
1066
1067 function ruleExists( $table, $rule ) {
1068 global $wgDBmwschema;
1069 $exists = $this->selectField( 'pg_rules', 'rulename',
1070 array(
1071 'rulename' => $rule,
1072 'tablename' => $table,
1073 'schemaname' => $wgDBmwschema
1074 )
1075 );
1076 return $exists === $rule;
1077 }
1078
1079 function constraintExists( $table, $constraint ) {
1080 global $wgDBmwschema;
1081 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1082 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1083 $this->addQuotes( $wgDBmwschema ),
1084 $this->addQuotes( $table ),
1085 $this->addQuotes( $constraint )
1086 );
1087 $res = $this->query( $SQL );
1088 if ( !$res ) {
1089 return null;
1090 }
1091 $rows = $res->numRows();
1092 return $rows;
1093 }
1094
1095 /**
1096 * Query whether a given schema exists. Returns the name of the owner
1097 */
1098 function schemaExists( $schema ) {
1099 $eschema = str_replace( "'", "''", $schema );
1100 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
1101 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
1102 $res = $this->query( $SQL );
1103 if ( $res && $res->numRows() ) {
1104 $row = $res->fetchObject();
1105 $owner = $row->rolname;
1106 } else {
1107 $owner = false;
1108 }
1109 return $owner;
1110 }
1111
1112 function fieldInfo( $table, $field ) {
1113 return PostgresField::fromText( $this, $table, $field );
1114 }
1115
1116 /**
1117 * pg_field_type() wrapper
1118 */
1119 function fieldType( $res, $index ) {
1120 if ( $res instanceof ResultWrapper ) {
1121 $res = $res->result;
1122 }
1123 return pg_field_type( $res, $index );
1124 }
1125
1126 /* Not even sure why this is used in the main codebase... */
1127 function limitResultForUpdate( $sql, $num ) {
1128 return $sql;
1129 }
1130
1131 function encodeBlob( $b ) {
1132 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1133 }
1134
1135 function decodeBlob( $b ) {
1136 if ( $b instanceof Blob ) {
1137 $b = $b->fetch();
1138 }
1139 return pg_unescape_bytea( $b );
1140 }
1141
1142 function strencode( $s ) { # Should not be called by us
1143 return pg_escape_string( $this->mConn, $s );
1144 }
1145
1146 function addQuotes( $s ) {
1147 if ( is_null( $s ) ) {
1148 return 'NULL';
1149 } elseif ( is_bool( $s ) ) {
1150 return intval( $s );
1151 } elseif ( $s instanceof Blob ) {
1152 return "'" . $s->fetch( $s ) . "'";
1153 }
1154 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1155 }
1156
1157 /**
1158 * Postgres specific version of replaceVars.
1159 * Calls the parent version in Database.php
1160 *
1161 * @private
1162 *
1163 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1164 *
1165 * @return string SQL string
1166 */
1167 protected function replaceVars( $ins ) {
1168 $ins = parent::replaceVars( $ins );
1169
1170 if ( $this->numeric_version >= 8.3 ) {
1171 // Thanks for not providing backwards-compatibility, 8.3
1172 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1173 }
1174
1175 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1176 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1177 }
1178
1179 return $ins;
1180 }
1181
1182 /**
1183 * Various select options
1184 *
1185 * @private
1186 *
1187 * @param $options Array: an associative array of options to be turned into
1188 * an SQL query, valid keys are listed in the function.
1189 * @return array
1190 */
1191 function makeSelectOptions( $options ) {
1192 $preLimitTail = $postLimitTail = '';
1193 $startOpts = $useIndex = '';
1194
1195 $noKeyOptions = array();
1196 foreach ( $options as $key => $option ) {
1197 if ( is_numeric( $key ) ) {
1198 $noKeyOptions[$option] = true;
1199 }
1200 }
1201
1202 if ( isset( $options['GROUP BY'] ) ) {
1203 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1204 }
1205 if ( isset( $options['HAVING'] ) ) {
1206 $preLimitTail .= " HAVING {$options['HAVING']}";
1207 }
1208 if ( isset( $options['ORDER BY'] ) ) {
1209 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1210 }
1211
1212 //if ( isset( $options['LIMIT'] ) ) {
1213 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1214 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1215 // : false );
1216 //}
1217
1218 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1219 $postLimitTail .= ' FOR UPDATE';
1220 }
1221 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1222 $postLimitTail .= ' LOCK IN SHARE MODE';
1223 }
1224 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1225 $startOpts .= 'DISTINCT';
1226 }
1227
1228 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1229 }
1230
1231 function setFakeMaster( $enabled = true ) {}
1232
1233 function getDBname() {
1234 return $this->mDBname;
1235 }
1236
1237 function getServer() {
1238 return $this->mServer;
1239 }
1240
1241 function buildConcat( $stringList ) {
1242 return implode( ' || ', $stringList );
1243 }
1244
1245 public function getSearchEngine() {
1246 return 'SearchPostgres';
1247 }
1248 } // end DatabasePostgres class