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