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