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