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