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