(bug 31361) broken messages on Special:GlobalBlock.
[lhc/web/wiklou.git] / includes / db / DatabasePostgres.php
1 <?php
2 /**
3 * This is the Postgres database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 class PostgresField implements Field {
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
11
12 /**
13 * @param $db DatabaseBase
14 * @param $table
15 * @param $field
16 * @return null|PostgresField
17 */
18 static function fromText( $db, $table, $field ) {
19 global $wgDBmwschema;
20
21 $q = <<<SQL
22 SELECT
23 attnotnull, attlen, COALESCE(conname, '') AS conname,
24 COALESCE(condeferred, 'f') AS deferred,
25 COALESCE(condeferrable, 'f') AS deferrable,
26 CASE WHEN typname = 'int2' THEN 'smallint'
27 WHEN typname = 'int4' THEN 'integer'
28 WHEN typname = 'int8' THEN 'bigint'
29 WHEN typname = 'bpchar' THEN 'char'
30 ELSE typname END AS typname
31 FROM pg_class c
32 JOIN pg_namespace n ON (n.oid = c.relnamespace)
33 JOIN pg_attribute a ON (a.attrelid = c.oid)
34 JOIN pg_type t ON (t.oid = a.atttypid)
35 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
36 WHERE relkind = 'r'
37 AND nspname=%s
38 AND relname=%s
39 AND attname=%s;
40 SQL;
41
42 $table = $db->tableName( $table, 'raw' );
43 $res = $db->query(
44 sprintf( $q,
45 $db->addQuotes( $wgDBmwschema ),
46 $db->addQuotes( $table ),
47 $db->addQuotes( $field )
48 )
49 );
50 $row = $db->fetchObject( $res );
51 if ( !$row ) {
52 return null;
53 }
54 $n = new PostgresField;
55 $n->type = $row->typname;
56 $n->nullable = ( $row->attnotnull == 'f' );
57 $n->name = $field;
58 $n->tablename = $table;
59 $n->max_length = $row->attlen;
60 $n->deferrable = ( $row->deferrable == 't' );
61 $n->deferred = ( $row->deferred == 't' );
62 $n->conname = $row->conname;
63 return $n;
64 }
65
66 function name() {
67 return $this->name;
68 }
69
70 function tableName() {
71 return $this->tablename;
72 }
73
74 function type() {
75 return $this->type;
76 }
77
78 function isNullable() {
79 return $this->nullable;
80 }
81
82 function maxLength() {
83 return $this->max_length;
84 }
85
86 function is_deferrable() {
87 return $this->deferrable;
88 }
89
90 function is_deferred() {
91 return $this->deferred;
92 }
93
94 function conname() {
95 return $this->conname;
96 }
97
98 }
99
100 /**
101 * @ingroup Database
102 */
103 class DatabasePostgres extends DatabaseBase {
104 var $mInsertId = null;
105 var $mLastResult = null;
106 var $numeric_version = null;
107 var $mAffectedRows = null;
108
109 function getType() {
110 return 'postgres';
111 }
112
113 function cascadingDeletes() {
114 return true;
115 }
116 function cleanupTriggers() {
117 return true;
118 }
119 function strictIPs() {
120 return true;
121 }
122 function realTimestamps() {
123 return true;
124 }
125 function implicitGroupby() {
126 return false;
127 }
128 function implicitOrderby() {
129 return false;
130 }
131 function searchableIPs() {
132 return true;
133 }
134 function functionalIndexes() {
135 return true;
136 }
137
138 function hasConstraint( $name ) {
139 global $wgDBmwschema;
140 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
141 pg_escape_string( $this->mConn, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn, $wgDBmwschema ) ."'";
142 $res = $this->doQuery( $SQL );
143 return $this->numRows( $res );
144 }
145
146 /**
147 * Usually aborts on failure
148 */
149 function open( $server, $user, $password, $dbName ) {
150 # Test for Postgres support, to avoid suppressed fatal error
151 if ( !function_exists( 'pg_connect' ) ) {
152 throw new DBConnectionError( $this, "Postgres functions missing, have you compiled PHP with the --with-pgsql option?\n (Note: if you recently installed PHP, you may need to restart your webserver and database)\n" );
153 }
154
155 global $wgDBport;
156
157 if ( !strlen( $user ) ) { # e.g. the class is being loaded
158 return;
159 }
160
161 $this->close();
162 $this->mServer = $server;
163 $port = $wgDBport;
164 $this->mUser = $user;
165 $this->mPassword = $password;
166 $this->mDBname = $dbName;
167
168 $connectVars = array(
169 'dbname' => $dbName,
170 'user' => $user,
171 'password' => $password
172 );
173 if ( $server != false && $server != '' ) {
174 $connectVars['host'] = $server;
175 }
176 if ( $port != false && $port != '' ) {
177 $connectVars['port'] = $port;
178 }
179 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW );
180
181 $this->installErrorHandler();
182 $this->mConn = pg_connect( $connectString );
183 $phpError = $this->restoreErrorHandler();
184
185 if ( !$this->mConn ) {
186 wfDebug( "DB connection error\n" );
187 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
188 wfDebug( $this->lastError() . "\n" );
189 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
190 }
191
192 $this->mOpened = true;
193
194 global $wgCommandLineMode;
195 # If called from the command-line (e.g. importDump), only show errors
196 if ( $wgCommandLineMode ) {
197 $this->doQuery( "SET client_min_messages = 'ERROR'" );
198 }
199
200 $this->query( "SET client_encoding='UTF8'", __METHOD__ );
201 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
202 $this->query( "SET timezone = 'GMT'", __METHOD__ );
203
204 global $wgDBmwschema;
205 if ( $this->schemaExists( $wgDBmwschema ) ) {
206 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
207 $this->doQuery( "SET search_path = $safeschema" );
208 } else {
209 $this->doQuery( "SET search_path = public" );
210 }
211
212 return $this->mConn;
213 }
214
215 /**
216 * Postgres doesn't support selectDB in the same way MySQL does. So if the
217 * DB name doesn't match the open connection, open a new one
218 * @return
219 */
220 function selectDB( $db ) {
221 if ( $this->mDBname !== $db ) {
222 return (bool)$this->open( $this->mServer, $this->mUser, $this->mPassword, $db );
223 } else {
224 return true;
225 }
226 }
227
228 function makeConnectionString( $vars ) {
229 $s = '';
230 foreach ( $vars as $name => $value ) {
231 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
232 }
233 return $s;
234 }
235
236 /**
237 * Closes a database connection, if it is open
238 * Returns success, true if already closed
239 */
240 function close() {
241 $this->mOpened = false;
242 if ( $this->mConn ) {
243 return pg_close( $this->mConn );
244 } else {
245 return true;
246 }
247 }
248
249 protected function doQuery( $sql ) {
250 if ( function_exists( 'mb_convert_encoding' ) ) {
251 $sql = mb_convert_encoding( $sql, 'UTF-8' );
252 }
253 $this->mLastResult = pg_query( $this->mConn, $sql );
254 $this->mAffectedRows = null; // use pg_affected_rows(mLastResult)
255 return $this->mLastResult;
256 }
257
258 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
259 return $this->query( $sql, $fname, true );
260 }
261
262 function freeResult( $res ) {
263 if ( $res instanceof ResultWrapper ) {
264 $res = $res->result;
265 }
266 wfSuppressWarnings();
267 $ok = pg_free_result( $res );
268 wfRestoreWarnings();
269 if ( !$ok ) {
270 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
271 }
272 }
273
274 function fetchObject( $res ) {
275 if ( $res instanceof ResultWrapper ) {
276 $res = $res->result;
277 }
278 wfSuppressWarnings();
279 $row = pg_fetch_object( $res );
280 wfRestoreWarnings();
281 # @todo FIXME: HACK HACK HACK HACK debug
282
283 # @todo hashar: not sure if the following test really trigger if the object
284 # fetching failed.
285 if( pg_last_error( $this->mConn ) ) {
286 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
287 }
288 return $row;
289 }
290
291 function fetchRow( $res ) {
292 if ( $res instanceof ResultWrapper ) {
293 $res = $res->result;
294 }
295 wfSuppressWarnings();
296 $row = pg_fetch_array( $res );
297 wfRestoreWarnings();
298 if( pg_last_error( $this->mConn ) ) {
299 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
300 }
301 return $row;
302 }
303
304 function numRows( $res ) {
305 if ( $res instanceof ResultWrapper ) {
306 $res = $res->result;
307 }
308 wfSuppressWarnings();
309 $n = pg_num_rows( $res );
310 wfRestoreWarnings();
311 if( pg_last_error( $this->mConn ) ) {
312 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
313 }
314 return $n;
315 }
316
317 function numFields( $res ) {
318 if ( $res instanceof ResultWrapper ) {
319 $res = $res->result;
320 }
321 return pg_num_fields( $res );
322 }
323
324 function fieldName( $res, $n ) {
325 if ( $res instanceof ResultWrapper ) {
326 $res = $res->result;
327 }
328 return pg_field_name( $res, $n );
329 }
330
331 /**
332 * This must be called after nextSequenceVal
333 */
334 function insertId() {
335 return $this->mInsertId;
336 }
337
338 function dataSeek( $res, $row ) {
339 if ( $res instanceof ResultWrapper ) {
340 $res = $res->result;
341 }
342 return pg_result_seek( $res, $row );
343 }
344
345 function lastError() {
346 if ( $this->mConn ) {
347 return pg_last_error();
348 } else {
349 return 'No database connection';
350 }
351 }
352 function lastErrno() {
353 return pg_last_error() ? 1 : 0;
354 }
355
356 function affectedRows() {
357 if ( !is_null( $this->mAffectedRows ) ) {
358 // Forced result for simulated queries
359 return $this->mAffectedRows;
360 }
361 if( empty( $this->mLastResult ) ) {
362 return 0;
363 }
364 return pg_affected_rows( $this->mLastResult );
365 }
366
367 /**
368 * Estimate rows in dataset
369 * Returns estimated count, based on EXPLAIN output
370 * This is not necessarily an accurate estimate, so use sparingly
371 * Returns -1 if count cannot be found
372 * Takes same arguments as Database::select()
373 */
374 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
375 $options['EXPLAIN'] = true;
376 $res = $this->select( $table, $vars, $conds, $fname, $options );
377 $rows = -1;
378 if ( $res ) {
379 $row = $this->fetchRow( $res );
380 $count = array();
381 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
382 $rows = $count[1];
383 }
384 }
385 return $rows;
386 }
387
388 /**
389 * Returns information about an index
390 * If errors are explicitly ignored, returns NULL on failure
391 */
392 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
393 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
394 $res = $this->query( $sql, $fname );
395 if ( !$res ) {
396 return null;
397 }
398 foreach ( $res as $row ) {
399 if ( $row->indexname == $this->indexName( $index ) ) {
400 return $row;
401 }
402 }
403 return false;
404 }
405
406 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
407 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
408 " AND indexdef LIKE 'CREATE UNIQUE%(" .
409 $this->strencode( $this->indexName( $index ) ) .
410 ")'";
411 $res = $this->query( $sql, $fname );
412 if ( !$res ) {
413 return null;
414 }
415 foreach ( $res as $row ) {
416 return true;
417 }
418 return false;
419 }
420
421 /**
422 * INSERT wrapper, inserts an array into a table
423 *
424 * $args may be a single associative array, or an array of these with numeric keys,
425 * for multi-row insert (Postgres version 8.2 and above only).
426 *
427 * @param $table String: Name of the table to insert to.
428 * @param $args Array: Items to insert into the table.
429 * @param $fname String: Name of the function, for profiling
430 * @param $options String or Array. Valid options: IGNORE
431 *
432 * @return bool Success of insert operation. IGNORE always returns true.
433 */
434 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
435 if ( !count( $args ) ) {
436 return true;
437 }
438
439 $table = $this->tableName( $table );
440 if (! isset( $this->numeric_version ) ) {
441 $this->getServerVersion();
442 }
443
444 if ( !is_array( $options ) ) {
445 $options = array( $options );
446 }
447
448 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
449 $multi = true;
450 $keys = array_keys( $args[0] );
451 } else {
452 $multi = false;
453 $keys = array_keys( $args );
454 }
455
456 // If IGNORE is set, we use savepoints to emulate mysql's behavior
457 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
458
459 // If we are not in a transaction, we need to be for savepoint trickery
460 $didbegin = 0;
461 if ( $ignore ) {
462 if ( !$this->mTrxLevel ) {
463 $this->begin();
464 $didbegin = 1;
465 }
466 $olde = error_reporting( 0 );
467 // For future use, we may want to track the number of actual inserts
468 // Right now, insert (all writes) simply return true/false
469 $numrowsinserted = 0;
470 }
471
472 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
473
474 if ( $multi ) {
475 if ( $this->numeric_version >= 8.2 && !$ignore ) {
476 $first = true;
477 foreach ( $args as $row ) {
478 if ( $first ) {
479 $first = false;
480 } else {
481 $sql .= ',';
482 }
483 $sql .= '(' . $this->makeList( $row ) . ')';
484 }
485 $res = (bool)$this->query( $sql, $fname, $ignore );
486 } else {
487 $res = true;
488 $origsql = $sql;
489 foreach ( $args as $row ) {
490 $tempsql = $origsql;
491 $tempsql .= '(' . $this->makeList( $row ) . ')';
492
493 if ( $ignore ) {
494 pg_query( $this->mConn, "SAVEPOINT $ignore" );
495 }
496
497 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
498
499 if ( $ignore ) {
500 $bar = pg_last_error();
501 if ( $bar != false ) {
502 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
503 } else {
504 pg_query( $this->mConn, "RELEASE $ignore" );
505 $numrowsinserted++;
506 }
507 }
508
509 // If any of them fail, we fail overall for this function call
510 // Note that this will be ignored if IGNORE is set
511 if ( !$tempres ) {
512 $res = false;
513 }
514 }
515 }
516 } else {
517 // Not multi, just a lone insert
518 if ( $ignore ) {
519 pg_query($this->mConn, "SAVEPOINT $ignore");
520 }
521
522 $sql .= '(' . $this->makeList( $args ) . ')';
523 $res = (bool)$this->query( $sql, $fname, $ignore );
524 if ( $ignore ) {
525 $bar = pg_last_error();
526 if ( $bar != false ) {
527 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
528 } else {
529 pg_query( $this->mConn, "RELEASE $ignore" );
530 $numrowsinserted++;
531 }
532 }
533 }
534 if ( $ignore ) {
535 $olde = error_reporting( $olde );
536 if ( $didbegin ) {
537 $this->commit();
538 }
539
540 // Set the affected row count for the whole operation
541 $this->mAffectedRows = $numrowsinserted;
542
543 // IGNORE always returns true
544 return true;
545 }
546
547 return $res;
548 }
549
550 /**
551 * INSERT SELECT wrapper
552 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
553 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
554 * $conds may be "*" to copy the whole table
555 * srcTable may be an array of tables.
556 * @todo FIXME: Implement this a little better (seperate select/insert)?
557 */
558 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
559 $insertOptions = array(), $selectOptions = array() )
560 {
561 $destTable = $this->tableName( $destTable );
562
563 // If IGNORE is set, we use savepoints to emulate mysql's behavior
564 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
565
566 if( is_array( $insertOptions ) ) {
567 $insertOptions = implode( ' ', $insertOptions );
568 }
569 if( !is_array( $selectOptions ) ) {
570 $selectOptions = array( $selectOptions );
571 }
572 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
573 if( is_array( $srcTable ) ) {
574 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
575 } else {
576 $srcTable = $this->tableName( $srcTable );
577 }
578
579 // If we are not in a transaction, we need to be for savepoint trickery
580 $didbegin = 0;
581 if ( $ignore ) {
582 if( !$this->mTrxLevel ) {
583 $this->begin();
584 $didbegin = 1;
585 }
586 $olde = error_reporting( 0 );
587 $numrowsinserted = 0;
588 pg_query( $this->mConn, "SAVEPOINT $ignore");
589 }
590
591 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
592 " SELECT $startOpts " . implode( ',', $varMap ) .
593 " FROM $srcTable $useIndex";
594
595 if ( $conds != '*' ) {
596 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
597 }
598
599 $sql .= " $tailOpts";
600
601 $res = (bool)$this->query( $sql, $fname, $ignore );
602 if( $ignore ) {
603 $bar = pg_last_error();
604 if( $bar != false ) {
605 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
606 } else {
607 pg_query( $this->mConn, "RELEASE $ignore" );
608 $numrowsinserted++;
609 }
610 $olde = error_reporting( $olde );
611 if( $didbegin ) {
612 $this->commit();
613 }
614
615 // Set the affected row count for the whole operation
616 $this->mAffectedRows = $numrowsinserted;
617
618 // IGNORE always returns true
619 return true;
620 }
621
622 return $res;
623 }
624
625 function tableName( $name, $format = 'quoted' ) {
626 # Replace reserved words with better ones
627 switch( $name ) {
628 case 'user':
629 return 'mwuser';
630 case 'text':
631 return 'pagecontent';
632 default:
633 return parent::tableName( $name, $format );
634 }
635 }
636
637 /**
638 * Return the next in a sequence, save the value for retrieval via insertId()
639 */
640 function nextSequenceValue( $seqName ) {
641 $safeseq = str_replace( "'", "''", $seqName );
642 $res = $this->query( "SELECT nextval('$safeseq')" );
643 $row = $this->fetchRow( $res );
644 $this->mInsertId = $row[0];
645 return $this->mInsertId;
646 }
647
648 /**
649 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
650 */
651 function currentSequenceValue( $seqName ) {
652 $safeseq = str_replace( "'", "''", $seqName );
653 $res = $this->query( "SELECT currval('$safeseq')" );
654 $row = $this->fetchRow( $res );
655 $currval = $row[0];
656 return $currval;
657 }
658
659 # Returns the size of a text field, or -1 for "unlimited"
660 function textFieldSize( $table, $field ) {
661 $table = $this->tableName( $table );
662 $sql = "SELECT t.typname as ftype,a.atttypmod as size
663 FROM pg_class c, pg_attribute a, pg_type t
664 WHERE relname='$table' AND a.attrelid=c.oid AND
665 a.atttypid=t.oid and a.attname='$field'";
666 $res =$this->query( $sql );
667 $row = $this->fetchObject( $res );
668 if ( $row->ftype == 'varchar' ) {
669 $size = $row->size - 4;
670 } else {
671 $size = $row->size;
672 }
673 return $size;
674 }
675
676 function limitResult( $sql, $limit, $offset = false ) {
677 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
678 }
679
680 function wasDeadlock() {
681 return $this->lastErrno() == '40P01';
682 }
683
684 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
685 $newName = $this->addIdentifierQuotes( $newName );
686 $oldName = $this->addIdentifierQuotes( $oldName );
687 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
688 }
689
690 function timestamp( $ts = 0 ) {
691 return wfTimestamp( TS_POSTGRES, $ts );
692 }
693
694 /**
695 * Return aggregated value function call
696 */
697 function aggregateValue( $valuedata, $valuename = 'value' ) {
698 return $valuedata;
699 }
700
701 /**
702 * @return string wikitext of a link to the server software's web site
703 */
704 public static function getSoftwareLink() {
705 return '[http://www.postgresql.org/ PostgreSQL]';
706 }
707
708 /**
709 * @return string Version information from the database
710 */
711 function getServerVersion() {
712 if ( !isset( $this->numeric_version ) ) {
713 $versionInfo = pg_version( $this->mConn );
714 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
715 // Old client, abort install
716 $this->numeric_version = '7.3 or earlier';
717 } elseif ( isset( $versionInfo['server'] ) ) {
718 // Normal client
719 $this->numeric_version = $versionInfo['server'];
720 } else {
721 // Bug 16937: broken pgsql extension from PHP<5.3
722 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
723 }
724 }
725 return $this->numeric_version;
726 }
727
728 /**
729 * Query whether a given relation exists (in the given schema, or the
730 * default mw one if not given)
731 */
732 function relationExists( $table, $types, $schema = false ) {
733 global $wgDBmwschema;
734 if ( !is_array( $types ) ) {
735 $types = array( $types );
736 }
737 if ( !$schema ) {
738 $schema = $wgDBmwschema;
739 }
740 $table = $this->tableName( $table, 'raw' );
741 $etable = $this->addQuotes( $table );
742 $eschema = $this->addQuotes( $schema );
743 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
744 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
745 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
746 $res = $this->query( $SQL );
747 $count = $res ? $res->numRows() : 0;
748 return (bool)$count;
749 }
750
751 /**
752 * For backward compatibility, this function checks both tables and
753 * views.
754 */
755 function tableExists( $table, $schema = false ) {
756 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
757 }
758
759 function sequenceExists( $sequence, $schema = false ) {
760 return $this->relationExists( $sequence, 'S', $schema );
761 }
762
763 function triggerExists( $table, $trigger ) {
764 global $wgDBmwschema;
765
766 $q = <<<SQL
767 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
768 WHERE relnamespace=pg_namespace.oid AND relkind='r'
769 AND tgrelid=pg_class.oid
770 AND nspname=%s AND relname=%s AND tgname=%s
771 SQL;
772 $res = $this->query(
773 sprintf(
774 $q,
775 $this->addQuotes( $wgDBmwschema ),
776 $this->addQuotes( $table ),
777 $this->addQuotes( $trigger )
778 )
779 );
780 if ( !$res ) {
781 return null;
782 }
783 $rows = $res->numRows();
784 return $rows;
785 }
786
787 function ruleExists( $table, $rule ) {
788 global $wgDBmwschema;
789 $exists = $this->selectField( 'pg_rules', 'rulename',
790 array(
791 'rulename' => $rule,
792 'tablename' => $table,
793 'schemaname' => $wgDBmwschema
794 )
795 );
796 return $exists === $rule;
797 }
798
799 function constraintExists( $table, $constraint ) {
800 global $wgDBmwschema;
801 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
802 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
803 $this->addQuotes( $wgDBmwschema ),
804 $this->addQuotes( $table ),
805 $this->addQuotes( $constraint )
806 );
807 $res = $this->query( $SQL );
808 if ( !$res ) {
809 return null;
810 }
811 $rows = $res->numRows();
812 return $rows;
813 }
814
815 /**
816 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
817 */
818 function schemaExists( $schema ) {
819 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
820 array( 'nspname' => $schema ), __METHOD__ );
821 return (bool)$exists;
822 }
823
824 /**
825 * Returns true if a given role (i.e. user) exists, false otherwise.
826 */
827 function roleExists( $roleName ) {
828 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
829 array( 'rolname' => $roleName ), __METHOD__ );
830 return (bool)$exists;
831 }
832
833 function fieldInfo( $table, $field ) {
834 return PostgresField::fromText( $this, $table, $field );
835 }
836
837 /**
838 * pg_field_type() wrapper
839 */
840 function fieldType( $res, $index ) {
841 if ( $res instanceof ResultWrapper ) {
842 $res = $res->result;
843 }
844 return pg_field_type( $res, $index );
845 }
846
847 /* Not even sure why this is used in the main codebase... */
848 function limitResultForUpdate( $sql, $num ) {
849 return $sql;
850 }
851
852 /**
853 * @param $b
854 * @return Blob
855 */
856 function encodeBlob( $b ) {
857 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
858 }
859
860 function decodeBlob( $b ) {
861 if ( $b instanceof Blob ) {
862 $b = $b->fetch();
863 }
864 return pg_unescape_bytea( $b );
865 }
866
867 function strencode( $s ) { # Should not be called by us
868 return pg_escape_string( $this->mConn, $s );
869 }
870
871 /**
872 * @param $s null|bool|Blob
873 * @return int|string
874 */
875 function addQuotes( $s ) {
876 if ( is_null( $s ) ) {
877 return 'NULL';
878 } elseif ( is_bool( $s ) ) {
879 return intval( $s );
880 } elseif ( $s instanceof Blob ) {
881 $ret = "'" . $s->fetch( $s ) . "'";
882 if ( $this->numeric_version >= 8.1 ) {
883 $ret = "E$ret";
884 }
885 return $ret;
886 }
887 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
888 }
889
890 /**
891 * Postgres specific version of replaceVars.
892 * Calls the parent version in Database.php
893 *
894 * @private
895 *
896 * @param $ins String: SQL string, read from a stream (usually tables.sql)
897 *
898 * @return string SQL string
899 */
900 protected function replaceVars( $ins ) {
901 $ins = parent::replaceVars( $ins );
902
903 if ( $this->numeric_version >= 8.3 ) {
904 // Thanks for not providing backwards-compatibility, 8.3
905 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
906 }
907
908 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
909 $ins = str_replace( 'USING gin', 'USING gist', $ins );
910 }
911
912 return $ins;
913 }
914
915 /**
916 * Various select options
917 *
918 * @private
919 *
920 * @param $options Array: an associative array of options to be turned into
921 * an SQL query, valid keys are listed in the function.
922 * @return array
923 */
924 function makeSelectOptions( $options ) {
925 $preLimitTail = $postLimitTail = '';
926 $startOpts = $useIndex = '';
927
928 $noKeyOptions = array();
929 foreach ( $options as $key => $option ) {
930 if ( is_numeric( $key ) ) {
931 $noKeyOptions[$option] = true;
932 }
933 }
934
935 if ( isset( $options['GROUP BY'] ) ) {
936 $gb = is_array( $options['GROUP BY'] )
937 ? implode( ',', $options['GROUP BY'] )
938 : $options['GROUP BY'];
939 $preLimitTail .= " GROUP BY {$gb}";
940 }
941
942 if ( isset( $options['HAVING'] ) ) {
943 $preLimitTail .= " HAVING {$options['HAVING']}";
944 }
945
946 if ( isset( $options['ORDER BY'] ) ) {
947 $ob = is_array( $options['ORDER BY'] )
948 ? implode( ',', $options['ORDER BY'] )
949 : $options['ORDER BY'];
950 $preLimitTail .= " ORDER BY {$ob}";
951 }
952
953 //if ( isset( $options['LIMIT'] ) ) {
954 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
955 // isset( $options['OFFSET'] ) ? $options['OFFSET']
956 // : false );
957 //}
958
959 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
960 $postLimitTail .= ' FOR UPDATE';
961 }
962 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
963 $postLimitTail .= ' LOCK IN SHARE MODE';
964 }
965 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
966 $startOpts .= 'DISTINCT';
967 }
968
969 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
970 }
971
972 function setFakeMaster( $enabled = true ) {}
973
974 function getDBname() {
975 return $this->mDBname;
976 }
977
978 function getServer() {
979 return $this->mServer;
980 }
981
982 function buildConcat( $stringList ) {
983 return implode( ' || ', $stringList );
984 }
985
986 public function getSearchEngine() {
987 return 'SearchPostgres';
988 }
989 } // end DatabasePostgres class