Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[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'] = 'require';
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 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 Wikimedia\suppressWarnings();
278 $ok = pg_free_result( ResultWrapper::unwrap( $res ) );
279 Wikimedia\restoreWarnings();
280 if ( !$ok ) {
281 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
282 }
283 }
284
285 public function fetchObject( $res ) {
286 Wikimedia\suppressWarnings();
287 $row = pg_fetch_object( ResultWrapper::unwrap( $res ) );
288 Wikimedia\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 Wikimedia\suppressWarnings();
306 $row = pg_fetch_array( ResultWrapper::unwrap( $res ) );
307 Wikimedia\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 Wikimedia\suppressWarnings();
326 $n = pg_num_rows( ResultWrapper::unwrap( $res ) );
327 Wikimedia\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 * @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://www.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__, self::QUERY_IGNORE_DBO_TRX );
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(
991 "SELECT current_schemas(false)",
992 __METHOD__,
993 self::QUERY_IGNORE_DBO_TRX
994 );
995 $row = $this->fetchRow( $res );
996 $schemas = [];
997
998 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
999
1000 return $this->pg_array_parse( $row[0], $schemas );
1001 }
1002
1003 /**
1004 * Return search patch for schemas
1005 * This is different from getSchemas() since it contain magic keywords
1006 * (like "$user").
1007 * Needs transaction
1008 *
1009 * @since 1.19
1010 * @return array How to search for table names schemas for the current user
1011 */
1012 public function getSearchPath() {
1013 $res = $this->query( "SHOW search_path", __METHOD__, self::QUERY_IGNORE_DBO_TRX );
1014 $row = $this->fetchRow( $res );
1015
1016 /* PostgreSQL returns SHOW values as strings */
1017
1018 return explode( ",", $row[0] );
1019 }
1020
1021 /**
1022 * Update search_path, values should already be sanitized
1023 * Values may contain magic keywords like "$user"
1024 * @since 1.19
1025 *
1026 * @param array $search_path List of schemas to be searched by default
1027 */
1028 private function setSearchPath( $search_path ) {
1029 $this->query(
1030 "SET search_path = " . implode( ", ", $search_path ),
1031 __METHOD__,
1032 self::QUERY_IGNORE_DBO_TRX
1033 );
1034 }
1035
1036 /**
1037 * Determine default schema for the current application
1038 * Adjust this session schema search path if desired schema exists
1039 * and is not alread there.
1040 *
1041 * We need to have name of the core schema stored to be able
1042 * to query database metadata.
1043 *
1044 * This will be also called by the installer after the schema is created
1045 *
1046 * @since 1.19
1047 *
1048 * @param string $desiredSchema
1049 */
1050 public function determineCoreSchema( $desiredSchema ) {
1051 if ( $this->trxLevel() ) {
1052 // We do not want the schema selection to change on ROLLBACK or INSERT SELECT.
1053 // See https://www.postgresql.org/docs/8.3/sql-set.html
1054 throw new DBUnexpectedError(
1055 $this,
1056 __METHOD__ . ": a transaction is currently active."
1057 );
1058 }
1059
1060 if ( $this->schemaExists( $desiredSchema ) ) {
1061 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
1062 $this->coreSchema = $desiredSchema;
1063 $this->queryLogger->debug(
1064 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
1065 } else {
1066 /**
1067 * Prepend our schema (e.g. 'mediawiki') in front
1068 * of the search path
1069 * Fixes T17816
1070 */
1071 $search_path = $this->getSearchPath();
1072 array_unshift( $search_path, $this->addIdentifierQuotes( $desiredSchema ) );
1073 $this->setSearchPath( $search_path );
1074 $this->coreSchema = $desiredSchema;
1075 $this->queryLogger->debug(
1076 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
1077 }
1078 } else {
1079 $this->coreSchema = $this->getCurrentSchema();
1080 $this->queryLogger->debug(
1081 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
1082 $this->coreSchema . "\"\n" );
1083 }
1084 }
1085
1086 /**
1087 * Return schema name for core application tables
1088 *
1089 * @since 1.19
1090 * @return string Core schema name
1091 */
1092 public function getCoreSchema() {
1093 return $this->coreSchema;
1094 }
1095
1096 /**
1097 * Return schema names for temporary tables and core application tables
1098 *
1099 * @since 1.31
1100 * @return string[] schema names
1101 */
1102 public function getCoreSchemas() {
1103 if ( $this->tempSchema ) {
1104 return [ $this->tempSchema, $this->getCoreSchema() ];
1105 }
1106
1107 $res = $this->query(
1108 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()", __METHOD__
1109 );
1110 $row = $this->fetchObject( $res );
1111 if ( $row ) {
1112 $this->tempSchema = $row->nspname;
1113 return [ $this->tempSchema, $this->getCoreSchema() ];
1114 }
1115
1116 return [ $this->getCoreSchema() ];
1117 }
1118
1119 public function getServerVersion() {
1120 if ( !isset( $this->numericVersion ) ) {
1121 $conn = $this->getBindingHandle();
1122 $versionInfo = pg_version( $conn );
1123 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1124 // Old client, abort install
1125 $this->numericVersion = '7.3 or earlier';
1126 } elseif ( isset( $versionInfo['server'] ) ) {
1127 // Normal client
1128 $this->numericVersion = $versionInfo['server'];
1129 } else {
1130 // T18937: broken pgsql extension from PHP<5.3
1131 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1132 }
1133 }
1134
1135 return $this->numericVersion;
1136 }
1137
1138 /**
1139 * Query whether a given relation exists (in the given schema, or the
1140 * default mw one if not given)
1141 * @param string $table
1142 * @param array|string $types
1143 * @param bool|string $schema
1144 * @return bool
1145 */
1146 private function relationExists( $table, $types, $schema = false ) {
1147 if ( !is_array( $types ) ) {
1148 $types = [ $types ];
1149 }
1150 if ( $schema === false ) {
1151 $schemas = $this->getCoreSchemas();
1152 } else {
1153 $schemas = [ $schema ];
1154 }
1155 $table = $this->realTableName( $table, 'raw' );
1156 $etable = $this->addQuotes( $table );
1157 foreach ( $schemas as $schema ) {
1158 $eschema = $this->addQuotes( $schema );
1159 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1160 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1161 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1162 $res = $this->query( $sql );
1163 if ( $res && $res->numRows() ) {
1164 return true;
1165 }
1166 }
1167
1168 return false;
1169 }
1170
1171 /**
1172 * For backward compatibility, this function checks both tables and views.
1173 * @param string $table
1174 * @param string $fname
1175 * @param bool|string $schema
1176 * @return bool
1177 */
1178 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1179 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1180 }
1181
1182 public function sequenceExists( $sequence, $schema = false ) {
1183 return $this->relationExists( $sequence, 'S', $schema );
1184 }
1185
1186 public function triggerExists( $table, $trigger ) {
1187 $q = <<<SQL
1188 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1189 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1190 AND tgrelid=pg_class.oid
1191 AND nspname=%s AND relname=%s AND tgname=%s
1192 SQL;
1193 foreach ( $this->getCoreSchemas() as $schema ) {
1194 $res = $this->query(
1195 sprintf(
1196 $q,
1197 $this->addQuotes( $schema ),
1198 $this->addQuotes( $table ),
1199 $this->addQuotes( $trigger )
1200 )
1201 );
1202 if ( $res && $res->numRows() ) {
1203 return true;
1204 }
1205 }
1206
1207 return false;
1208 }
1209
1210 public function ruleExists( $table, $rule ) {
1211 $exists = $this->selectField( 'pg_rules', 'rulename',
1212 [
1213 'rulename' => $rule,
1214 'tablename' => $table,
1215 'schemaname' => $this->getCoreSchemas()
1216 ]
1217 );
1218
1219 return $exists === $rule;
1220 }
1221
1222 public function constraintExists( $table, $constraint ) {
1223 foreach ( $this->getCoreSchemas() as $schema ) {
1224 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1225 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1226 $this->addQuotes( $schema ),
1227 $this->addQuotes( $table ),
1228 $this->addQuotes( $constraint )
1229 );
1230 $res = $this->query( $sql );
1231 if ( $res && $res->numRows() ) {
1232 return true;
1233 }
1234 }
1235 return false;
1236 }
1237
1238 /**
1239 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1240 * @param string $schema
1241 * @return bool
1242 */
1243 public function schemaExists( $schema ) {
1244 if ( !strlen( $schema ) ) {
1245 return false; // short-circuit
1246 }
1247
1248 $res = $this->query(
1249 "SELECT 1 FROM pg_catalog.pg_namespace " .
1250 "WHERE nspname = " . $this->addQuotes( $schema ) . " LIMIT 1",
1251 __METHOD__,
1252 self::QUERY_IGNORE_DBO_TRX
1253 );
1254
1255 return ( $this->numRows( $res ) > 0 );
1256 }
1257
1258 /**
1259 * Returns true if a given role (i.e. user) exists, false otherwise.
1260 * @param string $roleName
1261 * @return bool
1262 */
1263 public function roleExists( $roleName ) {
1264 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1265 [ 'rolname' => $roleName ], __METHOD__ );
1266
1267 return (bool)$exists;
1268 }
1269
1270 /**
1271 * @param string $table
1272 * @param string $field
1273 * @return PostgresField|null
1274 */
1275 public function fieldInfo( $table, $field ) {
1276 return PostgresField::fromText( $this, $table, $field );
1277 }
1278
1279 /**
1280 * pg_field_type() wrapper
1281 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1282 * @param int $index Field number, starting from 0
1283 * @return string
1284 */
1285 public function fieldType( $res, $index ) {
1286 return pg_field_type( ResultWrapper::unwrap( $res ), $index );
1287 }
1288
1289 public function encodeBlob( $b ) {
1290 return new PostgresBlob( pg_escape_bytea( $b ) );
1291 }
1292
1293 public function decodeBlob( $b ) {
1294 if ( $b instanceof PostgresBlob ) {
1295 $b = $b->fetch();
1296 } elseif ( $b instanceof Blob ) {
1297 return $b->fetch();
1298 }
1299
1300 return pg_unescape_bytea( $b );
1301 }
1302
1303 public function strencode( $s ) {
1304 // Should not be called by us
1305 return pg_escape_string( $this->getBindingHandle(), (string)$s );
1306 }
1307
1308 public function addQuotes( $s ) {
1309 $conn = $this->getBindingHandle();
1310
1311 if ( is_null( $s ) ) {
1312 return 'NULL';
1313 } elseif ( is_bool( $s ) ) {
1314 return intval( $s );
1315 } elseif ( $s instanceof Blob ) {
1316 if ( $s instanceof PostgresBlob ) {
1317 $s = $s->fetch();
1318 } else {
1319 $s = pg_escape_bytea( $conn, $s->fetch() );
1320 }
1321 return "'$s'";
1322 } elseif ( $s instanceof NextSequenceValue ) {
1323 return 'DEFAULT';
1324 }
1325
1326 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1327 }
1328
1329 public function makeSelectOptions( $options ) {
1330 $preLimitTail = $postLimitTail = '';
1331 $startOpts = $useIndex = $ignoreIndex = '';
1332
1333 $noKeyOptions = [];
1334 foreach ( $options as $key => $option ) {
1335 if ( is_numeric( $key ) ) {
1336 $noKeyOptions[$option] = true;
1337 }
1338 }
1339
1340 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1341
1342 $preLimitTail .= $this->makeOrderBy( $options );
1343
1344 if ( isset( $options['FOR UPDATE'] ) ) {
1345 $postLimitTail .= ' FOR UPDATE OF ' .
1346 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1347 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1348 $postLimitTail .= ' FOR UPDATE';
1349 }
1350
1351 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1352 $startOpts .= 'DISTINCT';
1353 }
1354
1355 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1356 }
1357
1358 public function buildConcat( $stringList ) {
1359 return implode( ' || ', $stringList );
1360 }
1361
1362 public function buildGroupConcatField(
1363 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1364 ) {
1365 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1366
1367 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1368 }
1369
1370 public function buildStringCast( $field ) {
1371 return $field . '::text';
1372 }
1373
1374 public function streamStatementEnd( &$sql, &$newLine ) {
1375 # Allow dollar quoting for function declarations
1376 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1377 if ( $this->delimiter ) {
1378 $this->delimiter = false;
1379 } else {
1380 $this->delimiter = ';';
1381 }
1382 }
1383
1384 return parent::streamStatementEnd( $sql, $newLine );
1385 }
1386
1387 public function doLockTables( array $read, array $write, $method ) {
1388 $tablesWrite = [];
1389 foreach ( $write as $table ) {
1390 $tablesWrite[] = $this->tableName( $table );
1391 }
1392 $tablesRead = [];
1393 foreach ( $read as $table ) {
1394 $tablesRead[] = $this->tableName( $table );
1395 }
1396
1397 // Acquire locks for the duration of the current transaction...
1398 if ( $tablesWrite ) {
1399 $this->query(
1400 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1401 $method
1402 );
1403 }
1404 if ( $tablesRead ) {
1405 $this->query(
1406 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1407 $method
1408 );
1409 }
1410
1411 return true;
1412 }
1413
1414 public function lockIsFree( $lockName, $method ) {
1415 if ( !parent::lockIsFree( $lockName, $method ) ) {
1416 return false; // already held
1417 }
1418 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1419 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1420 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1421 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1422 $row = $this->fetchObject( $result );
1423
1424 return ( $row->lockstatus === 't' );
1425 }
1426
1427 public function lock( $lockName, $method, $timeout = 5 ) {
1428 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1429 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1430 $loop = new WaitConditionLoop(
1431 function () use ( $lockName, $key, $timeout, $method ) {
1432 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1433 $row = $this->fetchObject( $res );
1434 if ( $row->lockstatus === 't' ) {
1435 parent::lock( $lockName, $method, $timeout ); // record
1436 return true;
1437 }
1438
1439 return WaitConditionLoop::CONDITION_CONTINUE;
1440 },
1441 $timeout
1442 );
1443
1444 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1445 }
1446
1447 public function unlock( $lockName, $method ) {
1448 // http://www.postgresql.org/docs/9.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1449 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1450 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1451 $row = $this->fetchObject( $result );
1452
1453 if ( $row->lockstatus === 't' ) {
1454 parent::unlock( $lockName, $method ); // record
1455 return true;
1456 }
1457
1458 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1459
1460 return false;
1461 }
1462
1463 public function serverIsReadOnly() {
1464 $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1465 $row = $this->fetchObject( $res );
1466
1467 return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1468 }
1469
1470 public static function getAttributes() {
1471 return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS => true ];
1472 }
1473
1474 /**
1475 * @param string $lockName
1476 * @return string Integer
1477 */
1478 private function bigintFromLockName( $lockName ) {
1479 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1480 }
1481 }
1482
1483 /**
1484 * @deprecated since 1.29
1485 */
1486 class_alias( DatabasePostgres::class, 'DatabasePostgres' );