Merge "(bug 37249) validate export-demo.xml against current export.xsd"
[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 = array( $insertOptions );
845 }
846
847 /*
848 * If IGNORE is set, we use savepoints to emulate mysql's behavior
849 * Ignore LOW PRIORITY option, since it is MySQL-specific
850 */
851 $savepoint = null;
852 if ( in_array( 'IGNORE', $insertOptions ) ) {
853 $savepoint = new SavepointPostgres( $this, 'mw' );
854 $olde = error_reporting( 0 );
855 $numrowsinserted = 0;
856 $savepoint->savepoint();
857 }
858
859 if( !is_array( $selectOptions ) ) {
860 $selectOptions = array( $selectOptions );
861 }
862 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
863 if( is_array( $srcTable ) ) {
864 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
865 } else {
866 $srcTable = $this->tableName( $srcTable );
867 }
868
869 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
870 " SELECT $startOpts " . implode( ',', $varMap ) .
871 " FROM $srcTable $useIndex";
872
873 if ( $conds != '*' ) {
874 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
875 }
876
877 $sql .= " $tailOpts";
878
879 $res = (bool)$this->query( $sql, $fname, $savepoint );
880 if( $savepoint ) {
881 $bar = pg_last_error();
882 if( $bar != false ) {
883 $savepoint->rollback();
884 } else {
885 $savepoint->release();
886 $numrowsinserted++;
887 }
888 $olde = error_reporting( $olde );
889 $savepoint->commit();
890
891 // Set the affected row count for the whole operation
892 $this->mAffectedRows = $numrowsinserted;
893
894 // IGNORE always returns true
895 return true;
896 }
897
898 return $res;
899 }
900
901 function tableName( $name, $format = 'quoted' ) {
902 # Replace reserved words with better ones
903 switch( $name ) {
904 case 'user':
905 return $this->realTableName( 'mwuser', $format );
906 case 'text':
907 return $this->realTableName( 'pagecontent', $format );
908 default:
909 return $this->realTableName( $name, $format );
910 }
911 }
912
913 /* Don't cheat on installer */
914 function realTableName( $name, $format = 'quoted' ) {
915 return parent::tableName( $name, $format );
916 }
917
918 /**
919 * Return the next in a sequence, save the value for retrieval via insertId()
920 * @return null
921 */
922 function nextSequenceValue( $seqName ) {
923 $safeseq = str_replace( "'", "''", $seqName );
924 $res = $this->query( "SELECT nextval('$safeseq')" );
925 $row = $this->fetchRow( $res );
926 $this->mInsertId = $row[0];
927 return $this->mInsertId;
928 }
929
930 /**
931 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
932 * @return
933 */
934 function currentSequenceValue( $seqName ) {
935 $safeseq = str_replace( "'", "''", $seqName );
936 $res = $this->query( "SELECT currval('$safeseq')" );
937 $row = $this->fetchRow( $res );
938 $currval = $row[0];
939 return $currval;
940 }
941
942 # Returns the size of a text field, or -1 for "unlimited"
943 function textFieldSize( $table, $field ) {
944 $table = $this->tableName( $table );
945 $sql = "SELECT t.typname as ftype,a.atttypmod as size
946 FROM pg_class c, pg_attribute a, pg_type t
947 WHERE relname='$table' AND a.attrelid=c.oid AND
948 a.atttypid=t.oid and a.attname='$field'";
949 $res =$this->query( $sql );
950 $row = $this->fetchObject( $res );
951 if ( $row->ftype == 'varchar' ) {
952 $size = $row->size - 4;
953 } else {
954 $size = $row->size;
955 }
956 return $size;
957 }
958
959 function limitResult( $sql, $limit, $offset = false ) {
960 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
961 }
962
963 function wasDeadlock() {
964 return $this->lastErrno() == '40P01';
965 }
966
967 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
968 $newName = $this->addIdentifierQuotes( $newName );
969 $oldName = $this->addIdentifierQuotes( $oldName );
970 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
971 }
972
973 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
974 $eschema = $this->addQuotes( $this->getCoreSchema() );
975 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
976 $endArray = array();
977
978 foreach( $result as $table ) {
979 $vars = get_object_vars($table);
980 $table = array_pop( $vars );
981 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
982 $endArray[] = $table;
983 }
984 }
985
986 return $endArray;
987 }
988
989 function timestamp( $ts = 0 ) {
990 return wfTimestamp( TS_POSTGRES, $ts );
991 }
992
993 /*
994 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
995 * to http://www.php.net/manual/en/ref.pgsql.php
996 *
997 * Parsing a postgres array can be a tricky problem, he's my
998 * take on this, it handles multi-dimensional arrays plus
999 * escaping using a nasty regexp to determine the limits of each
1000 * data-item.
1001 *
1002 * This should really be handled by PHP PostgreSQL module
1003 *
1004 * @since 1.19
1005 * @param $text string: postgreql array returned in a text form like {a,b}
1006 * @param $output string
1007 * @param $limit int
1008 * @param $offset int
1009 * @return string
1010 */
1011 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1012 if( false === $limit ) {
1013 $limit = strlen( $text )-1;
1014 $output = array();
1015 }
1016 if( '{}' == $text ) {
1017 return $output;
1018 }
1019 do {
1020 if ( '{' != $text{$offset} ) {
1021 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1022 $text, $match, 0, $offset );
1023 $offset += strlen( $match[0] );
1024 $output[] = ( '"' != $match[1]{0}
1025 ? $match[1]
1026 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1027 if ( '},' == $match[3] ) {
1028 return $output;
1029 }
1030 } else {
1031 $offset = $this->pg_array_parse( $text, $output, $limit, $offset+1 );
1032 }
1033 } while ( $limit > $offset );
1034 return $output;
1035 }
1036
1037 /**
1038 * Return aggregated value function call
1039 */
1040 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1041 return $valuedata;
1042 }
1043
1044 /**
1045 * @return string wikitext of a link to the server software's web site
1046 */
1047 public static function getSoftwareLink() {
1048 return '[http://www.postgresql.org/ PostgreSQL]';
1049 }
1050
1051
1052 /**
1053 * Return current schema (executes SELECT current_schema())
1054 * Needs transaction
1055 *
1056 * @since 1.19
1057 * @return string return default schema for the current session
1058 */
1059 function getCurrentSchema() {
1060 $res = $this->query( "SELECT current_schema()", __METHOD__);
1061 $row = $this->fetchRow( $res );
1062 return $row[0];
1063 }
1064
1065 /**
1066 * Return list of schemas which are accessible without schema name
1067 * This is list does not contain magic keywords like "$user"
1068 * Needs transaction
1069 *
1070 * @seealso getSearchPath()
1071 * @seealso setSearchPath()
1072 * @since 1.19
1073 * @return array list of actual schemas for the current sesson
1074 */
1075 function getSchemas() {
1076 $res = $this->query( "SELECT current_schemas(false)", __METHOD__);
1077 $row = $this->fetchRow( $res );
1078 $schemas = array();
1079 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1080 return $this->pg_array_parse($row[0], $schemas);
1081 }
1082
1083 /**
1084 * Return search patch for schemas
1085 * This is different from getSchemas() since it contain magic keywords
1086 * (like "$user").
1087 * Needs transaction
1088 *
1089 * @since 1.19
1090 * @return array how to search for table names schemas for the current user
1091 */
1092 function getSearchPath() {
1093 $res = $this->query( "SHOW search_path", __METHOD__);
1094 $row = $this->fetchRow( $res );
1095 /* PostgreSQL returns SHOW values as strings */
1096 return explode(",", $row[0]);
1097 }
1098
1099 /**
1100 * Update search_path, values should already be sanitized
1101 * Values may contain magic keywords like "$user"
1102 * @since 1.19
1103 *
1104 * @param $search_path array list of schemas to be searched by default
1105 */
1106 function setSearchPath( $search_path ) {
1107 $this->query( "SET search_path = " . implode(", ", $search_path) );
1108 }
1109
1110 /**
1111 * Determine default schema for MediaWiki core
1112 * Adjust this session schema search path if desired schema exists
1113 * and is not alread there.
1114 *
1115 * We need to have name of the core schema stored to be able
1116 * to query database metadata.
1117 *
1118 * This will be also called by the installer after the schema is created
1119 *
1120 * @since 1.19
1121 * @param $desired_schema string
1122 */
1123 function determineCoreSchema( $desired_schema ) {
1124 $this->begin( __METHOD__ );
1125 if ( $this->schemaExists( $desired_schema ) ) {
1126 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1127 $this->mCoreSchema = $desired_schema;
1128 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
1129 } else {
1130 /**
1131 * Prepend our schema (e.g. 'mediawiki') in front
1132 * of the search path
1133 * Fixes bug 15816
1134 */
1135 $search_path = $this->getSearchPath();
1136 array_unshift( $search_path,
1137 $this->addIdentifierQuotes( $desired_schema ));
1138 $this->setSearchPath( $search_path );
1139 $this->mCoreSchema = $desired_schema;
1140 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
1141 }
1142 } else {
1143 $this->mCoreSchema = $this->getCurrentSchema();
1144 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema ."\"\n");
1145 }
1146 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1147 $this->commit( __METHOD__ );
1148 }
1149
1150 /**
1151 * Return schema name fore core MediaWiki tables
1152 *
1153 * @since 1.19
1154 * @return string core schema name
1155 */
1156 function getCoreSchema() {
1157 return $this->mCoreSchema;
1158 }
1159
1160 /**
1161 * @return string Version information from the database
1162 */
1163 function getServerVersion() {
1164 if ( !isset( $this->numeric_version ) ) {
1165 $versionInfo = pg_version( $this->mConn );
1166 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1167 // Old client, abort install
1168 $this->numeric_version = '7.3 or earlier';
1169 } elseif ( isset( $versionInfo['server'] ) ) {
1170 // Normal client
1171 $this->numeric_version = $versionInfo['server'];
1172 } else {
1173 // Bug 16937: broken pgsql extension from PHP<5.3
1174 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1175 }
1176 }
1177 return $this->numeric_version;
1178 }
1179
1180 /**
1181 * Query whether a given relation exists (in the given schema, or the
1182 * default mw one if not given)
1183 * @return bool
1184 */
1185 function relationExists( $table, $types, $schema = false ) {
1186 if ( !is_array( $types ) ) {
1187 $types = array( $types );
1188 }
1189 if ( !$schema ) {
1190 $schema = $this->getCoreSchema();
1191 }
1192 $table = $this->realTableName( $table, 'raw' );
1193 $etable = $this->addQuotes( $table );
1194 $eschema = $this->addQuotes( $schema );
1195 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1196 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1197 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1198 $res = $this->query( $SQL );
1199 $count = $res ? $res->numRows() : 0;
1200 return (bool)$count;
1201 }
1202
1203 /**
1204 * For backward compatibility, this function checks both tables and
1205 * views.
1206 * @return bool
1207 */
1208 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1209 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1210 }
1211
1212 function sequenceExists( $sequence, $schema = false ) {
1213 return $this->relationExists( $sequence, 'S', $schema );
1214 }
1215
1216 function triggerExists( $table, $trigger ) {
1217 $q = <<<SQL
1218 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1219 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1220 AND tgrelid=pg_class.oid
1221 AND nspname=%s AND relname=%s AND tgname=%s
1222 SQL;
1223 $res = $this->query(
1224 sprintf(
1225 $q,
1226 $this->addQuotes( $this->getCoreSchema() ),
1227 $this->addQuotes( $table ),
1228 $this->addQuotes( $trigger )
1229 )
1230 );
1231 if ( !$res ) {
1232 return null;
1233 }
1234 $rows = $res->numRows();
1235 return $rows;
1236 }
1237
1238 function ruleExists( $table, $rule ) {
1239 $exists = $this->selectField( 'pg_rules', 'rulename',
1240 array(
1241 'rulename' => $rule,
1242 'tablename' => $table,
1243 'schemaname' => $this->getCoreSchema()
1244 )
1245 );
1246 return $exists === $rule;
1247 }
1248
1249 function constraintExists( $table, $constraint ) {
1250 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1251 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1252 $this->addQuotes( $this->getCoreSchema() ),
1253 $this->addQuotes( $table ),
1254 $this->addQuotes( $constraint )
1255 );
1256 $res = $this->query( $SQL );
1257 if ( !$res ) {
1258 return null;
1259 }
1260 $rows = $res->numRows();
1261 return $rows;
1262 }
1263
1264 /**
1265 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1266 * @return bool
1267 */
1268 function schemaExists( $schema ) {
1269 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1270 array( 'nspname' => $schema ), __METHOD__ );
1271 return (bool)$exists;
1272 }
1273
1274 /**
1275 * Returns true if a given role (i.e. user) exists, false otherwise.
1276 * @return bool
1277 */
1278 function roleExists( $roleName ) {
1279 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1280 array( 'rolname' => $roleName ), __METHOD__ );
1281 return (bool)$exists;
1282 }
1283
1284 function fieldInfo( $table, $field ) {
1285 return PostgresField::fromText( $this, $table, $field );
1286 }
1287
1288 /**
1289 * pg_field_type() wrapper
1290 * @return string
1291 */
1292 function fieldType( $res, $index ) {
1293 if ( $res instanceof ResultWrapper ) {
1294 $res = $res->result;
1295 }
1296 return pg_field_type( $res, $index );
1297 }
1298
1299 /* Not even sure why this is used in the main codebase... */
1300 function limitResultForUpdate( $sql, $num ) {
1301 return $sql;
1302 }
1303
1304 /**
1305 * @param $b
1306 * @return Blob
1307 */
1308 function encodeBlob( $b ) {
1309 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1310 }
1311
1312 function decodeBlob( $b ) {
1313 if ( $b instanceof Blob ) {
1314 $b = $b->fetch();
1315 }
1316 return pg_unescape_bytea( $b );
1317 }
1318
1319 function strencode( $s ) { # Should not be called by us
1320 return pg_escape_string( $this->mConn, $s );
1321 }
1322
1323 /**
1324 * @param $s null|bool|Blob
1325 * @return int|string
1326 */
1327 function addQuotes( $s ) {
1328 if ( is_null( $s ) ) {
1329 return 'NULL';
1330 } elseif ( is_bool( $s ) ) {
1331 return intval( $s );
1332 } elseif ( $s instanceof Blob ) {
1333 return "'" . $s->fetch( $s ) . "'";
1334 }
1335 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1336 }
1337
1338 /**
1339 * Postgres specific version of replaceVars.
1340 * Calls the parent version in Database.php
1341 *
1342 * @private
1343 *
1344 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1345 *
1346 * @return string SQL string
1347 */
1348 protected function replaceVars( $ins ) {
1349 $ins = parent::replaceVars( $ins );
1350
1351 if ( $this->numeric_version >= 8.3 ) {
1352 // Thanks for not providing backwards-compatibility, 8.3
1353 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1354 }
1355
1356 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1357 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1358 }
1359
1360 return $ins;
1361 }
1362
1363 /**
1364 * Various select options
1365 *
1366 * @private
1367 *
1368 * @param $options Array: an associative array of options to be turned into
1369 * an SQL query, valid keys are listed in the function.
1370 * @return array
1371 */
1372 function makeSelectOptions( $options ) {
1373 $preLimitTail = $postLimitTail = '';
1374 $startOpts = $useIndex = '';
1375
1376 $noKeyOptions = array();
1377 foreach ( $options as $key => $option ) {
1378 if ( is_numeric( $key ) ) {
1379 $noKeyOptions[$option] = true;
1380 }
1381 }
1382
1383 if ( isset( $options['GROUP BY'] ) ) {
1384 $gb = is_array( $options['GROUP BY'] )
1385 ? implode( ',', $options['GROUP BY'] )
1386 : $options['GROUP BY'];
1387 $preLimitTail .= " GROUP BY {$gb}";
1388 }
1389
1390 if ( isset( $options['HAVING'] ) ) {
1391 $preLimitTail .= " HAVING {$options['HAVING']}";
1392 }
1393
1394 if ( isset( $options['ORDER BY'] ) ) {
1395 $ob = is_array( $options['ORDER BY'] )
1396 ? implode( ',', $options['ORDER BY'] )
1397 : $options['ORDER BY'];
1398 $preLimitTail .= " ORDER BY {$ob}";
1399 }
1400
1401 //if ( isset( $options['LIMIT'] ) ) {
1402 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1403 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1404 // : false );
1405 //}
1406
1407 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1408 $postLimitTail .= ' FOR UPDATE';
1409 }
1410 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1411 $postLimitTail .= ' LOCK IN SHARE MODE';
1412 }
1413 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1414 $startOpts .= 'DISTINCT';
1415 }
1416
1417 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1418 }
1419
1420 function setFakeMaster( $enabled = true ) {}
1421
1422 function getDBname() {
1423 return $this->mDBname;
1424 }
1425
1426 function getServer() {
1427 return $this->mServer;
1428 }
1429
1430 function buildConcat( $stringList ) {
1431 return implode( ' || ', $stringList );
1432 }
1433
1434 public function getSearchEngine() {
1435 return 'SearchPostgres';
1436 }
1437
1438 public function streamStatementEnd( &$sql, &$newLine ) {
1439 # Allow dollar quoting for function declarations
1440 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1441 if ( $this->delimiter ) {
1442 $this->delimiter = false;
1443 }
1444 else {
1445 $this->delimiter = ';';
1446 }
1447 }
1448 return parent::streamStatementEnd( $sql, $newLine );
1449 }
1450 } // end DatabasePostgres class