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