All the databases but MySQL were overriding DatabaseBase::deleteJoin() with the same...
[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, false );
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 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 if ( !@pg_free_result( $res ) ) {
267 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
268 }
269 }
270
271 function fetchObject( $res ) {
272 if ( $res instanceof ResultWrapper ) {
273 $res = $res->result;
274 }
275 @$row = pg_fetch_object( $res );
276 # @todo FIXME: HACK HACK HACK HACK debug
277
278 # @todo hashar: not sure if the following test really trigger if the object
279 # fetching failed.
280 if( pg_last_error( $this->mConn ) ) {
281 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
282 }
283 return $row;
284 }
285
286 function fetchRow( $res ) {
287 if ( $res instanceof ResultWrapper ) {
288 $res = $res->result;
289 }
290 @$row = pg_fetch_array( $res );
291 if( pg_last_error( $this->mConn ) ) {
292 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
293 }
294 return $row;
295 }
296
297 function numRows( $res ) {
298 if ( $res instanceof ResultWrapper ) {
299 $res = $res->result;
300 }
301 @$n = pg_num_rows( $res );
302 if( pg_last_error( $this->mConn ) ) {
303 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
304 }
305 return $n;
306 }
307
308 function numFields( $res ) {
309 if ( $res instanceof ResultWrapper ) {
310 $res = $res->result;
311 }
312 return pg_num_fields( $res );
313 }
314
315 function fieldName( $res, $n ) {
316 if ( $res instanceof ResultWrapper ) {
317 $res = $res->result;
318 }
319 return pg_field_name( $res, $n );
320 }
321
322 /**
323 * This must be called after nextSequenceVal
324 */
325 function insertId() {
326 return $this->mInsertId;
327 }
328
329 function dataSeek( $res, $row ) {
330 if ( $res instanceof ResultWrapper ) {
331 $res = $res->result;
332 }
333 return pg_result_seek( $res, $row );
334 }
335
336 function lastError() {
337 if ( $this->mConn ) {
338 return pg_last_error();
339 } else {
340 return 'No database connection';
341 }
342 }
343 function lastErrno() {
344 return pg_last_error() ? 1 : 0;
345 }
346
347 function affectedRows() {
348 if ( !is_null( $this->mAffectedRows ) ) {
349 // Forced result for simulated queries
350 return $this->mAffectedRows;
351 }
352 if( empty( $this->mLastResult ) ) {
353 return 0;
354 }
355 return pg_affected_rows( $this->mLastResult );
356 }
357
358 /**
359 * Estimate rows in dataset
360 * Returns estimated count, based on EXPLAIN output
361 * This is not necessarily an accurate estimate, so use sparingly
362 * Returns -1 if count cannot be found
363 * Takes same arguments as Database::select()
364 */
365 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
366 $options['EXPLAIN'] = true;
367 $res = $this->select( $table, $vars, $conds, $fname, $options );
368 $rows = -1;
369 if ( $res ) {
370 $row = $this->fetchRow( $res );
371 $count = array();
372 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
373 $rows = $count[1];
374 }
375 }
376 return $rows;
377 }
378
379 /**
380 * Returns information about an index
381 * If errors are explicitly ignored, returns NULL on failure
382 */
383 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
384 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
385 $res = $this->query( $sql, $fname );
386 if ( !$res ) {
387 return null;
388 }
389 foreach ( $res as $row ) {
390 if ( $row->indexname == $this->indexName( $index ) ) {
391 return $row;
392 }
393 }
394 return false;
395 }
396
397 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
398 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
399 " AND indexdef LIKE 'CREATE UNIQUE%(" .
400 $this->strencode( $this->indexName( $index ) ) .
401 ")'";
402 $res = $this->query( $sql, $fname );
403 if ( !$res ) {
404 return null;
405 }
406 foreach ( $res as $row ) {
407 return true;
408 }
409 return false;
410 }
411
412 /**
413 * INSERT wrapper, inserts an array into a table
414 *
415 * $args may be a single associative array, or an array of these with numeric keys,
416 * for multi-row insert (Postgres version 8.2 and above only).
417 *
418 * @param $table String: Name of the table to insert to.
419 * @param $args Array: Items to insert into the table.
420 * @param $fname String: Name of the function, for profiling
421 * @param $options String or Array. Valid options: IGNORE
422 *
423 * @return bool Success of insert operation. IGNORE always returns true.
424 */
425 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
426 if ( !count( $args ) ) {
427 return true;
428 }
429
430 $table = $this->tableName( $table );
431 if (! isset( $this->numeric_version ) ) {
432 $this->getServerVersion();
433 }
434
435 if ( !is_array( $options ) ) {
436 $options = array( $options );
437 }
438
439 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
440 $multi = true;
441 $keys = array_keys( $args[0] );
442 } else {
443 $multi = false;
444 $keys = array_keys( $args );
445 }
446
447 // If IGNORE is set, we use savepoints to emulate mysql's behavior
448 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
449
450 // If we are not in a transaction, we need to be for savepoint trickery
451 $didbegin = 0;
452 if ( $ignore ) {
453 if ( !$this->mTrxLevel ) {
454 $this->begin();
455 $didbegin = 1;
456 }
457 $olde = error_reporting( 0 );
458 // For future use, we may want to track the number of actual inserts
459 // Right now, insert (all writes) simply return true/false
460 $numrowsinserted = 0;
461 }
462
463 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
464
465 if ( $multi ) {
466 if ( $this->numeric_version >= 8.2 && !$ignore ) {
467 $first = true;
468 foreach ( $args as $row ) {
469 if ( $first ) {
470 $first = false;
471 } else {
472 $sql .= ',';
473 }
474 $sql .= '(' . $this->makeList( $row ) . ')';
475 }
476 $res = (bool)$this->query( $sql, $fname, $ignore );
477 } else {
478 $res = true;
479 $origsql = $sql;
480 foreach ( $args as $row ) {
481 $tempsql = $origsql;
482 $tempsql .= '(' . $this->makeList( $row ) . ')';
483
484 if ( $ignore ) {
485 pg_query( $this->mConn, "SAVEPOINT $ignore" );
486 }
487
488 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
489
490 if ( $ignore ) {
491 $bar = pg_last_error();
492 if ( $bar != false ) {
493 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
494 } else {
495 pg_query( $this->mConn, "RELEASE $ignore" );
496 $numrowsinserted++;
497 }
498 }
499
500 // If any of them fail, we fail overall for this function call
501 // Note that this will be ignored if IGNORE is set
502 if ( !$tempres ) {
503 $res = false;
504 }
505 }
506 }
507 } else {
508 // Not multi, just a lone insert
509 if ( $ignore ) {
510 pg_query($this->mConn, "SAVEPOINT $ignore");
511 }
512
513 $sql .= '(' . $this->makeList( $args ) . ')';
514 $res = (bool)$this->query( $sql, $fname, $ignore );
515 if ( $ignore ) {
516 $bar = pg_last_error();
517 if ( $bar != false ) {
518 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
519 } else {
520 pg_query( $this->mConn, "RELEASE $ignore" );
521 $numrowsinserted++;
522 }
523 }
524 }
525 if ( $ignore ) {
526 $olde = error_reporting( $olde );
527 if ( $didbegin ) {
528 $this->commit();
529 }
530
531 // Set the affected row count for the whole operation
532 $this->mAffectedRows = $numrowsinserted;
533
534 // IGNORE always returns true
535 return true;
536 }
537
538 return $res;
539 }
540
541 /**
542 * INSERT SELECT wrapper
543 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
544 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
545 * $conds may be "*" to copy the whole table
546 * srcTable may be an array of tables.
547 * @todo FIXME: Implement this a little better (seperate select/insert)?
548 */
549 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
550 $insertOptions = array(), $selectOptions = array() )
551 {
552 $destTable = $this->tableName( $destTable );
553
554 // If IGNORE is set, we use savepoints to emulate mysql's behavior
555 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
556
557 if( is_array( $insertOptions ) ) {
558 $insertOptions = implode( ' ', $insertOptions );
559 }
560 if( !is_array( $selectOptions ) ) {
561 $selectOptions = array( $selectOptions );
562 }
563 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
564 if( is_array( $srcTable ) ) {
565 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
566 } else {
567 $srcTable = $this->tableName( $srcTable );
568 }
569
570 // If we are not in a transaction, we need to be for savepoint trickery
571 $didbegin = 0;
572 if ( $ignore ) {
573 if( !$this->mTrxLevel ) {
574 $this->begin();
575 $didbegin = 1;
576 }
577 $olde = error_reporting( 0 );
578 $numrowsinserted = 0;
579 pg_query( $this->mConn, "SAVEPOINT $ignore");
580 }
581
582 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
583 " SELECT $startOpts " . implode( ',', $varMap ) .
584 " FROM $srcTable $useIndex";
585
586 if ( $conds != '*' ) {
587 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
588 }
589
590 $sql .= " $tailOpts";
591
592 $res = (bool)$this->query( $sql, $fname, $ignore );
593 if( $ignore ) {
594 $bar = pg_last_error();
595 if( $bar != false ) {
596 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
597 } else {
598 pg_query( $this->mConn, "RELEASE $ignore" );
599 $numrowsinserted++;
600 }
601 $olde = error_reporting( $olde );
602 if( $didbegin ) {
603 $this->commit();
604 }
605
606 // Set the affected row count for the whole operation
607 $this->mAffectedRows = $numrowsinserted;
608
609 // IGNORE always returns true
610 return true;
611 }
612
613 return $res;
614 }
615
616 function tableName( $name, $quoted = true ) {
617 # Replace reserved words with better ones
618 switch( $name ) {
619 case 'user':
620 return 'mwuser';
621 case 'text':
622 return 'pagecontent';
623 default:
624 return parent::tableName( $name, $quoted );
625 }
626 }
627
628 /**
629 * Return the next in a sequence, save the value for retrieval via insertId()
630 */
631 function nextSequenceValue( $seqName ) {
632 $safeseq = str_replace( "'", "''", $seqName );
633 $res = $this->query( "SELECT nextval('$safeseq')" );
634 $row = $this->fetchRow( $res );
635 $this->mInsertId = $row[0];
636 return $this->mInsertId;
637 }
638
639 /**
640 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
641 */
642 function currentSequenceValue( $seqName ) {
643 $safeseq = str_replace( "'", "''", $seqName );
644 $res = $this->query( "SELECT currval('$safeseq')" );
645 $row = $this->fetchRow( $res );
646 $currval = $row[0];
647 return $currval;
648 }
649
650 /**
651 * REPLACE query wrapper
652 * Postgres simulates this with a DELETE followed by INSERT
653 * $row is the row to insert, an associative array
654 * $uniqueIndexes is an array of indexes. Each element may be either a
655 * field name or an array of field names
656 *
657 * It may be more efficient to leave off unique indexes which are unlikely to collide.
658 * However if you do this, you run the risk of encountering errors which wouldn't have
659 * occurred in MySQL
660 */
661 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
662 $table = $this->tableName( $table );
663
664 if ( count( $rows ) == 0 ) {
665 return;
666 }
667
668 # Single row case
669 if ( !is_array( reset( $rows ) ) ) {
670 $rows = array( $rows );
671 }
672
673 foreach( $rows as $row ) {
674 # Delete rows which collide
675 if ( $uniqueIndexes ) {
676 $sql = "DELETE FROM $table WHERE ";
677 $first = true;
678 foreach ( $uniqueIndexes as $index ) {
679 if ( $first ) {
680 $first = false;
681 $sql .= '(';
682 } else {
683 $sql .= ') OR (';
684 }
685 if ( is_array( $index ) ) {
686 $first2 = true;
687 foreach ( $index as $col ) {
688 if ( $first2 ) {
689 $first2 = false;
690 } else {
691 $sql .= ' AND ';
692 }
693 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
694 }
695 } else {
696 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
697 }
698 }
699 $sql .= ')';
700 $this->query( $sql, $fname );
701 }
702
703 # Now insert the row
704 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES ) .') VALUES (' .
705 $this->makeList( $row, LIST_COMMA ) . ')';
706 $this->query( $sql, $fname );
707 }
708 }
709
710 # Returns the size of a text field, or -1 for "unlimited"
711 function textFieldSize( $table, $field ) {
712 $table = $this->tableName( $table );
713 $sql = "SELECT t.typname as ftype,a.atttypmod as size
714 FROM pg_class c, pg_attribute a, pg_type t
715 WHERE relname='$table' AND a.attrelid=c.oid AND
716 a.atttypid=t.oid and a.attname='$field'";
717 $res =$this->query( $sql );
718 $row = $this->fetchObject( $res );
719 if ( $row->ftype == 'varchar' ) {
720 $size = $row->size - 4;
721 } else {
722 $size = $row->size;
723 }
724 return $size;
725 }
726
727 function limitResult( $sql, $limit, $offset = false ) {
728 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
729 }
730
731 function wasDeadlock() {
732 return $this->lastErrno() == '40P01';
733 }
734
735 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
736 $newName = $this->addIdentifierQuotes( $newName );
737 $oldName = $this->addIdentifierQuotes( $oldName );
738 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
739 }
740
741 function timestamp( $ts = 0 ) {
742 return wfTimestamp( TS_POSTGRES, $ts );
743 }
744
745 /**
746 * Return aggregated value function call
747 */
748 function aggregateValue( $valuedata, $valuename = 'value' ) {
749 return $valuedata;
750 }
751
752 /**
753 * @return string wikitext of a link to the server software's web site
754 */
755 public static function getSoftwareLink() {
756 return '[http://www.postgresql.org/ PostgreSQL]';
757 }
758
759 /**
760 * @return string Version information from the database
761 */
762 function getServerVersion() {
763 if ( !isset( $this->numeric_version ) ) {
764 $versionInfo = pg_version( $this->mConn );
765 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
766 // Old client, abort install
767 $this->numeric_version = '7.3 or earlier';
768 } elseif ( isset( $versionInfo['server'] ) ) {
769 // Normal client
770 $this->numeric_version = $versionInfo['server'];
771 } else {
772 // Bug 16937: broken pgsql extension from PHP<5.3
773 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
774 }
775 }
776 return $this->numeric_version;
777 }
778
779 /**
780 * Query whether a given relation exists (in the given schema, or the
781 * default mw one if not given)
782 */
783 function relationExists( $table, $types, $schema = false ) {
784 global $wgDBmwschema;
785 if ( !is_array( $types ) ) {
786 $types = array( $types );
787 }
788 if ( !$schema ) {
789 $schema = $wgDBmwschema;
790 }
791 $table = $this->tableName( $table, false );
792 $etable = $this->addQuotes( $table );
793 $eschema = $this->addQuotes( $schema );
794 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
795 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
796 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
797 $res = $this->query( $SQL );
798 $count = $res ? $res->numRows() : 0;
799 return (bool)$count;
800 }
801
802 /**
803 * For backward compatibility, this function checks both tables and
804 * views.
805 */
806 function tableExists( $table, $schema = false ) {
807 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
808 }
809
810 function sequenceExists( $sequence, $schema = false ) {
811 return $this->relationExists( $sequence, 'S', $schema );
812 }
813
814 function triggerExists( $table, $trigger ) {
815 global $wgDBmwschema;
816
817 $q = <<<SQL
818 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
819 WHERE relnamespace=pg_namespace.oid AND relkind='r'
820 AND tgrelid=pg_class.oid
821 AND nspname=%s AND relname=%s AND tgname=%s
822 SQL;
823 $res = $this->query(
824 sprintf(
825 $q,
826 $this->addQuotes( $wgDBmwschema ),
827 $this->addQuotes( $table ),
828 $this->addQuotes( $trigger )
829 )
830 );
831 if ( !$res ) {
832 return null;
833 }
834 $rows = $res->numRows();
835 return $rows;
836 }
837
838 function ruleExists( $table, $rule ) {
839 global $wgDBmwschema;
840 $exists = $this->selectField( 'pg_rules', 'rulename',
841 array(
842 'rulename' => $rule,
843 'tablename' => $table,
844 'schemaname' => $wgDBmwschema
845 )
846 );
847 return $exists === $rule;
848 }
849
850 function constraintExists( $table, $constraint ) {
851 global $wgDBmwschema;
852 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
853 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
854 $this->addQuotes( $wgDBmwschema ),
855 $this->addQuotes( $table ),
856 $this->addQuotes( $constraint )
857 );
858 $res = $this->query( $SQL );
859 if ( !$res ) {
860 return null;
861 }
862 $rows = $res->numRows();
863 return $rows;
864 }
865
866 /**
867 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
868 */
869 function schemaExists( $schema ) {
870 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
871 array( 'nspname' => $schema ), __METHOD__ );
872 return (bool)$exists;
873 }
874
875 /**
876 * Returns true if a given role (i.e. user) exists, false otherwise.
877 */
878 function roleExists( $roleName ) {
879 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
880 array( 'rolname' => $roleName ), __METHOD__ );
881 return (bool)$exists;
882 }
883
884 function fieldInfo( $table, $field ) {
885 return PostgresField::fromText( $this, $table, $field );
886 }
887
888 /**
889 * pg_field_type() wrapper
890 */
891 function fieldType( $res, $index ) {
892 if ( $res instanceof ResultWrapper ) {
893 $res = $res->result;
894 }
895 return pg_field_type( $res, $index );
896 }
897
898 /* Not even sure why this is used in the main codebase... */
899 function limitResultForUpdate( $sql, $num ) {
900 return $sql;
901 }
902
903 /**
904 * @param $b
905 * @return Blob
906 */
907 function encodeBlob( $b ) {
908 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
909 }
910
911 function decodeBlob( $b ) {
912 if ( $b instanceof Blob ) {
913 $b = $b->fetch();
914 }
915 return pg_unescape_bytea( $b );
916 }
917
918 function strencode( $s ) { # Should not be called by us
919 return pg_escape_string( $this->mConn, $s );
920 }
921
922 /**
923 * @param $s null|bool|Blob
924 * @return int|string
925 */
926 function addQuotes( $s ) {
927 if ( is_null( $s ) ) {
928 return 'NULL';
929 } elseif ( is_bool( $s ) ) {
930 return intval( $s );
931 } elseif ( $s instanceof Blob ) {
932 return "'" . $s->fetch( $s ) . "'";
933 }
934 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
935 }
936
937 /**
938 * Postgres specific version of replaceVars.
939 * Calls the parent version in Database.php
940 *
941 * @private
942 *
943 * @param $ins String: SQL string, read from a stream (usually tables.sql)
944 *
945 * @return string SQL string
946 */
947 protected function replaceVars( $ins ) {
948 $ins = parent::replaceVars( $ins );
949
950 if ( $this->numeric_version >= 8.3 ) {
951 // Thanks for not providing backwards-compatibility, 8.3
952 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
953 }
954
955 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
956 $ins = str_replace( 'USING gin', 'USING gist', $ins );
957 }
958
959 return $ins;
960 }
961
962 /**
963 * Various select options
964 *
965 * @private
966 *
967 * @param $options Array: an associative array of options to be turned into
968 * an SQL query, valid keys are listed in the function.
969 * @return array
970 */
971 function makeSelectOptions( $options ) {
972 $preLimitTail = $postLimitTail = '';
973 $startOpts = $useIndex = '';
974
975 $noKeyOptions = array();
976 foreach ( $options as $key => $option ) {
977 if ( is_numeric( $key ) ) {
978 $noKeyOptions[$option] = true;
979 }
980 }
981
982 if ( isset( $options['GROUP BY'] ) ) {
983 $gb = is_array( $options['GROUP BY'] )
984 ? implode( ',', $options['GROUP BY'] )
985 : $options['GROUP BY'];
986 $preLimitTail .= " GROUP BY {$gb}";
987 }
988
989 if ( isset( $options['HAVING'] ) ) {
990 $preLimitTail .= " HAVING {$options['HAVING']}";
991 }
992
993 if ( isset( $options['ORDER BY'] ) ) {
994 $ob = is_array( $options['ORDER BY'] )
995 ? implode( ',', $options['ORDER BY'] )
996 : $options['ORDER BY'];
997 $preLimitTail .= " ORDER BY {$ob}";
998 }
999
1000 //if ( isset( $options['LIMIT'] ) ) {
1001 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1002 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1003 // : false );
1004 //}
1005
1006 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1007 $postLimitTail .= ' FOR UPDATE';
1008 }
1009 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1010 $postLimitTail .= ' LOCK IN SHARE MODE';
1011 }
1012 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1013 $startOpts .= 'DISTINCT';
1014 }
1015
1016 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1017 }
1018
1019 function setFakeMaster( $enabled = true ) {}
1020
1021 function getDBname() {
1022 return $this->mDBname;
1023 }
1024
1025 function getServer() {
1026 return $this->mServer;
1027 }
1028
1029 function buildConcat( $stringList ) {
1030 return implode( ' || ', $stringList );
1031 }
1032
1033 public function getSearchEngine() {
1034 return 'SearchPostgres';
1035 }
1036 } // end DatabasePostgres class