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