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