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