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