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