rdbms: define wasLockTimeout() for postgres
[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 // https://www.postgresql.org/docs/8.2/static/errcodes-appendix.html
803 return $this->lastErrno() === '40P01';
804 }
805
806 public function wasLockTimeout() {
807 // https://www.postgresql.org/docs/8.2/static/errcodes-appendix.html
808 return $this->lastErrno() === '55P03';
809 }
810
811 public function duplicateTableStructure(
812 $oldName, $newName, $temporary = false, $fname = __METHOD__
813 ) {
814 $newName = $this->addIdentifierQuotes( $newName );
815 $oldName = $this->addIdentifierQuotes( $oldName );
816
817 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName " .
818 "(LIKE $oldName INCLUDING DEFAULTS INCLUDING INDEXES)", $fname );
819 }
820
821 public function listTables( $prefix = null, $fname = __METHOD__ ) {
822 $eschema = $this->addQuotes( $this->getCoreSchema() );
823 $result = $this->query(
824 "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
825 $endArray = [];
826
827 foreach ( $result as $table ) {
828 $vars = get_object_vars( $table );
829 $table = array_pop( $vars );
830 if ( !$prefix || strpos( $table, $prefix ) === 0 ) {
831 $endArray[] = $table;
832 }
833 }
834
835 return $endArray;
836 }
837
838 public function timestamp( $ts = 0 ) {
839 $ct = new ConvertibleTimestamp( $ts );
840
841 return $ct->getTimestamp( TS_POSTGRES );
842 }
843
844 /**
845 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
846 * to https://secure.php.net/manual/en/ref.pgsql.php
847 *
848 * Parsing a postgres array can be a tricky problem, he's my
849 * take on this, it handles multi-dimensional arrays plus
850 * escaping using a nasty regexp to determine the limits of each
851 * data-item.
852 *
853 * This should really be handled by PHP PostgreSQL module
854 *
855 * @since 1.19
856 * @param string $text Postgreql array returned in a text form like {a,b}
857 * @param string[] $output
858 * @param int|bool $limit
859 * @param int $offset
860 * @return string[]
861 */
862 private function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
863 if ( false === $limit ) {
864 $limit = strlen( $text ) - 1;
865 $output = [];
866 }
867 if ( '{}' == $text ) {
868 return $output;
869 }
870 do {
871 if ( '{' != $text[$offset] ) {
872 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
873 $text, $match, 0, $offset );
874 $offset += strlen( $match[0] );
875 $output[] = ( '"' != $match[1][0]
876 ? $match[1]
877 : stripcslashes( substr( $match[1], 1, -1 ) ) );
878 if ( '},' == $match[3] ) {
879 return $output;
880 }
881 } else {
882 $offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
883 }
884 } while ( $limit > $offset );
885
886 return $output;
887 }
888
889 public function aggregateValue( $valuedata, $valuename = 'value' ) {
890 return $valuedata;
891 }
892
893 public function getSoftwareLink() {
894 return '[{{int:version-db-postgres-url}} PostgreSQL]';
895 }
896
897 /**
898 * Return current schema (executes SELECT current_schema())
899 * Needs transaction
900 *
901 * @since 1.19
902 * @return string Default schema for the current session
903 */
904 public function getCurrentSchema() {
905 $res = $this->query( "SELECT current_schema()", __METHOD__ );
906 $row = $this->fetchRow( $res );
907
908 return $row[0];
909 }
910
911 /**
912 * Return list of schemas which are accessible without schema name
913 * This is list does not contain magic keywords like "$user"
914 * Needs transaction
915 *
916 * @see getSearchPath()
917 * @see setSearchPath()
918 * @since 1.19
919 * @return array List of actual schemas for the current sesson
920 */
921 public function getSchemas() {
922 $res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
923 $row = $this->fetchRow( $res );
924 $schemas = [];
925
926 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
927
928 return $this->pg_array_parse( $row[0], $schemas );
929 }
930
931 /**
932 * Return search patch for schemas
933 * This is different from getSchemas() since it contain magic keywords
934 * (like "$user").
935 * Needs transaction
936 *
937 * @since 1.19
938 * @return array How to search for table names schemas for the current user
939 */
940 public function getSearchPath() {
941 $res = $this->query( "SHOW search_path", __METHOD__ );
942 $row = $this->fetchRow( $res );
943
944 /* PostgreSQL returns SHOW values as strings */
945
946 return explode( ",", $row[0] );
947 }
948
949 /**
950 * Update search_path, values should already be sanitized
951 * Values may contain magic keywords like "$user"
952 * @since 1.19
953 *
954 * @param array $search_path List of schemas to be searched by default
955 */
956 private function setSearchPath( $search_path ) {
957 $this->query( "SET search_path = " . implode( ", ", $search_path ) );
958 }
959
960 /**
961 * Determine default schema for the current application
962 * Adjust this session schema search path if desired schema exists
963 * and is not alread there.
964 *
965 * We need to have name of the core schema stored to be able
966 * to query database metadata.
967 *
968 * This will be also called by the installer after the schema is created
969 *
970 * @since 1.19
971 *
972 * @param string $desiredSchema
973 */
974 public function determineCoreSchema( $desiredSchema ) {
975 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
976 if ( $this->schemaExists( $desiredSchema ) ) {
977 if ( in_array( $desiredSchema, $this->getSchemas() ) ) {
978 $this->coreSchema = $desiredSchema;
979 $this->queryLogger->debug(
980 "Schema \"" . $desiredSchema . "\" already in the search path\n" );
981 } else {
982 /**
983 * Prepend our schema (e.g. 'mediawiki') in front
984 * of the search path
985 * Fixes T17816
986 */
987 $search_path = $this->getSearchPath();
988 array_unshift( $search_path,
989 $this->addIdentifierQuotes( $desiredSchema ) );
990 $this->setSearchPath( $search_path );
991 $this->coreSchema = $desiredSchema;
992 $this->queryLogger->debug(
993 "Schema \"" . $desiredSchema . "\" added to the search path\n" );
994 }
995 } else {
996 $this->coreSchema = $this->getCurrentSchema();
997 $this->queryLogger->debug(
998 "Schema \"" . $desiredSchema . "\" not found, using current \"" .
999 $this->coreSchema . "\"\n" );
1000 }
1001 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
1002 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
1003 }
1004
1005 /**
1006 * Return schema name for core application tables
1007 *
1008 * @since 1.19
1009 * @return string Core schema name
1010 */
1011 public function getCoreSchema() {
1012 return $this->coreSchema;
1013 }
1014
1015 public function getServerVersion() {
1016 if ( !isset( $this->numericVersion ) ) {
1017 $conn = $this->getBindingHandle();
1018 $versionInfo = pg_version( $conn );
1019 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
1020 // Old client, abort install
1021 $this->numericVersion = '7.3 or earlier';
1022 } elseif ( isset( $versionInfo['server'] ) ) {
1023 // Normal client
1024 $this->numericVersion = $versionInfo['server'];
1025 } else {
1026 // T18937: broken pgsql extension from PHP<5.3
1027 $this->numericVersion = pg_parameter_status( $conn, 'server_version' );
1028 }
1029 }
1030
1031 return $this->numericVersion;
1032 }
1033
1034 /**
1035 * Query whether a given relation exists (in the given schema, or the
1036 * default mw one if not given)
1037 * @param string $table
1038 * @param array|string $types
1039 * @param bool|string $schema
1040 * @return bool
1041 */
1042 private function relationExists( $table, $types, $schema = false ) {
1043 if ( !is_array( $types ) ) {
1044 $types = [ $types ];
1045 }
1046 if ( $schema === false ) {
1047 $schema = $this->getCoreSchema();
1048 }
1049 $table = $this->realTableName( $table, 'raw' );
1050 $etable = $this->addQuotes( $table );
1051 $eschema = $this->addQuotes( $schema );
1052 $sql = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1053 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1054 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1055 $res = $this->query( $sql );
1056 $count = $res ? $res->numRows() : 0;
1057
1058 return (bool)$count;
1059 }
1060
1061 /**
1062 * For backward compatibility, this function checks both tables and views.
1063 * @param string $table
1064 * @param string $fname
1065 * @param bool|string $schema
1066 * @return bool
1067 */
1068 public function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1069 return $this->relationExists( $table, [ 'r', 'v' ], $schema );
1070 }
1071
1072 public function sequenceExists( $sequence, $schema = false ) {
1073 return $this->relationExists( $sequence, 'S', $schema );
1074 }
1075
1076 public function triggerExists( $table, $trigger ) {
1077 $q = <<<SQL
1078 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1079 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1080 AND tgrelid=pg_class.oid
1081 AND nspname=%s AND relname=%s AND tgname=%s
1082 SQL;
1083 $res = $this->query(
1084 sprintf(
1085 $q,
1086 $this->addQuotes( $this->getCoreSchema() ),
1087 $this->addQuotes( $table ),
1088 $this->addQuotes( $trigger )
1089 )
1090 );
1091 if ( !$res ) {
1092 return null;
1093 }
1094 $rows = $res->numRows();
1095
1096 return $rows;
1097 }
1098
1099 public function ruleExists( $table, $rule ) {
1100 $exists = $this->selectField( 'pg_rules', 'rulename',
1101 [
1102 'rulename' => $rule,
1103 'tablename' => $table,
1104 'schemaname' => $this->getCoreSchema()
1105 ]
1106 );
1107
1108 return $exists === $rule;
1109 }
1110
1111 public function constraintExists( $table, $constraint ) {
1112 $sql = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
1113 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1114 $this->addQuotes( $this->getCoreSchema() ),
1115 $this->addQuotes( $table ),
1116 $this->addQuotes( $constraint )
1117 );
1118 $res = $this->query( $sql );
1119 if ( !$res ) {
1120 return null;
1121 }
1122 $rows = $res->numRows();
1123
1124 return $rows;
1125 }
1126
1127 /**
1128 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1129 * @param string $schema
1130 * @return bool
1131 */
1132 public function schemaExists( $schema ) {
1133 if ( !strlen( $schema ) ) {
1134 return false; // short-circuit
1135 }
1136
1137 $exists = $this->selectField(
1138 '"pg_catalog"."pg_namespace"', 1, [ 'nspname' => $schema ], __METHOD__ );
1139
1140 return (bool)$exists;
1141 }
1142
1143 /**
1144 * Returns true if a given role (i.e. user) exists, false otherwise.
1145 * @param string $roleName
1146 * @return bool
1147 */
1148 public function roleExists( $roleName ) {
1149 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1150 [ 'rolname' => $roleName ], __METHOD__ );
1151
1152 return (bool)$exists;
1153 }
1154
1155 /**
1156 * @param string $table
1157 * @param string $field
1158 * @return PostgresField|null
1159 */
1160 public function fieldInfo( $table, $field ) {
1161 return PostgresField::fromText( $this, $table, $field );
1162 }
1163
1164 /**
1165 * pg_field_type() wrapper
1166 * @param ResultWrapper|resource $res ResultWrapper or PostgreSQL query result resource
1167 * @param int $index Field number, starting from 0
1168 * @return string
1169 */
1170 public function fieldType( $res, $index ) {
1171 if ( $res instanceof ResultWrapper ) {
1172 $res = $res->result;
1173 }
1174
1175 return pg_field_type( $res, $index );
1176 }
1177
1178 public function encodeBlob( $b ) {
1179 return new PostgresBlob( pg_escape_bytea( $b ) );
1180 }
1181
1182 public function decodeBlob( $b ) {
1183 if ( $b instanceof PostgresBlob ) {
1184 $b = $b->fetch();
1185 } elseif ( $b instanceof Blob ) {
1186 return $b->fetch();
1187 }
1188
1189 return pg_unescape_bytea( $b );
1190 }
1191
1192 public function strencode( $s ) {
1193 // Should not be called by us
1194 return pg_escape_string( $this->getBindingHandle(), (string)$s );
1195 }
1196
1197 public function addQuotes( $s ) {
1198 $conn = $this->getBindingHandle();
1199
1200 if ( is_null( $s ) ) {
1201 return 'NULL';
1202 } elseif ( is_bool( $s ) ) {
1203 return intval( $s );
1204 } elseif ( $s instanceof Blob ) {
1205 if ( $s instanceof PostgresBlob ) {
1206 $s = $s->fetch();
1207 } else {
1208 $s = pg_escape_bytea( $conn, $s->fetch() );
1209 }
1210 return "'$s'";
1211 } elseif ( $s instanceof NextSequenceValue ) {
1212 return 'DEFAULT';
1213 }
1214
1215 return "'" . pg_escape_string( $conn, (string)$s ) . "'";
1216 }
1217
1218 /**
1219 * Postgres specific version of replaceVars.
1220 * Calls the parent version in Database.php
1221 *
1222 * @param string $ins SQL string, read from a stream (usually tables.sql)
1223 * @return string SQL string
1224 */
1225 protected function replaceVars( $ins ) {
1226 $ins = parent::replaceVars( $ins );
1227
1228 if ( $this->numericVersion >= 8.3 ) {
1229 // Thanks for not providing backwards-compatibility, 8.3
1230 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1231 }
1232
1233 if ( $this->numericVersion <= 8.1 ) { // Our minimum version
1234 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1235 }
1236
1237 return $ins;
1238 }
1239
1240 public function makeSelectOptions( $options ) {
1241 $preLimitTail = $postLimitTail = '';
1242 $startOpts = $useIndex = $ignoreIndex = '';
1243
1244 $noKeyOptions = [];
1245 foreach ( $options as $key => $option ) {
1246 if ( is_numeric( $key ) ) {
1247 $noKeyOptions[$option] = true;
1248 }
1249 }
1250
1251 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1252
1253 $preLimitTail .= $this->makeOrderBy( $options );
1254
1255 if ( isset( $options['FOR UPDATE'] ) ) {
1256 $postLimitTail .= ' FOR UPDATE OF ' .
1257 implode( ', ', array_map( [ $this, 'tableName' ], $options['FOR UPDATE'] ) );
1258 } elseif ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1259 $postLimitTail .= ' FOR UPDATE';
1260 }
1261
1262 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1263 $startOpts .= 'DISTINCT';
1264 }
1265
1266 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1267 }
1268
1269 public function getDBname() {
1270 return $this->dbName;
1271 }
1272
1273 public function getServer() {
1274 return $this->server;
1275 }
1276
1277 public function buildConcat( $stringList ) {
1278 return implode( ' || ', $stringList );
1279 }
1280
1281 public function buildGroupConcatField(
1282 $delimiter, $table, $field, $conds = '', $options = [], $join_conds = []
1283 ) {
1284 $fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
1285
1286 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1287 }
1288
1289 public function buildStringCast( $field ) {
1290 return $field . '::text';
1291 }
1292
1293 public function streamStatementEnd( &$sql, &$newLine ) {
1294 # Allow dollar quoting for function declarations
1295 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1296 if ( $this->delimiter ) {
1297 $this->delimiter = false;
1298 } else {
1299 $this->delimiter = ';';
1300 }
1301 }
1302
1303 return parent::streamStatementEnd( $sql, $newLine );
1304 }
1305
1306 public function doLockTables( array $read, array $write, $method ) {
1307 $tablesWrite = [];
1308 foreach ( $write as $table ) {
1309 $tablesWrite[] = $this->tableName( $table );
1310 }
1311 $tablesRead = [];
1312 foreach ( $read as $table ) {
1313 $tablesRead[] = $this->tableName( $table );
1314 }
1315
1316 // Acquire locks for the duration of the current transaction...
1317 if ( $tablesWrite ) {
1318 $this->query(
1319 'LOCK TABLE ONLY ' . implode( ',', $tablesWrite ) . ' IN EXCLUSIVE MODE',
1320 $method
1321 );
1322 }
1323 if ( $tablesRead ) {
1324 $this->query(
1325 'LOCK TABLE ONLY ' . implode( ',', $tablesRead ) . ' IN SHARE MODE',
1326 $method
1327 );
1328 }
1329
1330 return true;
1331 }
1332
1333 public function lockIsFree( $lockName, $method ) {
1334 if ( !parent::lockIsFree( $lockName, $method ) ) {
1335 return false; // already held
1336 }
1337 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1338 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1339 $result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
1340 WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
1341 $row = $this->fetchObject( $result );
1342
1343 return ( $row->lockstatus === 't' );
1344 }
1345
1346 public function lock( $lockName, $method, $timeout = 5 ) {
1347 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1348 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1349 $loop = new WaitConditionLoop(
1350 function () use ( $lockName, $key, $timeout, $method ) {
1351 $res = $this->query( "SELECT pg_try_advisory_lock($key) AS lockstatus", $method );
1352 $row = $this->fetchObject( $res );
1353 if ( $row->lockstatus === 't' ) {
1354 parent::lock( $lockName, $method, $timeout ); // record
1355 return true;
1356 }
1357
1358 return WaitConditionLoop::CONDITION_CONTINUE;
1359 },
1360 $timeout
1361 );
1362
1363 return ( $loop->invoke() === $loop::CONDITION_REACHED );
1364 }
1365
1366 public function unlock( $lockName, $method ) {
1367 // http://www.postgresql.org/docs/8.2/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1368 $key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
1369 $result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
1370 $row = $this->fetchObject( $result );
1371
1372 if ( $row->lockstatus === 't' ) {
1373 parent::unlock( $lockName, $method ); // record
1374 return true;
1375 }
1376
1377 $this->queryLogger->debug( __METHOD__ . " failed to release lock\n" );
1378
1379 return false;
1380 }
1381
1382 public function serverIsReadOnly() {
1383 $res = $this->query( "SHOW default_transaction_read_only", __METHOD__ );
1384 $row = $this->fetchObject( $res );
1385
1386 return $row ? ( strtolower( $row->default_transaction_read_only ) === 'on' ) : false;
1387 }
1388
1389 /**
1390 * @param string $lockName
1391 * @return string Integer
1392 */
1393 private function bigintFromLockName( $lockName ) {
1394 return \Wikimedia\base_convert( substr( sha1( $lockName ), 0, 15 ), 16, 10 );
1395 }
1396 }
1397
1398 class_alias( DatabasePostgres::class, 'DatabasePostgres' );