Add some @see to doc blocks
[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 int $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 if ( $tempIgnore ) {
525 /* Check for constraint violation */
526 if ( $errno === '23505' ) {
527 parent::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
528
529 return;
530 }
531 }
532 /* Transaction stays in the ERROR state until rolledback */
533 if ( $this->mTrxLevel ) {
534 $this->rollback( __METHOD__ );
535 };
536 parent::reportQueryError( $error, $errno, $sql, $fname, false );
537 }
538
539 function queryIgnore( $sql, $fname = __METHOD__ ) {
540 return $this->query( $sql, $fname, true );
541 }
542
543 /**
544 * @param stdClass|ResultWrapper $res
545 * @throws DBUnexpectedError
546 */
547 function freeResult( $res ) {
548 if ( $res instanceof ResultWrapper ) {
549 $res = $res->result;
550 }
551 wfSuppressWarnings();
552 $ok = pg_free_result( $res );
553 wfRestoreWarnings();
554 if ( !$ok ) {
555 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
556 }
557 }
558
559 /**
560 * @param ResultWrapper|stdClass $res
561 * @return stdClass
562 * @throws DBUnexpectedError
563 */
564 function fetchObject( $res ) {
565 if ( $res instanceof ResultWrapper ) {
566 $res = $res->result;
567 }
568 wfSuppressWarnings();
569 $row = pg_fetch_object( $res );
570 wfRestoreWarnings();
571 # @todo FIXME: HACK HACK HACK HACK debug
572
573 # @todo hashar: not sure if the following test really trigger if the object
574 # fetching failed.
575 if ( pg_last_error( $this->mConn ) ) {
576 throw new DBUnexpectedError(
577 $this,
578 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
579 );
580 }
581
582 return $row;
583 }
584
585 function fetchRow( $res ) {
586 if ( $res instanceof ResultWrapper ) {
587 $res = $res->result;
588 }
589 wfSuppressWarnings();
590 $row = pg_fetch_array( $res );
591 wfRestoreWarnings();
592 if ( pg_last_error( $this->mConn ) ) {
593 throw new DBUnexpectedError(
594 $this,
595 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
596 );
597 }
598
599 return $row;
600 }
601
602 function numRows( $res ) {
603 if ( $res instanceof ResultWrapper ) {
604 $res = $res->result;
605 }
606 wfSuppressWarnings();
607 $n = pg_num_rows( $res );
608 wfRestoreWarnings();
609 if ( pg_last_error( $this->mConn ) ) {
610 throw new DBUnexpectedError(
611 $this,
612 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) )
613 );
614 }
615
616 return $n;
617 }
618
619 function numFields( $res ) {
620 if ( $res instanceof ResultWrapper ) {
621 $res = $res->result;
622 }
623
624 return pg_num_fields( $res );
625 }
626
627 function fieldName( $res, $n ) {
628 if ( $res instanceof ResultWrapper ) {
629 $res = $res->result;
630 }
631
632 return pg_field_name( $res, $n );
633 }
634
635 /**
636 * Return the result of the last call to nextSequenceValue();
637 * This must be called after nextSequenceValue().
638 *
639 * @return int|null
640 */
641 function insertId() {
642 return $this->mInsertId;
643 }
644
645 /**
646 * @param mixed $res
647 * @param int $row
648 * @return bool
649 */
650 function dataSeek( $res, $row ) {
651 if ( $res instanceof ResultWrapper ) {
652 $res = $res->result;
653 }
654
655 return pg_result_seek( $res, $row );
656 }
657
658 function lastError() {
659 if ( $this->mConn ) {
660 if ( $this->mLastResult ) {
661 return pg_result_error( $this->mLastResult );
662 } else {
663 return pg_last_error();
664 }
665 } else {
666 return 'No database connection';
667 }
668 }
669
670 function lastErrno() {
671 if ( $this->mLastResult ) {
672 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
673 } else {
674 return false;
675 }
676 }
677
678 function affectedRows() {
679 if ( !is_null( $this->mAffectedRows ) ) {
680 // Forced result for simulated queries
681 return $this->mAffectedRows;
682 }
683 if ( empty( $this->mLastResult ) ) {
684 return 0;
685 }
686
687 return pg_affected_rows( $this->mLastResult );
688 }
689
690 /**
691 * Estimate rows in dataset
692 * Returns estimated count, based on EXPLAIN output
693 * This is not necessarily an accurate estimate, so use sparingly
694 * Returns -1 if count cannot be found
695 * Takes same arguments as Database::select()
696 *
697 * @param string $table
698 * @param string $vars
699 * @param string $conds
700 * @param string $fname
701 * @param array $options
702 * @return int
703 */
704 function estimateRowCount( $table, $vars = '*', $conds = '',
705 $fname = __METHOD__, $options = array()
706 ) {
707 $options['EXPLAIN'] = true;
708 $res = $this->select( $table, $vars, $conds, $fname, $options );
709 $rows = -1;
710 if ( $res ) {
711 $row = $this->fetchRow( $res );
712 $count = array();
713 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
714 $rows = $count[1];
715 }
716 }
717
718 return $rows;
719 }
720
721 /**
722 * Returns information about an index
723 * If errors are explicitly ignored, returns NULL on failure
724 *
725 * @param string $table
726 * @param string $index
727 * @param string $fname
728 * @return bool|null
729 */
730 function indexInfo( $table, $index, $fname = __METHOD__ ) {
731 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
732 $res = $this->query( $sql, $fname );
733 if ( !$res ) {
734 return null;
735 }
736 foreach ( $res as $row ) {
737 if ( $row->indexname == $this->indexName( $index ) ) {
738 return $row;
739 }
740 }
741
742 return false;
743 }
744
745 /**
746 * Returns is of attributes used in index
747 *
748 * @since 1.19
749 * @param string $index
750 * @param bool|string $schema
751 * @return array
752 */
753 function indexAttributes( $index, $schema = false ) {
754 if ( $schema === false ) {
755 $schema = $this->getCoreSchema();
756 }
757 /*
758 * A subquery would be not needed if we didn't care about the order
759 * of attributes, but we do
760 */
761 $sql = <<<__INDEXATTR__
762
763 SELECT opcname,
764 attname,
765 i.indoption[s.g] as option,
766 pg_am.amname
767 FROM
768 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
769 FROM
770 pg_index isub
771 JOIN pg_class cis
772 ON cis.oid=isub.indexrelid
773 JOIN pg_namespace ns
774 ON cis.relnamespace = ns.oid
775 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
776 pg_attribute,
777 pg_opclass opcls,
778 pg_am,
779 pg_class ci
780 JOIN pg_index i
781 ON ci.oid=i.indexrelid
782 JOIN pg_class ct
783 ON ct.oid = i.indrelid
784 JOIN pg_namespace n
785 ON ci.relnamespace = n.oid
786 WHERE
787 ci.relname='$index' AND n.nspname='$schema'
788 AND attrelid = ct.oid
789 AND i.indkey[s.g] = attnum
790 AND i.indclass[s.g] = opcls.oid
791 AND pg_am.oid = opcls.opcmethod
792 __INDEXATTR__;
793 $res = $this->query( $sql, __METHOD__ );
794 $a = array();
795 if ( $res ) {
796 foreach ( $res as $row ) {
797 $a[] = array(
798 $row->attname,
799 $row->opcname,
800 $row->amname,
801 $row->option );
802 }
803 } else {
804 return null;
805 }
806
807 return $a;
808 }
809
810 function indexUnique( $table, $index, $fname = __METHOD__ ) {
811 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
812 " AND indexdef LIKE 'CREATE UNIQUE%(" .
813 $this->strencode( $this->indexName( $index ) ) .
814 ")'";
815 $res = $this->query( $sql, $fname );
816 if ( !$res ) {
817 return null;
818 }
819
820 return $res->numRows() > 0;
821 }
822
823 /**
824 * Change the FOR UPDATE option as necessary based on the join conditions. Then pass
825 * to the parent function to get the actual SQL text.
826 *
827 * In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
828 * can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to do
829 * so causes a DB error. This wrapper checks which tables can be locked and adjusts it accordingly.
830 *
831 * MySQL uses "ORDER BY NULL" as an optimization hint, but that syntax is illegal in PostgreSQL.
832 * @see DatabaseBase::selectSQLText
833 */
834 function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
835 $options = array(), $join_conds = array()
836 ) {
837 if ( is_array( $options ) ) {
838 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
839 if ( $forUpdateKey !== false && $join_conds ) {
840 unset( $options[$forUpdateKey] );
841
842 foreach ( $join_conds as $table_cond => $join_cond ) {
843 if ( 0 === preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_cond[0] ) ) {
844 $options['FOR UPDATE'][] = $table_cond;
845 }
846 }
847 }
848
849 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
850 unset( $options['ORDER BY'] );
851 }
852 }
853
854 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
855 }
856
857 /**
858 * INSERT wrapper, inserts an array into a table
859 *
860 * $args may be a single associative array, or an array of these with numeric keys,
861 * for multi-row insert (Postgres version 8.2 and above only).
862 *
863 * @param string $table Name of the table to insert to.
864 * @param array $args Items to insert into the table.
865 * @param string $fname Name of the function, for profiling
866 * @param array|string $options String or array. Valid options: IGNORE
867 * @return bool Success of insert operation. IGNORE always returns true.
868 */
869 function insert( $table, $args, $fname = __METHOD__, $options = array() ) {
870 if ( !count( $args ) ) {
871 return true;
872 }
873
874 $table = $this->tableName( $table );
875 if ( !isset( $this->numericVersion ) ) {
876 $this->getServerVersion();
877 }
878
879 if ( !is_array( $options ) ) {
880 $options = array( $options );
881 }
882
883 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
884 $multi = true;
885 $keys = array_keys( $args[0] );
886 } else {
887 $multi = false;
888 $keys = array_keys( $args );
889 }
890
891 // If IGNORE is set, we use savepoints to emulate mysql's behavior
892 $savepoint = null;
893 if ( in_array( 'IGNORE', $options ) ) {
894 $savepoint = new SavepointPostgres( $this, 'mw' );
895 $olde = error_reporting( 0 );
896 // For future use, we may want to track the number of actual inserts
897 // Right now, insert (all writes) simply return true/false
898 $numrowsinserted = 0;
899 }
900
901 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
902
903 if ( $multi ) {
904 if ( $this->numericVersion >= 8.2 && !$savepoint ) {
905 $first = true;
906 foreach ( $args as $row ) {
907 if ( $first ) {
908 $first = false;
909 } else {
910 $sql .= ',';
911 }
912 $sql .= '(' . $this->makeList( $row ) . ')';
913 }
914 $res = (bool)$this->query( $sql, $fname, $savepoint );
915 } else {
916 $res = true;
917 $origsql = $sql;
918 foreach ( $args as $row ) {
919 $tempsql = $origsql;
920 $tempsql .= '(' . $this->makeList( $row ) . ')';
921
922 if ( $savepoint ) {
923 $savepoint->savepoint();
924 }
925
926 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
927
928 if ( $savepoint ) {
929 $bar = pg_last_error();
930 if ( $bar != false ) {
931 $savepoint->rollback();
932 } else {
933 $savepoint->release();
934 $numrowsinserted++;
935 }
936 }
937
938 // If any of them fail, we fail overall for this function call
939 // Note that this will be ignored if IGNORE is set
940 if ( !$tempres ) {
941 $res = false;
942 }
943 }
944 }
945 } else {
946 // Not multi, just a lone insert
947 if ( $savepoint ) {
948 $savepoint->savepoint();
949 }
950
951 $sql .= '(' . $this->makeList( $args ) . ')';
952 $res = (bool)$this->query( $sql, $fname, $savepoint );
953 if ( $savepoint ) {
954 $bar = pg_last_error();
955 if ( $bar != false ) {
956 $savepoint->rollback();
957 } else {
958 $savepoint->release();
959 $numrowsinserted++;
960 }
961 }
962 }
963 if ( $savepoint ) {
964 error_reporting( $olde );
965 $savepoint->commit();
966
967 // Set the affected row count for the whole operation
968 $this->mAffectedRows = $numrowsinserted;
969
970 // IGNORE always returns true
971 return true;
972 }
973
974 return $res;
975 }
976
977 /**
978 * INSERT SELECT wrapper
979 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
980 * Source items may be literals rather then field names, but strings should
981 * be quoted with Database::addQuotes()
982 * $conds may be "*" to copy the whole table
983 * srcTable may be an array of tables.
984 * @todo FIXME: Implement this a little better (seperate select/insert)?
985 *
986 * @param string $destTable
987 * @param array|string $srcTable
988 * @param array $varMap
989 * @param array $conds
990 * @param string $fname
991 * @param array $insertOptions
992 * @param array $selectOptions
993 * @return bool
994 */
995 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
996 $insertOptions = array(), $selectOptions = array() ) {
997 $destTable = $this->tableName( $destTable );
998
999 if ( !is_array( $insertOptions ) ) {
1000 $insertOptions = array( $insertOptions );
1001 }
1002
1003 /*
1004 * If IGNORE is set, we use savepoints to emulate mysql's behavior
1005 * Ignore LOW PRIORITY option, since it is MySQL-specific
1006 */
1007 $savepoint = null;
1008 if ( in_array( 'IGNORE', $insertOptions ) ) {
1009 $savepoint = new SavepointPostgres( $this, 'mw' );
1010 $olde = error_reporting( 0 );
1011 $numrowsinserted = 0;
1012 $savepoint->savepoint();
1013 }
1014
1015 if ( !is_array( $selectOptions ) ) {
1016 $selectOptions = array( $selectOptions );
1017 }
1018 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1019 if ( is_array( $srcTable ) ) {
1020 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1021 } else {
1022 $srcTable = $this->tableName( $srcTable );
1023 }
1024
1025 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1026 " SELECT $startOpts " . implode( ',', $varMap ) .
1027 " FROM $srcTable $useIndex";
1028
1029 if ( $conds != '*' ) {
1030 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1031 }
1032
1033 $sql .= " $tailOpts";
1034
1035 $res = (bool)$this->query( $sql, $fname, $savepoint );
1036 if ( $savepoint ) {
1037 $bar = pg_last_error();
1038 if ( $bar != false ) {
1039 $savepoint->rollback();
1040 } else {
1041 $savepoint->release();
1042 $numrowsinserted++;
1043 }
1044 error_reporting( $olde );
1045 $savepoint->commit();
1046
1047 // Set the affected row count for the whole operation
1048 $this->mAffectedRows = $numrowsinserted;
1049
1050 // IGNORE always returns true
1051 return true;
1052 }
1053
1054 return $res;
1055 }
1056
1057 function tableName( $name, $format = 'quoted' ) {
1058 # Replace reserved words with better ones
1059 switch ( $name ) {
1060 case 'user':
1061 return $this->realTableName( 'mwuser', $format );
1062 case 'text':
1063 return $this->realTableName( 'pagecontent', $format );
1064 default:
1065 return $this->realTableName( $name, $format );
1066 }
1067 }
1068
1069 /* Don't cheat on installer */
1070 function realTableName( $name, $format = 'quoted' ) {
1071 return parent::tableName( $name, $format );
1072 }
1073
1074 /**
1075 * Return the next in a sequence, save the value for retrieval via insertId()
1076 *
1077 * @param string $seqName
1078 * @return int|null
1079 */
1080 function nextSequenceValue( $seqName ) {
1081 $safeseq = str_replace( "'", "''", $seqName );
1082 $res = $this->query( "SELECT nextval('$safeseq')" );
1083 $row = $this->fetchRow( $res );
1084 $this->mInsertId = $row[0];
1085
1086 return $this->mInsertId;
1087 }
1088
1089 /**
1090 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
1091 *
1092 * @param string $seqName
1093 * @return int
1094 */
1095 function currentSequenceValue( $seqName ) {
1096 $safeseq = str_replace( "'", "''", $seqName );
1097 $res = $this->query( "SELECT currval('$safeseq')" );
1098 $row = $this->fetchRow( $res );
1099 $currval = $row[0];
1100
1101 return $currval;
1102 }
1103
1104 # Returns the size of a text field, or -1 for "unlimited"
1105 function textFieldSize( $table, $field ) {
1106 $table = $this->tableName( $table );
1107 $sql = "SELECT t.typname as ftype,a.atttypmod as size
1108 FROM pg_class c, pg_attribute a, pg_type t
1109 WHERE relname='$table' AND a.attrelid=c.oid AND
1110 a.atttypid=t.oid and a.attname='$field'";
1111 $res = $this->query( $sql );
1112 $row = $this->fetchObject( $res );
1113 if ( $row->ftype == 'varchar' ) {
1114 $size = $row->size - 4;
1115 } else {
1116 $size = $row->size;
1117 }
1118
1119 return $size;
1120 }
1121
1122 function limitResult( $sql, $limit, $offset = false ) {
1123 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
1124 }
1125
1126 function wasDeadlock() {
1127 return $this->lastErrno() == '40P01';
1128 }
1129
1130 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
1131 $newName = $this->addIdentifierQuotes( $newName );
1132 $oldName = $this->addIdentifierQuotes( $oldName );
1133
1134 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
1135 "(LIKE $oldName INCLUDING DEFAULTS)", $fname );
1136 }
1137
1138 function listTables( $prefix = null, $fname = __METHOD__ ) {
1139 $eschema = $this->addQuotes( $this->getCoreSchema() );
1140 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
1141 $endArray = array();
1142
1143 foreach ( $result as $table ) {
1144 $vars = get_object_vars( $table );
1145 $table = array_pop( $vars );
1146 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
1147 $endArray[] = $table;
1148 }
1149 }
1150
1151 return $endArray;
1152 }
1153
1154 function timestamp( $ts = 0 ) {
1155 return wfTimestamp( TS_POSTGRES, $ts );
1156 }
1157
1158 /**
1159 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
1160 * to http://www.php.net/manual/en/ref.pgsql.php
1161 *
1162 * Parsing a postgres array can be a tricky problem, he's my
1163 * take on this, it handles multi-dimensional arrays plus
1164 * escaping using a nasty regexp to determine the limits of each
1165 * data-item.
1166 *
1167 * This should really be handled by PHP PostgreSQL module
1168 *
1169 * @since 1.19
1170 * @param string $text Postgreql array returned in a text form like {a,b}
1171 * @param string $output
1172 * @param int $limit
1173 * @param int $offset
1174 * @return string
1175 */
1176 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1177 if ( false === $limit ) {
1178 $limit = strlen( $text ) - 1;
1179 $output = array();
1180 }
1181 if ( '{}' == $text ) {
1182 return $output;
1183 }
1184 do {
1185 if ( '{' != $text[$offset] ) {
1186 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1187 $text, $match, 0, $offset );
1188 $offset += strlen( $match[0] );
1189 $output[] = ( '"' != $match[1][0]
1190 ? $match[1]
1191 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1192 if ( '},' == $match[3] ) {
1193 return $output;
1194 }
1195 } else {
1196 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
1197 }
1198 } while ( $limit > $offset );
1199
1200 return $output;
1201 }
1202
1203 /**
1204 * Return aggregated value function call
1205 * @param array $valuedata
1206 * @param string $valuename
1207 * @return array
1208 */
1209 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1210 return $valuedata;
1211 }
1212
1213 /**
1214 * @return string Wikitext of a link to the server software's web site
1215 */
1216 public function getSoftwareLink() {
1217 return '[{{int:version-db-postgres-url}} PostgreSQL]';
1218 }
1219
1220 /**
1221 * Return current schema (executes SELECT current_schema())
1222 * Needs transaction
1223 *
1224 * @since 1.19
1225 * @return string Default schema for the current session
1226 */
1227 function getCurrentSchema() {
1228 $res = $this->query( "SELECT current_schema()", __METHOD__ );
1229 $row = $this->fetchRow( $res );
1230
1231 return $row[0];
1232 }
1233
1234 /**
1235 * Return list of schemas which are accessible without schema name
1236 * This is list does not contain magic keywords like "$user"
1237 * Needs transaction
1238 *
1239 * @see getSearchPath()
1240 * @see setSearchPath()
1241 * @since 1.19
1242 * @return array List of actual schemas for the current sesson
1243 */
1244 function getSchemas() {
1245 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1246 $row = $this->fetchRow( $res );
1247 $schemas = array();
1248
1249 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1250
1251 return $this->pg_array_parse( $row[0], $schemas );
1252 }
1253
1254 /**
1255 * Return search patch for schemas
1256 * This is different from getSchemas() since it contain magic keywords
1257 * (like "$user").
1258 * Needs transaction
1259 *
1260 * @since 1.19
1261 * @return array How to search for table names schemas for the current user
1262 */
1263 function getSearchPath() {
1264 $res = $this->query( "SHOW search_path", __METHOD__ );
1265 $row = $this->fetchRow( $res );
1266
1267 /* PostgreSQL returns SHOW values as strings */
1268
1269 return explode( ",", $row[0] );
1270 }
1271
1272 /**
1273 * Update search_path, values should already be sanitized
1274 * Values may contain magic keywords like "$user"
1275 * @since 1.19
1276 *
1277 * @param array $search_path List of schemas to be searched by default
1278 */
1279 function setSearchPath( $search_path ) {
1280 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1281 }
1282
1283 /**
1284 * Determine default schema for MediaWiki core
1285 * Adjust this session schema search path if desired schema exists
1286 * and is not alread there.
1287 *
1288 * We need to have name of the core schema stored to be able
1289 * to query database metadata.
1290 *
1291 * This will be also called by the installer after the schema is created
1292 *
1293 * @since 1.19
1294 *
1295 * @param string $desiredSchema
1296 */
1297 function determineCoreSchema( $desiredSchema ) {
1298 $this->begin( __METHOD__ );
1299 if ( $this->schemaExists( $desiredSchema ) ) {
1300 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1301 $this->mCoreSchema = $desiredSchema;
1302 wfDebug( "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1303 } else {
1304 /**
1305 * Prepend our schema (e.g. 'mediawiki') in front
1306 * of the search path
1307 * Fixes bug 15816
1308 */
1309 $search_path = $this->getSearchPath();
1310 array_unshift( $search_path,
1311 $this->addIdentifierQuotes( $desiredSchema ) );
1312 $this->setSearchPath( $search_path );
1313 $this->mCoreSchema = $desiredSchema;
1314 wfDebug( "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1315 }
1316 } else {
1317 $this->mCoreSchema = $this->getCurrentSchema();
1318 wfDebug( "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1319 $this->mCoreSchema . "\"\n" );
1320 }
1321 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1322 $this->commit( __METHOD__ );
1323 }
1324
1325 /**
1326 * Return schema name fore core MediaWiki tables
1327 *
1328 * @since 1.19
1329 * @return string Core schema name
1330 */
1331 function getCoreSchema() {
1332 return $this->mCoreSchema;
1333 }
1334
1335 /**
1336 * @return string Version information from the database
1337 */
1338 function getServerVersion() {
1339 if ( !isset( $this->numericVersion ) ) {
1340 $versionInfo = pg_version( $this->mConn );
1341 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1342 // Old client, abort install
1343 $this->numericVersion = '7.3 or earlier';
1344 } elseif ( isset( $versionInfo['server'] ) ) {
1345 // Normal client
1346 $this->numericVersion = $versionInfo['server'];
1347 } else {
1348 // Bug 16937: broken pgsql extension from PHP<5.3
1349 $this->numericVersion = pg_parameter_status( $this->mConn, 'server_version' );
1350 }
1351 }
1352
1353 return $this->numericVersion;
1354 }
1355
1356 /**
1357 * Query whether a given relation exists (in the given schema, or the
1358 * default mw one if not given)
1359 * @param string $table
1360 * @param array|string $types
1361 * @param bool|string $schema
1362 * @return bool
1363 */
1364 function relationExists( $table, $types, $schema = false ) {
1365 if ( !is_array( $types ) ) {
1366 $types = array( $types );
1367 }
1368 if ( !$schema ) {
1369 $schema = $this->getCoreSchema();
1370 }
1371 $table = $this->realTableName( $table, 'raw' );
1372 $etable = $this->addQuotes( $table );
1373 $eschema = $this->addQuotes( $schema );
1374 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1375 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1376 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1377 $res = $this->query( $sql );
1378 $count = $res ? $res->numRows() : 0;
1379
1380 return (bool)$count;
1381 }
1382
1383 /**
1384 * For backward compatibility, this function checks both tables and
1385 * views.
1386 * @param string $table
1387 * @param string $fname
1388 * @param bool|string $schema
1389 * @return bool
1390 */
1391 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1392 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1393 }
1394
1395 function sequenceExists( $sequence, $schema = false ) {
1396 return $this->relationExists( $sequence, 'S', $schema );
1397 }
1398
1399 function triggerExists( $table, $trigger ) {
1400 $q = <<<SQL
1401 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1402 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1403 AND tgrelid=pg_class.oid
1404 AND nspname=%s AND relname=%s AND tgname=%s
1405 SQL;
1406 $res = $this->query(
1407 sprintf(
1408 $q,
1409 $this->addQuotes( $this->getCoreSchema() ),
1410 $this->addQuotes( $table ),
1411 $this->addQuotes( $trigger )
1412 )
1413 );
1414 if ( !$res ) {
1415 return null;
1416 }
1417 $rows = $res->numRows();
1418
1419 return $rows;
1420 }
1421
1422 function ruleExists( $table, $rule ) {
1423 $exists = $this->selectField( 'pg_rules', 'rulename',
1424 array(
1425 'rulename' => $rule,
1426 'tablename' => $table,
1427 'schemaname' => $this->getCoreSchema()
1428 )
1429 );
1430
1431 return $exists === $rule;
1432 }
1433
1434 function constraintExists( $table, $constraint ) {
1435 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1436 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1437 $this->addQuotes( $this->getCoreSchema() ),
1438 $this->addQuotes( $table ),
1439 $this->addQuotes( $constraint )
1440 );
1441 $res = $this->query( $sql );
1442 if ( !$res ) {
1443 return null;
1444 }
1445 $rows = $res->numRows();
1446
1447 return $rows;
1448 }
1449
1450 /**
1451 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1452 * @param string $schema
1453 * @return bool
1454 */
1455 function schemaExists( $schema ) {
1456 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1457 array( 'nspname' => $schema ), __METHOD__ );
1458
1459 return (bool)$exists;
1460 }
1461
1462 /**
1463 * Returns true if a given role (i.e. user) exists, false otherwise.
1464 * @param string $roleName
1465 * @return bool
1466 */
1467 function roleExists( $roleName ) {
1468 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1469 array( 'rolname' => $roleName ), __METHOD__ );
1470
1471 return (bool)$exists;
1472 }
1473
1474 function fieldInfo( $table, $field ) {
1475 return PostgresField::fromText( $this, $table, $field );
1476 }
1477
1478 /**
1479 * pg_field_type() wrapper
1480 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1481 * @param int $index Field number, starting from 0
1482 * @return string
1483 */
1484 function fieldType( $res, $index ) {
1485 if ( $res instanceof ResultWrapper ) {
1486 $res = $res->result;
1487 }
1488
1489 return pg_field_type( $res, $index );
1490 }
1491
1492 /**
1493 * @param string $b
1494 * @return Blob
1495 */
1496 function encodeBlob( $b ) {
1497 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1498 }
1499
1500 function decodeBlob( $b ) {
1501 if ( $b instanceof Blob ) {
1502 $b = $b->fetch();
1503 }
1504
1505 return pg_unescape_bytea( $b );
1506 }
1507
1508 function strencode( $s ) { # Should not be called by us
1509 return pg_escape_string( $this->mConn, $s );
1510 }
1511
1512 /**
1513 * @param null|bool|Blob $s
1514 * @return int|string
1515 */
1516 function addQuotes( $s ) {
1517 if ( is_null( $s ) ) {
1518 return 'NULL';
1519 } elseif ( is_bool( $s ) ) {
1520 return intval( $s );
1521 } elseif ( $s instanceof Blob ) {
1522 return "'" . $s->fetch( $s ) . "'";
1523 }
1524
1525 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1526 }
1527
1528 /**
1529 * Postgres specific version of replaceVars.
1530 * Calls the parent version in Database.php
1531 *
1532 * @param string $ins SQL string, read from a stream (usually tables.sql)
1533 * @return string SQL string
1534 */
1535 protected function replaceVars( $ins ) {
1536 $ins = parent::replaceVars( $ins );
1537
1538 if ( $this->numericVersion >= 8.3 ) {
1539 // Thanks for not providing backwards-compatibility, 8.3
1540 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1541 }
1542
1543 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1544 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1545 }
1546
1547 return $ins;
1548 }
1549
1550 /**
1551 * Various select options
1552 *
1553 * @param array $options An associative array of options to be turned into
1554 * an SQL query, valid keys are listed in the function.
1555 * @return array
1556 */
1557 function makeSelectOptions( $options ) {
1558 $preLimitTail = $postLimitTail = '';
1559 $startOpts = $useIndex = '';
1560
1561 $noKeyOptions = array();
1562 foreach ( $options as $key => $option ) {
1563 if ( is_numeric( $key ) ) {
1564 $noKeyOptions[$option] = true;
1565 }
1566 }
1567
1568 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1569
1570 $preLimitTail .= $this->makeOrderBy( $options );
1571
1572 //if ( isset( $options['LIMIT'] ) ) {
1573 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1574 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1575 // : false );
1576 //}
1577
1578 if ( isset( $options['FOR UPDATE'] ) ) {
1579 $postLimitTail .= ' FOR UPDATE OF ' .
1580 implode( ', ', array_map( array( &$this, 'tableName' ), $options['FOR UPDATE'] ) );
1581 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1582 $postLimitTail .= ' FOR UPDATE';
1583 }
1584
1585 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1586 $startOpts .= 'DISTINCT';
1587 }
1588
1589 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1590 }
1591
1592 function getDBname() {
1593 return $this->mDBname;
1594 }
1595
1596 function getServer() {
1597 return $this->mServer;
1598 }
1599
1600 function buildConcat( $stringList ) {
1601 return implode( ' || ', $stringList );
1602 }
1603
1604 public function buildGroupConcatField(
1605 $delimiter, $table, $field, $conds = '', $options = array(), $join_conds = array()
1606 ) {
1607 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1608
1609 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1610 }
1611
1612 public function getSearchEngine() {
1613 return 'SearchPostgres';
1614 }
1615
1616 public function streamStatementEnd( &$sql, &$newLine ) {
1617 # Allow dollar quoting for function declarations
1618 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1619 if ( $this->delimiter ) {
1620 $this->delimiter = false;
1621 } else {
1622 $this->delimiter = ';';
1623 }
1624 }
1625
1626 return parent::streamStatementEnd( $sql, $newLine );
1627 }
1628
1629 /**
1630 * Check to see if a named lock is available. This is non-blocking.
1631 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1632 *
1633 * @param string $lockName Name of lock to poll
1634 * @param string $method Name of method calling us
1635 * @return bool
1636 * @since 1.20
1637 */
1638 public function lockIsFree( $lockName, $method ) {
1639 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1640 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1641 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1642 $row = $this->fetchObject( $result );
1643
1644 return ( $row->lockstatus === 't' );
1645 }
1646
1647 /**
1648 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1649 * @param string $lockName
1650 * @param string $method
1651 * @param int $timeout
1652 * @return bool
1653 */
1654 public function lock( $lockName, $method, $timeout = 5 ) {
1655 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1656 for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1657 $result = $this->query(
1658 "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1659 $row = $this->fetchObject( $result );
1660 if ( $row->lockstatus === 't' ) {
1661 return true;
1662 } else {
1663 sleep( 1 );
1664 }
1665 }
1666 wfDebug( __METHOD__ . " failed to acquire lock\n" );
1667
1668 return false;
1669 }
1670
1671 /**
1672 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKSFROM
1673 * PG DOCS: http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1674 * @param string $lockName
1675 * @param string $method
1676 * @return bool
1677 */
1678 public function unlock( $lockName, $method ) {
1679 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1680 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1681 $row = $this->fetchObject( $result );
1682
1683 return ( $row->lockstatus === 't' );
1684 }
1685
1686 /**
1687 * @param string $lockName
1688 * @return string Integer
1689 */
1690 private function bigintFromLockName( $lockName ) {
1691 return wfBaseConvert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1692 }
1693 } // end DatabasePostgres class