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