94509a3c023ace981ca16d42bdbae0b58624cacf
[lhc/web/wiklou.git] / includes / libs / rdbms / database / 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 namespace Wikimedia\Rdbms;
24
25 use Wikimedia\Timestamp\ConvertibleTimestamp;
26 use Wikimedia\WaitConditionLoop;
27 use Wikimedia;
28 use Exception;
29
30 /**
31 * @ingroup Database
32 */
33 class DatabasePostgres extends Database {
34 /** @var int|bool */
35 protected $port;
36
37 /** @var resource */
38 protected $lastResultHandle = null;
39
40 /** @var float|string */
41 private $numericVersion = null;
42 /** @var string Connect string to open a PostgreSQL connection */
43 private $connectString;
44 /** @var string */
45 private $coreSchema;
46 /** @var string */
47 private $tempSchema;
48 /** @var string[] Map of (reserved table name => alternate table name) */
49 private $keywordTableMap = [];
50
51 /**
52 * @see Database::__construct()
53 * @param array $params Additional parameters include:
54 * - keywordTableMap : Map of reserved table names to alternative table names to use
55 */
56 public function __construct( array $params ) {
57 $this->port = isset( $params['port'] ) ? $params['port'] : false;
58 $this->keywordTableMap = isset( $params['keywordTableMap'] )
59 ? $params['keywordTableMap']
60 : [];
61
62 parent::__construct( $params );
63 }
64
65 public function getType() {
66 return 'postgres';
67 }
68
69 public function implicitGroupby() {
70 return false;
71 }
72
73 public function implicitOrderby() {
74 return false;
75 }
76
77 public function hasConstraint( $name ) {
78 foreach ( $this->getCoreSchemas() as $schema ) {
79 $sql = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n " .
80 "WHERE c.connamespace = n.oid AND conname = " .
81 $this->addQuotes( $name ) . " AND n.nspname = " .
82 $this->addQuotes( $schema );
83 $res = $this->doQuery( $sql );
84 if ( $res && $this->numRows( $res ) ) {
85 return true;
86 }
87 }
88 return false;
89 }
90
91 public function open( $server, $user, $password, $dbName ) {
92 # Test for Postgres support, to avoid suppressed fatal error
93 if ( !function_exists( 'pg_connect' ) ) {
94 throw new DBConnectionError(
95 $this,
96 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
97 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
98 "webserver and database)\n"
99 );
100 }
101
102 $this->server = $server;
103 $this->user = $user;
104 $this->password = $password;
105 $this->dbName = $dbName;
106
107 $connectVars = [
108 // pg_connect() user $user as the default database. Since a database is *required*,
109 // at least pick a "don't care" database that is more likely to exist. This case
110 // arrises when LoadBalancer::getConnection( $i, [], '' ) is used.
111 'dbname' => strlen( $dbName ) ? $dbName : 'postgres',
112 'user' => $user,
113 'password' => $password
114 ];
115 if ( $server != false && $server != '' ) {
116 $connectVars['host'] = $server;
117 }
118 if ( (int)$this->port > 0 ) {
119 $connectVars['port'] = (int)$this->port;
120 }
121 if ( $this->flags & self::DBO_SSL ) {
122 $connectVars['sslmode'] = 1;
123 }
124
125 $this->connectString = $this->makeConnectionString( $connectVars );
126 $this->close();
127 $this->installErrorHandler();
128
129 try {
130 // Use new connections to let LoadBalancer/LBFactory handle reuse
131 $this->conn = pg_connect( $this->connectString, PGSQL_CONNECT_FORCE_NEW );
132 } catch ( Exception $ex ) {
133 $this->restoreErrorHandler();
134 throw $ex;
135 }
136
137 $phpError = $this->restoreErrorHandler();
138
139 if ( !$this->conn ) {
140 $this->queryLogger->debug(
141 "DB connection error\n" .
142 "Server: $server, Database: $dbName, User: $user, Password: " .
143 substr( $password, 0, 3 ) . "...\n"
144 );
145 $this->queryLogger->debug( $this->lastError() . "\n" );
146 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
147 }
148
149 $this->opened = true;
150
151 # If called from the command-line (e.g. importDump), only show errors
152 if ( $this->cliMode ) {
153 $this->doQuery( "SET client_min_messages = 'ERROR'" );
154 }
155
156 $this->query( "SET client_encoding='UTF8'", __METHOD__ );
157 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
158 $this->query( "SET timezone = 'GMT'", __METHOD__ );
159 $this->query( "SET standard_conforming_strings = on", __METHOD__ );
160 $this->query( "SET bytea_output = 'escape'", __METHOD__ ); // PHP bug 53127
161
162 $this->determineCoreSchema( $this->schema );
163 // The schema to be used is now in the search path; no need for explicit qualification
164 $this->schema = '';
165
166 return $this->conn;
167 }
168
169 public function databasesAreIndependent() {
170 return true;
171 }
172
173 /**
174 * Postgres doesn't support selectDB in the same way MySQL does. So if the
175 * DB name doesn't match the open connection, open a new one
176 * @param string $db
177 * @return bool
178 * @throws DBUnexpectedError
179 */
180 public function selectDB( $db ) {
181 if ( $this->dbName !== $db ) {
182 return (bool)$this->open( $this->server, $this->user, $this->password, $db );
183 } else {
184 return true;
185 }
186 }
187
188 /**
189 * @param string[] $vars
190 * @return string
191 */
192 private function makeConnectionString( $vars ) {
193 $s = '';
194 foreach ( $vars as $name => $value ) {
195 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
196 }
197
198 return $s;
199 }
200
201 protected function closeConnection() {
202 return $this->conn ? pg_close( $this->conn ) : true;
203 }
204
205 protected function isTransactableQuery( $sql ) {
206 return parent::isTransactableQuery( $sql ) &&
207 !preg_match( '/^SELECT\s+pg_(try_|)advisory_\w+\(/', $sql );
208 }
209
210 public function doQuery( $sql ) {
211 $conn = $this->getBindingHandle();
212
213 $sql = mb_convert_encoding( $sql, 'UTF-8' );
214 // Clear previously left over PQresult
215 while ( $res = pg_get_result( $conn ) ) {
216 pg_free_result( $res );
217 }
218 if ( pg_send_query( $conn, $sql ) === false ) {
219 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
220 }
221 $this->lastResultHandle = pg_get_result( $conn );
222 if ( pg_result_error( $this->lastResultHandle ) ) {
223 return false;
224 }
225
226 return $this->lastResultHandle;
227 }
228
229 protected function dumpError() {
230 $diags = [
231 PGSQL_DIAG_SEVERITY,
232 PGSQL_DIAG_SQLSTATE,
233 PGSQL_DIAG_MESSAGE_PRIMARY,
234 PGSQL_DIAG_MESSAGE_DETAIL,
235 PGSQL_DIAG_MESSAGE_HINT,
236 PGSQL_DIAG_STATEMENT_POSITION,
237 PGSQL_DIAG_INTERNAL_POSITION,
238 PGSQL_DIAG_INTERNAL_QUERY,
239 PGSQL_DIAG_CONTEXT,
240 PGSQL_DIAG_SOURCE_FILE,
241 PGSQL_DIAG_SOURCE_LINE,
242 PGSQL_DIAG_SOURCE_FUNCTION
243 ];
244 foreach ( $diags as $d ) {
245 $this->queryLogger->debug( sprintf( "PgSQL ERROR(%d): %s\n",
246 $d, pg_result_error_field( $this->lastResultHandle, $d ) ) );
247 }
248 }
249
250 public function freeResult( $res ) {
251 if ( $res instanceof ResultWrapper ) {
252 $res = $res->result;
253 }
254 Wikimedia\suppressWarnings();
255 $ok = pg_free_result( $res );
256 Wikimedia\restoreWarnings();
257 if ( !$ok ) {
258 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
259 }
260 }
261
262 public function fetchObject( $res ) {
263 if ( $res instanceof ResultWrapper ) {
264 $res = $res->result;
265 }
266 Wikimedia\suppressWarnings();
267 $row = pg_fetch_object( $res );
268 Wikimedia\restoreWarnings();
269 # @todo FIXME: HACK HACK HACK HACK debug
270
271 # @todo hashar: not sure if the following test really trigger if the object
272 # fetching failed.
273 $conn = $this->getBindingHandle();
274 if ( pg_last_error( $conn ) ) {
275 throw new DBUnexpectedError(
276 $this,
277 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
278 );
279 }
280
281 return $row;
282 }
283
284 public function fetchRow( $res ) {
285 if ( $res instanceof ResultWrapper ) {
286 $res = $res->result;
287 }
288 Wikimedia\suppressWarnings();
289 $row = pg_fetch_array( $res );
290 Wikimedia\restoreWarnings();
291
292 $conn = $this->getBindingHandle();
293 if ( pg_last_error( $conn ) ) {
294 throw new DBUnexpectedError(
295 $this,
296 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
297 );
298 }
299
300 return $row;
301 }
302
303 public function numRows( $res ) {
304 if ( $res instanceof ResultWrapper ) {
305 $res = $res->result;
306 }
307 Wikimedia\suppressWarnings();
308 $n = pg_num_rows( $res );
309 Wikimedia\restoreWarnings();
310
311 $conn = $this->getBindingHandle();
312 if ( pg_last_error( $conn ) ) {
313 throw new DBUnexpectedError(
314 $this,
315 'SQL error: ' . htmlspecialchars( pg_last_error( $conn ) )
316 );
317 }
318
319 return $n;
320 }
321
322 public function numFields( $res ) {
323 if ( $res instanceof ResultWrapper ) {
324 $res = $res->result;
325 }
326
327 return pg_num_fields( $res );
328 }
329
330 public function fieldName( $res, $n ) {
331 if ( $res instanceof ResultWrapper ) {
332 $res = $res->result;
333 }
334
335 return pg_field_name( $res, $n );
336 }
337
338 public function insertId() {
339 $res = $this->query( "SELECT lastval()" );
340 $row = $this->fetchRow( $res );
341 return is_null( $row[0] ) ? null : (int)$row[0];
342 }
343
344 public function dataSeek( $res, $row ) {
345 if ( $res instanceof ResultWrapper ) {
346 $res = $res->result;
347 }
348
349 return pg_result_seek( $res, $row );
350 }
351
352 public function lastError() {
353 if ( $this->conn ) {
354 if ( $this->lastResultHandle ) {
355 return pg_result_error( $this->lastResultHandle );
356 } else {
357 return pg_last_error();
358 }
359 }
360
361 return $this->getLastPHPError() ?: 'No database connection';
362 }
363
364 public function lastErrno() {
365 if ( $this->lastResultHandle ) {
366 return pg_result_error_field( $this->lastResultHandle, PGSQL_DIAG_SQLSTATE );
367 } else {
368 return false;
369 }
370 }
371
372 protected function fetchAffectedRowCount() {
373 if ( !$this->lastResultHandle ) {
374 return 0;
375 }
376
377 return pg_affected_rows( $this->lastResultHandle );
378 }
379
380 /**
381 * Estimate rows in dataset
382 * Returns estimated count, based on EXPLAIN output
383 * This is not necessarily an accurate estimate, so use sparingly
384 * Returns -1 if count cannot be found
385 * Takes same arguments as Database::select()
386 *
387 * @param string $table
388 * @param string $var
389 * @param string $conds
390 * @param string $fname
391 * @param array $options
392 * @param array $join_conds
393 * @return int
394 */
395 public function estimateRowCount( $table, $var = '*', $conds = '',
396 $fname = __METHOD__, $options = [], $join_conds = []
397 ) {
398 $conds = $this->normalizeConditions( $conds, $fname );
399 $column = $this->extractSingleFieldFromList( $var );
400 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
401 $conds[] = "$column IS NOT NULL";
402 }
403
404 $options['EXPLAIN'] = true;
405 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
406 $rows = -1;
407 if ( $res ) {
408 $row = $this->fetchRow( $res );
409 $count = [];
410 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
411 $rows = (int)$count[1];
412 }
413 }
414
415 return $rows;
416 }
417
418 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
419 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
420 $res = $this->query( $sql, $fname );
421 if ( !$res ) {
422 return null;
423 }
424 foreach ( $res as $row ) {
425 if ( $row->indexname == $this->indexName( $index ) ) {
426 return $row;
427 }
428 }
429
430 return false;
431 }
432
433 public function indexAttributes( $index, $schema = false ) {
434 if ( $schema === false ) {
435 $schemas = $this->getCoreSchemas();
436 } else {
437 $schemas = [ $schema ];
438 }
439
440 $eindex = $this->addQuotes( $index );
441
442 foreach ( $schemas as $schema ) {
443 $eschema = $this->addQuotes( $schema );
444 /*
445 * A subquery would be not needed if we didn't care about the order
446 * of attributes, but we do
447 */
448 $sql = <<<__INDEXATTR__
449
450 SELECT opcname,
451 attname,
452 i.indoption[s.g] as option,
453 pg_am.amname
454 FROM
455 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
456 FROM
457 pg_index isub
458 JOIN pg_class cis
459 ON cis.oid=isub.indexrelid
460 JOIN pg_namespace ns
461 ON cis.relnamespace = ns.oid
462 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
463 pg_attribute,
464 pg_opclass opcls,
465 pg_am,
466 pg_class ci
467 JOIN pg_index i
468 ON ci.oid=i.indexrelid
469 JOIN pg_class ct
470 ON ct.oid = i.indrelid
471 JOIN pg_namespace n
472 ON ci.relnamespace = n.oid
473 WHERE
474 ci.relname=$eindex AND n.nspname=$eschema
475 AND attrelid = ct.oid
476 AND i.indkey[s.g] = attnum
477 AND i.indclass[s.g] = opcls.oid
478 AND pg_am.oid = opcls.opcmethod
479 __INDEXATTR__;
480 $res = $this->query( $sql, __METHOD__ );
481 $a = [];
482 if ( $res ) {
483 foreach ( $res as $row ) {
484 $a[] = [
485 $row->attname,
486 $row->opcname,
487 $row->amname,
488 $row->option ];
489 }
490 return $a;
491 }
492 }
493 return null;
494 }
495
496 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
497 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'" .
498 " AND indexdef LIKE 'CREATE UNIQUE%(" .
499 $this->strencode( $this->indexName( $index ) ) .
500 ")'";
501 $res = $this->query( $sql, $fname );
502 if ( !$res ) {
503 return null;
504 }
505
506 return $res->numRows() > 0;
507 }
508
509 public function selectSQLText(
510 $table, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
511 ) {
512 if ( is_string( $options ) ) {
513 $options = [ $options ];
514 }
515
516 // Change the FOR UPDATE option as necessary based on the join conditions. Then pass
517 // to the parent function to get the actual SQL text.
518 // In Postgres when using FOR UPDATE, only the main table and tables that are inner joined
519 // can be locked. That means tables in an outer join cannot be FOR UPDATE locked. Trying to
520 // do so causes a DB error. This wrapper checks which tables can be locked and adjusts it
521 // accordingly.
522 // MySQL uses "ORDER BY NULL" as an optimization hint, but that is illegal in PostgreSQL.
523 if ( is_array( $options ) ) {
524 $forUpdateKey = array_search( 'FOR UPDATE', $options, true );
525 if ( $forUpdateKey !== false && $join_conds ) {
526 unset( $options[$forUpdateKey] );
527 $options['FOR UPDATE'] = [];
528
529 $toCheck = $table;
530 reset( $toCheck );
531 while ( $toCheck ) {
532 $alias = key( $toCheck );
533 $name = $toCheck[$alias];
534 unset( $toCheck[$alias] );
535
536 $hasAlias = !is_numeric( $alias );
537 if ( !$hasAlias && is_string( $name ) ) {
538 $alias = $name;
539 }
540
541 if ( !isset( $join_conds[$alias] ) ||
542 !preg_match( '/^(?:LEFT|RIGHT|FULL)(?: OUTER)? JOIN$/i', $join_conds[$alias][0] )
543 ) {
544 if ( is_array( $name ) ) {
545 // It's a parenthesized group, process all the tables inside the group.
546 $toCheck = array_merge( $toCheck, $name );
547 } else {
548 // Quote alias names so $this->tableName() won't mangle them
549 $options['FOR UPDATE'][] = $hasAlias ? $this->addIdentifierQuotes( $alias ) : $alias;
550 }
551 }
552 }
553 }
554
555 if ( isset( $options['ORDER BY'] ) && $options['ORDER BY'] == 'NULL' ) {
556 unset( $options['ORDER BY'] );
557 }
558 }
559
560 return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
561 }
562
563 /** @inheritDoc */
564 public function insert( $table, $args, $fname = __METHOD__, $options = [] ) {
565 if ( !count( $args ) ) {
566 return true;
567 }
568
569 $table = $this->tableName( $table );
570 if ( !isset( $this->numericVersion ) ) {
571 $this->getServerVersion();
572 }
573
574 if ( !is_array( $options ) ) {
575 $options = [ $options ];
576 }
577
578 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
579 $rows = $args;
580 $keys = array_keys( $args[0] );
581 } else {
582 $rows = [ $args ];
583 $keys = array_keys( $args );
584 }
585
586 $ignore = in_array( 'IGNORE', $options );
587
588 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
589
590 if ( $this->numericVersion >= 9.5 || !$ignore ) {
591 // No IGNORE or our PG has "ON CONFLICT DO NOTHING"
592 $first = true;
593 foreach ( $rows as $row ) {
594 if ( $first ) {
595 $first = false;
596 } else {
597 $sql .= ',';
598 }
599 $sql .= '(' . $this->makeList( $row ) . ')';
600 }
601 if ( $ignore ) {
602 $sql .= ' ON CONFLICT DO NOTHING';
603 }
604 $this->query( $sql, $fname );
605 } else {
606 // Emulate IGNORE by doing each row individually, with savepoints
607 // to roll back as necessary.
608 $numrowsinserted = 0;
609
610 $tok = $this->startAtomic( "$fname (outer)", self::ATOMIC_CANCELABLE );
611 try {
612 foreach ( $rows as $row ) {
613 $tempsql = $sql;
614 $tempsql .= '(' . $this->makeList( $row ) . ')';
615
616 $this->startAtomic( "$fname (inner)", self::ATOMIC_CANCELABLE );
617 try {
618 $this->query( $tempsql, $fname );
619 $this->endAtomic( "$fname (inner)" );
620 $numrowsinserted++;
621 } catch ( DBQueryError $e ) {
622 $this->cancelAtomic( "$fname (inner)" );
623 // Our IGNORE is supposed to ignore duplicate key errors, but not others.
624 // (even though MySQL's version apparently ignores all errors)
625 if ( $e->errno !== '23505' ) {
626 throw $e;
627 }
628 }
629 }
630 } catch ( Exception $e ) {
631 $this->cancelAtomic( "$fname (outer)", $tok );
632 throw $e;
633 }
634 $this->endAtomic( "$fname (outer)" );
635
636 // Set the affected row count for the whole operation
637 $this->affectedRowCount = $numrowsinserted;
638 }
639
640 return true;
641 }
642
643 protected function makeUpdateOptionsArray( $options ) {
644 if ( !is_array( $options ) ) {
645 $options = [ $options ];
646 }
647
648 // PostgreSQL doesn't support anything like "ignore" for
649 // UPDATE.
650 $options = array_diff( $options, [ 'IGNORE' ] );
651
652 return parent::makeUpdateOptionsArray( $options );
653 }
654
655 /**
656 * INSERT SELECT wrapper
657 * $varMap must be an associative array of the form [ 'dest1' => 'source1', ... ]
658 * Source items may be literals rather then field names, but strings should
659 * be quoted with Database::addQuotes()
660 * $conds may be "*" to copy the whole table
661 * srcTable may be an array of tables.
662 * @todo FIXME: Implement this a little better (seperate select/insert)?
663 *
664 * @param string $destTable
665 * @param array|string $srcTable
666 * @param array $varMap
667 * @param array $conds
668 * @param string $fname
669 * @param array $insertOptions
670 * @param array $selectOptions
671 * @param array $selectJoinConds
672 * @return bool
673 */
674 public function nativeInsertSelect(
675 $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
676 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
677 ) {
678 if ( !is_array( $insertOptions ) ) {
679 $insertOptions = [ $insertOptions ];
680 }
681
682 if ( in_array( 'IGNORE', $insertOptions ) ) {
683 if ( $this->getServerVersion() >= 9.5 ) {
684 // Use ON CONFLICT DO NOTHING if we have it for IGNORE
685 $destTable = $this->tableName( $destTable );
686
687 $selectSql = $this->selectSQLText(
688 $srcTable,
689 array_values( $varMap ),
690 $conds,
691 $fname,
692 $selectOptions,
693 $selectJoinConds
694 );
695
696 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
697 $selectSql . ' ON CONFLICT DO NOTHING';
698
699 return $this->query( $sql, $fname );
700 } else {
701 // IGNORE and we don't have ON CONFLICT DO NOTHING, so just use the non-native version
702 return $this->nonNativeInsertSelect(
703 $destTable, $srcTable, $varMap, $conds, $fname,
704 $insertOptions, $selectOptions, $selectJoinConds
705 );
706 }
707 }
708
709 return parent::nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname,
710 $insertOptions, $selectOptions, $selectJoinConds );
711 }
712
713 public function tableName( $name, $format = 'quoted' ) {
714 // Replace reserved words with better ones
715 $name = $this->remappedTableName( $name );
716
717 return parent::tableName( $name, $format );
718 }
719
720 /**
721 * @param string $name
722 * @return string Value of $name or remapped name if $name is a reserved keyword
723 */
724 public function remappedTableName( $name ) {
725 return isset( $this->keywordTableMap[$name] ) ? $this->keywordTableMap[$name] : $name;
726 }
727
728 /**
729 * @param string $name
730 * @param string $format
731 * @return string Qualified and encoded (if requested) table name
732 */
733 public function realTableName( $name, $format = 'quoted' ) {
734 return parent::tableName( $name, $format );
735 }
736
737 public function nextSequenceValue( $seqName ) {
738 return new NextSequenceValue;
739 }
740
741 /**
742 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
743 *
744 * @param string $seqName
745 * @return int
746 */
747 public function currentSequenceValue( $seqName ) {
748 $safeseq = str_replace( "'", "''", $seqName );
749 $res = $this->query( "SELECT currval('$safeseq')" );
750 $row = $this->fetchRow( $res );
751 $currval = $row[0];
752
753 return $currval;
754 }
755
756 public function textFieldSize( $table, $field ) {
757 $table = $this->tableName( $table );
758 $sql = "SELECT t.typname as ftype,a.atttypmod as size
759 FROM pg_class c, pg_attribute a, pg_type t
760 WHERE relname='$table' AND a.attrelid=c.oid AND
761 a.atttypid=t.oid and a.attname='$field'";
762 $res = $this->query( $sql );
763 $row = $this->fetchObject( $res );
764 if ( $row->ftype == 'varchar' ) {
765 $size = $row->size - 4;
766 } else {
767 $size = $row->size;
768 }
769
770 return $size;
771 }
772
773 public function limitResult( $sql, $limit, $offset = false ) {
774 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
775 }
776
777 public function wasDeadlock() {
778 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
779 return $this->lastErrno() === '40P01';
780 }
781
782 public function wasLockTimeout() {
783 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
784 return $this->lastErrno() === '55P03';
785 }
786
787 public function wasConnectionError( $errno ) {
788 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
789 static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
790
791 return in_array( $errno, $codes, true );
792 }
793
794 protected function wasKnownStatementRollbackError() {
795 return false; // transaction has to be rolled-back from error state
796 }
797
798 public function duplicateTableStructure(
799 $oldName, $newName, $temporary = false, $fname = __METHOD__
800 ) {
801 $newNameE = $this->addIdentifierQuotes( $newName );
802 $oldNameE = $this->addIdentifierQuotes( $oldName );
803
804 $temporary = $temporary ? 'TEMPORARY' : '';
805
806 $ret = $this->query( "CREATE $temporary TABLE $newNameE " .
807 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)", $fname );
808 if ( !$ret ) {
809 return $ret;
810 }
811
812 $res = $this->query( 'SELECT attname FROM pg_class c'
813 . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
814 . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
815 . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
816 . ' WHERE relkind = \'r\''
817 . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
818 . ' AND relname = ' . $this->addQuotes( $oldName )
819 . ' AND adsrc LIKE \'nextval(%\'',
820 $fname
821 );
822 $row = $this->fetchObject( $res );
823 if ( $row ) {
824 $field = $row->attname;
825 $newSeq = "{$newName}_{$field}_seq";
826 $fieldE = $this->addIdentifierQuotes( $field );
827 $newSeqE = $this->addIdentifierQuotes( $newSeq );
828 $newSeqQ = $this->addQuotes( $newSeq );
829 $this->query( "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE", $fname );
830 $this->query(
831 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
832 $fname
833 );
834 }
835
836 return $ret;
837 }
838
839 public function resetSequenceForTable( $table, $fname = __METHOD__ ) {
840 $table = $this->tableName( $table, 'raw' );
841 foreach ( $this->getCoreSchemas() as $schema ) {
842 $res = $this->query(
843 'SELECT c.oid FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace)'
844 . ' WHERE relkind = \'r\''
845 . ' AND nspname = ' . $this->addQuotes( $schema )
846 . ' AND relname = ' . $this->addQuotes( $table ),
847 $fname
848 );
849 if ( !$res || !$this->numRows( $res ) ) {
850 continue;
851 }
852
853 $oid = $this->fetchObject( $res )->oid;
854 $res = $this->query( 'SELECT adsrc FROM pg_attribute a'
855 . ' JOIN pg_attrdef d ON (a.attrelid=d.adrelid and a.attnum=d.adnum)'
856 . " WHERE a.attrelid = $oid"
857 . ' AND adsrc LIKE \'nextval(%\'',
858 $fname
859 );
860 $row = $this->fetchObject( $res );
861 if ( $row ) {
862 $this->query(
863 'SELECT ' . preg_replace( '/^nextval\((.+)\)$/', 'setval($1,1,false)', $row->adsrc ),
864 $fname
865 );
866 return true;
867 }
868 return false;
869 }
870
871 return false;
872 }
873
874 public function listTables( $prefix = null, $fname = __METHOD__ ) {
875 $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
876 $result = $this->query(
877 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)", $fname );
878 $endArray = [];
879
880 foreach ( $result as $table ) {
881 $vars = get_object_vars( $table );
882 $table = array_pop( $vars );
883 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
884 $endArray[] = $table;
885 }
886 }
887
888 return $endArray;
889 }
890
891 public function timestamp( $ts = 0 ) {
892 $ct = new ConvertibleTimestamp( $ts );
893
894 return $ct->getTimestamp( TS_POSTGRES );
895 }
896
897 /**
898 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
899 * to https://secure.php.net/manual/en/ref.pgsql.php
900 *
901 * Parsing a postgres array can be a tricky problem, he's my
902 * take on this, it handles multi-dimensional arrays plus
903 * escaping using a nasty regexp to determine the limits of each
904 * data-item.
905 *
906 * This should really be handled by PHP PostgreSQL module
907 *
908 * @since 1.19
909 * @param string $text Postgreql array returned in a text form like {a,b}
910 * @param string[] $output
911 * @param int|bool $limit
912 * @param int $offset
913 * @return string[]
914 */
915 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
916 if ( false === $limit ) {
917 $limit = strlen( $text ) - 1;
918 $output = [];
919 }
920 if ( '{}' == $text ) {
921 return $output;
922 }
923 do {
924 if ( '{' != $text[$offset] ) {
925 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
926 $text, $match, 0, $offset );
927 $offset += strlen( $match[0] );
928 $output[] = ( '"' != $match[1][0]
929 ? $match[1]
930 : stripcslashes( substr( $match[1], 1, -1 ) ) );
931 if ( '},' == $match[3] ) {
932 return $output;
933 }
934 } else {
935 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
936 }
937 } while ( $limit > $offset );
938
939 return $output;
940 }
941
942 public function aggregateValue( $valuedata, $valuename = 'value' ) {
943 return $valuedata;
944 }
945
946 public function getSoftwareLink() {
947 return '[{{int:version-db-postgres-url}} PostgreSQL]';
948 }
949
950 /**
951 * Return current schema (executes SELECT current_schema())
952 * Needs transaction
953 *
954 * @since 1.19
955 * @return string Default schema for the current session
956 */
957 public function getCurrentSchema() {
958 $res = $this->query( "SELECT current_schema()", __METHOD__ );
959 $row = $this->fetchRow( $res );
960
961 return $row[0];
962 }
963
964 /**
965 * Return list of schemas which are accessible without schema name
966 * This is list does not contain magic keywords like "$user"
967 * Needs transaction
968 *
969 * @see getSearchPath()
970 * @see setSearchPath()
971 * @since 1.19
972 * @return array List of actual schemas for the current sesson
973 */
974 public function getSchemas() {
975 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
976 $row = $this->fetchRow( $res );
977 $schemas = [];
978
979 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
980
981 return $this->pg_array_parse( $row[0], $schemas );
982 }
983
984 /**
985 * Return search patch for schemas
986 * This is different from getSchemas() since it contain magic keywords
987 * (like "$user").
988 * Needs transaction
989 *
990 * @since 1.19
991 * @return array How to search for table names schemas for the current user
992 */
993 public function getSearchPath() {
994 $res = $this->query( "SHOW search_path", __METHOD__ );
995 $row = $this->fetchRow( $res );
996
997 /* PostgreSQL returns SHOW values as strings */
998
999 return explode( ",", $row[0] );
1000 }
1001
1002 /**
1003 * Update search_path, values should already be sanitized
1004 * Values may contain magic keywords like "$user"
1005 * @since 1.19
1006 *
1007 * @param array $search_path List of schemas to be searched by default
1008 */
1009 private function setSearchPath( $search_path ) {
1010 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
1011 }
1012
1013 /**
1014 * Determine default schema for the current application
1015 * Adjust this session schema search path if desired schema exists
1016 * and is not alread there.
1017 *
1018 * We need to have name of the core schema stored to be able
1019 * to query database metadata.
1020 *
1021 * This will be also called by the installer after the schema is created
1022 *
1023 * @since 1.19
1024 *
1025 * @param string $desiredSchema
1026 */
1027 public function determineCoreSchema( $desiredSchema ) {
1028 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1029 if ( $this->schemaExists( $desiredSchema ) ) {
1030 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1031 $this->coreSchema = $desiredSchema;
1032 $this->queryLogger->debug(
1033 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1034 } else {
1035 /**
1036 * Prepend our schema (e.g. 'mediawiki') in front
1037 * of the search path
1038 * Fixes T17816
1039 */
1040 $search_path = $this->getSearchPath();
1041 array_unshift( $search_path,
1042 $this->addIdentifierQuotes( $desiredSchema ) );
1043 $this->setSearchPath( $search_path );
1044 $this->coreSchema = $desiredSchema;
1045 $this->queryLogger->debug(
1046 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1047 }
1048 } else {
1049 $this->coreSchema = $this->getCurrentSchema();
1050 $this->queryLogger->debug(
1051 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1052 $this->coreSchema . "\"\n" );
1053 }
1054 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1055 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1056 }
1057
1058 /**
1059 * Return schema name for core application tables
1060 *
1061 * @since 1.19
1062 * @return string Core schema name
1063 */
1064 public function getCoreSchema() {
1065 return $this->coreSchema;
1066 }
1067
1068 /**
1069 * Return schema names for temporary tables and core application tables
1070 *
1071 * @since 1.31
1072 * @return string[] schema names
1073 */
1074 public function getCoreSchemas() {
1075 if ( $this->tempSchema ) {
1076 return [ $this->tempSchema, $this->getCoreSchema() ];
1077 }
1078
1079 $res = $this->query(
1080 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1081 );
1082 $row = $this->fetchObject( $res );
1083 if ( $row ) {
1084 $this->tempSchema = $row->nspname;
1085 return [ $this->tempSchema, $this->getCoreSchema() ];
1086 }
1087
1088 return [ $this->getCoreSchema() ];
1089 }
1090
1091 public function getServerVersion() {
1092 if ( !isset( $this->numericVersion ) ) {
1093 $conn = $this->getBindingHandle();
1094 $versionInfo = pg_version( $conn );
1095 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1096 // Old client, abort install
1097 $this->numericVersion = '7.3 or earlier';
1098 } elseif ( isset( $versionInfo['server'] ) ) {
1099 // Normal client
1100 $this->numericVersion = $versionInfo['server'];
1101 } else {
1102 // T18937: broken pgsql extension from PHP<5.3
1103 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1104 }
1105 }
1106
1107 return $this->numericVersion;
1108 }
1109
1110 /**
1111 * Query whether a given relation exists (in the given schema, or the
1112 * default mw one if not given)
1113 * @param string $table
1114 * @param array|string $types
1115 * @param bool|string $schema
1116 * @return bool
1117 */
1118 private function relationExists( $table, $types, $schema = false ) {
1119 if ( !is_array( $types ) ) {
1120 $types = [ $types ];
1121 }
1122 if ( $schema === false ) {
1123 $schemas = $this->getCoreSchemas();
1124 } else {
1125 $schemas = [ $schema ];
1126 }
1127 $table = $this->realTableName( $table, 'raw' );
1128 $etable = $this->addQuotes( $table );
1129 foreach ( $schemas as $schema ) {
1130 $eschema = $this->addQuotes( $schema );
1131 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1132 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1133 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1134 $res = $this->query( $sql );
1135 if ( $res && $res->numRows() ) {
1136 return true;
1137 }
1138 }
1139
1140 return false;
1141 }
1142
1143 /**
1144 * For backward compatibility, this function checks both tables and views.
1145 * @param string $table
1146 * @param string $fname
1147 * @param bool|string $schema
1148 * @return bool
1149 */
1150 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1151 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1152 }
1153
1154 public function sequenceExists( $sequence, $schema = false ) {
1155 return $this->relationExists( $sequence, 'S', $schema );
1156 }
1157
1158 public function triggerExists( $table, $trigger ) {
1159 $q = <<<SQL
1160 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1161 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1162 AND tgrelid=pg_class.oid
1163 AND nspname=%s AND relname=%s AND tgname=%s
1164 SQL;
1165 foreach ( $this->getCoreSchemas() as $schema ) {
1166 $res = $this->query(
1167 sprintf(
1168 $q,
1169 $this->addQuotes( $schema ),
1170 $this->addQuotes( $table ),
1171 $this->addQuotes( $trigger )
1172 )
1173 );
1174 if ( $res && $res->numRows() ) {
1175 return true;
1176 }
1177 }
1178
1179 return false;
1180 }
1181
1182 public function ruleExists( $table, $rule ) {
1183 $exists = $this->selectField( 'pg_rules', 'rulename',
1184 [
1185 'rulename' => $rule,
1186 'tablename' => $table,
1187 'schemaname' => $this->getCoreSchemas()
1188 ]
1189 );
1190
1191 return $exists === $rule;
1192 }
1193
1194 public function constraintExists( $table, $constraint ) {
1195 foreach ( $this->getCoreSchemas() as $schema ) {
1196 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1197 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1198 $this->addQuotes( $schema ),
1199 $this->addQuotes( $table ),
1200 $this->addQuotes( $constraint )
1201 );
1202 $res = $this->query( $sql );
1203 if ( $res && $res->numRows() ) {
1204 return true;
1205 }
1206 }
1207 return false;
1208 }
1209
1210 /**
1211 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1212 * @param string $schema
1213 * @return bool
1214 */
1215 public function schemaExists( $schema ) {
1216 if ( !strlen( $schema ) ) {
1217 return false; // short-circuit
1218 }
1219
1220 $exists = $this->selectField(
1221 '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1222
1223 return (bool)$exists;
1224 }
1225
1226 /**
1227 * Returns true if a given role (i.e. user) exists, false otherwise.
1228 * @param string $roleName
1229 * @return bool
1230 */
1231 public function roleExists( $roleName ) {
1232 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1233 [ 'rolname' => $roleName ], __METHOD__ );
1234
1235 return (bool)$exists;
1236 }
1237
1238 /**
1239 * @param string $table
1240 * @param string $field
1241 * @return PostgresField|null
1242 */
1243 public function fieldInfo( $table, $field ) {
1244 return PostgresField::fromText( $this, $table, $field );
1245 }
1246
1247 /**
1248 * pg_field_type() wrapper
1249 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1250 * @param int $index Field number, starting from 0
1251 * @return string
1252 */
1253 public function fieldType( $res, $index ) {
1254 if ( $res instanceof ResultWrapper ) {
1255 $res = $res->result;
1256 }
1257
1258 return pg_field_type( $res, $index );
1259 }
1260
1261 public function encodeBlob( $b ) {
1262 return new PostgresBlob( pg_escape_bytea( $b ) );
1263 }
1264
1265 public function decodeBlob( $b ) {
1266 if ( $b instanceof PostgresBlob ) {
1267 $b = $b->fetch();
1268 } elseif ( $b instanceof Blob ) {
1269 return $b->fetch();
1270 }
1271
1272 return pg_unescape_bytea( $b );
1273 }
1274
1275 public function strencode( $s ) {
1276 // Should not be called by us
1277 return pg_escape_string( $this->getBindingHandle(), (string)$s );
1278 }
1279
1280 public function addQuotes( $s ) {
1281 $conn = $this->getBindingHandle();
1282
1283 if ( is_null( $s ) ) {
1284 return 'NULL';
1285 } elseif ( is_bool( $s ) ) {
1286 return intval( $s );
1287 } elseif ( $s instanceof Blob ) {
1288 if ( $s instanceof PostgresBlob ) {
1289 $s = $s->fetch();
1290 } else {
1291 $s = pg_escape_bytea( $conn, $s->fetch() );
1292 }
1293 return "'$s'";
1294 } elseif ( $s instanceof NextSequenceValue ) {
1295 return 'DEFAULT';
1296 }
1297
1298 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1299 }
1300
1301 public function makeSelectOptions( $options ) {
1302 $preLimitTail = $postLimitTail = '';
1303 $startOpts = $useIndex = $ignoreIndex = '';
1304
1305 $noKeyOptions = [];
1306 foreach ( $options as $key => $option ) {
1307 if ( is_numeric( $key ) ) {
1308 $noKeyOptions[$option] = true;
1309 }
1310 }
1311
1312 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1313
1314 $preLimitTail .= $this->makeOrderBy( $options );
1315
1316 if ( isset( $options['FOR UPDATE'] ) ) {
1317 $postLimitTail .= ' FOR UPDATE OF ' .
1318 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1319 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1320 $postLimitTail .= ' FOR UPDATE';
1321 }
1322
1323 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1324 $startOpts .= 'DISTINCT';
1325 }
1326
1327 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1328 }
1329
1330 public function getDBname() {
1331 return $this->dbName;
1332 }
1333
1334 public function getServer() {
1335 return $this->server;
1336 }
1337
1338 public function buildConcat( $stringList ) {
1339 return implode( ' || ', $stringList );
1340 }
1341
1342 public function buildGroupConcatField(
1343 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1344 ) {
1345 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1346
1347 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1348 }
1349
1350 public function buildStringCast( $field ) {
1351 return $field . '::text';
1352 }
1353
1354 public function streamStatementEnd( &$sql, &$newLine ) {
1355 # Allow dollar quoting for function declarations
1356 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1357 if ( $this->delimiter ) {
1358 $this->delimiter = false;
1359 } else {
1360 $this->delimiter = ';';
1361 }
1362 }
1363
1364 return parent::streamStatementEnd( $sql, $newLine );
1365 }
1366
1367 public function doLockTables( array $read, array $write, $method ) {
1368 $tablesWrite = [];
1369 foreach ( $write as $table ) {
1370 $tablesWrite[] = $this->tableName( $table );
1371 }
1372 $tablesRead = [];
1373 foreach ( $read as $table ) {
1374 $tablesRead[] = $this->tableName( $table );
1375 }
1376
1377 // Acquire locks for the duration of the current transaction...
1378 if ( $tablesWrite ) {
1379 $this->query(
1380 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1381 $method
1382 );
1383 }
1384 if ( $tablesRead ) {
1385 $this->query(
1386 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1387 $method
1388 );
1389 }
1390
1391 return true;
1392 }
1393
1394 public function lockIsFree( $lockName, $method ) {
1395 if ( !parent::lockIsFree( $lockName, $method ) ) {
1396 return false; // already held
1397 }
1398 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1399 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1400 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1401 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1402 $row = $this->fetchObject( $result );
1403
1404 return ( $row->lockstatus === 't' );
1405 }
1406
1407 public function lock( $lockName, $method, $timeout = 5 ) {
1408 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1409 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1410 $loop = new WaitConditionLoop(
1411 function () use ( $lockName, $key, $timeout, $method ) {
1412 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1413 $row = $this->fetchObject( $res );
1414 if ( $row->lockstatus === 't' ) {
1415 parent::lock( $lockName, $method, $timeout ); // record
1416 return true;
1417 }
1418
1419 return WaitConditionLoop::CONDITION_CONTINUE;
1420 },
1421 $timeout
1422 );
1423
1424 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1425 }
1426
1427 public function unlock( $lockName, $method ) {
1428 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1429 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1430 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1431 $row = $this->fetchObject( $result );
1432
1433 if ( $row->lockstatus === 't' ) {
1434 parent::unlock( $lockName, $method ); // record
1435 return true;
1436 }
1437
1438 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1439
1440 return false;
1441 }
1442
1443 public function serverIsReadOnly() {
1444 $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1445 $row = $this->fetchObject( $res );
1446
1447 return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1448 }
1449
1450 /**
1451 * @param string $lockName
1452 * @return string Integer
1453 */
1454 private function bigintFromLockName( $lockName ) {
1455 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1456 }
1457 }
1458
1459 class_alias( DatabasePostgres::class, 'DatabasePostgres' );