Handle PostgreSQL transaction errors and improve schema detection
[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, COALESCE(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->mConn->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 global $wgDebugDBTransactions;
319 if ( function_exists( 'mb_convert_encoding' ) ) {
320 $sql = mb_convert_encoding( $sql, 'UTF-8' );
321 }
322 $this->mTransactionState->check();
323 $this->mLastResult = pg_query( $this->mConn, $sql );
324 $this->mTransactionState->check();
325 $this->mAffectedRows = null;
326 return $this->mLastResult;
327 }
328
329 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
330 /* Transaction stays in the ERROR state until rolledback */
331 $this->rollback( __METHOD__ );
332 parent::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
333 }
334
335
336 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
337 return $this->query( $sql, $fname, true );
338 }
339
340 function freeResult( $res ) {
341 if ( $res instanceof ResultWrapper ) {
342 $res = $res->result;
343 }
344 wfSuppressWarnings();
345 $ok = pg_free_result( $res );
346 wfRestoreWarnings();
347 if ( !$ok ) {
348 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
349 }
350 }
351
352 function fetchObject( $res ) {
353 if ( $res instanceof ResultWrapper ) {
354 $res = $res->result;
355 }
356 wfSuppressWarnings();
357 $row = pg_fetch_object( $res );
358 wfRestoreWarnings();
359 # @todo FIXME: HACK HACK HACK HACK debug
360
361 # @todo hashar: not sure if the following test really trigger if the object
362 # fetching failed.
363 if( pg_last_error( $this->mConn ) ) {
364 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
365 }
366 return $row;
367 }
368
369 function fetchRow( $res ) {
370 if ( $res instanceof ResultWrapper ) {
371 $res = $res->result;
372 }
373 wfSuppressWarnings();
374 $row = pg_fetch_array( $res );
375 wfRestoreWarnings();
376 if( pg_last_error( $this->mConn ) ) {
377 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
378 }
379 return $row;
380 }
381
382 function numRows( $res ) {
383 if ( $res instanceof ResultWrapper ) {
384 $res = $res->result;
385 }
386 wfSuppressWarnings();
387 $n = pg_num_rows( $res );
388 wfRestoreWarnings();
389 if( pg_last_error( $this->mConn ) ) {
390 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
391 }
392 return $n;
393 }
394
395 function numFields( $res ) {
396 if ( $res instanceof ResultWrapper ) {
397 $res = $res->result;
398 }
399 return pg_num_fields( $res );
400 }
401
402 function fieldName( $res, $n ) {
403 if ( $res instanceof ResultWrapper ) {
404 $res = $res->result;
405 }
406 return pg_field_name( $res, $n );
407 }
408
409 /**
410 * This must be called after nextSequenceVal
411 * @return null
412 */
413 function insertId() {
414 return $this->mInsertId;
415 }
416
417 function dataSeek( $res, $row ) {
418 if ( $res instanceof ResultWrapper ) {
419 $res = $res->result;
420 }
421 return pg_result_seek( $res, $row );
422 }
423
424 function lastError() {
425 if ( $this->mConn ) {
426 return pg_last_error();
427 } else {
428 return 'No database connection';
429 }
430 }
431 function lastErrno() {
432 return pg_last_error() ? 1 : 0;
433 }
434
435 function affectedRows() {
436 if ( !is_null( $this->mAffectedRows ) ) {
437 // Forced result for simulated queries
438 return $this->mAffectedRows;
439 }
440 if( empty( $this->mLastResult ) ) {
441 return 0;
442 }
443 return pg_affected_rows( $this->mLastResult );
444 }
445
446 /**
447 * Estimate rows in dataset
448 * Returns estimated count, based on EXPLAIN output
449 * This is not necessarily an accurate estimate, so use sparingly
450 * Returns -1 if count cannot be found
451 * Takes same arguments as Database::select()
452 * @return int
453 */
454 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
455 $options['EXPLAIN'] = true;
456 $res = $this->select( $table, $vars, $conds, $fname, $options );
457 $rows = -1;
458 if ( $res ) {
459 $row = $this->fetchRow( $res );
460 $count = array();
461 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
462 $rows = $count[1];
463 }
464 }
465 return $rows;
466 }
467
468 /**
469 * Returns information about an index
470 * If errors are explicitly ignored, returns NULL on failure
471 * @return bool|null
472 */
473 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
474 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
475 $res = $this->query( $sql, $fname );
476 if ( !$res ) {
477 return null;
478 }
479 foreach ( $res as $row ) {
480 if ( $row->indexname == $this->indexName( $index ) ) {
481 return $row;
482 }
483 }
484 return false;
485 }
486
487 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
488 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
489 " AND indexdef LIKE 'CREATE UNIQUE%(" .
490 $this->strencode( $this->indexName( $index ) ) .
491 ")'";
492 $res = $this->query( $sql, $fname );
493 if ( !$res ) {
494 return null;
495 }
496 foreach ( $res as $row ) {
497 return true;
498 }
499 return false;
500 }
501
502 /**
503 * INSERT wrapper, inserts an array into a table
504 *
505 * $args may be a single associative array, or an array of these with numeric keys,
506 * for multi-row insert (Postgres version 8.2 and above only).
507 *
508 * @param $table String: Name of the table to insert to.
509 * @param $args Array: Items to insert into the table.
510 * @param $fname String: Name of the function, for profiling
511 * @param $options String or Array. Valid options: IGNORE
512 *
513 * @return bool Success of insert operation. IGNORE always returns true.
514 */
515 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
516 if ( !count( $args ) ) {
517 return true;
518 }
519
520 $table = $this->tableName( $table );
521 if (! isset( $this->numeric_version ) ) {
522 $this->getServerVersion();
523 }
524
525 if ( !is_array( $options ) ) {
526 $options = array( $options );
527 }
528
529 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
530 $multi = true;
531 $keys = array_keys( $args[0] );
532 } else {
533 $multi = false;
534 $keys = array_keys( $args );
535 }
536
537 // If IGNORE is set, we use savepoints to emulate mysql's behavior
538 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
539
540 // If we are not in a transaction, we need to be for savepoint trickery
541 $didbegin = 0;
542 if ( $ignore ) {
543 if ( !$this->mTrxLevel ) {
544 $this->begin( __METHOD__ );
545 $didbegin = 1;
546 }
547 $olde = error_reporting( 0 );
548 // For future use, we may want to track the number of actual inserts
549 // Right now, insert (all writes) simply return true/false
550 $numrowsinserted = 0;
551 }
552
553 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
554
555 if ( $multi ) {
556 if ( $this->numeric_version >= 8.2 && !$ignore ) {
557 $first = true;
558 foreach ( $args as $row ) {
559 if ( $first ) {
560 $first = false;
561 } else {
562 $sql .= ',';
563 }
564 $sql .= '(' . $this->makeList( $row ) . ')';
565 }
566 $res = (bool)$this->query( $sql, $fname, $ignore );
567 } else {
568 $res = true;
569 $origsql = $sql;
570 foreach ( $args as $row ) {
571 $tempsql = $origsql;
572 $tempsql .= '(' . $this->makeList( $row ) . ')';
573
574 if ( $ignore ) {
575 $this->doQuery( "SAVEPOINT $ignore" );
576 }
577
578 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
579
580 if ( $ignore ) {
581 $bar = pg_last_error();
582 if ( $bar != false ) {
583 $this->doQuery( $this->mConn, "ROLLBACK TO $ignore" );
584 } else {
585 $this->doQuery( $this->mConn, "RELEASE $ignore" );
586 $numrowsinserted++;
587 }
588 }
589
590 // If any of them fail, we fail overall for this function call
591 // Note that this will be ignored if IGNORE is set
592 if ( !$tempres ) {
593 $res = false;
594 }
595 }
596 }
597 } else {
598 // Not multi, just a lone insert
599 if ( $ignore ) {
600 $this->doQuery( "SAVEPOINT $ignore" );
601 }
602
603 $sql .= '(' . $this->makeList( $args ) . ')';
604 $res = (bool)$this->query( $sql, $fname, $ignore );
605 if ( $ignore ) {
606 $bar = pg_last_error();
607 if ( $bar != false ) {
608 $this->doQuery( "ROLLBACK TO $ignore" );
609 } else {
610 $this->doQuery( "RELEASE $ignore" );
611 $numrowsinserted++;
612 }
613 }
614 }
615 if ( $ignore ) {
616 $olde = error_reporting( $olde );
617 if ( $didbegin ) {
618 $this->commit( __METHOD__ );
619 }
620
621 // Set the affected row count for the whole operation
622 $this->mAffectedRows = $numrowsinserted;
623
624 // IGNORE always returns true
625 return true;
626 }
627
628 return $res;
629 }
630
631 /**
632 * INSERT SELECT wrapper
633 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
634 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
635 * $conds may be "*" to copy the whole table
636 * srcTable may be an array of tables.
637 * @todo FIXME: Implement this a little better (seperate select/insert)?
638 * @return bool
639 */
640 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
641 $insertOptions = array(), $selectOptions = array() )
642 {
643 $destTable = $this->tableName( $destTable );
644
645 // If IGNORE is set, we use savepoints to emulate mysql's behavior
646 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
647
648 if( is_array( $insertOptions ) ) {
649 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
650 }
651 if( !is_array( $selectOptions ) ) {
652 $selectOptions = array( $selectOptions );
653 }
654 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
655 if( is_array( $srcTable ) ) {
656 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
657 } else {
658 $srcTable = $this->tableName( $srcTable );
659 }
660
661 // If we are not in a transaction, we need to be for savepoint trickery
662 $didbegin = 0;
663 if ( $ignore ) {
664 if( !$this->mTrxLevel ) {
665 $this->begin( __METHOD__ );
666 $didbegin = 1;
667 }
668 $olde = error_reporting( 0 );
669 $numrowsinserted = 0;
670 $this->doQuery( "SAVEPOINT $ignore" );
671 }
672
673 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
674 " SELECT $startOpts " . implode( ',', $varMap ) .
675 " FROM $srcTable $useIndex";
676
677 if ( $conds != '*' ) {
678 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
679 }
680
681 $sql .= " $tailOpts";
682
683 $res = (bool)$this->query( $sql, $fname, $ignore );
684 if( $ignore ) {
685 $bar = pg_last_error();
686 if( $bar != false ) {
687 $this->doQuery( "ROLLBACK TO $ignore" );
688 } else {
689 $this->doQuery( "RELEASE $ignore" );
690 $numrowsinserted++;
691 }
692 $olde = error_reporting( $olde );
693 if( $didbegin ) {
694 $this->commit( __METHOD__ );
695 }
696
697 // Set the affected row count for the whole operation
698 $this->mAffectedRows = $numrowsinserted;
699
700 // IGNORE always returns true
701 return true;
702 }
703
704 return $res;
705 }
706
707 function tableName( $name, $format = 'quoted' ) {
708 # Replace reserved words with better ones
709 switch( $name ) {
710 case 'user':
711 return 'mwuser';
712 case 'text':
713 return 'pagecontent';
714 default:
715 return parent::tableName( $name, $format );
716 }
717 }
718
719 /**
720 * Return the next in a sequence, save the value for retrieval via insertId()
721 * @return null
722 */
723 function nextSequenceValue( $seqName ) {
724 $safeseq = str_replace( "'", "''", $seqName );
725 $res = $this->query( "SELECT nextval('$safeseq')" );
726 $row = $this->fetchRow( $res );
727 $this->mInsertId = $row[0];
728 return $this->mInsertId;
729 }
730
731 /**
732 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
733 * @return
734 */
735 function currentSequenceValue( $seqName ) {
736 $safeseq = str_replace( "'", "''", $seqName );
737 $res = $this->query( "SELECT currval('$safeseq')" );
738 $row = $this->fetchRow( $res );
739 $currval = $row[0];
740 return $currval;
741 }
742
743 # Returns the size of a text field, or -1 for "unlimited"
744 function textFieldSize( $table, $field ) {
745 $table = $this->tableName( $table );
746 $sql = "SELECT t.typname as ftype,a.atttypmod as size
747 FROM pg_class c, pg_attribute a, pg_type t
748 WHERE relname='$table' AND a.attrelid=c.oid AND
749 a.atttypid=t.oid and a.attname='$field'";
750 $res =$this->query( $sql );
751 $row = $this->fetchObject( $res );
752 if ( $row->ftype == 'varchar' ) {
753 $size = $row->size - 4;
754 } else {
755 $size = $row->size;
756 }
757 return $size;
758 }
759
760 function limitResult( $sql, $limit, $offset = false ) {
761 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
762 }
763
764 function wasDeadlock() {
765 return $this->lastErrno() == '40P01';
766 }
767
768 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
769 $newName = $this->addIdentifierQuotes( $newName );
770 $oldName = $this->addIdentifierQuotes( $oldName );
771 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
772 }
773
774 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
775 $eschema = $this->addQuotes( $this->getCoreSchema() );
776 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
777 $endArray = array();
778
779 foreach( $result as $table ) {
780 $vars = get_object_vars($table);
781 $table = array_pop( $vars );
782 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
783 $endArray[] = $table;
784 }
785 }
786
787 return $endArray;
788 }
789
790 function timestamp( $ts = 0 ) {
791 return wfTimestamp( TS_POSTGRES, $ts );
792 }
793
794
795 /*
796 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
797 * to http://www.php.net/manual/en/ref.pgsql.php
798 *
799 * Parsing a postgres array can be a tricky problem, he's my
800 * take on this, it handles multi-dimensional arrays plus
801 * escaping using a nasty regexp to determine the limits of each
802 * data-item.
803 *
804 * This should really be handled by PHP PostgreSQL module
805 *
806 * @since 1.20
807 * @param text string: postgreql array returned in a text form like {a,b}
808 * @param output string
809 * @param limit int
810 * @param offset int
811 * @return string
812 */
813
814 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
815 if( false === $limit ) {
816 $limit = strlen( $text )-1;
817 $output = array();
818 }
819 if( '{}' != $text )
820 do {
821 if ( '{' != $text{$offset} ) {
822 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
823 $text, $match, 0, $offset );
824 $offset += strlen( $match[0] );
825 $output[] = ( '"' != $match[1]{0}
826 ? $match[1]
827 : stripcslashes( substr( $match[1], 1, -1 ) ) );
828 if ( '},' == $match[3] )
829 return $output;
830 } else
831 $offset = $this->pg_array_parse( $text, $output[], $limit, $offset+1 );
832 } while ( $limit > $offset );
833 return $output;
834 }
835
836 /**
837 * Return aggregated value function call
838 */
839 function aggregateValue( $valuedata, $valuename = 'value' ) {
840 return $valuedata;
841 }
842
843 /**
844 * @return string wikitext of a link to the server software's web site
845 */
846 public static function getSoftwareLink() {
847 return '[http://www.postgresql.org/ PostgreSQL]';
848 }
849
850
851 /**
852 * Return current schema (executes SELECT current_schema())
853 * Needs transaction
854 *
855 * @since 1.20
856 * @return string return default schema for the current session
857 */
858 function getCurrentSchema() {
859 $res = $this->query( "SELECT current_schema()", __METHOD__);
860 $row = $this->fetchRow( $res );
861 return $row[0];
862 }
863
864 /**
865 * Return list of schemas which are accessible without schema name
866 * This is list does not contain magic keywords like "$user"
867 * Needs transaction
868 *
869 * @seealso getSearchPath()
870 * @seealso setSearchPath()
871 * @since 1.20
872 * @return array list of actual schemas for the current sesson
873 */
874 function getSchemas() {
875 $res = $this->query( "SELECT current_schemas(false)", __METHOD__);
876 $row = $this->fetchRow( $res );
877 $schemas = array();
878 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
879 return $this->pg_array_parse($row[0], $schemas);
880 }
881
882 /**
883 * Return search patch for schemas
884 * This is different from getSchemas() since it contain magic keywords
885 * (like "$user").
886 * Needs transaction
887 *
888 * @since 1.20
889 * @return array how to search for table names schemas for the current user
890 */
891 function getSearchPath() {
892 $res = $this->query( "SHOW search_path", __METHOD__);
893 $row = $this->fetchRow( $res );
894 /* PostgreSQL returns SHOW values as strings */
895 return explode(",", $row[0]);
896 }
897
898 function setSearchPath( $search_path ) {
899 /**
900 * Update search_path, values should already be sanitized
901 * Values may contain magic keywords like "$user"
902 * @since 1.20
903 *
904 * @param array list of schemas to be searched by default
905 */
906 $this->query( "SET search_path = " . implode(", ", $search_path) );
907 }
908
909 /**
910 * Determine default schema for MediaWiki core
911 * Adjust this session schema search path if desired schema exists
912 * and is not alread there.
913 *
914 * We need to have name of the core schema stored to be able
915 * to query database metadata.
916 *
917 * This will be also called by the installer after the schema is created
918 *
919 * @since 1.20
920 * @param desired_schema string
921 */
922 function determineCoreSchema( $desired_schema ) {
923 $this->begin( __METHOD__ );
924 if ( $this->schemaExists( $desired_schema ) ) {
925 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
926 $this->mCoreSchema = $desired_schema;
927 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
928 } else {
929 /**
930 * Apped our schema (e.g. 'mediawiki') in front
931 * of the search path
932 * Fixes bug 15816
933 */
934 $search_path = $this->getSearchPath();
935 array_unshift( $search_path,
936 $this->addIdentifierQuotes( $desired_schema ));
937 $this->setSearchPath( $search_path );
938 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
939 }
940 } else {
941 $this->mCoreSchema = $this->getCurrentSchema();
942 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema ."\"\n");
943 }
944 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
945 $this->commit( __METHOD__ );
946 }
947
948 /**
949 * Return schema name fore core MediaWiki tables
950 *
951 * @since 1.20
952 * @return string core schema name
953 */
954 function getCoreSchema() {
955 return $this->mCoreSchema;
956 }
957
958 /**
959 * @return string Version information from the database
960 */
961 function getServerVersion() {
962 if ( !isset( $this->numeric_version ) ) {
963 $versionInfo = pg_version( $this->mConn );
964 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
965 // Old client, abort install
966 $this->numeric_version = '7.3 or earlier';
967 } elseif ( isset( $versionInfo['server'] ) ) {
968 // Normal client
969 $this->numeric_version = $versionInfo['server'];
970 } else {
971 // Bug 16937: broken pgsql extension from PHP<5.3
972 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
973 }
974 }
975 return $this->numeric_version;
976 }
977
978 /**
979 * Query whether a given relation exists (in the given schema, or the
980 * default mw one if not given)
981 * @return bool
982 */
983 function relationExists( $table, $types, $schema = false ) {
984 if ( !is_array( $types ) ) {
985 $types = array( $types );
986 }
987 if ( !$schema ) {
988 $schema = $this->getCoreSchema();
989 }
990 $table = $this->tableName( $table, 'raw' );
991 $etable = $this->addQuotes( $table );
992 $eschema = $this->addQuotes( $schema );
993 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
994 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
995 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
996 $res = $this->query( $SQL );
997 $count = $res ? $res->numRows() : 0;
998 return (bool)$count;
999 }
1000
1001 /**
1002 * For backward compatibility, this function checks both tables and
1003 * views.
1004 * @return bool
1005 */
1006 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1007 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1008 }
1009
1010 function sequenceExists( $sequence, $schema = false ) {
1011 return $this->relationExists( $sequence, 'S', $schema );
1012 }
1013
1014 function triggerExists( $table, $trigger ) {
1015 $q = <<<SQL
1016 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1017 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1018 AND tgrelid=pg_class.oid
1019 AND nspname=%s AND relname=%s AND tgname=%s
1020 SQL;
1021 $res = $this->query(
1022 sprintf(
1023 $q,
1024 $this->addQuotes( $this->getCoreSchema() ),
1025 $this->addQuotes( $table ),
1026 $this->addQuotes( $trigger )
1027 )
1028 );
1029 if ( !$res ) {
1030 return null;
1031 }
1032 $rows = $res->numRows();
1033 return $rows;
1034 }
1035
1036 function ruleExists( $table, $rule ) {
1037 $exists = $this->selectField( 'pg_rules', 'rulename',
1038 array(
1039 'rulename' => $rule,
1040 'tablename' => $table,
1041 'schemaname' => $this->getCoreSchema()
1042 )
1043 );
1044 return $exists === $rule;
1045 }
1046
1047 function constraintExists( $table, $constraint ) {
1048 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1049 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1050 $this->addQuotes( $this->getCoreSchema() ),
1051 $this->addQuotes( $table ),
1052 $this->addQuotes( $constraint )
1053 );
1054 $res = $this->query( $SQL );
1055 if ( !$res ) {
1056 return null;
1057 }
1058 $rows = $res->numRows();
1059 return $rows;
1060 }
1061
1062 /**
1063 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1064 * @return bool
1065 */
1066 function schemaExists( $schema ) {
1067 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1068 array( 'nspname' => $schema ), __METHOD__ );
1069 return (bool)$exists;
1070 }
1071
1072 /**
1073 * Returns true if a given role (i.e. user) exists, false otherwise.
1074 * @return bool
1075 */
1076 function roleExists( $roleName ) {
1077 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1078 array( 'rolname' => $roleName ), __METHOD__ );
1079 return (bool)$exists;
1080 }
1081
1082 function fieldInfo( $table, $field ) {
1083 return PostgresField::fromText( $this, $table, $field );
1084 }
1085
1086 /**
1087 * pg_field_type() wrapper
1088 * @return string
1089 */
1090 function fieldType( $res, $index ) {
1091 if ( $res instanceof ResultWrapper ) {
1092 $res = $res->result;
1093 }
1094 return pg_field_type( $res, $index );
1095 }
1096
1097 /* Not even sure why this is used in the main codebase... */
1098 function limitResultForUpdate( $sql, $num ) {
1099 return $sql;
1100 }
1101
1102 /**
1103 * @param $b
1104 * @return Blob
1105 */
1106 function encodeBlob( $b ) {
1107 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1108 }
1109
1110 function decodeBlob( $b ) {
1111 if ( $b instanceof Blob ) {
1112 $b = $b->fetch();
1113 }
1114 return pg_unescape_bytea( $b );
1115 }
1116
1117 function strencode( $s ) { # Should not be called by us
1118 return pg_escape_string( $this->mConn, $s );
1119 }
1120
1121 /**
1122 * @param $s null|bool|Blob
1123 * @return int|string
1124 */
1125 function addQuotes( $s ) {
1126 if ( is_null( $s ) ) {
1127 return 'NULL';
1128 } elseif ( is_bool( $s ) ) {
1129 return intval( $s );
1130 } elseif ( $s instanceof Blob ) {
1131 return "'" . $s->fetch( $s ) . "'";
1132 }
1133 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1134 }
1135
1136 /**
1137 * Postgres specific version of replaceVars.
1138 * Calls the parent version in Database.php
1139 *
1140 * @private
1141 *
1142 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1143 *
1144 * @return string SQL string
1145 */
1146 protected function replaceVars( $ins ) {
1147 $ins = parent::replaceVars( $ins );
1148
1149 if ( $this->numeric_version >= 8.3 ) {
1150 // Thanks for not providing backwards-compatibility, 8.3
1151 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1152 }
1153
1154 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1155 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1156 }
1157
1158 return $ins;
1159 }
1160
1161 /**
1162 * Various select options
1163 *
1164 * @private
1165 *
1166 * @param $options Array: an associative array of options to be turned into
1167 * an SQL query, valid keys are listed in the function.
1168 * @return array
1169 */
1170 function makeSelectOptions( $options ) {
1171 $preLimitTail = $postLimitTail = '';
1172 $startOpts = $useIndex = '';
1173
1174 $noKeyOptions = array();
1175 foreach ( $options as $key => $option ) {
1176 if ( is_numeric( $key ) ) {
1177 $noKeyOptions[$option] = true;
1178 }
1179 }
1180
1181 if ( isset( $options['GROUP BY'] ) ) {
1182 $gb = is_array( $options['GROUP BY'] )
1183 ? implode( ',', $options['GROUP BY'] )
1184 : $options['GROUP BY'];
1185 $preLimitTail .= " GROUP BY {$gb}";
1186 }
1187
1188 if ( isset( $options['HAVING'] ) ) {
1189 $preLimitTail .= " HAVING {$options['HAVING']}";
1190 }
1191
1192 if ( isset( $options['ORDER BY'] ) ) {
1193 $ob = is_array( $options['ORDER BY'] )
1194 ? implode( ',', $options['ORDER BY'] )
1195 : $options['ORDER BY'];
1196 $preLimitTail .= " ORDER BY {$ob}";
1197 }
1198
1199 //if ( isset( $options['LIMIT'] ) ) {
1200 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1201 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1202 // : false );
1203 //}
1204
1205 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1206 $postLimitTail .= ' FOR UPDATE';
1207 }
1208 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1209 $postLimitTail .= ' LOCK IN SHARE MODE';
1210 }
1211 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1212 $startOpts .= 'DISTINCT';
1213 }
1214
1215 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1216 }
1217
1218 function setFakeMaster( $enabled = true ) {}
1219
1220 function getDBname() {
1221 return $this->mDBname;
1222 }
1223
1224 function getServer() {
1225 return $this->mServer;
1226 }
1227
1228 function buildConcat( $stringList ) {
1229 return implode( ' || ', $stringList );
1230 }
1231
1232 public function getSearchEngine() {
1233 return 'SearchPostgres';
1234 }
1235
1236 public function streamStatementEnd( &$sql, &$newLine ) {
1237 # Allow dollar quoting for function declarations
1238 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1239 if ( $this->delimiter ) {
1240 $this->delimiter = false;
1241 }
1242 else {
1243 $this->delimiter = ';';
1244 }
1245 }
1246 return parent::streamStatementEnd( $sql, $newLine );
1247 }
1248 } // end DatabasePostgres class