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