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