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