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