Merge "Remove unused $wgDebugDBTransactions"
[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 $q = <<<SQL
20 SELECT
21 attnotnull, attlen, conname AS conname,
22 COALESCE(condeferred, 'f') AS deferred,
23 COALESCE(condeferrable, 'f') AS deferrable,
24 CASE WHEN typname = 'int2' THEN 'smallint'
25 WHEN typname = 'int4' THEN 'integer'
26 WHEN typname = 'int8' THEN 'bigint'
27 WHEN typname = 'bpchar' THEN 'char'
28 ELSE typname END AS typname
29 FROM pg_class c
30 JOIN pg_namespace n ON (n.oid = c.relnamespace)
31 JOIN pg_attribute a ON (a.attrelid = c.oid)
32 JOIN pg_type t ON (t.oid = a.atttypid)
33 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
34 WHERE relkind = 'r'
35 AND nspname=%s
36 AND relname=%s
37 AND attname=%s;
38 SQL;
39
40 $table = $db->tableName( $table, 'raw' );
41 $res = $db->query(
42 sprintf( $q,
43 $db->addQuotes( $db->getCoreSchema() ),
44 $db->addQuotes( $table ),
45 $db->addQuotes( $field )
46 )
47 );
48 $row = $db->fetchObject( $res );
49 if ( !$row ) {
50 return null;
51 }
52 $n = new PostgresField;
53 $n->type = $row->typname;
54 $n->nullable = ( $row->attnotnull == 'f' );
55 $n->name = $field;
56 $n->tablename = $table;
57 $n->max_length = $row->attlen;
58 $n->deferrable = ( $row->deferrable == 't' );
59 $n->deferred = ( $row->deferred == 't' );
60 $n->conname = $row->conname;
61 return $n;
62 }
63
64 function name() {
65 return $this->name;
66 }
67
68 function tableName() {
69 return $this->tablename;
70 }
71
72 function type() {
73 return $this->type;
74 }
75
76 function isNullable() {
77 return $this->nullable;
78 }
79
80 function maxLength() {
81 return $this->max_length;
82 }
83
84 function is_deferrable() {
85 return $this->deferrable;
86 }
87
88 function is_deferred() {
89 return $this->deferred;
90 }
91
92 function conname() {
93 return $this->conname;
94 }
95
96 }
97
98 /**
99 * Used to debug transaction processing
100 * Only used if $wgDebugDBTransactions is true
101 *
102 * @since 1.20
103 * @ingroup Database
104 */
105 class PostgresTransactionState {
106
107 static $WATCHED = array(
108 array(
109 "desc" => "Connection state changed from %s -> %s\n",
110 "states" => array(
111 PGSQL_CONNECTION_OK => "OK",
112 PGSQL_CONNECTION_BAD => "BAD"
113 )
114 ),
115 array(
116 "desc" => "Transaction state changed from %s -> %s\n",
117 "states" => array(
118 PGSQL_TRANSACTION_IDLE => "IDLE",
119 PGSQL_TRANSACTION_ACTIVE => "ACTIVE",
120 PGSQL_TRANSACTION_INTRANS => "TRANS",
121 PGSQL_TRANSACTION_INERROR => "ERROR",
122 PGSQL_TRANSACTION_UNKNOWN => "UNKNOWN"
123 )
124 )
125 );
126
127 public function __construct( $conn ) {
128 $this->mConn = $conn;
129 $this->update();
130 $this->mCurrentState = $this->mNewState;
131 }
132
133 public function update() {
134 $this->mNewState = array(
135 pg_connection_status( $this->mConn ),
136 pg_transaction_status( $this->mConn )
137 );
138 }
139
140 public function check() {
141 global $wgDebugDBTransactions;
142 $this->update();
143 if ( $wgDebugDBTransactions ) {
144 if ( $this->mCurrentState !== $this->mNewState ) {
145 $old = reset( $this->mCurrentState );
146 $new = reset( $this->mNewState );
147 foreach ( self::$WATCHED as $watched ) {
148 if ($old !== $new) {
149 $this->log_changed($old, $new, $watched);
150 }
151 $old = next( $this->mCurrentState );
152 $new = next( $this->mNewState );
153
154 }
155 }
156 }
157 $this->mCurrentState = $this->mNewState;
158 }
159
160 protected function describe_changed( $status, $desc_table ) {
161 if( isset( $desc_table[$status] ) ) {
162 return $desc_table[$status];
163 } else {
164 return "STATUS " . $status;
165 }
166 }
167
168 protected function log_changed( $old, $new, $watched ) {
169 wfDebug(sprintf($watched["desc"],
170 $this->describe_changed( $old, $watched["states"] ),
171 $this->describe_changed( $new, $watched["states"] ))
172 );
173 }
174 }
175
176 /**
177 * @ingroup Database
178 */
179 class DatabasePostgres extends DatabaseBase {
180 var $mInsertId = null;
181 var $mLastResult = null;
182 var $numeric_version = null;
183 var $mAffectedRows = null;
184
185 function getType() {
186 return 'postgres';
187 }
188
189 function cascadingDeletes() {
190 return true;
191 }
192 function cleanupTriggers() {
193 return true;
194 }
195 function strictIPs() {
196 return true;
197 }
198 function realTimestamps() {
199 return true;
200 }
201 function implicitGroupby() {
202 return false;
203 }
204 function implicitOrderby() {
205 return false;
206 }
207 function searchableIPs() {
208 return true;
209 }
210 function functionalIndexes() {
211 return true;
212 }
213
214 function hasConstraint( $name ) {
215 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
216 pg_escape_string( $this->mConn, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn, $this->getCoreSchema() ) ."'";
217 $res = $this->doQuery( $SQL );
218 return $this->numRows( $res );
219 }
220
221 /**
222 * Usually aborts on failure
223 * @return DatabaseBase|null
224 */
225 function open( $server, $user, $password, $dbName ) {
226 # Test for Postgres support, to avoid suppressed fatal error
227 if ( !function_exists( 'pg_connect' ) ) {
228 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" );
229 }
230
231 global $wgDBport;
232
233 if ( !strlen( $user ) ) { # e.g. the class is being loaded
234 return;
235 }
236
237 $this->mServer = $server;
238 $port = $wgDBport;
239 $this->mUser = $user;
240 $this->mPassword = $password;
241 $this->mDBname = $dbName;
242
243 $connectVars = array(
244 'dbname' => $dbName,
245 'user' => $user,
246 'password' => $password
247 );
248 if ( $server != false && $server != '' ) {
249 $connectVars['host'] = $server;
250 }
251 if ( $port != false && $port != '' ) {
252 $connectVars['port'] = $port;
253 }
254 $this->connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW );
255 $this->close();
256 $this->installErrorHandler();
257 $this->mConn = pg_connect( $this->connectString );
258 $phpError = $this->restoreErrorHandler();
259
260 if ( !$this->mConn ) {
261 wfDebug( "DB connection error\n" );
262 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
263 wfDebug( $this->lastError() . "\n" );
264 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
265 }
266
267 $this->mOpened = true;
268 $this->mTransactionState = new PostgresTransactionState( $this->mConn );
269
270 global $wgCommandLineMode;
271 # If called from the command-line (e.g. importDump), only show errors
272 if ( $wgCommandLineMode ) {
273 $this->doQuery( "SET client_min_messages = 'ERROR'" );
274 }
275
276 $this->query( "SET client_encoding='UTF8'", __METHOD__ );
277 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
278 $this->query( "SET timezone = 'GMT'", __METHOD__ );
279 $this->query( "SET standard_conforming_strings = on", __METHOD__ );
280
281 global $wgDBmwschema;
282 $this->determineCoreSchema( $wgDBmwschema );
283
284 return $this->mConn;
285 }
286
287 /**
288 * Postgres doesn't support selectDB in the same way MySQL does. So if the
289 * DB name doesn't match the open connection, open a new one
290 * @return
291 */
292 function selectDB( $db ) {
293 if ( $this->mDBname !== $db ) {
294 return (bool)$this->open( $this->mServer, $this->mUser, $this->mPassword, $db );
295 } else {
296 return true;
297 }
298 }
299
300 function makeConnectionString( $vars ) {
301 $s = '';
302 foreach ( $vars as $name => $value ) {
303 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
304 }
305 return $s;
306 }
307
308 /**
309 * Closes a database connection, if it is open
310 * Returns success, true if already closed
311 * @return bool
312 */
313 protected function closeConnection() {
314 return pg_close( $this->mConn );
315 }
316
317 protected function doQuery( $sql ) {
318 if ( function_exists( 'mb_convert_encoding' ) ) {
319 $sql = mb_convert_encoding( $sql, 'UTF-8' );
320 }
321 $this->mTransactionState->check();
322 $this->mLastResult = pg_query( $this->mConn, $sql );
323 $this->mTransactionState->check();
324 $this->mAffectedRows = null;
325 return $this->mLastResult;
326 }
327
328 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
329 /* Transaction stays in the ERROR state until rolledback */
330 $this->rollback( __METHOD__ );
331 parent::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
332 }
333
334
335 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
336 return $this->query( $sql, $fname, true );
337 }
338
339 function freeResult( $res ) {
340 if ( $res instanceof ResultWrapper ) {
341 $res = $res->result;
342 }
343 wfSuppressWarnings();
344 $ok = pg_free_result( $res );
345 wfRestoreWarnings();
346 if ( !$ok ) {
347 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
348 }
349 }
350
351 function fetchObject( $res ) {
352 if ( $res instanceof ResultWrapper ) {
353 $res = $res->result;
354 }
355 wfSuppressWarnings();
356 $row = pg_fetch_object( $res );
357 wfRestoreWarnings();
358 # @todo FIXME: HACK HACK HACK HACK debug
359
360 # @todo hashar: not sure if the following test really trigger if the object
361 # fetching failed.
362 if( pg_last_error( $this->mConn ) ) {
363 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
364 }
365 return $row;
366 }
367
368 function fetchRow( $res ) {
369 if ( $res instanceof ResultWrapper ) {
370 $res = $res->result;
371 }
372 wfSuppressWarnings();
373 $row = pg_fetch_array( $res );
374 wfRestoreWarnings();
375 if( pg_last_error( $this->mConn ) ) {
376 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
377 }
378 return $row;
379 }
380
381 function numRows( $res ) {
382 if ( $res instanceof ResultWrapper ) {
383 $res = $res->result;
384 }
385 wfSuppressWarnings();
386 $n = pg_num_rows( $res );
387 wfRestoreWarnings();
388 if( pg_last_error( $this->mConn ) ) {
389 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
390 }
391 return $n;
392 }
393
394 function numFields( $res ) {
395 if ( $res instanceof ResultWrapper ) {
396 $res = $res->result;
397 }
398 return pg_num_fields( $res );
399 }
400
401 function fieldName( $res, $n ) {
402 if ( $res instanceof ResultWrapper ) {
403 $res = $res->result;
404 }
405 return pg_field_name( $res, $n );
406 }
407
408 /**
409 * This must be called after nextSequenceVal
410 * @return null
411 */
412 function insertId() {
413 return $this->mInsertId;
414 }
415
416 function dataSeek( $res, $row ) {
417 if ( $res instanceof ResultWrapper ) {
418 $res = $res->result;
419 }
420 return pg_result_seek( $res, $row );
421 }
422
423 function lastError() {
424 if ( $this->mConn ) {
425 return pg_last_error();
426 } else {
427 return 'No database connection';
428 }
429 }
430 function lastErrno() {
431 return pg_last_error() ? 1 : 0;
432 }
433
434 function affectedRows() {
435 if ( !is_null( $this->mAffectedRows ) ) {
436 // Forced result for simulated queries
437 return $this->mAffectedRows;
438 }
439 if( empty( $this->mLastResult ) ) {
440 return 0;
441 }
442 return pg_affected_rows( $this->mLastResult );
443 }
444
445 /**
446 * Estimate rows in dataset
447 * Returns estimated count, based on EXPLAIN output
448 * This is not necessarily an accurate estimate, so use sparingly
449 * Returns -1 if count cannot be found
450 * Takes same arguments as Database::select()
451 * @return int
452 */
453 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
454 $options['EXPLAIN'] = true;
455 $res = $this->select( $table, $vars, $conds, $fname, $options );
456 $rows = -1;
457 if ( $res ) {
458 $row = $this->fetchRow( $res );
459 $count = array();
460 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
461 $rows = $count[1];
462 }
463 }
464 return $rows;
465 }
466
467 /**
468 * Returns information about an index
469 * If errors are explicitly ignored, returns NULL on failure
470 * @return bool|null
471 */
472 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
473 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
474 $res = $this->query( $sql, $fname );
475 if ( !$res ) {
476 return null;
477 }
478 foreach ( $res as $row ) {
479 if ( $row->indexname == $this->indexName( $index ) ) {
480 return $row;
481 }
482 }
483 return false;
484 }
485
486 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
487 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
488 " AND indexdef LIKE 'CREATE UNIQUE%(" .
489 $this->strencode( $this->indexName( $index ) ) .
490 ")'";
491 $res = $this->query( $sql, $fname );
492 if ( !$res ) {
493 return null;
494 }
495 foreach ( $res as $row ) {
496 return true;
497 }
498 return false;
499 }
500
501 /**
502 * INSERT wrapper, inserts an array into a table
503 *
504 * $args may be a single associative array, or an array of these with numeric keys,
505 * for multi-row insert (Postgres version 8.2 and above only).
506 *
507 * @param $table String: Name of the table to insert to.
508 * @param $args Array: Items to insert into the table.
509 * @param $fname String: Name of the function, for profiling
510 * @param $options String or Array. Valid options: IGNORE
511 *
512 * @return bool Success of insert operation. IGNORE always returns true.
513 */
514 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
515 if ( !count( $args ) ) {
516 return true;
517 }
518
519 $table = $this->tableName( $table );
520 if (! isset( $this->numeric_version ) ) {
521 $this->getServerVersion();
522 }
523
524 if ( !is_array( $options ) ) {
525 $options = array( $options );
526 }
527
528 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
529 $multi = true;
530 $keys = array_keys( $args[0] );
531 } else {
532 $multi = false;
533 $keys = array_keys( $args );
534 }
535
536 // If IGNORE is set, we use savepoints to emulate mysql's behavior
537 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
538
539 // If we are not in a transaction, we need to be for savepoint trickery
540 $didbegin = 0;
541 if ( $ignore ) {
542 if ( !$this->mTrxLevel ) {
543 $this->begin( __METHOD__ );
544 $didbegin = 1;
545 }
546 $olde = error_reporting( 0 );
547 // For future use, we may want to track the number of actual inserts
548 // Right now, insert (all writes) simply return true/false
549 $numrowsinserted = 0;
550 }
551
552 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
553
554 if ( $multi ) {
555 if ( $this->numeric_version >= 8.2 && !$ignore ) {
556 $first = true;
557 foreach ( $args as $row ) {
558 if ( $first ) {
559 $first = false;
560 } else {
561 $sql .= ',';
562 }
563 $sql .= '(' . $this->makeList( $row ) . ')';
564 }
565 $res = (bool)$this->query( $sql, $fname, $ignore );
566 } else {
567 $res = true;
568 $origsql = $sql;
569 foreach ( $args as $row ) {
570 $tempsql = $origsql;
571 $tempsql .= '(' . $this->makeList( $row ) . ')';
572
573 if ( $ignore ) {
574 $this->doQuery( "SAVEPOINT $ignore" );
575 }
576
577 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
578
579 if ( $ignore ) {
580 $bar = pg_last_error();
581 if ( $bar != false ) {
582 $this->doQuery( $this->mConn, "ROLLBACK TO $ignore" );
583 } else {
584 $this->doQuery( $this->mConn, "RELEASE $ignore" );
585 $numrowsinserted++;
586 }
587 }
588
589 // If any of them fail, we fail overall for this function call
590 // Note that this will be ignored if IGNORE is set
591 if ( !$tempres ) {
592 $res = false;
593 }
594 }
595 }
596 } else {
597 // Not multi, just a lone insert
598 if ( $ignore ) {
599 $this->doQuery( "SAVEPOINT $ignore" );
600 }
601
602 $sql .= '(' . $this->makeList( $args ) . ')';
603 $res = (bool)$this->query( $sql, $fname, $ignore );
604 if ( $ignore ) {
605 $bar = pg_last_error();
606 if ( $bar != false ) {
607 $this->doQuery( "ROLLBACK TO $ignore" );
608 } else {
609 $this->doQuery( "RELEASE $ignore" );
610 $numrowsinserted++;
611 }
612 }
613 }
614 if ( $ignore ) {
615 $olde = error_reporting( $olde );
616 if ( $didbegin ) {
617 $this->commit( __METHOD__ );
618 }
619
620 // Set the affected row count for the whole operation
621 $this->mAffectedRows = $numrowsinserted;
622
623 // IGNORE always returns true
624 return true;
625 }
626
627 return $res;
628 }
629
630 /**
631 * INSERT SELECT wrapper
632 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
633 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
634 * $conds may be "*" to copy the whole table
635 * srcTable may be an array of tables.
636 * @todo FIXME: Implement this a little better (seperate select/insert)?
637 * @return bool
638 */
639 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
640 $insertOptions = array(), $selectOptions = array() )
641 {
642 $destTable = $this->tableName( $destTable );
643
644 // If IGNORE is set, we use savepoints to emulate mysql's behavior
645 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
646
647 if( is_array( $insertOptions ) ) {
648 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
649 }
650 if( !is_array( $selectOptions ) ) {
651 $selectOptions = array( $selectOptions );
652 }
653 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
654 if( is_array( $srcTable ) ) {
655 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
656 } else {
657 $srcTable = $this->tableName( $srcTable );
658 }
659
660 // If we are not in a transaction, we need to be for savepoint trickery
661 $didbegin = 0;
662 if ( $ignore ) {
663 if( !$this->mTrxLevel ) {
664 $this->begin( __METHOD__ );
665 $didbegin = 1;
666 }
667 $olde = error_reporting( 0 );
668 $numrowsinserted = 0;
669 $this->doQuery( "SAVEPOINT $ignore" );
670 }
671
672 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
673 " SELECT $startOpts " . implode( ',', $varMap ) .
674 " FROM $srcTable $useIndex";
675
676 if ( $conds != '*' ) {
677 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
678 }
679
680 $sql .= " $tailOpts";
681
682 $res = (bool)$this->query( $sql, $fname, $ignore );
683 if( $ignore ) {
684 $bar = pg_last_error();
685 if( $bar != false ) {
686 $this->doQuery( "ROLLBACK TO $ignore" );
687 } else {
688 $this->doQuery( "RELEASE $ignore" );
689 $numrowsinserted++;
690 }
691 $olde = error_reporting( $olde );
692 if( $didbegin ) {
693 $this->commit( __METHOD__ );
694 }
695
696 // Set the affected row count for the whole operation
697 $this->mAffectedRows = $numrowsinserted;
698
699 // IGNORE always returns true
700 return true;
701 }
702
703 return $res;
704 }
705
706 function tableName( $name, $format = 'quoted' ) {
707 # Replace reserved words with better ones
708 switch( $name ) {
709 case 'user':
710 return $this->realTableName( 'mwuser', $format );
711 case 'text':
712 return $this->realTableName( 'pagecontent', $format );
713 default:
714 return $this->realTableName( $name, $format );
715 }
716 }
717
718 /* Don't cheat on installer */
719 function realTableName( $name, $format = 'quoted' ) {
720 return parent::tableName( $name, $format );
721 }
722
723 /**
724 * Return the next in a sequence, save the value for retrieval via insertId()
725 * @return null
726 */
727 function nextSequenceValue( $seqName ) {
728 $safeseq = str_replace( "'", "''", $seqName );
729 $res = $this->query( "SELECT nextval('$safeseq')" );
730 $row = $this->fetchRow( $res );
731 $this->mInsertId = $row[0];
732 return $this->mInsertId;
733 }
734
735 /**
736 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
737 * @return
738 */
739 function currentSequenceValue( $seqName ) {
740 $safeseq = str_replace( "'", "''", $seqName );
741 $res = $this->query( "SELECT currval('$safeseq')" );
742 $row = $this->fetchRow( $res );
743 $currval = $row[0];
744 return $currval;
745 }
746
747 # Returns the size of a text field, or -1 for "unlimited"
748 function textFieldSize( $table, $field ) {
749 $table = $this->tableName( $table );
750 $sql = "SELECT t.typname as ftype,a.atttypmod as size
751 FROM pg_class c, pg_attribute a, pg_type t
752 WHERE relname='$table' AND a.attrelid=c.oid AND
753 a.atttypid=t.oid and a.attname='$field'";
754 $res =$this->query( $sql );
755 $row = $this->fetchObject( $res );
756 if ( $row->ftype == 'varchar' ) {
757 $size = $row->size - 4;
758 } else {
759 $size = $row->size;
760 }
761 return $size;
762 }
763
764 function limitResult( $sql, $limit, $offset = false ) {
765 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
766 }
767
768 function wasDeadlock() {
769 return $this->lastErrno() == '40P01';
770 }
771
772 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
773 $newName = $this->addIdentifierQuotes( $newName );
774 $oldName = $this->addIdentifierQuotes( $oldName );
775 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
776 }
777
778 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
779 $eschema = $this->addQuotes( $this->getCoreSchema() );
780 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
781 $endArray = array();
782
783 foreach( $result as $table ) {
784 $vars = get_object_vars($table);
785 $table = array_pop( $vars );
786 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
787 $endArray[] = $table;
788 }
789 }
790
791 return $endArray;
792 }
793
794 function timestamp( $ts = 0 ) {
795 return wfTimestamp( TS_POSTGRES, $ts );
796 }
797
798 /*
799 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
800 * to http://www.php.net/manual/en/ref.pgsql.php
801 *
802 * Parsing a postgres array can be a tricky problem, he's my
803 * take on this, it handles multi-dimensional arrays plus
804 * escaping using a nasty regexp to determine the limits of each
805 * data-item.
806 *
807 * This should really be handled by PHP PostgreSQL module
808 *
809 * @since 1.20
810 * @param $text string: postgreql array returned in a text form like {a,b}
811 * @param $output string
812 * @param $limit int
813 * @param $offset int
814 * @return string
815 */
816 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
817 if( false === $limit ) {
818 $limit = strlen( $text )-1;
819 $output = array();
820 }
821 if( '{}' == $text ) {
822 return $output;
823 }
824 do {
825 if ( '{' != $text{$offset} ) {
826 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
827 $text, $match, 0, $offset );
828 $offset += strlen( $match[0] );
829 $output[] = ( '"' != $match[1]{0}
830 ? $match[1]
831 : stripcslashes( substr( $match[1], 1, -1 ) ) );
832 if ( '},' == $match[3] ) {
833 return $output;
834 }
835 } else {
836 $offset = $this->pg_array_parse( $text, $output, $limit, $offset+1 );
837 }
838 } while ( $limit > $offset );
839 return $output;
840 }
841
842 /**
843 * Return aggregated value function call
844 */
845 function aggregateValue( $valuedata, $valuename = 'value' ) {
846 return $valuedata;
847 }
848
849 /**
850 * @return string wikitext of a link to the server software's web site
851 */
852 public static function getSoftwareLink() {
853 return '[http://www.postgresql.org/ PostgreSQL]';
854 }
855
856
857 /**
858 * Return current schema (executes SELECT current_schema())
859 * Needs transaction
860 *
861 * @since 1.20
862 * @return string return default schema for the current session
863 */
864 function getCurrentSchema() {
865 $res = $this->query( "SELECT current_schema()", __METHOD__);
866 $row = $this->fetchRow( $res );
867 return $row[0];
868 }
869
870 /**
871 * Return list of schemas which are accessible without schema name
872 * This is list does not contain magic keywords like "$user"
873 * Needs transaction
874 *
875 * @seealso getSearchPath()
876 * @seealso setSearchPath()
877 * @since 1.20
878 * @return array list of actual schemas for the current sesson
879 */
880 function getSchemas() {
881 $res = $this->query( "SELECT current_schemas(false)", __METHOD__);
882 $row = $this->fetchRow( $res );
883 $schemas = array();
884 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
885 return $this->pg_array_parse($row[0], $schemas);
886 }
887
888 /**
889 * Return search patch for schemas
890 * This is different from getSchemas() since it contain magic keywords
891 * (like "$user").
892 * Needs transaction
893 *
894 * @since 1.20
895 * @return array how to search for table names schemas for the current user
896 */
897 function getSearchPath() {
898 $res = $this->query( "SHOW search_path", __METHOD__);
899 $row = $this->fetchRow( $res );
900 /* PostgreSQL returns SHOW values as strings */
901 return explode(",", $row[0]);
902 }
903
904 /**
905 * Update search_path, values should already be sanitized
906 * Values may contain magic keywords like "$user"
907 * @since 1.20
908 *
909 * @param $search_path array list of schemas to be searched by default
910 */
911 function setSearchPath( $search_path ) {
912 $this->query( "SET search_path = " . implode(", ", $search_path) );
913 }
914
915 /**
916 * Determine default schema for MediaWiki core
917 * Adjust this session schema search path if desired schema exists
918 * and is not alread there.
919 *
920 * We need to have name of the core schema stored to be able
921 * to query database metadata.
922 *
923 * This will be also called by the installer after the schema is created
924 *
925 * @since 1.20
926 * @param desired_schema string
927 */
928 function determineCoreSchema( $desired_schema ) {
929 $this->begin( __METHOD__ );
930 if ( $this->schemaExists( $desired_schema ) ) {
931 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
932 $this->mCoreSchema = $desired_schema;
933 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
934 } else {
935 /**
936 * Append our schema (e.g. 'mediawiki') in front
937 * of the search path
938 * Fixes bug 15816
939 */
940 $search_path = $this->getSearchPath();
941 array_unshift( $search_path,
942 $this->addIdentifierQuotes( $desired_schema ));
943 $this->setSearchPath( $search_path );
944 $this->mCoreSchema = $desired_schema;
945 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
946 }
947 } else {
948 $this->mCoreSchema = $this->getCurrentSchema();
949 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema ."\"\n");
950 }
951 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
952 $this->commit( __METHOD__ );
953 }
954
955 /**
956 * Return schema name fore core MediaWiki tables
957 *
958 * @since 1.20
959 * @return string core schema name
960 */
961 function getCoreSchema() {
962 return $this->mCoreSchema;
963 }
964
965 /**
966 * @return string Version information from the database
967 */
968 function getServerVersion() {
969 if ( !isset( $this->numeric_version ) ) {
970 $versionInfo = pg_version( $this->mConn );
971 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
972 // Old client, abort install
973 $this->numeric_version = '7.3 or earlier';
974 } elseif ( isset( $versionInfo['server'] ) ) {
975 // Normal client
976 $this->numeric_version = $versionInfo['server'];
977 } else {
978 // Bug 16937: broken pgsql extension from PHP<5.3
979 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
980 }
981 }
982 return $this->numeric_version;
983 }
984
985 /**
986 * Query whether a given relation exists (in the given schema, or the
987 * default mw one if not given)
988 * @return bool
989 */
990 function relationExists( $table, $types, $schema = false ) {
991 if ( !is_array( $types ) ) {
992 $types = array( $types );
993 }
994 if ( !$schema ) {
995 $schema = $this->getCoreSchema();
996 }
997 $table = $this->realTableName( $table, 'raw' );
998 $etable = $this->addQuotes( $table );
999 $eschema = $this->addQuotes( $schema );
1000 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1001 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1002 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1003 $res = $this->query( $SQL );
1004 $count = $res ? $res->numRows() : 0;
1005 return (bool)$count;
1006 }
1007
1008 /**
1009 * For backward compatibility, this function checks both tables and
1010 * views.
1011 * @return bool
1012 */
1013 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1014 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1015 }
1016
1017 function sequenceExists( $sequence, $schema = false ) {
1018 return $this->relationExists( $sequence, 'S', $schema );
1019 }
1020
1021 function triggerExists( $table, $trigger ) {
1022 $q = <<<SQL
1023 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1024 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1025 AND tgrelid=pg_class.oid
1026 AND nspname=%s AND relname=%s AND tgname=%s
1027 SQL;
1028 $res = $this->query(
1029 sprintf(
1030 $q,
1031 $this->addQuotes( $this->getCoreSchema() ),
1032 $this->addQuotes( $table ),
1033 $this->addQuotes( $trigger )
1034 )
1035 );
1036 if ( !$res ) {
1037 return null;
1038 }
1039 $rows = $res->numRows();
1040 return $rows;
1041 }
1042
1043 function ruleExists( $table, $rule ) {
1044 $exists = $this->selectField( 'pg_rules', 'rulename',
1045 array(
1046 'rulename' => $rule,
1047 'tablename' => $table,
1048 'schemaname' => $this->getCoreSchema()
1049 )
1050 );
1051 return $exists === $rule;
1052 }
1053
1054 function constraintExists( $table, $constraint ) {
1055 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1056 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1057 $this->addQuotes( $this->getCoreSchema() ),
1058 $this->addQuotes( $table ),
1059 $this->addQuotes( $constraint )
1060 );
1061 $res = $this->query( $SQL );
1062 if ( !$res ) {
1063 return null;
1064 }
1065 $rows = $res->numRows();
1066 return $rows;
1067 }
1068
1069 /**
1070 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1071 * @return bool
1072 */
1073 function schemaExists( $schema ) {
1074 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1075 array( 'nspname' => $schema ), __METHOD__ );
1076 return (bool)$exists;
1077 }
1078
1079 /**
1080 * Returns true if a given role (i.e. user) exists, false otherwise.
1081 * @return bool
1082 */
1083 function roleExists( $roleName ) {
1084 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1085 array( 'rolname' => $roleName ), __METHOD__ );
1086 return (bool)$exists;
1087 }
1088
1089 function fieldInfo( $table, $field ) {
1090 return PostgresField::fromText( $this, $table, $field );
1091 }
1092
1093 /**
1094 * pg_field_type() wrapper
1095 * @return string
1096 */
1097 function fieldType( $res, $index ) {
1098 if ( $res instanceof ResultWrapper ) {
1099 $res = $res->result;
1100 }
1101 return pg_field_type( $res, $index );
1102 }
1103
1104 /* Not even sure why this is used in the main codebase... */
1105 function limitResultForUpdate( $sql, $num ) {
1106 return $sql;
1107 }
1108
1109 /**
1110 * @param $b
1111 * @return Blob
1112 */
1113 function encodeBlob( $b ) {
1114 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1115 }
1116
1117 function decodeBlob( $b ) {
1118 if ( $b instanceof Blob ) {
1119 $b = $b->fetch();
1120 }
1121 return pg_unescape_bytea( $b );
1122 }
1123
1124 function strencode( $s ) { # Should not be called by us
1125 return pg_escape_string( $this->mConn, $s );
1126 }
1127
1128 /**
1129 * @param $s null|bool|Blob
1130 * @return int|string
1131 */
1132 function addQuotes( $s ) {
1133 if ( is_null( $s ) ) {
1134 return 'NULL';
1135 } elseif ( is_bool( $s ) ) {
1136 return intval( $s );
1137 } elseif ( $s instanceof Blob ) {
1138 return "'" . $s->fetch( $s ) . "'";
1139 }
1140 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1141 }
1142
1143 /**
1144 * Postgres specific version of replaceVars.
1145 * Calls the parent version in Database.php
1146 *
1147 * @private
1148 *
1149 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1150 *
1151 * @return string SQL string
1152 */
1153 protected function replaceVars( $ins ) {
1154 $ins = parent::replaceVars( $ins );
1155
1156 if ( $this->numeric_version >= 8.3 ) {
1157 // Thanks for not providing backwards-compatibility, 8.3
1158 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1159 }
1160
1161 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1162 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1163 }
1164
1165 return $ins;
1166 }
1167
1168 /**
1169 * Various select options
1170 *
1171 * @private
1172 *
1173 * @param $options Array: an associative array of options to be turned into
1174 * an SQL query, valid keys are listed in the function.
1175 * @return array
1176 */
1177 function makeSelectOptions( $options ) {
1178 $preLimitTail = $postLimitTail = '';
1179 $startOpts = $useIndex = '';
1180
1181 $noKeyOptions = array();
1182 foreach ( $options as $key => $option ) {
1183 if ( is_numeric( $key ) ) {
1184 $noKeyOptions[$option] = true;
1185 }
1186 }
1187
1188 if ( isset( $options['GROUP BY'] ) ) {
1189 $gb = is_array( $options['GROUP BY'] )
1190 ? implode( ',', $options['GROUP BY'] )
1191 : $options['GROUP BY'];
1192 $preLimitTail .= " GROUP BY {$gb}";
1193 }
1194
1195 if ( isset( $options['HAVING'] ) ) {
1196 $preLimitTail .= " HAVING {$options['HAVING']}";
1197 }
1198
1199 if ( isset( $options['ORDER BY'] ) ) {
1200 $ob = is_array( $options['ORDER BY'] )
1201 ? implode( ',', $options['ORDER BY'] )
1202 : $options['ORDER BY'];
1203 $preLimitTail .= " ORDER BY {$ob}";
1204 }
1205
1206 //if ( isset( $options['LIMIT'] ) ) {
1207 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1208 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1209 // : false );
1210 //}
1211
1212 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1213 $postLimitTail .= ' FOR UPDATE';
1214 }
1215 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1216 $postLimitTail .= ' LOCK IN SHARE MODE';
1217 }
1218 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1219 $startOpts .= 'DISTINCT';
1220 }
1221
1222 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1223 }
1224
1225 function setFakeMaster( $enabled = true ) {}
1226
1227 function getDBname() {
1228 return $this->mDBname;
1229 }
1230
1231 function getServer() {
1232 return $this->mServer;
1233 }
1234
1235 function buildConcat( $stringList ) {
1236 return implode( ' || ', $stringList );
1237 }
1238
1239 public function getSearchEngine() {
1240 return 'SearchPostgres';
1241 }
1242
1243 public function streamStatementEnd( &$sql, &$newLine ) {
1244 # Allow dollar quoting for function declarations
1245 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1246 if ( $this->delimiter ) {
1247 $this->delimiter = false;
1248 }
1249 else {
1250 $this->delimiter = ';';
1251 }
1252 }
1253 return parent::streamStatementEnd( $sql, $newLine );
1254 }
1255 } // end DatabasePostgres class