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