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