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