PostgreSQL install fixes:
[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 # DELETE where the condition is a join
711 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
712 if ( !$conds ) {
713 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
714 }
715
716 $delTable = $this->tableName( $delTable );
717 $joinTable = $this->tableName( $joinTable );
718 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
719 if ( $conds != '*' ) {
720 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
721 }
722 $sql .= ')';
723
724 $this->query( $sql, $fname );
725 }
726
727 # Returns the size of a text field, or -1 for "unlimited"
728 function textFieldSize( $table, $field ) {
729 $table = $this->tableName( $table );
730 $sql = "SELECT t.typname as ftype,a.atttypmod as size
731 FROM pg_class c, pg_attribute a, pg_type t
732 WHERE relname='$table' AND a.attrelid=c.oid AND
733 a.atttypid=t.oid and a.attname='$field'";
734 $res =$this->query( $sql );
735 $row = $this->fetchObject( $res );
736 if ( $row->ftype == 'varchar' ) {
737 $size = $row->size - 4;
738 } else {
739 $size = $row->size;
740 }
741 return $size;
742 }
743
744 function limitResult( $sql, $limit, $offset = false ) {
745 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
746 }
747
748 function wasDeadlock() {
749 return $this->lastErrno() == '40P01';
750 }
751
752 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
753 $newName = $this->addIdentifierQuotes( $newName );
754 $oldName = $this->addIdentifierQuotes( $oldName );
755 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
756 }
757
758 function timestamp( $ts = 0 ) {
759 return wfTimestamp( TS_POSTGRES, $ts );
760 }
761
762 /**
763 * Return aggregated value function call
764 */
765 function aggregateValue( $valuedata, $valuename = 'value' ) {
766 return $valuedata;
767 }
768
769 /**
770 * @return string wikitext of a link to the server software's web site
771 */
772 public static function getSoftwareLink() {
773 return '[http://www.postgresql.org/ PostgreSQL]';
774 }
775
776 /**
777 * @return string Version information from the database
778 */
779 function getServerVersion() {
780 if ( !isset( $this->numeric_version ) ) {
781 $versionInfo = pg_version( $this->mConn );
782 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
783 // Old client, abort install
784 $this->numeric_version = '7.3 or earlier';
785 } elseif ( isset( $versionInfo['server'] ) ) {
786 // Normal client
787 $this->numeric_version = $versionInfo['server'];
788 } else {
789 // Bug 16937: broken pgsql extension from PHP<5.3
790 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
791 }
792 }
793 return $this->numeric_version;
794 }
795
796 /**
797 * Query whether a given relation exists (in the given schema, or the
798 * default mw one if not given)
799 */
800 function relationExists( $table, $types, $schema = false ) {
801 global $wgDBmwschema;
802 if ( !is_array( $types ) ) {
803 $types = array( $types );
804 }
805 if ( !$schema ) {
806 $schema = $wgDBmwschema;
807 }
808 $table = $this->tableName( $table, false );
809 $etable = $this->addQuotes( $table );
810 $eschema = $this->addQuotes( $schema );
811 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
812 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
813 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
814 $res = $this->query( $SQL );
815 $count = $res ? $res->numRows() : 0;
816 return (bool)$count;
817 }
818
819 /**
820 * For backward compatibility, this function checks both tables and
821 * views.
822 */
823 function tableExists( $table, $schema = false ) {
824 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
825 }
826
827 function sequenceExists( $sequence, $schema = false ) {
828 return $this->relationExists( $sequence, 'S', $schema );
829 }
830
831 function triggerExists( $table, $trigger ) {
832 global $wgDBmwschema;
833
834 $q = <<<SQL
835 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
836 WHERE relnamespace=pg_namespace.oid AND relkind='r'
837 AND tgrelid=pg_class.oid
838 AND nspname=%s AND relname=%s AND tgname=%s
839 SQL;
840 $res = $this->query(
841 sprintf(
842 $q,
843 $this->addQuotes( $wgDBmwschema ),
844 $this->addQuotes( $table ),
845 $this->addQuotes( $trigger )
846 )
847 );
848 if ( !$res ) {
849 return null;
850 }
851 $rows = $res->numRows();
852 return $rows;
853 }
854
855 function ruleExists( $table, $rule ) {
856 global $wgDBmwschema;
857 $exists = $this->selectField( 'pg_rules', 'rulename',
858 array(
859 'rulename' => $rule,
860 'tablename' => $table,
861 'schemaname' => $wgDBmwschema
862 )
863 );
864 return $exists === $rule;
865 }
866
867 function constraintExists( $table, $constraint ) {
868 global $wgDBmwschema;
869 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
870 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
871 $this->addQuotes( $wgDBmwschema ),
872 $this->addQuotes( $table ),
873 $this->addQuotes( $constraint )
874 );
875 $res = $this->query( $SQL );
876 if ( !$res ) {
877 return null;
878 }
879 $rows = $res->numRows();
880 return $rows;
881 }
882
883 /**
884 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
885 */
886 function schemaExists( $schema ) {
887 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
888 array( 'nspname' => $schema ), __METHOD__ );
889 return (bool)$exists;
890 }
891
892 /**
893 * Returns true if a given role (i.e. user) exists, false otherwise.
894 */
895 function roleExists( $roleName ) {
896 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
897 array( 'rolname' => $roleName ), __METHOD__ );
898 return (bool)$exists;
899 }
900
901 function fieldInfo( $table, $field ) {
902 return PostgresField::fromText( $this, $table, $field );
903 }
904
905 /**
906 * pg_field_type() wrapper
907 */
908 function fieldType( $res, $index ) {
909 if ( $res instanceof ResultWrapper ) {
910 $res = $res->result;
911 }
912 return pg_field_type( $res, $index );
913 }
914
915 /* Not even sure why this is used in the main codebase... */
916 function limitResultForUpdate( $sql, $num ) {
917 return $sql;
918 }
919
920 /**
921 * @param $b
922 * @return Blob
923 */
924 function encodeBlob( $b ) {
925 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
926 }
927
928 function decodeBlob( $b ) {
929 if ( $b instanceof Blob ) {
930 $b = $b->fetch();
931 }
932 return pg_unescape_bytea( $b );
933 }
934
935 function strencode( $s ) { # Should not be called by us
936 return pg_escape_string( $this->mConn, $s );
937 }
938
939 /**
940 * @param $s null|bool|Blob
941 * @return int|string
942 */
943 function addQuotes( $s ) {
944 if ( is_null( $s ) ) {
945 return 'NULL';
946 } elseif ( is_bool( $s ) ) {
947 return intval( $s );
948 } elseif ( $s instanceof Blob ) {
949 return "'" . $s->fetch( $s ) . "'";
950 }
951 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
952 }
953
954 /**
955 * Postgres specific version of replaceVars.
956 * Calls the parent version in Database.php
957 *
958 * @private
959 *
960 * @param $ins String: SQL string, read from a stream (usually tables.sql)
961 *
962 * @return string SQL string
963 */
964 protected function replaceVars( $ins ) {
965 $ins = parent::replaceVars( $ins );
966
967 if ( $this->numeric_version >= 8.3 ) {
968 // Thanks for not providing backwards-compatibility, 8.3
969 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
970 }
971
972 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
973 $ins = str_replace( 'USING gin', 'USING gist', $ins );
974 }
975
976 return $ins;
977 }
978
979 /**
980 * Various select options
981 *
982 * @private
983 *
984 * @param $options Array: an associative array of options to be turned into
985 * an SQL query, valid keys are listed in the function.
986 * @return array
987 */
988 function makeSelectOptions( $options ) {
989 $preLimitTail = $postLimitTail = '';
990 $startOpts = $useIndex = '';
991
992 $noKeyOptions = array();
993 foreach ( $options as $key => $option ) {
994 if ( is_numeric( $key ) ) {
995 $noKeyOptions[$option] = true;
996 }
997 }
998
999 if ( isset( $options['GROUP BY'] ) ) {
1000 $gb = is_array( $options['GROUP BY'] )
1001 ? implode( ',', $options['GROUP BY'] )
1002 : $options['GROUP BY'];
1003 $preLimitTail .= " GROUP BY {$gb}";
1004 }
1005
1006 if ( isset( $options['HAVING'] ) ) {
1007 $preLimitTail .= " HAVING {$options['HAVING']}";
1008 }
1009
1010 if ( isset( $options['ORDER BY'] ) ) {
1011 $ob = is_array( $options['ORDER BY'] )
1012 ? implode( ',', $options['ORDER BY'] )
1013 : $options['ORDER BY'];
1014 $preLimitTail .= " ORDER BY {$ob}";
1015 }
1016
1017 //if ( isset( $options['LIMIT'] ) ) {
1018 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1019 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1020 // : false );
1021 //}
1022
1023 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1024 $postLimitTail .= ' FOR UPDATE';
1025 }
1026 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1027 $postLimitTail .= ' LOCK IN SHARE MODE';
1028 }
1029 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1030 $startOpts .= 'DISTINCT';
1031 }
1032
1033 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1034 }
1035
1036 function setFakeMaster( $enabled = true ) {}
1037
1038 function getDBname() {
1039 return $this->mDBname;
1040 }
1041
1042 function getServer() {
1043 return $this->mServer;
1044 }
1045
1046 function buildConcat( $stringList ) {
1047 return implode( ' || ', $stringList );
1048 }
1049
1050 public function getSearchEngine() {
1051 return 'SearchPostgres';
1052 }
1053 } // end DatabasePostgres class