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