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