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