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