457bf384a8c39de45057973c56ea5ff7aae2c4a0
[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 if ( $this->mFlags & DBO_SSL ) {
360 $connectVars['sslmode'] = 1;
361 }
362
363 $this->connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW );
364 $this->close();
365 $this->installErrorHandler();
366 $this->mConn = pg_connect( $this->connectString );
367 $phpError = $this->restoreErrorHandler();
368
369 if ( !$this->mConn ) {
370 wfDebug( "DB connection error\n" );
371 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
372 wfDebug( $this->lastError() . "\n" );
373 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
374 }
375
376 $this->mOpened = true;
377 $this->mTransactionState = new PostgresTransactionState( $this->mConn );
378
379 global $wgCommandLineMode;
380 # If called from the command-line (e.g. importDump), only show errors
381 if ( $wgCommandLineMode ) {
382 $this->doQuery( "SET client_min_messages = 'ERROR'" );
383 }
384
385 $this->query( "SET client_encoding='UTF8'", __METHOD__ );
386 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
387 $this->query( "SET timezone = 'GMT'", __METHOD__ );
388 $this->query( "SET standard_conforming_strings = on", __METHOD__ );
389
390 global $wgDBmwschema;
391 $this->determineCoreSchema( $wgDBmwschema );
392
393 return $this->mConn;
394 }
395
396 /**
397 * Postgres doesn't support selectDB in the same way MySQL does. So if the
398 * DB name doesn't match the open connection, open a new one
399 * @return
400 */
401 function selectDB( $db ) {
402 if ( $this->mDBname !== $db ) {
403 return (bool)$this->open( $this->mServer, $this->mUser, $this->mPassword, $db );
404 } else {
405 return true;
406 }
407 }
408
409 function makeConnectionString( $vars ) {
410 $s = '';
411 foreach ( $vars as $name => $value ) {
412 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
413 }
414 return $s;
415 }
416
417 /**
418 * Closes a database connection, if it is open
419 * Returns success, true if already closed
420 * @return bool
421 */
422 protected function closeConnection() {
423 return pg_close( $this->mConn );
424 }
425
426 public function doQuery( $sql ) {
427 if ( function_exists( 'mb_convert_encoding' ) ) {
428 $sql = mb_convert_encoding( $sql, 'UTF-8' );
429 }
430 $this->mTransactionState->check();
431 if( pg_send_query( $this->mConn, $sql ) === false ) {
432 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
433 }
434 $this->mLastResult = pg_get_result( $this->mConn );
435 $this->mTransactionState->check();
436 $this->mAffectedRows = null;
437 if ( pg_result_error( $this->mLastResult ) ) {
438 return false;
439 }
440 return $this->mLastResult;
441 }
442
443 protected function dumpError () {
444 $diags = array( PGSQL_DIAG_SEVERITY,
445 PGSQL_DIAG_SQLSTATE,
446 PGSQL_DIAG_MESSAGE_PRIMARY,
447 PGSQL_DIAG_MESSAGE_DETAIL,
448 PGSQL_DIAG_MESSAGE_HINT,
449 PGSQL_DIAG_STATEMENT_POSITION,
450 PGSQL_DIAG_INTERNAL_POSITION,
451 PGSQL_DIAG_INTERNAL_QUERY,
452 PGSQL_DIAG_CONTEXT,
453 PGSQL_DIAG_SOURCE_FILE,
454 PGSQL_DIAG_SOURCE_LINE,
455 PGSQL_DIAG_SOURCE_FUNCTION );
456 foreach ( $diags as $d ) {
457 wfDebug( sprintf("PgSQL ERROR(%d): %s\n", $d, pg_result_error_field( $this->mLastResult, $d ) ) );
458 }
459 }
460
461 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
462 /* Transaction stays in the ERROR state until rolledback */
463 if ( $tempIgnore ) {
464 /* Check for constraint violation */
465 if ( $errno === '23505' ) {
466 parent::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
467 return;
468 }
469 }
470 /* Don't ignore serious errors */
471 $this->rollback( __METHOD__ );
472 parent::reportQueryError( $error, $errno, $sql, $fname, false );
473 }
474
475
476 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
477 return $this->query( $sql, $fname, true );
478 }
479
480 function freeResult( $res ) {
481 if ( $res instanceof ResultWrapper ) {
482 $res = $res->result;
483 }
484 wfSuppressWarnings();
485 $ok = pg_free_result( $res );
486 wfRestoreWarnings();
487 if ( !$ok ) {
488 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
489 }
490 }
491
492 function fetchObject( $res ) {
493 if ( $res instanceof ResultWrapper ) {
494 $res = $res->result;
495 }
496 wfSuppressWarnings();
497 $row = pg_fetch_object( $res );
498 wfRestoreWarnings();
499 # @todo FIXME: HACK HACK HACK HACK debug
500
501 # @todo hashar: not sure if the following test really trigger if the object
502 # fetching failed.
503 if( pg_last_error( $this->mConn ) ) {
504 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
505 }
506 return $row;
507 }
508
509 function fetchRow( $res ) {
510 if ( $res instanceof ResultWrapper ) {
511 $res = $res->result;
512 }
513 wfSuppressWarnings();
514 $row = pg_fetch_array( $res );
515 wfRestoreWarnings();
516 if( pg_last_error( $this->mConn ) ) {
517 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
518 }
519 return $row;
520 }
521
522 function numRows( $res ) {
523 if ( $res instanceof ResultWrapper ) {
524 $res = $res->result;
525 }
526 wfSuppressWarnings();
527 $n = pg_num_rows( $res );
528 wfRestoreWarnings();
529 if( pg_last_error( $this->mConn ) ) {
530 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
531 }
532 return $n;
533 }
534
535 function numFields( $res ) {
536 if ( $res instanceof ResultWrapper ) {
537 $res = $res->result;
538 }
539 return pg_num_fields( $res );
540 }
541
542 function fieldName( $res, $n ) {
543 if ( $res instanceof ResultWrapper ) {
544 $res = $res->result;
545 }
546 return pg_field_name( $res, $n );
547 }
548
549 /**
550 * This must be called after nextSequenceVal
551 * @return null
552 */
553 function insertId() {
554 return $this->mInsertId;
555 }
556
557 function dataSeek( $res, $row ) {
558 if ( $res instanceof ResultWrapper ) {
559 $res = $res->result;
560 }
561 return pg_result_seek( $res, $row );
562 }
563
564 function lastError() {
565 if ( $this->mConn ) {
566 if ( $this->mLastResult ) {
567 return pg_result_error( $this->mLastResult );
568 } else {
569 return pg_last_error();
570 }
571 } else {
572 return 'No database connection';
573 }
574 }
575 function lastErrno() {
576 if ( $this->mLastResult ) {
577 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
578 } else {
579 return false;
580 }
581 }
582
583 function affectedRows() {
584 if ( !is_null( $this->mAffectedRows ) ) {
585 // Forced result for simulated queries
586 return $this->mAffectedRows;
587 }
588 if( empty( $this->mLastResult ) ) {
589 return 0;
590 }
591 return pg_affected_rows( $this->mLastResult );
592 }
593
594 /**
595 * Estimate rows in dataset
596 * Returns estimated count, based on EXPLAIN output
597 * This is not necessarily an accurate estimate, so use sparingly
598 * Returns -1 if count cannot be found
599 * Takes same arguments as Database::select()
600 * @return int
601 */
602 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
603 $options['EXPLAIN'] = true;
604 $res = $this->select( $table, $vars, $conds, $fname, $options );
605 $rows = -1;
606 if ( $res ) {
607 $row = $this->fetchRow( $res );
608 $count = array();
609 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
610 $rows = $count[1];
611 }
612 }
613 return $rows;
614 }
615
616 /**
617 * Returns information about an index
618 * If errors are explicitly ignored, returns NULL on failure
619 * @return bool|null
620 */
621 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
622 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
623 $res = $this->query( $sql, $fname );
624 if ( !$res ) {
625 return null;
626 }
627 foreach ( $res as $row ) {
628 if ( $row->indexname == $this->indexName( $index ) ) {
629 return $row;
630 }
631 }
632 return false;
633 }
634
635 /**
636 * Returns is of attributes used in index
637 *
638 * @since 1.19
639 * @return Array
640 */
641 function indexAttributes ( $index, $schema = false ) {
642 if ( $schema === false )
643 $schema = $this->getCoreSchema();
644 /*
645 * A subquery would be not needed if we didn't care about the order
646 * of attributes, but we do
647 */
648 $sql = <<<__INDEXATTR__
649
650 SELECT opcname,
651 attname,
652 i.indoption[s.g] as option,
653 pg_am.amname
654 FROM
655 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
656 FROM
657 pg_index isub
658 JOIN pg_class cis
659 ON cis.oid=isub.indexrelid
660 JOIN pg_namespace ns
661 ON cis.relnamespace = ns.oid
662 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
663 pg_attribute,
664 pg_opclass opcls,
665 pg_am,
666 pg_class ci
667 JOIN pg_index i
668 ON ci.oid=i.indexrelid
669 JOIN pg_class ct
670 ON ct.oid = i.indrelid
671 JOIN pg_namespace n
672 ON ci.relnamespace = n.oid
673 WHERE
674 ci.relname='$index' AND n.nspname='$schema'
675 AND attrelid = ct.oid
676 AND i.indkey[s.g] = attnum
677 AND i.indclass[s.g] = opcls.oid
678 AND pg_am.oid = opcls.opcmethod
679 __INDEXATTR__;
680 $res = $this->query($sql, __METHOD__);
681 $a = array();
682 if ( $res ) {
683 foreach ( $res as $row ) {
684 $a[] = array(
685 $row->attname,
686 $row->opcname,
687 $row->amname,
688 $row->option);
689 }
690 } else {
691 return null;
692 }
693 return $a;
694 }
695
696
697 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
698 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
699 " AND indexdef LIKE 'CREATE UNIQUE%(" .
700 $this->strencode( $this->indexName( $index ) ) .
701 ")'";
702 $res = $this->query( $sql, $fname );
703 if ( !$res ) {
704 return null;
705 }
706 foreach ( $res as $row ) {
707 return true;
708 }
709 return false;
710 }
711
712 /**
713 * INSERT wrapper, inserts an array into a table
714 *
715 * $args may be a single associative array, or an array of these with numeric keys,
716 * for multi-row insert (Postgres version 8.2 and above only).
717 *
718 * @param $table String: Name of the table to insert to.
719 * @param $args Array: Items to insert into the table.
720 * @param $fname String: Name of the function, for profiling
721 * @param $options String or Array. Valid options: IGNORE
722 *
723 * @return bool Success of insert operation. IGNORE always returns true.
724 */
725 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
726 if ( !count( $args ) ) {
727 return true;
728 }
729
730 $table = $this->tableName( $table );
731 if (! isset( $this->numeric_version ) ) {
732 $this->getServerVersion();
733 }
734
735 if ( !is_array( $options ) ) {
736 $options = array( $options );
737 }
738
739 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
740 $multi = true;
741 $keys = array_keys( $args[0] );
742 } else {
743 $multi = false;
744 $keys = array_keys( $args );
745 }
746
747 // If IGNORE is set, we use savepoints to emulate mysql's behavior
748 $savepoint = null;
749 if ( in_array( 'IGNORE', $options ) ) {
750 $savepoint = new SavepointPostgres( $this, 'mw' );
751 $olde = error_reporting( 0 );
752 // For future use, we may want to track the number of actual inserts
753 // Right now, insert (all writes) simply return true/false
754 $numrowsinserted = 0;
755 }
756
757 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
758
759 if ( $multi ) {
760 if ( $this->numeric_version >= 8.2 && !$savepoint ) {
761 $first = true;
762 foreach ( $args as $row ) {
763 if ( $first ) {
764 $first = false;
765 } else {
766 $sql .= ',';
767 }
768 $sql .= '(' . $this->makeList( $row ) . ')';
769 }
770 $res = (bool)$this->query( $sql, $fname, $savepoint );
771 } else {
772 $res = true;
773 $origsql = $sql;
774 foreach ( $args as $row ) {
775 $tempsql = $origsql;
776 $tempsql .= '(' . $this->makeList( $row ) . ')';
777
778 if ( $savepoint ) {
779 $savepoint->savepoint();
780 }
781
782 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
783
784 if ( $savepoint ) {
785 $bar = pg_last_error();
786 if ( $bar != false ) {
787 $savepoint->rollback();
788 } else {
789 $savepoint->release();
790 $numrowsinserted++;
791 }
792 }
793
794 // If any of them fail, we fail overall for this function call
795 // Note that this will be ignored if IGNORE is set
796 if ( !$tempres ) {
797 $res = false;
798 }
799 }
800 }
801 } else {
802 // Not multi, just a lone insert
803 if ( $savepoint ) {
804 $savepoint->savepoint();
805 }
806
807 $sql .= '(' . $this->makeList( $args ) . ')';
808 $res = (bool)$this->query( $sql, $fname, $savepoint );
809 if ( $savepoint ) {
810 $bar = pg_last_error();
811 if ( $bar != false ) {
812 $savepoint->rollback();
813 } else {
814 $savepoint->release();
815 $numrowsinserted++;
816 }
817 }
818 }
819 if ( $savepoint ) {
820 $olde = error_reporting( $olde );
821 $savepoint->commit();
822
823 // Set the affected row count for the whole operation
824 $this->mAffectedRows = $numrowsinserted;
825
826 // IGNORE always returns true
827 return true;
828 }
829
830 return $res;
831 }
832
833 /**
834 * INSERT SELECT wrapper
835 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
836 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
837 * $conds may be "*" to copy the whole table
838 * srcTable may be an array of tables.
839 * @todo FIXME: Implement this a little better (seperate select/insert)?
840 * @return bool
841 */
842 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
843 $insertOptions = array(), $selectOptions = array() )
844 {
845 $destTable = $this->tableName( $destTable );
846
847 if( !is_array( $insertOptions ) ) {
848 $insertOptions = array( $insertOptions );
849 }
850
851 /*
852 * If IGNORE is set, we use savepoints to emulate mysql's behavior
853 * Ignore LOW PRIORITY option, since it is MySQL-specific
854 */
855 $savepoint = null;
856 if ( in_array( 'IGNORE', $insertOptions ) ) {
857 $savepoint = new SavepointPostgres( $this, 'mw' );
858 $olde = error_reporting( 0 );
859 $numrowsinserted = 0;
860 $savepoint->savepoint();
861 }
862
863 if( !is_array( $selectOptions ) ) {
864 $selectOptions = array( $selectOptions );
865 }
866 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
867 if( is_array( $srcTable ) ) {
868 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
869 } else {
870 $srcTable = $this->tableName( $srcTable );
871 }
872
873 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
874 " SELECT $startOpts " . implode( ',', $varMap ) .
875 " FROM $srcTable $useIndex";
876
877 if ( $conds != '*' ) {
878 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
879 }
880
881 $sql .= " $tailOpts";
882
883 $res = (bool)$this->query( $sql, $fname, $savepoint );
884 if( $savepoint ) {
885 $bar = pg_last_error();
886 if( $bar != false ) {
887 $savepoint->rollback();
888 } else {
889 $savepoint->release();
890 $numrowsinserted++;
891 }
892 $olde = error_reporting( $olde );
893 $savepoint->commit();
894
895 // Set the affected row count for the whole operation
896 $this->mAffectedRows = $numrowsinserted;
897
898 // IGNORE always returns true
899 return true;
900 }
901
902 return $res;
903 }
904
905 function tableName( $name, $format = 'quoted' ) {
906 # Replace reserved words with better ones
907 switch( $name ) {
908 case 'user':
909 return $this->realTableName( 'mwuser', $format );
910 case 'text':
911 return $this->realTableName( 'pagecontent', $format );
912 default:
913 return $this->realTableName( $name, $format );
914 }
915 }
916
917 /* Don't cheat on installer */
918 function realTableName( $name, $format = 'quoted' ) {
919 return parent::tableName( $name, $format );
920 }
921
922 /**
923 * Return the next in a sequence, save the value for retrieval via insertId()
924 * @return null
925 */
926 function nextSequenceValue( $seqName ) {
927 $safeseq = str_replace( "'", "''", $seqName );
928 $res = $this->query( "SELECT nextval('$safeseq')" );
929 $row = $this->fetchRow( $res );
930 $this->mInsertId = $row[0];
931 return $this->mInsertId;
932 }
933
934 /**
935 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
936 * @return
937 */
938 function currentSequenceValue( $seqName ) {
939 $safeseq = str_replace( "'", "''", $seqName );
940 $res = $this->query( "SELECT currval('$safeseq')" );
941 $row = $this->fetchRow( $res );
942 $currval = $row[0];
943 return $currval;
944 }
945
946 # Returns the size of a text field, or -1 for "unlimited"
947 function textFieldSize( $table, $field ) {
948 $table = $this->tableName( $table );
949 $sql = "SELECT t.typname as ftype,a.atttypmod as size
950 FROM pg_class c, pg_attribute a, pg_type t
951 WHERE relname='$table' AND a.attrelid=c.oid AND
952 a.atttypid=t.oid and a.attname='$field'";
953 $res =$this->query( $sql );
954 $row = $this->fetchObject( $res );
955 if ( $row->ftype == 'varchar' ) {
956 $size = $row->size - 4;
957 } else {
958 $size = $row->size;
959 }
960 return $size;
961 }
962
963 function limitResult( $sql, $limit, $offset = false ) {
964 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
965 }
966
967 function wasDeadlock() {
968 return $this->lastErrno() == '40P01';
969 }
970
971 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
972 $newName = $this->addIdentifierQuotes( $newName );
973 $oldName = $this->addIdentifierQuotes( $oldName );
974 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
975 }
976
977 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
978 $eschema = $this->addQuotes( $this->getCoreSchema() );
979 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
980 $endArray = array();
981
982 foreach( $result as $table ) {
983 $vars = get_object_vars($table);
984 $table = array_pop( $vars );
985 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
986 $endArray[] = $table;
987 }
988 }
989
990 return $endArray;
991 }
992
993 function timestamp( $ts = 0 ) {
994 return wfTimestamp( TS_POSTGRES, $ts );
995 }
996
997 /*
998 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
999 * to http://www.php.net/manual/en/ref.pgsql.php
1000 *
1001 * Parsing a postgres array can be a tricky problem, he's my
1002 * take on this, it handles multi-dimensional arrays plus
1003 * escaping using a nasty regexp to determine the limits of each
1004 * data-item.
1005 *
1006 * This should really be handled by PHP PostgreSQL module
1007 *
1008 * @since 1.19
1009 * @param $text string: postgreql array returned in a text form like {a,b}
1010 * @param $output string
1011 * @param $limit int
1012 * @param $offset int
1013 * @return string
1014 */
1015 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1016 if( false === $limit ) {
1017 $limit = strlen( $text )-1;
1018 $output = array();
1019 }
1020 if( '{}' == $text ) {
1021 return $output;
1022 }
1023 do {
1024 if ( '{' != $text{$offset} ) {
1025 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1026 $text, $match, 0, $offset );
1027 $offset += strlen( $match[0] );
1028 $output[] = ( '"' != $match[1]{0}
1029 ? $match[1]
1030 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1031 if ( '},' == $match[3] ) {
1032 return $output;
1033 }
1034 } else {
1035 $offset = $this->pg_array_parse( $text, $output, $limit, $offset+1 );
1036 }
1037 } while ( $limit > $offset );
1038 return $output;
1039 }
1040
1041 /**
1042 * Return aggregated value function call
1043 */
1044 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1045 return $valuedata;
1046 }
1047
1048 /**
1049 * @return string wikitext of a link to the server software's web site
1050 */
1051 public static function getSoftwareLink() {
1052 return '[http://www.postgresql.org/ PostgreSQL]';
1053 }
1054
1055
1056 /**
1057 * Return current schema (executes SELECT current_schema())
1058 * Needs transaction
1059 *
1060 * @since 1.19
1061 * @return string return default schema for the current session
1062 */
1063 function getCurrentSchema() {
1064 $res = $this->query( "SELECT current_schema()", __METHOD__);
1065 $row = $this->fetchRow( $res );
1066 return $row[0];
1067 }
1068
1069 /**
1070 * Return list of schemas which are accessible without schema name
1071 * This is list does not contain magic keywords like "$user"
1072 * Needs transaction
1073 *
1074 * @seealso getSearchPath()
1075 * @seealso setSearchPath()
1076 * @since 1.19
1077 * @return array list of actual schemas for the current sesson
1078 */
1079 function getSchemas() {
1080 $res = $this->query( "SELECT current_schemas(false)", __METHOD__);
1081 $row = $this->fetchRow( $res );
1082 $schemas = array();
1083 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1084 return $this->pg_array_parse($row[0], $schemas);
1085 }
1086
1087 /**
1088 * Return search patch for schemas
1089 * This is different from getSchemas() since it contain magic keywords
1090 * (like "$user").
1091 * Needs transaction
1092 *
1093 * @since 1.19
1094 * @return array how to search for table names schemas for the current user
1095 */
1096 function getSearchPath() {
1097 $res = $this->query( "SHOW search_path", __METHOD__);
1098 $row = $this->fetchRow( $res );
1099 /* PostgreSQL returns SHOW values as strings */
1100 return explode(",", $row[0]);
1101 }
1102
1103 /**
1104 * Update search_path, values should already be sanitized
1105 * Values may contain magic keywords like "$user"
1106 * @since 1.19
1107 *
1108 * @param $search_path array list of schemas to be searched by default
1109 */
1110 function setSearchPath( $search_path ) {
1111 $this->query( "SET search_path = " . implode(", ", $search_path) );
1112 }
1113
1114 /**
1115 * Determine default schema for MediaWiki core
1116 * Adjust this session schema search path if desired schema exists
1117 * and is not alread there.
1118 *
1119 * We need to have name of the core schema stored to be able
1120 * to query database metadata.
1121 *
1122 * This will be also called by the installer after the schema is created
1123 *
1124 * @since 1.19
1125 * @param $desired_schema string
1126 */
1127 function determineCoreSchema( $desired_schema ) {
1128 $this->begin( __METHOD__ );
1129 if ( $this->schemaExists( $desired_schema ) ) {
1130 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1131 $this->mCoreSchema = $desired_schema;
1132 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
1133 } else {
1134 /**
1135 * Prepend our schema (e.g. 'mediawiki') in front
1136 * of the search path
1137 * Fixes bug 15816
1138 */
1139 $search_path = $this->getSearchPath();
1140 array_unshift( $search_path,
1141 $this->addIdentifierQuotes( $desired_schema ));
1142 $this->setSearchPath( $search_path );
1143 $this->mCoreSchema = $desired_schema;
1144 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
1145 }
1146 } else {
1147 $this->mCoreSchema = $this->getCurrentSchema();
1148 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema ."\"\n");
1149 }
1150 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1151 $this->commit( __METHOD__ );
1152 }
1153
1154 /**
1155 * Return schema name fore core MediaWiki tables
1156 *
1157 * @since 1.19
1158 * @return string core schema name
1159 */
1160 function getCoreSchema() {
1161 return $this->mCoreSchema;
1162 }
1163
1164 /**
1165 * @return string Version information from the database
1166 */
1167 function getServerVersion() {
1168 if ( !isset( $this->numeric_version ) ) {
1169 $versionInfo = pg_version( $this->mConn );
1170 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1171 // Old client, abort install
1172 $this->numeric_version = '7.3 or earlier';
1173 } elseif ( isset( $versionInfo['server'] ) ) {
1174 // Normal client
1175 $this->numeric_version = $versionInfo['server'];
1176 } else {
1177 // Bug 16937: broken pgsql extension from PHP<5.3
1178 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1179 }
1180 }
1181 return $this->numeric_version;
1182 }
1183
1184 /**
1185 * Query whether a given relation exists (in the given schema, or the
1186 * default mw one if not given)
1187 * @return bool
1188 */
1189 function relationExists( $table, $types, $schema = false ) {
1190 if ( !is_array( $types ) ) {
1191 $types = array( $types );
1192 }
1193 if ( !$schema ) {
1194 $schema = $this->getCoreSchema();
1195 }
1196 $table = $this->realTableName( $table, 'raw' );
1197 $etable = $this->addQuotes( $table );
1198 $eschema = $this->addQuotes( $schema );
1199 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1200 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1201 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1202 $res = $this->query( $SQL );
1203 $count = $res ? $res->numRows() : 0;
1204 return (bool)$count;
1205 }
1206
1207 /**
1208 * For backward compatibility, this function checks both tables and
1209 * views.
1210 * @return bool
1211 */
1212 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1213 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1214 }
1215
1216 function sequenceExists( $sequence, $schema = false ) {
1217 return $this->relationExists( $sequence, 'S', $schema );
1218 }
1219
1220 function triggerExists( $table, $trigger ) {
1221 $q = <<<SQL
1222 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1223 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1224 AND tgrelid=pg_class.oid
1225 AND nspname=%s AND relname=%s AND tgname=%s
1226 SQL;
1227 $res = $this->query(
1228 sprintf(
1229 $q,
1230 $this->addQuotes( $this->getCoreSchema() ),
1231 $this->addQuotes( $table ),
1232 $this->addQuotes( $trigger )
1233 )
1234 );
1235 if ( !$res ) {
1236 return null;
1237 }
1238 $rows = $res->numRows();
1239 return $rows;
1240 }
1241
1242 function ruleExists( $table, $rule ) {
1243 $exists = $this->selectField( 'pg_rules', 'rulename',
1244 array(
1245 'rulename' => $rule,
1246 'tablename' => $table,
1247 'schemaname' => $this->getCoreSchema()
1248 )
1249 );
1250 return $exists === $rule;
1251 }
1252
1253 function constraintExists( $table, $constraint ) {
1254 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1255 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1256 $this->addQuotes( $this->getCoreSchema() ),
1257 $this->addQuotes( $table ),
1258 $this->addQuotes( $constraint )
1259 );
1260 $res = $this->query( $SQL );
1261 if ( !$res ) {
1262 return null;
1263 }
1264 $rows = $res->numRows();
1265 return $rows;
1266 }
1267
1268 /**
1269 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1270 * @return bool
1271 */
1272 function schemaExists( $schema ) {
1273 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1274 array( 'nspname' => $schema ), __METHOD__ );
1275 return (bool)$exists;
1276 }
1277
1278 /**
1279 * Returns true if a given role (i.e. user) exists, false otherwise.
1280 * @return bool
1281 */
1282 function roleExists( $roleName ) {
1283 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1284 array( 'rolname' => $roleName ), __METHOD__ );
1285 return (bool)$exists;
1286 }
1287
1288 function fieldInfo( $table, $field ) {
1289 return PostgresField::fromText( $this, $table, $field );
1290 }
1291
1292 /**
1293 * pg_field_type() wrapper
1294 * @return string
1295 */
1296 function fieldType( $res, $index ) {
1297 if ( $res instanceof ResultWrapper ) {
1298 $res = $res->result;
1299 }
1300 return pg_field_type( $res, $index );
1301 }
1302
1303 /**
1304 * @param $b
1305 * @return Blob
1306 */
1307 function encodeBlob( $b ) {
1308 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1309 }
1310
1311 function decodeBlob( $b ) {
1312 if ( $b instanceof Blob ) {
1313 $b = $b->fetch();
1314 }
1315 return pg_unescape_bytea( $b );
1316 }
1317
1318 function strencode( $s ) { # Should not be called by us
1319 return pg_escape_string( $this->mConn, $s );
1320 }
1321
1322 /**
1323 * @param $s null|bool|Blob
1324 * @return int|string
1325 */
1326 function addQuotes( $s ) {
1327 if ( is_null( $s ) ) {
1328 return 'NULL';
1329 } elseif ( is_bool( $s ) ) {
1330 return intval( $s );
1331 } elseif ( $s instanceof Blob ) {
1332 return "'" . $s->fetch( $s ) . "'";
1333 }
1334 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1335 }
1336
1337 /**
1338 * Postgres specific version of replaceVars.
1339 * Calls the parent version in Database.php
1340 *
1341 * @private
1342 *
1343 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1344 *
1345 * @return string SQL string
1346 */
1347 protected function replaceVars( $ins ) {
1348 $ins = parent::replaceVars( $ins );
1349
1350 if ( $this->numeric_version >= 8.3 ) {
1351 // Thanks for not providing backwards-compatibility, 8.3
1352 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1353 }
1354
1355 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1356 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1357 }
1358
1359 return $ins;
1360 }
1361
1362 /**
1363 * Various select options
1364 *
1365 * @private
1366 *
1367 * @param $options Array: an associative array of options to be turned into
1368 * an SQL query, valid keys are listed in the function.
1369 * @return array
1370 */
1371 function makeSelectOptions( $options ) {
1372 $preLimitTail = $postLimitTail = '';
1373 $startOpts = $useIndex = '';
1374
1375 $noKeyOptions = array();
1376 foreach ( $options as $key => $option ) {
1377 if ( is_numeric( $key ) ) {
1378 $noKeyOptions[$option] = true;
1379 }
1380 }
1381
1382 if ( isset( $options['GROUP BY'] ) ) {
1383 $gb = is_array( $options['GROUP BY'] )
1384 ? implode( ',', $options['GROUP BY'] )
1385 : $options['GROUP BY'];
1386 $preLimitTail .= " GROUP BY {$gb}";
1387 }
1388
1389 if ( isset( $options['HAVING'] ) ) {
1390 $preLimitTail .= " HAVING {$options['HAVING']}";
1391 }
1392
1393 if ( isset( $options['ORDER BY'] ) ) {
1394 $ob = is_array( $options['ORDER BY'] )
1395 ? implode( ',', $options['ORDER BY'] )
1396 : $options['ORDER BY'];
1397 $preLimitTail .= " ORDER BY {$ob}";
1398 }
1399
1400 //if ( isset( $options['LIMIT'] ) ) {
1401 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1402 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1403 // : false );
1404 //}
1405
1406 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1407 $postLimitTail .= ' FOR UPDATE';
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