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