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