Debian Codegraph @

includes/libs/rdbms/database/DatabasePostgres.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace Wikimedia\Rdbms;
22
23 use PgSql\Connection;
24 use PgSql\Result;
25 use RuntimeException;
26 use Wikimedia\Rdbms\Platform\PostgresPlatform;
27 use Wikimedia\Rdbms\Replication\ReplicationReporter;
28 use Wikimedia\WaitConditionLoop;
29
30 /**
31 * Postgres database abstraction layer.
32 *
33 * @ingroup Database
34 */
35 class DatabasePostgres extends Database {
36 /** @var int */
37 private $port;
38 /** @var string */
39 private $tempSchema;
40 /** @var float|string */
41 private $numericVersion;
42
43 /** @var Result|null */
44 private $lastResultHandle;
45
46 /** @var PostgresPlatform */
47 protected $platform;
48
49 /**
50 * @see Database::__construct()
51 * @param array $params Additional parameters include:
52 * - port: A port to append to the hostname
53 */
54 public function __construct( array $params ) {
55 $this->port = intval( $params['port'] ?? null );
56 parent::__construct( $params );
57
58 $this->platform = new PostgresPlatform(
59 $this,
60 $this->logger,
61 $this->currentDomain,
62 $this->errorLogger
63 );
64 $this->replicationReporter = new ReplicationReporter(
65 $params['topologyRole'],
66 $this->logger,
67 $params['srvCache']
68 );
69 }
70
71 public function getType() {
72 return 'postgres';
73 }
74
75 protected function open( $server, $user, $password, $db, $schema, $tablePrefix ) {
76 if ( !function_exists( 'pg_connect' ) ) {
77 throw $this->newExceptionAfterConnectError(
78 "Postgres functions missing, have you compiled PHP with the --with-pgsql\n" .
79 "option? (Note: if you recently installed PHP, you may need to restart your\n" .
80 "webserver and database)"
81 );
82 }
83
84 $this->close( __METHOD__ );
85
86 $connectVars = [
87 // A database must be specified in order to connect to Postgres. If $dbName is not
88 // specified, then use the standard "postgres" database that should exist by default.
89 'dbname' => ( $db !== null && $db !== '' ) ? $db : 'postgres',
90 'user' => $user,
91 'password' => $password
92 ];
93 if ( $server !== null && $server !== '' ) {
94 $connectVars['host'] = $server;
95 }
96 if ( $this->port > 0 ) {
97 $connectVars['port'] = $this->port;
98 }
99 if ( $this->ssl ) {
100 $connectVars['sslmode'] = 'require';
101 }
102 $connectString = $this->makeConnectionString( $connectVars );
103
104 $this->installErrorHandler();
105 try {
106 $this->conn = pg_connect( $connectString, PGSQL_CONNECT_FORCE_NEW ) ?: null;
107 } catch ( RuntimeException $e ) {
108 $this->restoreErrorHandler();
109 throw $this->newExceptionAfterConnectError( $e->getMessage() );
110 }
111 $error = $this->restoreErrorHandler();
112
113 if ( !$this->conn ) {
114 throw $this->newExceptionAfterConnectError( $error ?: $this->lastError() );
115 }
116
117 try {
118 // Since no transaction is active at this point, any SET commands should apply
119 // for the entire session (e.g. will not be reverted on transaction rollback).
120 // See https://www.postgresql.org/docs/8.3/sql-set.html
121 $variables = [
122 'client_encoding' => 'UTF8',
123 'datestyle' => 'ISO, YMD',
124 'timezone' => 'GMT',
125 'standard_conforming_strings' => 'on',
126 'bytea_output' => 'escape',
127 'client_min_messages' => 'ERROR'
128 ];
129 foreach ( $variables as $var => $val ) {
130 $sql = 'SET ' . $this->platform->addIdentifierQuotes( $var ) . ' = ' . $this->addQuotes( $val );
131 $query = new Query( $sql, self::QUERY_NO_RETRY | self::QUERY_CHANGE_TRX, 'SET' );
132 $this->query( $query, __METHOD__ );
133 }
134 $this->determineCoreSchema( $schema );
135 $this->currentDomain = new DatabaseDomain( $db, $schema, $tablePrefix );
136 $this->platform->setCurrentDomain( $this->currentDomain );
137 } catch ( RuntimeException $e ) {
138 throw $this->newExceptionAfterConnectError( $e->getMessage() );
139 }
140 }
141
142 public function databasesAreIndependent() {
143 return true;
144 }
145
146 public function doSelectDomain( DatabaseDomain $domain ) {
147 $database = $domain->getDatabase();
148 if ( $database === null ) {
149 // A null database means "don't care" so leave it as is and update the table prefix
150 $this->currentDomain = new DatabaseDomain(
151 $this->currentDomain->getDatabase(),
152 $domain->getSchema() ?? $this->currentDomain->getSchema(),
153 $domain->getTablePrefix()
154 );
155 $this->platform->setCurrentDomain( $this->currentDomain );
156 } elseif ( $this->getDBname() !== $database ) {
157 // Postgres doesn't support selectDB in the same way MySQL does.
158 // So if the DB name doesn't match the open connection, open a new one
159 $this->open(
160 $this->connectionParams[self::CONN_HOST],
161 $this->connectionParams[self::CONN_USER],
162 $this->connectionParams[self::CONN_PASSWORD],
163 $database,
164 $domain->getSchema(),
165 $domain->getTablePrefix()
166 );
167 } else {
168 $this->currentDomain = $domain;
169 $this->platform->setCurrentDomain( $domain );
170 }
171
172 return true;
173 }
174
175 protected function getBindingHandle(): Connection {
176 return parent::getBindingHandle();
177 }
178
179 /**
180 * @param string[] $vars
181 * @return string
182 */
183 private function makeConnectionString( $vars ) {
184 $s = '';
185 foreach ( $vars as $name => $value ) {
186 $s .= "$name='" . str_replace( [ "\\", "'" ], [ "\\\\", "\\'" ], $value ) . "' ";
187 }
188
189 return $s;
190 }
191
192 protected function closeConnection() {
193 return $this->conn ? pg_close( $this->conn ) : true;
194 }
195
196 public function doSingleStatementQuery( string $sql ): QueryStatus {
197 $conn = $this->getBindingHandle();
198
199 $sql = mb_convert_encoding( $sql, 'UTF-8' );
200 // Clear any previously left over result
201 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
202 while ( $priorRes = pg_get_result( $conn ) ) {
203 pg_free_result( $priorRes );
204 }
205
206 if ( pg_send_query( $conn, $sql ) === false ) {
207 throw new DBUnexpectedError( $this, "Unable to post new query to PostgreSQL\n" );
208 }
209
210 $pgRes = pg_get_result( $conn );
211 $this->lastResultHandle = $pgRes;
212 $res = pg_result_error( $pgRes ) ? false : $pgRes;
213
214 return new QueryStatus(
215 is_bool( $res ) ? $res : new PostgresResultWrapper( $this, $conn, $res ),
216 $pgRes ? pg_affected_rows( $pgRes ) : 0,
217 $this->lastError(),
218 $this->lastErrno()
219 );
220 }
221
222 protected function dumpError() {
223 $diags = [
224 PGSQL_DIAG_SEVERITY,
225 PGSQL_DIAG_SQLSTATE,
226 PGSQL_DIAG_MESSAGE_PRIMARY,
227 PGSQL_DIAG_MESSAGE_DETAIL,
228 PGSQL_DIAG_MESSAGE_HINT,
229 PGSQL_DIAG_STATEMENT_POSITION,
230 PGSQL_DIAG_INTERNAL_POSITION,
231 PGSQL_DIAG_INTERNAL_QUERY,
232 PGSQL_DIAG_CONTEXT,
233 PGSQL_DIAG_SOURCE_FILE,
234 PGSQL_DIAG_SOURCE_LINE,
235 PGSQL_DIAG_SOURCE_FUNCTION
236 ];
237 foreach ( $diags as $d ) {
238 $this->logger->debug( sprintf( "PgSQL ERROR(%d): %s",
239 $d, pg_result_error_field( $this->lastResultHandle, $d ) ) );
240 }
241 }
242
243 protected function lastInsertId() {
244 // Avoid using query() to prevent unwanted side-effects like changing affected
245 // row counts or connection retries. Note that lastval() is connection-specific.
246 // Note that this causes "lastval is not yet defined in this session" errors if
247 // nextval() was never directly or implicitly triggered (error out any transaction).
248 $qs = $this->doSingleStatementQuery( "SELECT lastval() AS id" );
249
250 return $qs->res ? (int)$qs->res->fetchRow()['id'] : 0;
251 }
252
253 public function lastError() {
254 if ( $this->conn ) {
255 if ( $this->lastResultHandle ) {
256 return pg_result_error( $this->lastResultHandle );
257 } else {
258 return pg_last_error() ?: $this->lastConnectError;
259 }
260 }
261
262 return $this->getLastPHPError() ?: 'No database connection';
263 }
264
265 public function lastErrno() {
266 if ( $this->lastResultHandle ) {
267 $lastErrno = pg_result_error_field( $this->lastResultHandle, PGSQL_DIAG_SQLSTATE );
268 if ( $lastErrno !== false ) {
269 return $lastErrno;
270 }
271 }
272
273 return '00000';
274 }
275
276 public function estimateRowCount( $table, $var = '*', $conds = '',
277 $fname = __METHOD__, $options = [], $join_conds = []
278 ): int {
279 $conds = $this->platform->normalizeConditions( $conds, $fname );
280 $column = $this->platform->extractSingleFieldFromList( $var );
281 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
282 $conds[] = "$column IS NOT NULL";
283 }
284
285 $options['EXPLAIN'] = true;
286 $res = $this->select( $table, $var, $conds, $fname, $options, $join_conds );
287 $rows = -1;
288 if ( $res ) {
289 $row = $res->fetchRow();
290 $count = [];
291 if ( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
292 $rows = (int)$count[1];
293 }
294 }
295
296 return $rows;
297 }
298
299 public function indexInfo( $table, $index, $fname = __METHOD__ ) {
300 $components = $this->platform->qualifiedTableComponents( $table );
301 if ( count( $components ) === 1 ) {
302 $schema = $this->getCoreSchema();
303 $tableComponent = $components[0];
304 } elseif ( count( $components ) === 2 ) {
305 [ $schema, $tableComponent ] = $components;
306 } else {
307 [ , $schema, $tableComponent ] = $components;
308 }
309 $encSchema = $this->addQuotes( $schema );
310 $encTable = $this->addQuotes( $tableComponent );
311 $encIndex = $this->addQuotes( $this->platform->indexName( $index ) );
312 $query = new Query(
313 "SELECT indexname,indexdef FROM pg_indexes " .
314 "WHERE schemaname=$encSchema AND tablename=$encTable AND indexname=$encIndex",
315 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
316 'SELECT'
317 );
318 $res = $this->query( $query );
319 $row = $res->fetchObject();
320
321 if ( $row ) {
322 return [ 'unique' => ( strpos( $row->indexdef, 'CREATE UNIQUE ' ) === 0 ) ];
323 }
324
325 return false;
326 }
327
328 public function indexAttributes( $index, $schema = false ) {
329 if ( $schema === false ) {
330 $schemas = $this->getCoreSchemas();
331 } else {
332 $schemas = [ $schema ];
333 }
334
335 $eindex = $this->addQuotes( $index );
336
337 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
338 foreach ( $schemas as $schema ) {
339 $eschema = $this->addQuotes( $schema );
340 /*
341 * A subquery would be not needed if we didn't care about the order
342 * of attributes, but we do
343 */
344 $sql = <<<__INDEXATTR__
345
346 SELECT opcname,
347 attname,
348 i.indoption[s.g] as option,
349 pg_am.amname
350 FROM
351 (SELECT generate_series(array_lower(isub.indkey,1), array_upper(isub.indkey,1)) AS g
352 FROM
353 pg_index isub
354 JOIN pg_class cis
355 ON cis.oid=isub.indexrelid
356 JOIN pg_namespace ns
357 ON cis.relnamespace = ns.oid
358 WHERE cis.relname=$eindex AND ns.nspname=$eschema) AS s,
359 pg_attribute,
360 pg_opclass opcls,
361 pg_am,
362 pg_class ci
363 JOIN pg_index i
364 ON ci.oid=i.indexrelid
365 JOIN pg_class ct
366 ON ct.oid = i.indrelid
367 JOIN pg_namespace n
368 ON ci.relnamespace = n.oid
369 WHERE
370 ci.relname=$eindex AND n.nspname=$eschema
371 AND attrelid = ct.oid
372 AND i.indkey[s.g] = attnum
373 AND i.indclass[s.g] = opcls.oid
374 AND pg_am.oid = opcls.opcmethod
375 __INDEXATTR__;
376 $query = new Query( $sql, $flags, 'SELECT' );
377 $res = $this->query( $query, __METHOD__ );
378 $a = [];
379 if ( $res ) {
380 foreach ( $res as $row ) {
381 $a[] = [
382 $row->attname,
383 $row->opcname,
384 $row->amname,
385 $row->option ];
386 }
387 return $a;
388 }
389 }
390 return null;
391 }
392
393 protected function doInsertSelectNative(
394 $destTable,
395 $srcTable,
396 array $varMap,
397 $conds,
398 $fname,
399 array $insertOptions,
400 array $selectOptions,
401 $selectJoinConds
402 ) {
403 if ( in_array( 'IGNORE', $insertOptions ) ) {
404 // Use "ON CONFLICT DO" if we have it for IGNORE
405 $destTableEnc = $this->tableName( $destTable );
406
407 $selectSql = $this->selectSQLText(
408 $srcTable,
409 array_values( $varMap ),
410 $conds,
411 $fname,
412 $selectOptions,
413 $selectJoinConds
414 );
415
416 $sql = "INSERT INTO $destTableEnc (" . implode( ',', array_keys( $varMap ) ) . ') ' .
417 $selectSql . ' ON CONFLICT DO NOTHING';
418 $query = new Query( $sql, self::QUERY_CHANGE_ROWS, 'INSERT', $destTable );
419 $this->query( $query, $fname );
420 } else {
421 parent::doInsertSelectNative( $destTable, $srcTable, $varMap, $conds, $fname,
422 $insertOptions, $selectOptions, $selectJoinConds );
423 }
424 }
425
426 public function getValueTypesForWithClause( $table ) {
427 $typesByColumn = [];
428
429 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
430 $encTable = $this->addQuotes( $table );
431 foreach ( $this->getCoreSchemas() as $schema ) {
432 $encSchema = $this->addQuotes( $schema );
433 $sql = "SELECT column_name,udt_name " .
434 "FROM information_schema.columns " .
435 "WHERE table_name = $encTable AND table_schema = $encSchema";
436 $query = new Query( $sql, $flags, 'SELECT' );
437 $res = $this->query( $query, __METHOD__ );
438 if ( $res->numRows() ) {
439 foreach ( $res as $row ) {
440 $typesByColumn[$row->column_name] = $row->udt_name;
441 }
442 break;
443 }
444 }
445
446 return $typesByColumn;
447 }
448
449 protected function isConnectionError( $errno ) {
450 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
451 static $codes = [ '08000', '08003', '08006', '08001', '08004', '57P01', '57P03', '53300' ];
452
453 return in_array( $errno, $codes, true );
454 }
455
456 protected function isQueryTimeoutError( $errno ) {
457 // https://www.postgresql.org/docs/9.2/static/errcodes-appendix.html
458 return ( $errno === '57014' );
459 }
460
461 protected function isKnownStatementRollbackError( $errno ) {
462 return false; // transaction has to be rolled-back from error state
463 }
464
465 public function duplicateTableStructure(
466 $oldName, $newName, $temporary = false, $fname = __METHOD__
467 ) {
468 $newNameE = $this->platform->addIdentifierQuotes( $newName );
469 $oldNameE = $this->platform->addIdentifierQuotes( $oldName );
470
471 $temporary = $temporary ? 'TEMPORARY' : '';
472 $query = new Query(
473 "CREATE $temporary TABLE $newNameE " .
474 "(LIKE $oldNameE INCLUDING DEFAULTS INCLUDING INDEXES)",
475 self::QUERY_PSEUDO_PERMANENT | self::QUERY_CHANGE_SCHEMA,
476 $temporary ? 'CREATE TEMPORARY' : 'CREATE',
477 // Use a dot to avoid double-prefixing in Database::getTempTableWrites()
478 '.' . $newName
479 );
480 $ret = $this->query( $query, $fname );
481 if ( !$ret ) {
482 return $ret;
483 }
484
485 $sql = 'SELECT attname FROM pg_class c'
486 . ' JOIN pg_namespace n ON (n.oid = c.relnamespace)'
487 . ' JOIN pg_attribute a ON (a.attrelid = c.oid)'
488 . ' JOIN pg_attrdef d ON (c.oid=d.adrelid and a.attnum=d.adnum)'
489 . ' WHERE relkind = \'r\''
490 . ' AND nspname = ' . $this->addQuotes( $this->getCoreSchema() )
491 . ' AND relname = ' . $this->addQuotes( $oldName )
492 . ' AND pg_get_expr(adbin, adrelid) LIKE \'nextval(%\'';
493 $query = new Query(
494 $sql,
495 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
496 'SELECT'
497 );
498
499 $res = $this->query( $query, $fname );
500 $row = $res->fetchObject();
501 if ( $row ) {
502 $field = $row->attname;
503 $newSeq = "{$newName}_{$field}_seq";
504 $fieldE = $this->platform->addIdentifierQuotes( $field );
505 $newSeqE = $this->platform->addIdentifierQuotes( $newSeq );
506 $newSeqQ = $this->addQuotes( $newSeq );
507 $query = new Query(
508 "CREATE $temporary SEQUENCE $newSeqE OWNED BY $newNameE.$fieldE",
509 self::QUERY_CHANGE_SCHEMA,
510 'CREATE',
511 // Do not treat this is as a table modification on top of the CREATE above.
512 null
513 );
514 $this->query( $query, $fname );
515 $query = new Query(
516 "ALTER TABLE $newNameE ALTER COLUMN $fieldE SET DEFAULT nextval({$newSeqQ}::regclass)",
517 self::QUERY_CHANGE_SCHEMA,
518 'ALTER',
519 // Do not treat this is as a table modification on top of the CREATE above.
520 null
521 );
522 $this->query( $query, $fname );
523 }
524
525 return $ret;
526 }
527
528 public function truncateTable( $table, $fname = __METHOD__ ) {
529 $sql = "TRUNCATE TABLE " . $this->tableName( $table ) . " RESTART IDENTITY";
530 $query = new Query( $sql, self::QUERY_CHANGE_SCHEMA, 'TRUNCATE', $table );
531 $this->query( $query, $fname );
532 }
533
534 /**
535 * @param string $prefix Only show tables with this prefix, e.g. mw_
536 * @param string $fname Calling function name
537 * @return string[]
538 * @suppress SecurityCheck-SQLInjection array_map not recognized T204911
539 */
540 public function listTables( $prefix = '', $fname = __METHOD__ ) {
541 $eschemas = implode( ',', array_map( [ $this, 'addQuotes' ], $this->getCoreSchemas() ) );
542 $query = new Query(
543 "SELECT DISTINCT tablename FROM pg_tables WHERE schemaname IN ($eschemas)",
544 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
545 'SELECT'
546 );
547 $result = $this->query( $query, $fname );
548 $endArray = [];
549
550 foreach ( $result as $table ) {
551 $vars = get_object_vars( $table );
552 $table = array_pop( $vars );
553 if ( $prefix == '' || strpos( $table, $prefix ) === 0 ) {
554 $endArray[] = $table;
555 }
556 }
557
558 return $endArray;
559 }
560
561 /**
562 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
563 * to https://www.php.net/manual/en/ref.pgsql.php
564 *
565 * Parsing a postgres array can be a tricky problem, he's my
566 * take on this, it handles multi-dimensional arrays plus
567 * escaping using a nasty regexp to determine the limits of each
568 * data-item.
569 *
570 * This should really be handled by PHP PostgreSQL module
571 *
572 * @since 1.19
573 * @param string $text Postgreql array returned in a text form like {a,b}
574 * @param string[] &$output
575 * @param int|false $limit
576 * @param int $offset
577 * @return string[]
578 */
579 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
580 if ( $limit === false ) {
581 $limit = strlen( $text ) - 1;
582 $output = [];
583 }
584 if ( $text == '{}' ) {
585 return $output;
586 }
587 do {
588 if ( $text[$offset] != '{' ) {
589 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
590 $text, $match, 0, $offset );
591 $offset += strlen( $match[0] );
592 $output[] = ( $match[1][0] != '"'
593 ? $match[1]
594 : stripcslashes( substr( $match[1], 1, -1 ) ) );
595 if ( $match[3] == '},' ) {
596 return $output;
597 }
598 } else {
599 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
600 }
601 } while ( $limit > $offset );
602
603 return $output;
604 }
605
606 public function getSoftwareLink() {
607 return '[{{int:version-db-postgres-url}} PostgreSQL]';
608 }
609
610 /**
611 * Return current schema (executes SELECT current_schema())
612 * Needs transaction
613 *
614 * @since 1.19
615 * @return string Default schema for the current session
616 */
617 public function getCurrentSchema() {
618 $query = new Query(
619 "SELECT current_schema()",
620 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
621 'SELECT'
622 );
623 $res = $this->query( $query, __METHOD__ );
624 $row = $res->fetchRow();
625
626 return $row[0];
627 }
628
629 /**
630 * Return list of schemas which are accessible without schema name
631 * This is list does not contain magic keywords like "$user"
632 * Needs transaction
633 *
634 * @see getSearchPath()
635 * @see setSearchPath()
636 * @since 1.19
637 * @return array List of actual schemas for the current session
638 */
639 public function getSchemas() {
640 $query = new Query(
641 "SELECT current_schemas(false)",
642 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
643 'SELECT'
644 );
645 $res = $this->query( $query, __METHOD__ );
646 $row = $res->fetchRow();
647 $schemas = [];
648
649 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
650
651 return $this->pg_array_parse( $row[0], $schemas );
652 }
653
654 /**
655 * Return search patch for schemas
656 * This is different from getSchemas() since it contain magic keywords
657 * (like "$user").
658 * Needs transaction
659 *
660 * @since 1.19
661 * @return array How to search for table names schemas for the current user
662 */
663 public function getSearchPath() {
664 $query = new Query(
665 "SHOW search_path",
666 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
667 'SHOW'
668 );
669 $res = $this->query( $query, __METHOD__ );
670 $row = $res->fetchRow();
671
672 /* PostgreSQL returns SHOW values as strings */
673
674 return explode( ",", $row[0] );
675 }
676
677 /**
678 * Update search_path, values should already be sanitized
679 * Values may contain magic keywords like "$user"
680 * @since 1.19
681 *
682 * @param string[] $search_path List of schemas to be searched by default
683 */
684 private function setSearchPath( $search_path ) {
685 $query = new Query(
686 "SET search_path = " . implode( ", ", $search_path ),
687 self::QUERY_CHANGE_TRX,
688 'SET'
689 );
690 $this->query( $query, __METHOD__ );
691 }
692
693 /**
694 * Determine default schema for the current application
695 * Adjust this session schema search path if desired schema exists
696 * and is not already there.
697 *
698 * We need to have name of the core schema stored to be able
699 * to query database metadata.
700 *
701 * This will be also called by the installer after the schema is created
702 *
703 * @since 1.19
704 *
705 * @param string|null $desiredSchema
706 */
707 public function determineCoreSchema( $desiredSchema ) {
708 if ( $this->trxLevel() ) {
709 // We do not want the schema selection to change on ROLLBACK or INSERT SELECT.
710 // See https://www.postgresql.org/docs/8.3/sql-set.html
711 throw new DBUnexpectedError(
712 $this,
713 __METHOD__ . ": a transaction is currently active"
714 );
715 }
716
717 if ( $this->schemaExists( $desiredSchema ) ) {
718 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
719 $this->platform->setCoreSchema( $desiredSchema );
720 $this->logger->debug(
721 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
722 } else {
723 // Prepend the desired schema to the search path (T17816)
724 $search_path = $this->getSearchPath();
725 array_unshift( $search_path, $this->platform->addIdentifierQuotes( $desiredSchema ) );
726 $this->setSearchPath( $search_path );
727 $this->platform->setCoreSchema( $desiredSchema );
728 $this->logger->debug(
729 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
730 }
731 } else {
732 $this->platform->setCoreSchema( $this->getCurrentSchema() );
733 $this->logger->debug(
734 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
735 $this->getCoreSchema() . "\"\n" );
736 }
737 }
738
739 /**
740 * Return schema name for core application tables
741 *
742 * @since 1.19
743 * @return string Core schema name
744 */
745 public function getCoreSchema() {
746 return $this->platform->getCoreSchema();
747 }
748
749 /**
750 * Return schema names for temporary tables and core application tables
751 *
752 * @since 1.31
753 * @return string[] schema names
754 */
755 public function getCoreSchemas() {
756 if ( $this->tempSchema ) {
757 return [ $this->tempSchema, $this->getCoreSchema() ];
758 }
759 $query = new Query(
760 "SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = pg_my_temp_schema()",
761 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
762 'SELECT'
763 );
764 $res = $this->query( $query, __METHOD__ );
765 $row = $res->fetchObject();
766 if ( $row ) {
767 $this->tempSchema = $row->nspname;
768 return [ $this->tempSchema, $this->getCoreSchema() ];
769 }
770
771 return [ $this->getCoreSchema() ];
772 }
773
774 public function getServerVersion() {
775 if ( !isset( $this->numericVersion ) ) {
776 // Works on PG 7.4+
777 $this->numericVersion = pg_version( $this->getBindingHandle() )['server'];
778 }
779
780 return $this->numericVersion;
781 }
782
783 /**
784 * Query whether a given relation exists (in the given schema, or the
785 * default mw one if not given)
786 * @param string $table
787 * @param array|string $types
788 * @return bool
789 */
790 private function relationExists( $table, $types ) {
791 if ( !is_array( $types ) ) {
792 $types = [ $types ];
793 }
794 $schemas = $this->getCoreSchemas();
795 $components = $this->platform->qualifiedTableComponents( $table );
796 $etable = $this->addQuotes( end( $components ) );
797 foreach ( $schemas as $schema ) {
798 $eschema = $this->addQuotes( $schema );
799 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
800 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
801 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
802 $query = new Query(
803 $sql,
804 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
805 'SELECT'
806 );
807 $res = $this->query( $query, __METHOD__ );
808 if ( $res && $res->numRows() ) {
809 return true;
810 }
811 }
812
813 return false;
814 }
815
816 public function tableExists( $table, $fname = __METHOD__ ) {
817 return $this->relationExists( $table, [ 'r', 'v' ] );
818 }
819
820 public function sequenceExists( $sequence ) {
821 return $this->relationExists( $sequence, 'S' );
822 }
823
824 public function constraintExists( $table, $constraint ) {
825 foreach ( $this->getCoreSchemas() as $schema ) {
826 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
827 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
828 $this->addQuotes( $schema ),
829 $this->addQuotes( $table ),
830 $this->addQuotes( $constraint )
831 );
832 $query = new Query(
833 $sql,
834 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
835 'SELECT'
836 );
837 $res = $this->query( $query, __METHOD__ );
838 if ( $res && $res->numRows() ) {
839 return true;
840 }
841 }
842 return false;
843 }
844
845 /**
846 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
847 * @param string|null $schema
848 * @return bool
849 */
850 public function schemaExists( $schema ) {
851 if ( !strlen( $schema ?? '' ) ) {
852 return false; // short-circuit
853 }
854 $query = new Query(
855 "SELECT 1 FROM pg_catalog.pg_namespace " .
856 "WHERE nspname = " . $this->addQuotes( $schema ) . " LIMIT 1",
857 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
858 'SELECT'
859 );
860 $res = $this->query( $query, __METHOD__ );
861
862 return ( $res->numRows() > 0 );
863 }
864
865 /**
866 * Returns true if a given role (i.e. user) exists, false otherwise.
867 * @param string $roleName
868 * @return bool
869 */
870 public function roleExists( $roleName ) {
871 $query = new Query(
872 "SELECT 1 FROM pg_catalog.pg_roles " .
873 "WHERE rolname = " . $this->addQuotes( $roleName ) . " LIMIT 1",
874 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
875 'SELECT'
876 );
877 $res = $this->query( $query, __METHOD__ );
878
879 return ( $res->numRows() > 0 );
880 }
881
882 /**
883 * @param string $table
884 * @param string $field
885 * @return PostgresField|null
886 */
887 public function fieldInfo( $table, $field ) {
888 return PostgresField::fromText( $this, $table, $field );
889 }
890
891 public function encodeBlob( $b ) {
892 $conn = $this->getBindingHandle();
893
894 return new PostgresBlob( pg_escape_bytea( $conn, $b ) );
895 }
896
897 public function decodeBlob( $b ) {
898 if ( $b instanceof PostgresBlob ) {
899 $b = $b->fetch();
900 } elseif ( $b instanceof Blob ) {
901 return $b->fetch();
902 }
903
904 return pg_unescape_bytea( $b );
905 }
906
907 public function strencode( $s ) {
908 // Should not be called by us
909 return pg_escape_string( $this->getBindingHandle(), (string)$s );
910 }
911
912 public function addQuotes( $s ) {
913 if ( $s instanceof RawSQLValue ) {
914 return $s->toSql();
915 }
916 $conn = $this->getBindingHandle();
917
918 if ( $s === null ) {
919 return 'NULL';
920 } elseif ( is_bool( $s ) ) {
921 return (string)intval( $s );
922 } elseif ( is_int( $s ) ) {
923 return (string)$s;
924 } elseif ( $s instanceof Blob ) {
925 if ( $s instanceof PostgresBlob ) {
926 $s = $s->fetch();
927 } else {
928 $s = pg_escape_bytea( $conn, $s->fetch() );
929 }
930 return "'$s'";
931 }
932
933 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
934 }
935
936 public function streamStatementEnd( &$sql, &$newLine ) {
937 # Allow dollar quoting for function declarations
938 if ( str_starts_with( $newLine, '$mw$' ) ) {
939 if ( $this->delimiter ) {
940 $this->delimiter = false;
941 } else {
942 $this->delimiter = ';';
943 }
944 }
945
946 return parent::streamStatementEnd( $sql, $newLine );
947 }
948
949 public function doLockIsFree( string $lockName, string $method ) {
950 $query = new Query(
951 $this->platform->lockIsFreeSQLText( $lockName ),
952 self::QUERY_CHANGE_LOCKS,
953 'SELECT'
954 );
955 $res = $this->query( $query, $method );
956 $row = $res->fetchObject();
957
958 return (bool)$row->unlocked;
959 }
960
961 public function doLock( string $lockName, string $method, int $timeout ) {
962 $query = new Query(
963 $this->platform->lockSQLText( $lockName, $timeout ),
964 self::QUERY_CHANGE_LOCKS,
965 'SELECT'
966 );
967
968 $acquired = null;
969 $loop = new WaitConditionLoop(
970 function () use ( $query, $method, &$acquired ) {
971 $res = $this->query( $query, $method );
972 $row = $res->fetchObject();
973
974 if ( $row->acquired !== null ) {
975 $acquired = (float)$row->acquired;
976
977 return WaitConditionLoop::CONDITION_REACHED;
978 }
979
980 return WaitConditionLoop::CONDITION_CONTINUE;
981 },
982 $timeout
983 );
984 $loop->invoke();
985
986 return $acquired;
987 }
988
989 public function doUnlock( string $lockName, string $method ) {
990 $query = new Query(
991 $this->platform->unlockSQLText( $lockName ),
992 self::QUERY_CHANGE_LOCKS,
993 'SELECT'
994 );
995 $result = $this->query( $query, $method );
996 $row = $result->fetchObject();
997
998 return (bool)$row->released;
999 }
1000
1001 protected function doFlushSession( $fname ) {
1002 $flags = self::QUERY_CHANGE_LOCKS | self::QUERY_NO_RETRY;
1003
1004 // https://www.postgresql.org/docs/9.1/functions-admin.html
1005 $sql = "SELECT pg_advisory_unlock_all()";
1006 $query = new Query( $sql, $flags, 'UNLOCK' );
1007 $qs = $this->executeQuery( $query, __METHOD__, $flags );
1008 if ( $qs->res === false ) {
1009 $this->reportQueryError( $qs->message, $qs->code, $sql, $fname, true );
1010 }
1011 }
1012
1013 public function serverIsReadOnly() {
1014 $query = new Query(
1015 "SHOW default_transaction_read_only",
1016 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
1017 'SHOW'
1018 );
1019 $res = $this->query( $query, __METHOD__ );
1020 $row = $res->fetchObject();
1021
1022 return $row && strtolower( $row->default_transaction_read_only ) === 'on';
1023 }
1024
1025 protected function getInsertIdColumnForUpsert( $table ) {
1026 $column = null;
1027
1028 $flags = self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE;
1029 $components = $this->platform->qualifiedTableComponents( $table );
1030 $encTable = $this->addQuotes( end( $components ) );
1031 foreach ( $this->getCoreSchemas() as $schema ) {
1032 $encSchema = $this->addQuotes( $schema );
1033 $query = new Query(
1034 "SELECT column_name,data_type,column_default " .
1035 "FROM information_schema.columns " .
1036 "WHERE table_name = $encTable AND table_schema = $encSchema",
1037 self::QUERY_IGNORE_DBO_TRX | self::QUERY_CHANGE_NONE,
1038 'SELECT'
1039 );
1040 $res = $this->query( $query, __METHOD__ );
1041 if ( $res->numRows() ) {
1042 foreach ( $res as $row ) {
1043 if (
1044 $row->column_default !== null &&
1045 str_starts_with( $row->column_default, "nextval(" ) &&
1046 in_array( $row->data_type, [ 'integer', 'bigint' ], true )
1047 ) {
1048 $column = $row->column_name;
1049 }
1050 }
1051 break;
1052 }
1053 }
1054
1055 return $column;
1056 }
1057
1058 public static function getAttributes() {
1059 return [ self::ATTR_SCHEMAS_AS_TABLE_GROUPS => true ];
1060 }
1061 }