f0838bb6900a6972ce096cb2d5ac542afd99d50c
[lhc/web/wiklou.git] / includes / db / DatabasePostgres.php
1 <?php
2 /**
3 * This is the Postgres database abstraction layer.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 class PostgresField implements Field {
25 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname,
26 $has_default, $default;
27
28 /**
29 * @param $db DatabaseBase
30 * @param $table
31 * @param $field
32 * @return null|PostgresField
33 */
34 static function fromText( $db, $table, $field ) {
35 $q = <<<SQL
36 SELECT
37 attnotnull, attlen, conname AS conname,
38 atthasdef,
39 adsrc,
40 COALESCE(condeferred, 'f') AS deferred,
41 COALESCE(condeferrable, 'f') AS deferrable,
42 CASE WHEN typname = 'int2' THEN 'smallint'
43 WHEN typname = 'int4' THEN 'integer'
44 WHEN typname = 'int8' THEN 'bigint'
45 WHEN typname = 'bpchar' THEN 'char'
46 ELSE typname END AS typname
47 FROM pg_class c
48 JOIN pg_namespace n ON (n.oid = c.relnamespace)
49 JOIN pg_attribute a ON (a.attrelid = c.oid)
50 JOIN pg_type t ON (t.oid = a.atttypid)
51 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
52 LEFT JOIN pg_attrdef d on c.oid=d.adrelid and a.attnum=d.adnum
53 WHERE relkind = 'r'
54 AND nspname=%s
55 AND relname=%s
56 AND attname=%s;
57 SQL;
58
59 $table = $db->tableName( $table, 'raw' );
60 $res = $db->query(
61 sprintf( $q,
62 $db->addQuotes( $db->getCoreSchema() ),
63 $db->addQuotes( $table ),
64 $db->addQuotes( $field )
65 )
66 );
67 $row = $db->fetchObject( $res );
68 if ( !$row ) {
69 return null;
70 }
71 $n = new PostgresField;
72 $n->type = $row->typname;
73 $n->nullable = ( $row->attnotnull == 'f' );
74 $n->name = $field;
75 $n->tablename = $table;
76 $n->max_length = $row->attlen;
77 $n->deferrable = ( $row->deferrable == 't' );
78 $n->deferred = ( $row->deferred == 't' );
79 $n->conname = $row->conname;
80 $n->has_default = ( $row->atthasdef === 't' );
81 $n->default = $row->adsrc;
82 return $n;
83 }
84
85 function name() {
86 return $this->name;
87 }
88
89 function tableName() {
90 return $this->tablename;
91 }
92
93 function type() {
94 return $this->type;
95 }
96
97 function isNullable() {
98 return $this->nullable;
99 }
100
101 function maxLength() {
102 return $this->max_length;
103 }
104
105 function is_deferrable() {
106 return $this->deferrable;
107 }
108
109 function is_deferred() {
110 return $this->deferred;
111 }
112
113 function conname() {
114 return $this->conname;
115 }
116 /**
117 * @since 1.19
118 */
119 function defaultValue() {
120 if( $this->has_default ) {
121 return $this->default;
122 } else {
123 return false;
124 }
125 }
126
127 }
128
129 /**
130 * Used to debug transaction processing
131 * Only used if $wgDebugDBTransactions is true
132 *
133 * @since 1.19
134 * @ingroup Database
135 */
136 class PostgresTransactionState {
137
138 static $WATCHED = array(
139 array(
140 "desc" => "%s: Connection state changed from %s -> %s\n",
141 "states" => array(
142 PGSQL_CONNECTION_OK => "OK",
143 PGSQL_CONNECTION_BAD => "BAD"
144 )
145 ),
146 array(
147 "desc" => "%s: Transaction state changed from %s -> %s\n",
148 "states" => array(
149 PGSQL_TRANSACTION_IDLE => "IDLE",
150 PGSQL_TRANSACTION_ACTIVE => "ACTIVE",
151 PGSQL_TRANSACTION_INTRANS => "TRANS",
152 PGSQL_TRANSACTION_INERROR => "ERROR",
153 PGSQL_TRANSACTION_UNKNOWN => "UNKNOWN"
154 )
155 )
156 );
157
158 public function __construct( $conn ) {
159 $this->mConn = $conn;
160 $this->update();
161 $this->mCurrentState = $this->mNewState;
162 }
163
164 public function update() {
165 $this->mNewState = array(
166 pg_connection_status( $this->mConn ),
167 pg_transaction_status( $this->mConn )
168 );
169 }
170
171 public function check() {
172 global $wgDebugDBTransactions;
173 $this->update();
174 if ( $wgDebugDBTransactions ) {
175 if ( $this->mCurrentState !== $this->mNewState ) {
176 $old = reset( $this->mCurrentState );
177 $new = reset( $this->mNewState );
178 foreach ( self::$WATCHED as $watched ) {
179 if ($old !== $new) {
180 $this->log_changed($old, $new, $watched);
181 }
182 $old = next( $this->mCurrentState );
183 $new = next( $this->mNewState );
184
185 }
186 }
187 }
188 $this->mCurrentState = $this->mNewState;
189 }
190
191 protected function describe_changed( $status, $desc_table ) {
192 if( isset( $desc_table[$status] ) ) {
193 return $desc_table[$status];
194 } else {
195 return "STATUS " . $status;
196 }
197 }
198
199 protected function log_changed( $old, $new, $watched ) {
200 wfDebug(sprintf($watched["desc"],
201 $this->mConn,
202 $this->describe_changed( $old, $watched["states"] ),
203 $this->describe_changed( $new, $watched["states"] ))
204 );
205 }
206 }
207
208 /**
209 * Manage savepoints within a transaction
210 * @ingroup Database
211 * @since 1.19
212 */
213 class SavepointPostgres {
214 /**
215 * Establish a savepoint within a transaction
216 */
217 protected $dbw;
218 protected $id;
219 protected $didbegin;
220
221 public function __construct ($dbw, $id) {
222 $this->dbw = $dbw;
223 $this->id = $id;
224 $this->didbegin = false;
225 /* If we are not in a transaction, we need to be for savepoint trickery */
226 if ( !$dbw->trxLevel() ) {
227 $dbw->begin( "FOR SAVEPOINT" );
228 $this->didbegin = true;
229 }
230 }
231
232 public function __destruct() {
233 if ( $this->didbegin ) {
234 $this->dbw->rollback();
235 }
236 }
237
238 public function commit() {
239 if ( $this->didbegin ) {
240 $this->dbw->commit();
241 }
242 }
243
244 protected function query( $keyword, $msg_ok, $msg_failed ) {
245 global $wgDebugDBTransactions;
246 if ( $this->dbw->doQuery( $keyword . " " . $this->id ) !== false ) {
247 if ( $wgDebugDBTransactions ) {
248 wfDebug( sprintf ($msg_ok, $this->id ) );
249 }
250 } else {
251 wfDebug( sprintf ($msg_failed, $this->id ) );
252 }
253 }
254
255 public function savepoint() {
256 $this->query("SAVEPOINT",
257 "Transaction state: savepoint \"%s\" established.\n",
258 "Transaction state: establishment of savepoint \"%s\" FAILED.\n"
259 );
260 }
261
262 public function release() {
263 $this->query("RELEASE",
264 "Transaction state: savepoint \"%s\" released.\n",
265 "Transaction state: release of savepoint \"%s\" FAILED.\n"
266 );
267 }
268
269 public function rollback() {
270 $this->query("ROLLBACK TO",
271 "Transaction state: savepoint \"%s\" rolled back.\n",
272 "Transaction state: rollback of savepoint \"%s\" FAILED.\n"
273 );
274 }
275
276 public function __toString() {
277 return (string)$this->id;
278 }
279 }
280
281 /**
282 * @ingroup Database
283 */
284 class DatabasePostgres extends DatabaseBase {
285 var $mInsertId = null;
286 var $mLastResult = null;
287 var $numeric_version = null;
288 var $mAffectedRows = null;
289
290 function getType() {
291 return 'postgres';
292 }
293
294 function cascadingDeletes() {
295 return true;
296 }
297 function cleanupTriggers() {
298 return true;
299 }
300 function strictIPs() {
301 return true;
302 }
303 function realTimestamps() {
304 return true;
305 }
306 function implicitGroupby() {
307 return false;
308 }
309 function implicitOrderby() {
310 return false;
311 }
312 function searchableIPs() {
313 return true;
314 }
315 function functionalIndexes() {
316 return true;
317 }
318
319 function hasConstraint( $name ) {
320 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
321 pg_escape_string( $this->mConn, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn, $this->getCoreSchema() ) ."'";
322 $res = $this->doQuery( $SQL );
323 return $this->numRows( $res );
324 }
325
326 /**
327 * Usually aborts on failure
328 * @return DatabaseBase|null
329 */
330 function open( $server, $user, $password, $dbName ) {
331 # Test for Postgres support, to avoid suppressed fatal error
332 if ( !function_exists( 'pg_connect' ) ) {
333 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" );
334 }
335
336 global $wgDBport;
337
338 if ( !strlen( $user ) ) { # e.g. the class is being loaded
339 return;
340 }
341
342 $this->mServer = $server;
343 $port = $wgDBport;
344 $this->mUser = $user;
345 $this->mPassword = $password;
346 $this->mDBname = $dbName;
347
348 $connectVars = array(
349 'dbname' => $dbName,
350 'user' => $user,
351 'password' => $password
352 );
353 if ( $server != false && $server != '' ) {
354 $connectVars['host'] = $server;
355 }
356 if ( $port != false && $port != '' ) {
357 $connectVars['port'] = $port;
358 }
359 $this->connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW );
360 $this->close();
361 $this->installErrorHandler();
362 $this->mConn = pg_connect( $this->connectString );
363 $phpError = $this->restoreErrorHandler();
364
365 if ( !$this->mConn ) {
366 wfDebug( "DB connection error\n" );
367 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
368 wfDebug( $this->lastError() . "\n" );
369 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
370 }
371
372 $this->mOpened = true;
373 $this->mTransactionState = new PostgresTransactionState( $this->mConn );
374
375 global $wgCommandLineMode;
376 # If called from the command-line (e.g. importDump), only show errors
377 if ( $wgCommandLineMode ) {
378 $this->doQuery( "SET client_min_messages = 'ERROR'" );
379 }
380
381 $this->query( "SET client_encoding='UTF8'", __METHOD__ );
382 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
383 $this->query( "SET timezone = 'GMT'", __METHOD__ );
384 $this->query( "SET standard_conforming_strings = on", __METHOD__ );
385
386 global $wgDBmwschema;
387 $this->determineCoreSchema( $wgDBmwschema );
388
389 return $this->mConn;
390 }
391
392 /**
393 * Postgres doesn't support selectDB in the same way MySQL does. So if the
394 * DB name doesn't match the open connection, open a new one
395 * @return
396 */
397 function selectDB( $db ) {
398 if ( $this->mDBname !== $db ) {
399 return (bool)$this->open( $this->mServer, $this->mUser, $this->mPassword, $db );
400 } else {
401 return true;
402 }
403 }
404
405 function makeConnectionString( $vars ) {
406 $s = '';
407 foreach ( $vars as $name => $value ) {
408 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
409 }
410 return $s;
411 }
412
413 /**
414 * Closes a database connection, if it is open
415 * Returns success, true if already closed
416 * @return bool
417 */
418 protected function closeConnection() {
419 return pg_close( $this->mConn );
420 }
421
422 public function doQuery( $sql ) {
423 if ( function_exists( 'mb_convert_encoding' ) ) {
424 $sql = mb_convert_encoding( $sql, 'UTF-8' );
425 }
426 $this->mTransactionState->check();
427 if( pg_send_query( $this->mConn, $sql ) === false ) {
428 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
429 }
430 $this->mLastResult = pg_get_result( $this->mConn );
431 $this->mTransactionState->check();
432 $this->mAffectedRows = null;
433 if ( pg_result_error( $this->mLastResult ) ) {
434 return false;
435 }
436 return $this->mLastResult;
437 }
438
439 protected function dumpError () {
440 $diags = array( PGSQL_DIAG_SEVERITY,
441 PGSQL_DIAG_SQLSTATE,
442 PGSQL_DIAG_MESSAGE_PRIMARY,
443 PGSQL_DIAG_MESSAGE_DETAIL,
444 PGSQL_DIAG_MESSAGE_HINT,
445 PGSQL_DIAG_STATEMENT_POSITION,
446 PGSQL_DIAG_INTERNAL_POSITION,
447 PGSQL_DIAG_INTERNAL_QUERY,
448 PGSQL_DIAG_CONTEXT,
449 PGSQL_DIAG_SOURCE_FILE,
450 PGSQL_DIAG_SOURCE_LINE,
451 PGSQL_DIAG_SOURCE_FUNCTION );
452 foreach ( $diags as $d ) {
453 wfDebug( sprintf("PgSQL ERROR(%d): %s\n", $d, pg_result_error_field( $this->mLastResult, $d ) ) );
454 }
455 }
456
457 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
458 /* Transaction stays in the ERROR state until rolledback */
459 if ( $tempIgnore ) {
460 /* Check for constraint violation */
461 if ( $errno === '23505' ) {
462 parent::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
463 return;
464 }
465 }
466 /* Don't ignore serious errors */
467 $this->rollback( __METHOD__ );
468 parent::reportQueryError( $error, $errno, $sql, $fname, false );
469 }
470
471
472 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
473 return $this->query( $sql, $fname, true );
474 }
475
476 function freeResult( $res ) {
477 if ( $res instanceof ResultWrapper ) {
478 $res = $res->result;
479 }
480 wfSuppressWarnings();
481 $ok = pg_free_result( $res );
482 wfRestoreWarnings();
483 if ( !$ok ) {
484 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
485 }
486 }
487
488 function fetchObject( $res ) {
489 if ( $res instanceof ResultWrapper ) {
490 $res = $res->result;
491 }
492 wfSuppressWarnings();
493 $row = pg_fetch_object( $res );
494 wfRestoreWarnings();
495 # @todo FIXME: HACK HACK HACK HACK debug
496
497 # @todo hashar: not sure if the following test really trigger if the object
498 # fetching failed.
499 if( pg_last_error( $this->mConn ) ) {
500 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
501 }
502 return $row;
503 }
504
505 function fetchRow( $res ) {
506 if ( $res instanceof ResultWrapper ) {
507 $res = $res->result;
508 }
509 wfSuppressWarnings();
510 $row = pg_fetch_array( $res );
511 wfRestoreWarnings();
512 if( pg_last_error( $this->mConn ) ) {
513 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
514 }
515 return $row;
516 }
517
518 function numRows( $res ) {
519 if ( $res instanceof ResultWrapper ) {
520 $res = $res->result;
521 }
522 wfSuppressWarnings();
523 $n = pg_num_rows( $res );
524 wfRestoreWarnings();
525 if( pg_last_error( $this->mConn ) ) {
526 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
527 }
528 return $n;
529 }
530
531 function numFields( $res ) {
532 if ( $res instanceof ResultWrapper ) {
533 $res = $res->result;
534 }
535 return pg_num_fields( $res );
536 }
537
538 function fieldName( $res, $n ) {
539 if ( $res instanceof ResultWrapper ) {
540 $res = $res->result;
541 }
542 return pg_field_name( $res, $n );
543 }
544
545 /**
546 * This must be called after nextSequenceVal
547 * @return null
548 */
549 function insertId() {
550 return $this->mInsertId;
551 }
552
553 function dataSeek( $res, $row ) {
554 if ( $res instanceof ResultWrapper ) {
555 $res = $res->result;
556 }
557 return pg_result_seek( $res, $row );
558 }
559
560 function lastError() {
561 if ( $this->mConn ) {
562 if ( $this->mLastResult ) {
563 return pg_result_error( $this->mLastResult );
564 } else {
565 return pg_last_error();
566 }
567 } else {
568 return 'No database connection';
569 }
570 }
571 function lastErrno() {
572 if ( $this->mLastResult ) {
573 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
574 } else {
575 return false;
576 }
577 }
578
579 function affectedRows() {
580 if ( !is_null( $this->mAffectedRows ) ) {
581 // Forced result for simulated queries
582 return $this->mAffectedRows;
583 }
584 if( empty( $this->mLastResult ) ) {
585 return 0;
586 }
587 return pg_affected_rows( $this->mLastResult );
588 }
589
590 /**
591 * Estimate rows in dataset
592 * Returns estimated count, based on EXPLAIN output
593 * This is not necessarily an accurate estimate, so use sparingly
594 * Returns -1 if count cannot be found
595 * Takes same arguments as Database::select()
596 * @return int
597 */
598 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
599 $options['EXPLAIN'] = true;
600 $res = $this->select( $table, $vars, $conds, $fname, $options );
601 $rows = -1;
602 if ( $res ) {
603 $row = $this->fetchRow( $res );
604 $count = array();
605 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
606 $rows = $count[1];
607 }
608 }
609 return $rows;
610 }
611
612 /**
613 * Returns information about an index
614 * If errors are explicitly ignored, returns NULL on failure
615 * @return bool|null
616 */
617 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
618 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
619 $res = $this->query( $sql, $fname );
620 if ( !$res ) {
621 return null;
622 }
623 foreach ( $res as $row ) {
624 if ( $row->indexname == $this->indexName( $index ) ) {
625 return $row;
626 }
627 }
628 return false;
629 }
630
631 /**
632 * Returns is of attributes used in index
633 *
634 * @since 1.19
635 * @return Array
636 */
637 function indexAttributes ( $index, $schema = false ) {
638 if ( $schema === false )
639 $schema = $this->getCoreSchema();
640 /*
641 * A subquery would be not needed if we didn't care about the order
642 * of attributes, but we do
643 */
644 $sql = <<<__INDEXATTR__
645
646 SELECT opcname,
647 attname,
648 i.indoption[s.g] as option,
649 pg_am.amname
650 FROM
651 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
652 FROM
653 pg_index isub
654 JOIN pg_class cis
655 ON cis.oid=isub.indexrelid
656 JOIN pg_namespace ns
657 ON cis.relnamespace = ns.oid
658 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
659 pg_attribute,
660 pg_opclass opcls,
661 pg_am,
662 pg_class ci
663 JOIN pg_index i
664 ON ci.oid=i.indexrelid
665 JOIN pg_class ct
666 ON ct.oid = i.indrelid
667 JOIN pg_namespace n
668 ON ci.relnamespace = n.oid
669 WHERE
670 ci.relname='$index' AND n.nspname='$schema'
671 AND attrelid = ct.oid
672 AND i.indkey[s.g] = attnum
673 AND i.indclass[s.g] = opcls.oid
674 AND pg_am.oid = opcls.opcmethod
675 __INDEXATTR__;
676 $res = $this->query($sql, __METHOD__);
677 $a = array();
678 if ( $res ) {
679 foreach ( $res as $row ) {
680 $a[] = array(
681 $row->attname,
682 $row->opcname,
683 $row->amname,
684 $row->option);
685 }
686 } else {
687 return null;
688 }
689 return $a;
690 }
691
692
693 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
694 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
695 " AND indexdef LIKE 'CREATE UNIQUE%(" .
696 $this->strencode( $this->indexName( $index ) ) .
697 ")'";
698 $res = $this->query( $sql, $fname );
699 if ( !$res ) {
700 return null;
701 }
702 foreach ( $res as $row ) {
703 return true;
704 }
705 return false;
706 }
707
708 /**
709 * INSERT wrapper, inserts an array into a table
710 *
711 * $args may be a single associative array, or an array of these with numeric keys,
712 * for multi-row insert (Postgres version 8.2 and above only).
713 *
714 * @param $table String: Name of the table to insert to.
715 * @param $args Array: Items to insert into the table.
716 * @param $fname String: Name of the function, for profiling
717 * @param $options String or Array. Valid options: IGNORE
718 *
719 * @return bool Success of insert operation. IGNORE always returns true.
720 */
721 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
722 if ( !count( $args ) ) {
723 return true;
724 }
725
726 $table = $this->tableName( $table );
727 if (! isset( $this->numeric_version ) ) {
728 $this->getServerVersion();
729 }
730
731 if ( !is_array( $options ) ) {
732 $options = array( $options );
733 }
734
735 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
736 $multi = true;
737 $keys = array_keys( $args[0] );
738 } else {
739 $multi = false;
740 $keys = array_keys( $args );
741 }
742
743 // If IGNORE is set, we use savepoints to emulate mysql's behavior
744 $savepoint = null;
745 if ( in_array( 'IGNORE', $options ) ) {
746 $savepoint = new SavepointPostgres( $this, 'mw' );
747 $olde = error_reporting( 0 );
748 // For future use, we may want to track the number of actual inserts
749 // Right now, insert (all writes) simply return true/false
750 $numrowsinserted = 0;
751 }
752
753 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
754
755 if ( $multi ) {
756 if ( $this->numeric_version >= 8.2 && !$savepoint ) {
757 $first = true;
758 foreach ( $args as $row ) {
759 if ( $first ) {
760 $first = false;
761 } else {
762 $sql .= ',';
763 }
764 $sql .= '(' . $this->makeList( $row ) . ')';
765 }
766 $res = (bool)$this->query( $sql, $fname, $savepoint );
767 } else {
768 $res = true;
769 $origsql = $sql;
770 foreach ( $args as $row ) {
771 $tempsql = $origsql;
772 $tempsql .= '(' . $this->makeList( $row ) . ')';
773
774 if ( $savepoint ) {
775 $savepoint->savepoint();
776 }
777
778 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
779
780 if ( $savepoint ) {
781 $bar = pg_last_error();
782 if ( $bar != false ) {
783 $savepoint->rollback();
784 } else {
785 $savepoint->release();
786 $numrowsinserted++;
787 }
788 }
789
790 // If any of them fail, we fail overall for this function call
791 // Note that this will be ignored if IGNORE is set
792 if ( !$tempres ) {
793 $res = false;
794 }
795 }
796 }
797 } else {
798 // Not multi, just a lone insert
799 if ( $savepoint ) {
800 $savepoint->savepoint();
801 }
802
803 $sql .= '(' . $this->makeList( $args ) . ')';
804 $res = (bool)$this->query( $sql, $fname, $savepoint );
805 if ( $savepoint ) {
806 $bar = pg_last_error();
807 if ( $bar != false ) {
808 $savepoint->rollback();
809 } else {
810 $savepoint->release();
811 $numrowsinserted++;
812 }
813 }
814 }
815 if ( $savepoint ) {
816 $olde = error_reporting( $olde );
817 $savepoint->commit();
818
819 // Set the affected row count for the whole operation
820 $this->mAffectedRows = $numrowsinserted;
821
822 // IGNORE always returns true
823 return true;
824 }
825
826 return $res;
827 }
828
829 /**
830 * INSERT SELECT wrapper
831 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
832 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
833 * $conds may be "*" to copy the whole table
834 * srcTable may be an array of tables.
835 * @todo FIXME: Implement this a little better (seperate select/insert)?
836 * @return bool
837 */
838 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
839 $insertOptions = array(), $selectOptions = array() )
840 {
841 $destTable = $this->tableName( $destTable );
842
843 if( is_array( $insertOptions ) ) {
844 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
845 }
846 if( !is_array( $selectOptions ) ) {
847 $selectOptions = array( $selectOptions );
848 }
849 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
850 if( is_array( $srcTable ) ) {
851 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
852 } else {
853 $srcTable = $this->tableName( $srcTable );
854 }
855
856 // If IGNORE is set, we use savepoints to emulate mysql's behavior
857 $savepoint = null;
858 if ( in_array( 'IGNORE', $options ) ) {
859 $savepoint = new SavepointPostgres( $this, 'mw' );
860 $olde = error_reporting( 0 );
861 $numrowsinserted = 0;
862 $savepoint->savepoint();
863 }
864
865 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
866 " SELECT $startOpts " . implode( ',', $varMap ) .
867 " FROM $srcTable $useIndex";
868
869 if ( $conds != '*' ) {
870 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
871 }
872
873 $sql .= " $tailOpts";
874
875 $res = (bool)$this->query( $sql, $fname, $savepoint );
876 if( $savepoint ) {
877 $bar = pg_last_error();
878 if( $bar != false ) {
879 $savepoint->rollback();
880 } else {
881 $savepoint->release();
882 $numrowsinserted++;
883 }
884 $olde = error_reporting( $olde );
885 $savepoint->commit();
886
887 // Set the affected row count for the whole operation
888 $this->mAffectedRows = $numrowsinserted;
889
890 // IGNORE always returns true
891 return true;
892 }
893
894 return $res;
895 }
896
897 function tableName( $name, $format = 'quoted' ) {
898 # Replace reserved words with better ones
899 switch( $name ) {
900 case 'user':
901 return $this->realTableName( 'mwuser', $format );
902 case 'text':
903 return $this->realTableName( 'pagecontent', $format );
904 default:
905 return $this->realTableName( $name, $format );
906 }
907 }
908
909 /* Don't cheat on installer */
910 function realTableName( $name, $format = 'quoted' ) {
911 return parent::tableName( $name, $format );
912 }
913
914 /**
915 * Return the next in a sequence, save the value for retrieval via insertId()
916 * @return null
917 */
918 function nextSequenceValue( $seqName ) {
919 $safeseq = str_replace( "'", "''", $seqName );
920 $res = $this->query( "SELECT nextval('$safeseq')" );
921 $row = $this->fetchRow( $res );
922 $this->mInsertId = $row[0];
923 return $this->mInsertId;
924 }
925
926 /**
927 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
928 * @return
929 */
930 function currentSequenceValue( $seqName ) {
931 $safeseq = str_replace( "'", "''", $seqName );
932 $res = $this->query( "SELECT currval('$safeseq')" );
933 $row = $this->fetchRow( $res );
934 $currval = $row[0];
935 return $currval;
936 }
937
938 # Returns the size of a text field, or -1 for "unlimited"
939 function textFieldSize( $table, $field ) {
940 $table = $this->tableName( $table );
941 $sql = "SELECT t.typname as ftype,a.atttypmod as size
942 FROM pg_class c, pg_attribute a, pg_type t
943 WHERE relname='$table' AND a.attrelid=c.oid AND
944 a.atttypid=t.oid and a.attname='$field'";
945 $res =$this->query( $sql );
946 $row = $this->fetchObject( $res );
947 if ( $row->ftype == 'varchar' ) {
948 $size = $row->size - 4;
949 } else {
950 $size = $row->size;
951 }
952 return $size;
953 }
954
955 function limitResult( $sql, $limit, $offset = false ) {
956 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
957 }
958
959 function wasDeadlock() {
960 return $this->lastErrno() == '40P01';
961 }
962
963 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
964 $newName = $this->addIdentifierQuotes( $newName );
965 $oldName = $this->addIdentifierQuotes( $oldName );
966 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
967 }
968
969 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
970 $eschema = $this->addQuotes( $this->getCoreSchema() );
971 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
972 $endArray = array();
973
974 foreach( $result as $table ) {
975 $vars = get_object_vars($table);
976 $table = array_pop( $vars );
977 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
978 $endArray[] = $table;
979 }
980 }
981
982 return $endArray;
983 }
984
985 function timestamp( $ts = 0 ) {
986 return wfTimestamp( TS_POSTGRES, $ts );
987 }
988
989 /*
990 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
991 * to http://www.php.net/manual/en/ref.pgsql.php
992 *
993 * Parsing a postgres array can be a tricky problem, he's my
994 * take on this, it handles multi-dimensional arrays plus
995 * escaping using a nasty regexp to determine the limits of each
996 * data-item.
997 *
998 * This should really be handled by PHP PostgreSQL module
999 *
1000 * @since 1.19
1001 * @param $text string: postgreql array returned in a text form like {a,b}
1002 * @param $output string
1003 * @param $limit int
1004 * @param $offset int
1005 * @return string
1006 */
1007 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1008 if( false === $limit ) {
1009 $limit = strlen( $text )-1;
1010 $output = array();
1011 }
1012 if( '{}' == $text ) {
1013 return $output;
1014 }
1015 do {
1016 if ( '{' != $text{$offset} ) {
1017 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1018 $text, $match, 0, $offset );
1019 $offset += strlen( $match[0] );
1020 $output[] = ( '"' != $match[1]{0}
1021 ? $match[1]
1022 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1023 if ( '},' == $match[3] ) {
1024 return $output;
1025 }
1026 } else {
1027 $offset = $this->pg_array_parse( $text, $output, $limit, $offset+1 );
1028 }
1029 } while ( $limit > $offset );
1030 return $output;
1031 }
1032
1033 /**
1034 * Return aggregated value function call
1035 */
1036 function aggregateValue( $valuedata, $valuename = 'value' ) {
1037 return $valuedata;
1038 }
1039
1040 /**
1041 * @return string wikitext of a link to the server software's web site
1042 */
1043 public static function getSoftwareLink() {
1044 return '[http://www.postgresql.org/ PostgreSQL]';
1045 }
1046
1047
1048 /**
1049 * Return current schema (executes SELECT current_schema())
1050 * Needs transaction
1051 *
1052 * @since 1.19
1053 * @return string return default schema for the current session
1054 */
1055 function getCurrentSchema() {
1056 $res = $this->query( "SELECT current_schema()", __METHOD__);
1057 $row = $this->fetchRow( $res );
1058 return $row[0];
1059 }
1060
1061 /**
1062 * Return list of schemas which are accessible without schema name
1063 * This is list does not contain magic keywords like "$user"
1064 * Needs transaction
1065 *
1066 * @seealso getSearchPath()
1067 * @seealso setSearchPath()
1068 * @since 1.19
1069 * @return array list of actual schemas for the current sesson
1070 */
1071 function getSchemas() {
1072 $res = $this->query( "SELECT current_schemas(false)", __METHOD__);
1073 $row = $this->fetchRow( $res );
1074 $schemas = array();
1075 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1076 return $this->pg_array_parse($row[0], $schemas);
1077 }
1078
1079 /**
1080 * Return search patch for schemas
1081 * This is different from getSchemas() since it contain magic keywords
1082 * (like "$user").
1083 * Needs transaction
1084 *
1085 * @since 1.19
1086 * @return array how to search for table names schemas for the current user
1087 */
1088 function getSearchPath() {
1089 $res = $this->query( "SHOW search_path", __METHOD__);
1090 $row = $this->fetchRow( $res );
1091 /* PostgreSQL returns SHOW values as strings */
1092 return explode(",", $row[0]);
1093 }
1094
1095 /**
1096 * Update search_path, values should already be sanitized
1097 * Values may contain magic keywords like "$user"
1098 * @since 1.19
1099 *
1100 * @param $search_path array list of schemas to be searched by default
1101 */
1102 function setSearchPath( $search_path ) {
1103 $this->query( "SET search_path = " . implode(", ", $search_path) );
1104 }
1105
1106 /**
1107 * Determine default schema for MediaWiki core
1108 * Adjust this session schema search path if desired schema exists
1109 * and is not alread there.
1110 *
1111 * We need to have name of the core schema stored to be able
1112 * to query database metadata.
1113 *
1114 * This will be also called by the installer after the schema is created
1115 *
1116 * @since 1.19
1117 * @param $desired_schema string
1118 */
1119 function determineCoreSchema( $desired_schema ) {
1120 $this->begin( __METHOD__ );
1121 if ( $this->schemaExists( $desired_schema ) ) {
1122 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1123 $this->mCoreSchema = $desired_schema;
1124 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
1125 } else {
1126 /**
1127 * Prepend our schema (e.g. 'mediawiki') in front
1128 * of the search path
1129 * Fixes bug 15816
1130 */
1131 $search_path = $this->getSearchPath();
1132 array_unshift( $search_path,
1133 $this->addIdentifierQuotes( $desired_schema ));
1134 $this->setSearchPath( $search_path );
1135 $this->mCoreSchema = $desired_schema;
1136 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
1137 }
1138 } else {
1139 $this->mCoreSchema = $this->getCurrentSchema();
1140 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema ."\"\n");
1141 }
1142 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1143 $this->commit( __METHOD__ );
1144 }
1145
1146 /**
1147 * Return schema name fore core MediaWiki tables
1148 *
1149 * @since 1.19
1150 * @return string core schema name
1151 */
1152 function getCoreSchema() {
1153 return $this->mCoreSchema;
1154 }
1155
1156 /**
1157 * @return string Version information from the database
1158 */
1159 function getServerVersion() {
1160 if ( !isset( $this->numeric_version ) ) {
1161 $versionInfo = pg_version( $this->mConn );
1162 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1163 // Old client, abort install
1164 $this->numeric_version = '7.3 or earlier';
1165 } elseif ( isset( $versionInfo['server'] ) ) {
1166 // Normal client
1167 $this->numeric_version = $versionInfo['server'];
1168 } else {
1169 // Bug 16937: broken pgsql extension from PHP<5.3
1170 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1171 }
1172 }
1173 return $this->numeric_version;
1174 }
1175
1176 /**
1177 * Query whether a given relation exists (in the given schema, or the
1178 * default mw one if not given)
1179 * @return bool
1180 */
1181 function relationExists( $table, $types, $schema = false ) {
1182 if ( !is_array( $types ) ) {
1183 $types = array( $types );
1184 }
1185 if ( !$schema ) {
1186 $schema = $this->getCoreSchema();
1187 }
1188 $table = $this->realTableName( $table, 'raw' );
1189 $etable = $this->addQuotes( $table );
1190 $eschema = $this->addQuotes( $schema );
1191 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1192 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1193 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1194 $res = $this->query( $SQL );
1195 $count = $res ? $res->numRows() : 0;
1196 return (bool)$count;
1197 }
1198
1199 /**
1200 * For backward compatibility, this function checks both tables and
1201 * views.
1202 * @return bool
1203 */
1204 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1205 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1206 }
1207
1208 function sequenceExists( $sequence, $schema = false ) {
1209 return $this->relationExists( $sequence, 'S', $schema );
1210 }
1211
1212 function triggerExists( $table, $trigger ) {
1213 $q = <<<SQL
1214 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1215 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1216 AND tgrelid=pg_class.oid
1217 AND nspname=%s AND relname=%s AND tgname=%s
1218 SQL;
1219 $res = $this->query(
1220 sprintf(
1221 $q,
1222 $this->addQuotes( $this->getCoreSchema() ),
1223 $this->addQuotes( $table ),
1224 $this->addQuotes( $trigger )
1225 )
1226 );
1227 if ( !$res ) {
1228 return null;
1229 }
1230 $rows = $res->numRows();
1231 return $rows;
1232 }
1233
1234 function ruleExists( $table, $rule ) {
1235 $exists = $this->selectField( 'pg_rules', 'rulename',
1236 array(
1237 'rulename' => $rule,
1238 'tablename' => $table,
1239 'schemaname' => $this->getCoreSchema()
1240 )
1241 );
1242 return $exists === $rule;
1243 }
1244
1245 function constraintExists( $table, $constraint ) {
1246 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1247 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1248 $this->addQuotes( $this->getCoreSchema() ),
1249 $this->addQuotes( $table ),
1250 $this->addQuotes( $constraint )
1251 );
1252 $res = $this->query( $SQL );
1253 if ( !$res ) {
1254 return null;
1255 }
1256 $rows = $res->numRows();
1257 return $rows;
1258 }
1259
1260 /**
1261 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1262 * @return bool
1263 */
1264 function schemaExists( $schema ) {
1265 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1266 array( 'nspname' => $schema ), __METHOD__ );
1267 return (bool)$exists;
1268 }
1269
1270 /**
1271 * Returns true if a given role (i.e. user) exists, false otherwise.
1272 * @return bool
1273 */
1274 function roleExists( $roleName ) {
1275 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1276 array( 'rolname' => $roleName ), __METHOD__ );
1277 return (bool)$exists;
1278 }
1279
1280 function fieldInfo( $table, $field ) {
1281 return PostgresField::fromText( $this, $table, $field );
1282 }
1283
1284 /**
1285 * pg_field_type() wrapper
1286 * @return string
1287 */
1288 function fieldType( $res, $index ) {
1289 if ( $res instanceof ResultWrapper ) {
1290 $res = $res->result;
1291 }
1292 return pg_field_type( $res, $index );
1293 }
1294
1295 /* Not even sure why this is used in the main codebase... */
1296 function limitResultForUpdate( $sql, $num ) {
1297 return $sql;
1298 }
1299
1300 /**
1301 * @param $b
1302 * @return Blob
1303 */
1304 function encodeBlob( $b ) {
1305 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1306 }
1307
1308 function decodeBlob( $b ) {
1309 if ( $b instanceof Blob ) {
1310 $b = $b->fetch();
1311 }
1312 return pg_unescape_bytea( $b );
1313 }
1314
1315 function strencode( $s ) { # Should not be called by us
1316 return pg_escape_string( $this->mConn, $s );
1317 }
1318
1319 /**
1320 * @param $s null|bool|Blob
1321 * @return int|string
1322 */
1323 function addQuotes( $s ) {
1324 if ( is_null( $s ) ) {
1325 return 'NULL';
1326 } elseif ( is_bool( $s ) ) {
1327 return intval( $s );
1328 } elseif ( $s instanceof Blob ) {
1329 return "'" . $s->fetch( $s ) . "'";
1330 }
1331 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1332 }
1333
1334 /**
1335 * Postgres specific version of replaceVars.
1336 * Calls the parent version in Database.php
1337 *
1338 * @private
1339 *
1340 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1341 *
1342 * @return string SQL string
1343 */
1344 protected function replaceVars( $ins ) {
1345 $ins = parent::replaceVars( $ins );
1346
1347 if ( $this->numeric_version >= 8.3 ) {
1348 // Thanks for not providing backwards-compatibility, 8.3
1349 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1350 }
1351
1352 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1353 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1354 }
1355
1356 return $ins;
1357 }
1358
1359 /**
1360 * Various select options
1361 *
1362 * @private
1363 *
1364 * @param $options Array: an associative array of options to be turned into
1365 * an SQL query, valid keys are listed in the function.
1366 * @return array
1367 */
1368 function makeSelectOptions( $options ) {
1369 $preLimitTail = $postLimitTail = '';
1370 $startOpts = $useIndex = '';
1371
1372 $noKeyOptions = array();
1373 foreach ( $options as $key => $option ) {
1374 if ( is_numeric( $key ) ) {
1375 $noKeyOptions[$option] = true;
1376 }
1377 }
1378
1379 if ( isset( $options['GROUP BY'] ) ) {
1380 $gb = is_array( $options['GROUP BY'] )
1381 ? implode( ',', $options['GROUP BY'] )
1382 : $options['GROUP BY'];
1383 $preLimitTail .= " GROUP BY {$gb}";
1384 }
1385
1386 if ( isset( $options['HAVING'] ) ) {
1387 $preLimitTail .= " HAVING {$options['HAVING']}";
1388 }
1389
1390 if ( isset( $options['ORDER BY'] ) ) {
1391 $ob = is_array( $options['ORDER BY'] )
1392 ? implode( ',', $options['ORDER BY'] )
1393 : $options['ORDER BY'];
1394 $preLimitTail .= " ORDER BY {$ob}";
1395 }
1396
1397 //if ( isset( $options['LIMIT'] ) ) {
1398 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1399 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1400 // : false );
1401 //}
1402
1403 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1404 $postLimitTail .= ' FOR UPDATE';
1405 }
1406 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1407 $postLimitTail .= ' LOCK IN SHARE MODE';
1408 }
1409 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1410 $startOpts .= 'DISTINCT';
1411 }
1412
1413 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1414 }
1415
1416 function setFakeMaster( $enabled = true ) {}
1417
1418 function getDBname() {
1419 return $this->mDBname;
1420 }
1421
1422 function getServer() {
1423 return $this->mServer;
1424 }
1425
1426 function buildConcat( $stringList ) {
1427 return implode( ' || ', $stringList );
1428 }
1429
1430 public function getSearchEngine() {
1431 return 'SearchPostgres';
1432 }
1433
1434 public function streamStatementEnd( &$sql, &$newLine ) {
1435 # Allow dollar quoting for function declarations
1436 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1437 if ( $this->delimiter ) {
1438 $this->delimiter = false;
1439 }
1440 else {
1441 $this->delimiter = ';';
1442 }
1443 }
1444 return parent::streamStatementEnd( $sql, $newLine );
1445 }
1446 } // end DatabasePostgres class