Merge "Moved JobQueueDB::recycleAndDeleteStaleJobs() function below overriden ones."
[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 $this->mConn = pg_connect( $this->connectString );
374 $phpError = $this->restoreErrorHandler();
375
376 if ( !$this->mConn ) {
377 wfDebug( "DB connection error\n" );
378 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
379 wfDebug( $this->lastError() . "\n" );
380 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
381 }
382
383 $this->mOpened = true;
384 $this->mTransactionState = new PostgresTransactionState( $this->mConn );
385
386 global $wgCommandLineMode;
387 # If called from the command-line (e.g. importDump), only show errors
388 if ( $wgCommandLineMode ) {
389 $this->doQuery( "SET client_min_messages = 'ERROR'" );
390 }
391
392 $this->query( "SET client_encoding='UTF8'", __METHOD__ );
393 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
394 $this->query( "SET timezone = 'GMT'", __METHOD__ );
395 $this->query( "SET standard_conforming_strings = on", __METHOD__ );
396 if ( $this->getServerVersion() >= 9.0 ) {
397 $this->query( "SET bytea_output = 'escape'", __METHOD__ ); // PHP bug 53127
398 }
399
400 global $wgDBmwschema;
401 $this->determineCoreSchema( $wgDBmwschema );
402
403 return $this->mConn;
404 }
405
406 /**
407 * Postgres doesn't support selectDB in the same way MySQL does. So if the
408 * DB name doesn't match the open connection, open a new one
409 * @return
410 */
411 function selectDB( $db ) {
412 if ( $this->mDBname !== $db ) {
413 return (bool)$this->open( $this->mServer, $this->mUser, $this->mPassword, $db );
414 } else {
415 return true;
416 }
417 }
418
419 function makeConnectionString( $vars ) {
420 $s = '';
421 foreach ( $vars as $name => $value ) {
422 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
423 }
424 return $s;
425 }
426
427 /**
428 * Closes a database connection, if it is open
429 * Returns success, true if already closed
430 * @return bool
431 */
432 protected function closeConnection() {
433 return pg_close( $this->mConn );
434 }
435
436 public function doQuery( $sql ) {
437 if ( function_exists( 'mb_convert_encoding' ) ) {
438 $sql = mb_convert_encoding( $sql, 'UTF-8' );
439 }
440 $this->mTransactionState->check();
441 if( pg_send_query( $this->mConn, $sql ) === false ) {
442 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
443 }
444 $this->mLastResult = pg_get_result( $this->mConn );
445 $this->mTransactionState->check();
446 $this->mAffectedRows = null;
447 if ( pg_result_error( $this->mLastResult ) ) {
448 return false;
449 }
450 return $this->mLastResult;
451 }
452
453 protected function dumpError() {
454 $diags = array( PGSQL_DIAG_SEVERITY,
455 PGSQL_DIAG_SQLSTATE,
456 PGSQL_DIAG_MESSAGE_PRIMARY,
457 PGSQL_DIAG_MESSAGE_DETAIL,
458 PGSQL_DIAG_MESSAGE_HINT,
459 PGSQL_DIAG_STATEMENT_POSITION,
460 PGSQL_DIAG_INTERNAL_POSITION,
461 PGSQL_DIAG_INTERNAL_QUERY,
462 PGSQL_DIAG_CONTEXT,
463 PGSQL_DIAG_SOURCE_FILE,
464 PGSQL_DIAG_SOURCE_LINE,
465 PGSQL_DIAG_SOURCE_FUNCTION );
466 foreach ( $diags as $d ) {
467 wfDebug( sprintf("PgSQL ERROR(%d): %s\n", $d, pg_result_error_field( $this->mLastResult, $d ) ) );
468 }
469 }
470
471 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
472 /* Transaction stays in the ERROR state until rolledback */
473 if ( $tempIgnore ) {
474 /* Check for constraint violation */
475 if ( $errno === '23505' ) {
476 parent::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
477 return;
478 }
479 }
480 /* Don't ignore serious errors */
481 $this->rollback( __METHOD__ );
482 parent::reportQueryError( $error, $errno, $sql, $fname, false );
483 }
484
485 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
486 return $this->query( $sql, $fname, true );
487 }
488
489 function freeResult( $res ) {
490 if ( $res instanceof ResultWrapper ) {
491 $res = $res->result;
492 }
493 wfSuppressWarnings();
494 $ok = pg_free_result( $res );
495 wfRestoreWarnings();
496 if ( !$ok ) {
497 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
498 }
499 }
500
501 function fetchObject( $res ) {
502 if ( $res instanceof ResultWrapper ) {
503 $res = $res->result;
504 }
505 wfSuppressWarnings();
506 $row = pg_fetch_object( $res );
507 wfRestoreWarnings();
508 # @todo FIXME: HACK HACK HACK HACK debug
509
510 # @todo hashar: not sure if the following test really trigger if the object
511 # fetching failed.
512 if( pg_last_error( $this->mConn ) ) {
513 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
514 }
515 return $row;
516 }
517
518 function fetchRow( $res ) {
519 if ( $res instanceof ResultWrapper ) {
520 $res = $res->result;
521 }
522 wfSuppressWarnings();
523 $row = pg_fetch_array( $res );
524 wfRestoreWarnings();
525 if( pg_last_error( $this->mConn ) ) {
526 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
527 }
528 return $row;
529 }
530
531 function numRows( $res ) {
532 if ( $res instanceof ResultWrapper ) {
533 $res = $res->result;
534 }
535 wfSuppressWarnings();
536 $n = pg_num_rows( $res );
537 wfRestoreWarnings();
538 if( pg_last_error( $this->mConn ) ) {
539 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
540 }
541 return $n;
542 }
543
544 function numFields( $res ) {
545 if ( $res instanceof ResultWrapper ) {
546 $res = $res->result;
547 }
548 return pg_num_fields( $res );
549 }
550
551 function fieldName( $res, $n ) {
552 if ( $res instanceof ResultWrapper ) {
553 $res = $res->result;
554 }
555 return pg_field_name( $res, $n );
556 }
557
558 /**
559 * Return the result of the last call to nextSequenceValue();
560 * This must be called after nextSequenceValue().
561 *
562 * @return integer|null
563 */
564 function insertId() {
565 return $this->mInsertId;
566 }
567
568 function dataSeek( $res, $row ) {
569 if ( $res instanceof ResultWrapper ) {
570 $res = $res->result;
571 }
572 return pg_result_seek( $res, $row );
573 }
574
575 function lastError() {
576 if ( $this->mConn ) {
577 if ( $this->mLastResult ) {
578 return pg_result_error( $this->mLastResult );
579 } else {
580 return pg_last_error();
581 }
582 } else {
583 return 'No database connection';
584 }
585 }
586 function lastErrno() {
587 if ( $this->mLastResult ) {
588 return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
589 } else {
590 return false;
591 }
592 }
593
594 function affectedRows() {
595 if ( !is_null( $this->mAffectedRows ) ) {
596 // Forced result for simulated queries
597 return $this->mAffectedRows;
598 }
599 if( empty( $this->mLastResult ) ) {
600 return 0;
601 }
602 return pg_affected_rows( $this->mLastResult );
603 }
604
605 /**
606 * Estimate rows in dataset
607 * Returns estimated count, based on EXPLAIN output
608 * This is not necessarily an accurate estimate, so use sparingly
609 * Returns -1 if count cannot be found
610 * Takes same arguments as Database::select()
611 * @return int
612 */
613 function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
614 $options['EXPLAIN'] = true;
615 $res = $this->select( $table, $vars, $conds, $fname, $options );
616 $rows = -1;
617 if ( $res ) {
618 $row = $this->fetchRow( $res );
619 $count = array();
620 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
621 $rows = $count[1];
622 }
623 }
624 return $rows;
625 }
626
627 /**
628 * Returns information about an index
629 * If errors are explicitly ignored, returns NULL on failure
630 * @return bool|null
631 */
632 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
633 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
634 $res = $this->query( $sql, $fname );
635 if ( !$res ) {
636 return null;
637 }
638 foreach ( $res as $row ) {
639 if ( $row->indexname == $this->indexName( $index ) ) {
640 return $row;
641 }
642 }
643 return false;
644 }
645
646 /**
647 * Returns is of attributes used in index
648 *
649 * @since 1.19
650 * @return Array
651 */
652 function indexAttributes( $index, $schema = false ) {
653 if ( $schema === false )
654 $schema = $this->getCoreSchema();
655 /*
656 * A subquery would be not needed if we didn't care about the order
657 * of attributes, but we do
658 */
659 $sql = <<<__INDEXATTR__
660
661 SELECT opcname,
662 attname,
663 i.indoption[s.g] as option,
664 pg_am.amname
665 FROM
666 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
667 FROM
668 pg_index isub
669 JOIN pg_class cis
670 ON cis.oid=isub.indexrelid
671 JOIN pg_namespace ns
672 ON cis.relnamespace = ns.oid
673 WHERE cis.relname='$index' AND ns.nspname='$schema') AS s,
674 pg_attribute,
675 pg_opclass opcls,
676 pg_am,
677 pg_class ci
678 JOIN pg_index i
679 ON ci.oid=i.indexrelid
680 JOIN pg_class ct
681 ON ct.oid = i.indrelid
682 JOIN pg_namespace n
683 ON ci.relnamespace = n.oid
684 WHERE
685 ci.relname='$index' AND n.nspname='$schema'
686 AND attrelid = ct.oid
687 AND i.indkey[s.g] = attnum
688 AND i.indclass[s.g] = opcls.oid
689 AND pg_am.oid = opcls.opcmethod
690 __INDEXATTR__;
691 $res = $this->query( $sql, __METHOD__ );
692 $a = array();
693 if ( $res ) {
694 foreach ( $res as $row ) {
695 $a[] = array(
696 $row->attname,
697 $row->opcname,
698 $row->amname,
699 $row->option );
700 }
701 } else {
702 return null;
703 }
704 return $a;
705 }
706
707 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
708 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
709 " AND indexdef LIKE 'CREATE UNIQUE%(" .
710 $this->strencode( $this->indexName( $index ) ) .
711 ")'";
712 $res = $this->query( $sql, $fname );
713 if ( !$res ) {
714 return null;
715 }
716 foreach ( $res as $row ) {
717 return true;
718 }
719 return false;
720 }
721
722 /**
723 * INSERT wrapper, inserts an array into a table
724 *
725 * $args may be a single associative array, or an array of these with numeric keys,
726 * for multi-row insert (Postgres version 8.2 and above only).
727 *
728 * @param $table String: Name of the table to insert to.
729 * @param $args Array: Items to insert into the table.
730 * @param $fname String: Name of the function, for profiling
731 * @param string $options or Array. Valid options: IGNORE
732 *
733 * @return bool Success of insert operation. IGNORE always returns true.
734 */
735 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
736 if ( !count( $args ) ) {
737 return true;
738 }
739
740 $table = $this->tableName( $table );
741 if ( !isset( $this->numeric_version ) ) {
742 $this->getServerVersion();
743 }
744
745 if ( !is_array( $options ) ) {
746 $options = array( $options );
747 }
748
749 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
750 $multi = true;
751 $keys = array_keys( $args[0] );
752 } else {
753 $multi = false;
754 $keys = array_keys( $args );
755 }
756
757 // If IGNORE is set, we use savepoints to emulate mysql's behavior
758 $savepoint = null;
759 if ( in_array( 'IGNORE', $options ) ) {
760 $savepoint = new SavepointPostgres( $this, 'mw' );
761 $olde = error_reporting( 0 );
762 // For future use, we may want to track the number of actual inserts
763 // Right now, insert (all writes) simply return true/false
764 $numrowsinserted = 0;
765 }
766
767 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
768
769 if ( $multi ) {
770 if ( $this->numeric_version >= 8.2 && !$savepoint ) {
771 $first = true;
772 foreach ( $args as $row ) {
773 if ( $first ) {
774 $first = false;
775 } else {
776 $sql .= ',';
777 }
778 $sql .= '(' . $this->makeList( $row ) . ')';
779 }
780 $res = (bool)$this->query( $sql, $fname, $savepoint );
781 } else {
782 $res = true;
783 $origsql = $sql;
784 foreach ( $args as $row ) {
785 $tempsql = $origsql;
786 $tempsql .= '(' . $this->makeList( $row ) . ')';
787
788 if ( $savepoint ) {
789 $savepoint->savepoint();
790 }
791
792 $tempres = (bool)$this->query( $tempsql, $fname, $savepoint );
793
794 if ( $savepoint ) {
795 $bar = pg_last_error();
796 if ( $bar != false ) {
797 $savepoint->rollback();
798 } else {
799 $savepoint->release();
800 $numrowsinserted++;
801 }
802 }
803
804 // If any of them fail, we fail overall for this function call
805 // Note that this will be ignored if IGNORE is set
806 if ( !$tempres ) {
807 $res = false;
808 }
809 }
810 }
811 } else {
812 // Not multi, just a lone insert
813 if ( $savepoint ) {
814 $savepoint->savepoint();
815 }
816
817 $sql .= '(' . $this->makeList( $args ) . ')';
818 $res = (bool)$this->query( $sql, $fname, $savepoint );
819 if ( $savepoint ) {
820 $bar = pg_last_error();
821 if ( $bar != false ) {
822 $savepoint->rollback();
823 } else {
824 $savepoint->release();
825 $numrowsinserted++;
826 }
827 }
828 }
829 if ( $savepoint ) {
830 $olde = error_reporting( $olde );
831 $savepoint->commit();
832
833 // Set the affected row count for the whole operation
834 $this->mAffectedRows = $numrowsinserted;
835
836 // IGNORE always returns true
837 return true;
838 }
839
840 return $res;
841 }
842
843 /**
844 * INSERT SELECT wrapper
845 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
846 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
847 * $conds may be "*" to copy the whole table
848 * srcTable may be an array of tables.
849 * @todo FIXME: Implement this a little better (seperate select/insert)?
850 * @return bool
851 */
852 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
853 $insertOptions = array(), $selectOptions = array() )
854 {
855 $destTable = $this->tableName( $destTable );
856
857 if( !is_array( $insertOptions ) ) {
858 $insertOptions = array( $insertOptions );
859 }
860
861 /*
862 * If IGNORE is set, we use savepoints to emulate mysql's behavior
863 * Ignore LOW PRIORITY option, since it is MySQL-specific
864 */
865 $savepoint = null;
866 if ( in_array( 'IGNORE', $insertOptions ) ) {
867 $savepoint = new SavepointPostgres( $this, 'mw' );
868 $olde = error_reporting( 0 );
869 $numrowsinserted = 0;
870 $savepoint->savepoint();
871 }
872
873 if( !is_array( $selectOptions ) ) {
874 $selectOptions = array( $selectOptions );
875 }
876 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
877 if( is_array( $srcTable ) ) {
878 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
879 } else {
880 $srcTable = $this->tableName( $srcTable );
881 }
882
883 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
884 " SELECT $startOpts " . implode( ',', $varMap ) .
885 " FROM $srcTable $useIndex";
886
887 if ( $conds != '*' ) {
888 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
889 }
890
891 $sql .= " $tailOpts";
892
893 $res = (bool)$this->query( $sql, $fname, $savepoint );
894 if( $savepoint ) {
895 $bar = pg_last_error();
896 if( $bar != false ) {
897 $savepoint->rollback();
898 } else {
899 $savepoint->release();
900 $numrowsinserted++;
901 }
902 $olde = error_reporting( $olde );
903 $savepoint->commit();
904
905 // Set the affected row count for the whole operation
906 $this->mAffectedRows = $numrowsinserted;
907
908 // IGNORE always returns true
909 return true;
910 }
911
912 return $res;
913 }
914
915 function tableName( $name, $format = 'quoted' ) {
916 # Replace reserved words with better ones
917 switch( $name ) {
918 case 'user':
919 return $this->realTableName( 'mwuser', $format );
920 case 'text':
921 return $this->realTableName( 'pagecontent', $format );
922 default:
923 return $this->realTableName( $name, $format );
924 }
925 }
926
927 /* Don't cheat on installer */
928 function realTableName( $name, $format = 'quoted' ) {
929 return parent::tableName( $name, $format );
930 }
931
932 /**
933 * Return the next in a sequence, save the value for retrieval via insertId()
934 * @return null
935 */
936 function nextSequenceValue( $seqName ) {
937 $safeseq = str_replace( "'", "''", $seqName );
938 $res = $this->query( "SELECT nextval('$safeseq')" );
939 $row = $this->fetchRow( $res );
940 $this->mInsertId = $row[0];
941 return $this->mInsertId;
942 }
943
944 /**
945 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
946 * @return
947 */
948 function currentSequenceValue( $seqName ) {
949 $safeseq = str_replace( "'", "''", $seqName );
950 $res = $this->query( "SELECT currval('$safeseq')" );
951 $row = $this->fetchRow( $res );
952 $currval = $row[0];
953 return $currval;
954 }
955
956 # Returns the size of a text field, or -1 for "unlimited"
957 function textFieldSize( $table, $field ) {
958 $table = $this->tableName( $table );
959 $sql = "SELECT t.typname as ftype,a.atttypmod as size
960 FROM pg_class c, pg_attribute a, pg_type t
961 WHERE relname='$table' AND a.attrelid=c.oid AND
962 a.atttypid=t.oid and a.attname='$field'";
963 $res = $this->query( $sql );
964 $row = $this->fetchObject( $res );
965 if ( $row->ftype == 'varchar' ) {
966 $size = $row->size - 4;
967 } else {
968 $size = $row->size;
969 }
970 return $size;
971 }
972
973 function limitResult( $sql, $limit, $offset = false ) {
974 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
975 }
976
977 function wasDeadlock() {
978 return $this->lastErrno() == '40P01';
979 }
980
981 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
982 $newName = $this->addIdentifierQuotes( $newName );
983 $oldName = $this->addIdentifierQuotes( $oldName );
984 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
985 }
986
987 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
988 $eschema = $this->addQuotes( $this->getCoreSchema() );
989 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
990 $endArray = array();
991
992 foreach( $result as $table ) {
993 $vars = get_object_vars( $table );
994 $table = array_pop( $vars );
995 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
996 $endArray[] = $table;
997 }
998 }
999
1000 return $endArray;
1001 }
1002
1003 function timestamp( $ts = 0 ) {
1004 return wfTimestamp( TS_POSTGRES, $ts );
1005 }
1006
1007 /*
1008 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
1009 * to http://www.php.net/manual/en/ref.pgsql.php
1010 *
1011 * Parsing a postgres array can be a tricky problem, he's my
1012 * take on this, it handles multi-dimensional arrays plus
1013 * escaping using a nasty regexp to determine the limits of each
1014 * data-item.
1015 *
1016 * This should really be handled by PHP PostgreSQL module
1017 *
1018 * @since 1.19
1019 * @param $text string: postgreql array returned in a text form like {a,b}
1020 * @param $output string
1021 * @param $limit int
1022 * @param $offset int
1023 * @return string
1024 */
1025 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
1026 if( false === $limit ) {
1027 $limit = strlen( $text ) - 1;
1028 $output = array();
1029 }
1030 if( '{}' == $text ) {
1031 return $output;
1032 }
1033 do {
1034 if ( '{' != $text{$offset} ) {
1035 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
1036 $text, $match, 0, $offset );
1037 $offset += strlen( $match[0] );
1038 $output[] = ( '"' != $match[1]{0}
1039 ? $match[1]
1040 : stripcslashes( substr( $match[1], 1, -1 ) ) );
1041 if ( '},' == $match[3] ) {
1042 return $output;
1043 }
1044 } else {
1045 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
1046 }
1047 } while ( $limit > $offset );
1048 return $output;
1049 }
1050
1051 /**
1052 * Return aggregated value function call
1053 */
1054 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1055 return $valuedata;
1056 }
1057
1058 /**
1059 * @return string wikitext of a link to the server software's web site
1060 */
1061 public static function getSoftwareLink() {
1062 return '[http://www.postgresql.org/ PostgreSQL]';
1063 }
1064
1065 /**
1066 * Return current schema (executes SELECT current_schema())
1067 * Needs transaction
1068 *
1069 * @since 1.19
1070 * @return string return default schema for the current session
1071 */
1072 function getCurrentSchema() {
1073 $res = $this->query( "SELECT current_schema()", __METHOD__ );
1074 $row = $this->fetchRow( $res );
1075 return $row[0];
1076 }
1077
1078 /**
1079 * Return list of schemas which are accessible without schema name
1080 * This is list does not contain magic keywords like "$user"
1081 * Needs transaction
1082 *
1083 * @see getSearchPath()
1084 * @see setSearchPath()
1085 * @since 1.19
1086 * @return array list of actual schemas for the current sesson
1087 */
1088 function getSchemas() {
1089 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
1090 $row = $this->fetchRow( $res );
1091 $schemas = array();
1092 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
1093 return $this->pg_array_parse( $row[0], $schemas );
1094 }
1095
1096 /**
1097 * Return search patch for schemas
1098 * This is different from getSchemas() since it contain magic keywords
1099 * (like "$user").
1100 * Needs transaction
1101 *
1102 * @since 1.19
1103 * @return array how to search for table names schemas for the current user
1104 */
1105 function getSearchPath() {
1106 $res = $this->query( "SHOW search_path", __METHOD__ );
1107 $row = $this->fetchRow( $res );
1108 /* PostgreSQL returns SHOW values as strings */
1109 return explode( ",", $row[0] );
1110 }
1111
1112 /**
1113 * Update search_path, values should already be sanitized
1114 * Values may contain magic keywords like "$user"
1115 * @since 1.19
1116 *
1117 * @param $search_path array list of schemas to be searched by default
1118 */
1119 function setSearchPath( $search_path ) {
1120 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1121 }
1122
1123 /**
1124 * Determine default schema for MediaWiki core
1125 * Adjust this session schema search path if desired schema exists
1126 * and is not alread there.
1127 *
1128 * We need to have name of the core schema stored to be able
1129 * to query database metadata.
1130 *
1131 * This will be also called by the installer after the schema is created
1132 *
1133 * @since 1.19
1134 * @param $desired_schema string
1135 */
1136 function determineCoreSchema( $desired_schema ) {
1137 $this->begin( __METHOD__ );
1138 if ( $this->schemaExists( $desired_schema ) ) {
1139 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
1140 $this->mCoreSchema = $desired_schema;
1141 wfDebug( "Schema \"" . $desired_schema . "\" already in the search path\n" );
1142 } else {
1143 /**
1144 * Prepend our schema (e.g. 'mediawiki') in front
1145 * of the search path
1146 * Fixes bug 15816
1147 */
1148 $search_path = $this->getSearchPath();
1149 array_unshift( $search_path,
1150 $this->addIdentifierQuotes( $desired_schema ));
1151 $this->setSearchPath( $search_path );
1152 $this->mCoreSchema = $desired_schema;
1153 wfDebug( "Schema \"" . $desired_schema . "\" added to the search path\n" );
1154 }
1155 } else {
1156 $this->mCoreSchema = $this->getCurrentSchema();
1157 wfDebug( "Schema \"" . $desired_schema . "\" not found, using current \"" . $this->mCoreSchema . "\"\n" );
1158 }
1159 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1160 $this->commit( __METHOD__ );
1161 }
1162
1163 /**
1164 * Return schema name fore core MediaWiki tables
1165 *
1166 * @since 1.19
1167 * @return string core schema name
1168 */
1169 function getCoreSchema() {
1170 return $this->mCoreSchema;
1171 }
1172
1173 /**
1174 * @return string Version information from the database
1175 */
1176 function getServerVersion() {
1177 if ( !isset( $this->numeric_version ) ) {
1178 $versionInfo = pg_version( $this->mConn );
1179 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1180 // Old client, abort install
1181 $this->numeric_version = '7.3 or earlier';
1182 } elseif ( isset( $versionInfo['server'] ) ) {
1183 // Normal client
1184 $this->numeric_version = $versionInfo['server'];
1185 } else {
1186 // Bug 16937: broken pgsql extension from PHP<5.3
1187 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
1188 }
1189 }
1190 return $this->numeric_version;
1191 }
1192
1193 /**
1194 * Query whether a given relation exists (in the given schema, or the
1195 * default mw one if not given)
1196 * @return bool
1197 */
1198 function relationExists( $table, $types, $schema = false ) {
1199 if ( !is_array( $types ) ) {
1200 $types = array( $types );
1201 }
1202 if ( !$schema ) {
1203 $schema = $this->getCoreSchema();
1204 }
1205 $table = $this->realTableName( $table, 'raw' );
1206 $etable = $this->addQuotes( $table );
1207 $eschema = $this->addQuotes( $schema );
1208 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1209 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1210 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1211 $res = $this->query( $SQL );
1212 $count = $res ? $res->numRows() : 0;
1213 return (bool)$count;
1214 }
1215
1216 /**
1217 * For backward compatibility, this function checks both tables and
1218 * views.
1219 * @return bool
1220 */
1221 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1222 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1223 }
1224
1225 function sequenceExists( $sequence, $schema = false ) {
1226 return $this->relationExists( $sequence, 'S', $schema );
1227 }
1228
1229 function triggerExists( $table, $trigger ) {
1230 $q = <<<SQL
1231 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1232 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1233 AND tgrelid=pg_class.oid
1234 AND nspname=%s AND relname=%s AND tgname=%s
1235 SQL;
1236 $res = $this->query(
1237 sprintf(
1238 $q,
1239 $this->addQuotes( $this->getCoreSchema() ),
1240 $this->addQuotes( $table ),
1241 $this->addQuotes( $trigger )
1242 )
1243 );
1244 if ( !$res ) {
1245 return null;
1246 }
1247 $rows = $res->numRows();
1248 return $rows;
1249 }
1250
1251 function ruleExists( $table, $rule ) {
1252 $exists = $this->selectField( 'pg_rules', 'rulename',
1253 array(
1254 'rulename' => $rule,
1255 'tablename' => $table,
1256 'schemaname' => $this->getCoreSchema()
1257 )
1258 );
1259 return $exists === $rule;
1260 }
1261
1262 function constraintExists( $table, $constraint ) {
1263 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1264 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1265 $this->addQuotes( $this->getCoreSchema() ),
1266 $this->addQuotes( $table ),
1267 $this->addQuotes( $constraint )
1268 );
1269 $res = $this->query( $SQL );
1270 if ( !$res ) {
1271 return null;
1272 }
1273 $rows = $res->numRows();
1274 return $rows;
1275 }
1276
1277 /**
1278 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1279 * @return bool
1280 */
1281 function schemaExists( $schema ) {
1282 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1283 array( 'nspname' => $schema ), __METHOD__ );
1284 return (bool)$exists;
1285 }
1286
1287 /**
1288 * Returns true if a given role (i.e. user) exists, false otherwise.
1289 * @return bool
1290 */
1291 function roleExists( $roleName ) {
1292 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1293 array( 'rolname' => $roleName ), __METHOD__ );
1294 return (bool)$exists;
1295 }
1296
1297 function fieldInfo( $table, $field ) {
1298 return PostgresField::fromText( $this, $table, $field );
1299 }
1300
1301 /**
1302 * pg_field_type() wrapper
1303 * @return string
1304 */
1305 function fieldType( $res, $index ) {
1306 if ( $res instanceof ResultWrapper ) {
1307 $res = $res->result;
1308 }
1309 return pg_field_type( $res, $index );
1310 }
1311
1312 /**
1313 * @param $b
1314 * @return Blob
1315 */
1316 function encodeBlob( $b ) {
1317 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1318 }
1319
1320 function decodeBlob( $b ) {
1321 if ( $b instanceof Blob ) {
1322 $b = $b->fetch();
1323 }
1324 return pg_unescape_bytea( $b );
1325 }
1326
1327 function strencode( $s ) { # Should not be called by us
1328 return pg_escape_string( $this->mConn, $s );
1329 }
1330
1331 /**
1332 * @param $s null|bool|Blob
1333 * @return int|string
1334 */
1335 function addQuotes( $s ) {
1336 if ( is_null( $s ) ) {
1337 return 'NULL';
1338 } elseif ( is_bool( $s ) ) {
1339 return intval( $s );
1340 } elseif ( $s instanceof Blob ) {
1341 return "'" . $s->fetch( $s ) . "'";
1342 }
1343 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1344 }
1345
1346 /**
1347 * Postgres specific version of replaceVars.
1348 * Calls the parent version in Database.php
1349 *
1350 * @private
1351 *
1352 * @param string $ins SQL string, read from a stream (usually tables.sql)
1353 *
1354 * @return string SQL string
1355 */
1356 protected function replaceVars( $ins ) {
1357 $ins = parent::replaceVars( $ins );
1358
1359 if ( $this->numeric_version >= 8.3 ) {
1360 // Thanks for not providing backwards-compatibility, 8.3
1361 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1362 }
1363
1364 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1365 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1366 }
1367
1368 return $ins;
1369 }
1370
1371 /**
1372 * Various select options
1373 *
1374 * @private
1375 *
1376 * @param array $options an associative array of options to be turned into
1377 * an SQL query, valid keys are listed in the function.
1378 * @return array
1379 */
1380 function makeSelectOptions( $options ) {
1381 $preLimitTail = $postLimitTail = '';
1382 $startOpts = $useIndex = '';
1383
1384 $noKeyOptions = array();
1385 foreach ( $options as $key => $option ) {
1386 if ( is_numeric( $key ) ) {
1387 $noKeyOptions[$option] = true;
1388 }
1389 }
1390
1391 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1392
1393 $preLimitTail .= $this->makeOrderBy( $options );
1394
1395 //if ( isset( $options['LIMIT'] ) ) {
1396 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1397 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1398 // : false );
1399 //}
1400
1401 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1402 $postLimitTail .= ' FOR UPDATE';
1403 }
1404 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1405 $startOpts .= 'DISTINCT';
1406 }
1407
1408 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1409 }
1410
1411 function setFakeMaster( $enabled = true ) {
1412 }
1413
1414 function getDBname() {
1415 return $this->mDBname;
1416 }
1417
1418 function getServer() {
1419 return $this->mServer;
1420 }
1421
1422 function buildConcat( $stringList ) {
1423 return implode( ' || ', $stringList );
1424 }
1425
1426 public function getSearchEngine() {
1427 return 'SearchPostgres';
1428 }
1429
1430 public function streamStatementEnd( &$sql, &$newLine ) {
1431 # Allow dollar quoting for function declarations
1432 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1433 if ( $this->delimiter ) {
1434 $this->delimiter = false;
1435 }
1436 else {
1437 $this->delimiter = ';';
1438 }
1439 }
1440 return parent::streamStatementEnd( $sql, $newLine );
1441 }
1442
1443 /**
1444 * Check to see if a named lock is available. This is non-blocking.
1445 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1446 *
1447 * @param string $lockName name of lock to poll
1448 * @param string $method name of method calling us
1449 * @return Boolean
1450 * @since 1.20
1451 */
1452 public function lockIsFree( $lockName, $method ) {
1453 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1454 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1455 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1456 $row = $this->fetchObject( $result );
1457 return ( $row->lockstatus === 't' );
1458 }
1459
1460 /**
1461 * See http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1462 * @param $lockName string
1463 * @param $method string
1464 * @param $timeout int
1465 * @return bool
1466 */
1467 public function lock( $lockName, $method, $timeout = 5 ) {
1468 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1469 for ( $attempts = 1; $attempts <= $timeout; ++$attempts ) {
1470 $result = $this->query(
1471 "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1472 $row = $this->fetchObject( $result );
1473 if ( $row->lockstatus === 't' ) {
1474 return true;
1475 } else {
1476 sleep( 1 );
1477 }
1478 }
1479 wfDebug( __METHOD__ . " failed to acquire lock\n" );
1480 return false;
1481 }
1482
1483 /**
1484 * 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
1485 * @param $lockName string
1486 * @param $method string
1487 * @return bool
1488 */
1489 public function unlock( $lockName, $method ) {
1490 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1491 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1492 $row = $this->fetchObject( $result );
1493 return ( $row->lockstatus === 't' );
1494 }
1495
1496 /**
1497 * @param string $lockName
1498 * @return string Integer
1499 */
1500 private function bigintFromLockName( $lockName ) {
1501 return wfBaseConvert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1502 }
1503 } // end DatabasePostgres class