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