e2b38f52031eeb68aed775f321a9168b20b673de
[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->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 $this->realTableName( 'mwuser', $format );
712 case 'text':
713 return $this->realTableName( 'pagecontent', $format );
714 default:
715 return $this->realTableName( $name, $format );
716 }
717 }
718
719 /* Don't cheat on installer */
720 function realTableName( $name, $format = 'quoted' ) {
721 return parent::tableName( $name, $format );
722 }
723
724 /**
725 * Return the next in a sequence, save the value for retrieval via insertId()
726 * @return null
727 */
728 function nextSequenceValue( $seqName ) {
729 $safeseq = str_replace( "'", "''", $seqName );
730 $res = $this->query( "SELECT nextval('$safeseq')" );
731 $row = $this->fetchRow( $res );
732 $this->mInsertId = $row[0];
733 return $this->mInsertId;
734 }
735
736 /**
737 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
738 * @return
739 */
740 function currentSequenceValue( $seqName ) {
741 $safeseq = str_replace( "'", "''", $seqName );
742 $res = $this->query( "SELECT currval('$safeseq')" );
743 $row = $this->fetchRow( $res );
744 $currval = $row[0];
745 return $currval;
746 }
747
748 # Returns the size of a text field, or -1 for "unlimited"
749 function textFieldSize( $table, $field ) {
750 $table = $this->tableName( $table );
751 $sql = "SELECT t.typname as ftype,a.atttypmod as size
752 FROM pg_class c, pg_attribute a, pg_type t
753 WHERE relname='$table' AND a.attrelid=c.oid AND
754 a.atttypid=t.oid and a.attname='$field'";
755 $res =$this->query( $sql );
756 $row = $this->fetchObject( $res );
757 if ( $row->ftype == 'varchar' ) {
758 $size = $row->size - 4;
759 } else {
760 $size = $row->size;
761 }
762 return $size;
763 }
764
765 function limitResult( $sql, $limit, $offset = false ) {
766 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
767 }
768
769 function wasDeadlock() {
770 return $this->lastErrno() == '40P01';
771 }
772
773 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
774 $newName = $this->addIdentifierQuotes( $newName );
775 $oldName = $this->addIdentifierQuotes( $oldName );
776 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
777 }
778
779 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
780 $eschema = $this->addQuotes( $this->getCoreSchema() );
781 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
782 $endArray = array();
783
784 foreach( $result as $table ) {
785 $vars = get_object_vars($table);
786 $table = array_pop( $vars );
787 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
788 $endArray[] = $table;
789 }
790 }
791
792 return $endArray;
793 }
794
795 function timestamp( $ts = 0 ) {
796 return wfTimestamp( TS_POSTGRES, $ts );
797 }
798
799 /*
800 * Posted by cc[plus]php[at]c2se[dot]com on 25-Mar-2009 09:12
801 * to http://www.php.net/manual/en/ref.pgsql.php
802 *
803 * Parsing a postgres array can be a tricky problem, he's my
804 * take on this, it handles multi-dimensional arrays plus
805 * escaping using a nasty regexp to determine the limits of each
806 * data-item.
807 *
808 * This should really be handled by PHP PostgreSQL module
809 *
810 * @since 1.20
811 * @param $text string: postgreql array returned in a text form like {a,b}
812 * @param $output string
813 * @param $limit int
814 * @param $offset int
815 * @return string
816 */
817 function pg_array_parse( $text, &$output, $limit = false, $offset = 1 ) {
818 if( false === $limit ) {
819 $limit = strlen( $text )-1;
820 $output = array();
821 }
822 if( '{}' == $text ) {
823 return $output;
824 }
825 do {
826 if ( '{' != $text{$offset} ) {
827 preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/",
828 $text, $match, 0, $offset );
829 $offset += strlen( $match[0] );
830 $output[] = ( '"' != $match[1]{0}
831 ? $match[1]
832 : stripcslashes( substr( $match[1], 1, -1 ) ) );
833 if ( '},' == $match[3] ) {
834 return $output;
835 }
836 } else {
837 $offset = $this->pg_array_parse( $text, $output, $limit, $offset+1 );
838 }
839 } while ( $limit > $offset );
840 return $output;
841 }
842
843 /**
844 * Return aggregated value function call
845 */
846 function aggregateValue( $valuedata, $valuename = 'value' ) {
847 return $valuedata;
848 }
849
850 /**
851 * @return string wikitext of a link to the server software's web site
852 */
853 public static function getSoftwareLink() {
854 return '[http://www.postgresql.org/ PostgreSQL]';
855 }
856
857
858 /**
859 * Return current schema (executes SELECT current_schema())
860 * Needs transaction
861 *
862 * @since 1.20
863 * @return string return default schema for the current session
864 */
865 function getCurrentSchema() {
866 $res = $this->query( "SELECT current_schema()", __METHOD__);
867 $row = $this->fetchRow( $res );
868 return $row[0];
869 }
870
871 /**
872 * Return list of schemas which are accessible without schema name
873 * This is list does not contain magic keywords like "$user"
874 * Needs transaction
875 *
876 * @seealso getSearchPath()
877 * @seealso setSearchPath()
878 * @since 1.20
879 * @return array list of actual schemas for the current sesson
880 */
881 function getSchemas() {
882 $res = $this->query( "SELECT current_schemas(false)", __METHOD__);
883 $row = $this->fetchRow( $res );
884 $schemas = array();
885 /* PHP pgsql support does not support array type, "{a,b}" string is returned */
886 return $this->pg_array_parse($row[0], $schemas);
887 }
888
889 /**
890 * Return search patch for schemas
891 * This is different from getSchemas() since it contain magic keywords
892 * (like "$user").
893 * Needs transaction
894 *
895 * @since 1.20
896 * @return array how to search for table names schemas for the current user
897 */
898 function getSearchPath() {
899 $res = $this->query( "SHOW search_path", __METHOD__);
900 $row = $this->fetchRow( $res );
901 /* PostgreSQL returns SHOW values as strings */
902 return explode(",", $row[0]);
903 }
904
905 /**
906 * Update search_path, values should already be sanitized
907 * Values may contain magic keywords like "$user"
908 * @since 1.20
909 *
910 * @param $search_path array list of schemas to be searched by default
911 */
912 function setSearchPath( $search_path ) {
913 $this->query( "SET search_path = " . implode(", ", $search_path) );
914 }
915
916 /**
917 * Determine default schema for MediaWiki core
918 * Adjust this session schema search path if desired schema exists
919 * and is not alread there.
920 *
921 * We need to have name of the core schema stored to be able
922 * to query database metadata.
923 *
924 * This will be also called by the installer after the schema is created
925 *
926 * @since 1.20
927 * @param desired_schema string
928 */
929 function determineCoreSchema( $desired_schema ) {
930 $this->begin( __METHOD__ );
931 if ( $this->schemaExists( $desired_schema ) ) {
932 if ( in_array( $desired_schema, $this->getSchemas() ) ) {
933 $this->mCoreSchema = $desired_schema;
934 wfDebug("Schema \"" . $desired_schema . "\" already in the search path\n");
935 } else {
936 /**
937 * Append our schema (e.g. 'mediawiki') in front
938 * of the search path
939 * Fixes bug 15816
940 */
941 $search_path = $this->getSearchPath();
942 array_unshift( $search_path,
943 $this->addIdentifierQuotes( $desired_schema ));
944 $this->setSearchPath( $search_path );
945 $this->mCoreSchema = $desired_schema;
946 wfDebug("Schema \"" . $desired_schema . "\" added to the search path\n");
947 }
948 } else {
949 $this->mCoreSchema = $this->getCurrentSchema();
950 wfDebug("Schema \"" . $desired_schema . "\" not found, using current \"". $this->mCoreSchema ."\"\n");
951 }
952 /* Commit SET otherwise it will be rollbacked on error or IGNORE SELECT */
953 $this->commit( __METHOD__ );
954 }
955
956 /**
957 * Return schema name fore core MediaWiki tables
958 *
959 * @since 1.20
960 * @return string core schema name
961 */
962 function getCoreSchema() {
963 return $this->mCoreSchema;
964 }
965
966 /**
967 * @return string Version information from the database
968 */
969 function getServerVersion() {
970 if ( !isset( $this->numeric_version ) ) {
971 $versionInfo = pg_version( $this->mConn );
972 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
973 // Old client, abort install
974 $this->numeric_version = '7.3 or earlier';
975 } elseif ( isset( $versionInfo['server'] ) ) {
976 // Normal client
977 $this->numeric_version = $versionInfo['server'];
978 } else {
979 // Bug 16937: broken pgsql extension from PHP<5.3
980 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
981 }
982 }
983 return $this->numeric_version;
984 }
985
986 /**
987 * Query whether a given relation exists (in the given schema, or the
988 * default mw one if not given)
989 * @return bool
990 */
991 function relationExists( $table, $types, $schema = false ) {
992 if ( !is_array( $types ) ) {
993 $types = array( $types );
994 }
995 if ( !$schema ) {
996 $schema = $this->getCoreSchema();
997 }
998 $table = $this->realTableName( $table, 'raw' );
999 $etable = $this->addQuotes( $table );
1000 $eschema = $this->addQuotes( $schema );
1001 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
1002 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
1003 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
1004 $res = $this->query( $SQL );
1005 $count = $res ? $res->numRows() : 0;
1006 return (bool)$count;
1007 }
1008
1009 /**
1010 * For backward compatibility, this function checks both tables and
1011 * views.
1012 * @return bool
1013 */
1014 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
1015 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
1016 }
1017
1018 function sequenceExists( $sequence, $schema = false ) {
1019 return $this->relationExists( $sequence, 'S', $schema );
1020 }
1021
1022 function triggerExists( $table, $trigger ) {
1023 $q = <<<SQL
1024 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
1025 WHERE relnamespace=pg_namespace.oid AND relkind='r'
1026 AND tgrelid=pg_class.oid
1027 AND nspname=%s AND relname=%s AND tgname=%s
1028 SQL;
1029 $res = $this->query(
1030 sprintf(
1031 $q,
1032 $this->addQuotes( $this->getCoreSchema() ),
1033 $this->addQuotes( $table ),
1034 $this->addQuotes( $trigger )
1035 )
1036 );
1037 if ( !$res ) {
1038 return null;
1039 }
1040 $rows = $res->numRows();
1041 return $rows;
1042 }
1043
1044 function ruleExists( $table, $rule ) {
1045 $exists = $this->selectField( 'pg_rules', 'rulename',
1046 array(
1047 'rulename' => $rule,
1048 'tablename' => $table,
1049 'schemaname' => $this->getCoreSchema()
1050 )
1051 );
1052 return $exists === $rule;
1053 }
1054
1055 function constraintExists( $table, $constraint ) {
1056 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
1057 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
1058 $this->addQuotes( $this->getCoreSchema() ),
1059 $this->addQuotes( $table ),
1060 $this->addQuotes( $constraint )
1061 );
1062 $res = $this->query( $SQL );
1063 if ( !$res ) {
1064 return null;
1065 }
1066 $rows = $res->numRows();
1067 return $rows;
1068 }
1069
1070 /**
1071 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
1072 * @return bool
1073 */
1074 function schemaExists( $schema ) {
1075 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
1076 array( 'nspname' => $schema ), __METHOD__ );
1077 return (bool)$exists;
1078 }
1079
1080 /**
1081 * Returns true if a given role (i.e. user) exists, false otherwise.
1082 * @return bool
1083 */
1084 function roleExists( $roleName ) {
1085 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
1086 array( 'rolname' => $roleName ), __METHOD__ );
1087 return (bool)$exists;
1088 }
1089
1090 function fieldInfo( $table, $field ) {
1091 return PostgresField::fromText( $this, $table, $field );
1092 }
1093
1094 /**
1095 * pg_field_type() wrapper
1096 * @return string
1097 */
1098 function fieldType( $res, $index ) {
1099 if ( $res instanceof ResultWrapper ) {
1100 $res = $res->result;
1101 }
1102 return pg_field_type( $res, $index );
1103 }
1104
1105 /* Not even sure why this is used in the main codebase... */
1106 function limitResultForUpdate( $sql, $num ) {
1107 return $sql;
1108 }
1109
1110 /**
1111 * @param $b
1112 * @return Blob
1113 */
1114 function encodeBlob( $b ) {
1115 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
1116 }
1117
1118 function decodeBlob( $b ) {
1119 if ( $b instanceof Blob ) {
1120 $b = $b->fetch();
1121 }
1122 return pg_unescape_bytea( $b );
1123 }
1124
1125 function strencode( $s ) { # Should not be called by us
1126 return pg_escape_string( $this->mConn, $s );
1127 }
1128
1129 /**
1130 * @param $s null|bool|Blob
1131 * @return int|string
1132 */
1133 function addQuotes( $s ) {
1134 if ( is_null( $s ) ) {
1135 return 'NULL';
1136 } elseif ( is_bool( $s ) ) {
1137 return intval( $s );
1138 } elseif ( $s instanceof Blob ) {
1139 return "'" . $s->fetch( $s ) . "'";
1140 }
1141 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
1142 }
1143
1144 /**
1145 * Postgres specific version of replaceVars.
1146 * Calls the parent version in Database.php
1147 *
1148 * @private
1149 *
1150 * @param $ins String: SQL string, read from a stream (usually tables.sql)
1151 *
1152 * @return string SQL string
1153 */
1154 protected function replaceVars( $ins ) {
1155 $ins = parent::replaceVars( $ins );
1156
1157 if ( $this->numeric_version >= 8.3 ) {
1158 // Thanks for not providing backwards-compatibility, 8.3
1159 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
1160 }
1161
1162 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
1163 $ins = str_replace( 'USING gin', 'USING gist', $ins );
1164 }
1165
1166 return $ins;
1167 }
1168
1169 /**
1170 * Various select options
1171 *
1172 * @private
1173 *
1174 * @param $options Array: an associative array of options to be turned into
1175 * an SQL query, valid keys are listed in the function.
1176 * @return array
1177 */
1178 function makeSelectOptions( $options ) {
1179 $preLimitTail = $postLimitTail = '';
1180 $startOpts = $useIndex = '';
1181
1182 $noKeyOptions = array();
1183 foreach ( $options as $key => $option ) {
1184 if ( is_numeric( $key ) ) {
1185 $noKeyOptions[$option] = true;
1186 }
1187 }
1188
1189 if ( isset( $options['GROUP BY'] ) ) {
1190 $gb = is_array( $options['GROUP BY'] )
1191 ? implode( ',', $options['GROUP BY'] )
1192 : $options['GROUP BY'];
1193 $preLimitTail .= " GROUP BY {$gb}";
1194 }
1195
1196 if ( isset( $options['HAVING'] ) ) {
1197 $preLimitTail .= " HAVING {$options['HAVING']}";
1198 }
1199
1200 if ( isset( $options['ORDER BY'] ) ) {
1201 $ob = is_array( $options['ORDER BY'] )
1202 ? implode( ',', $options['ORDER BY'] )
1203 : $options['ORDER BY'];
1204 $preLimitTail .= " ORDER BY {$ob}";
1205 }
1206
1207 //if ( isset( $options['LIMIT'] ) ) {
1208 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1209 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1210 // : false );
1211 //}
1212
1213 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1214 $postLimitTail .= ' FOR UPDATE';
1215 }
1216 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1217 $postLimitTail .= ' LOCK IN SHARE MODE';
1218 }
1219 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1220 $startOpts .= 'DISTINCT';
1221 }
1222
1223 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1224 }
1225
1226 function setFakeMaster( $enabled = true ) {}
1227
1228 function getDBname() {
1229 return $this->mDBname;
1230 }
1231
1232 function getServer() {
1233 return $this->mServer;
1234 }
1235
1236 function buildConcat( $stringList ) {
1237 return implode( ' || ', $stringList );
1238 }
1239
1240 public function getSearchEngine() {
1241 return 'SearchPostgres';
1242 }
1243
1244 public function streamStatementEnd( &$sql, &$newLine ) {
1245 # Allow dollar quoting for function declarations
1246 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1247 if ( $this->delimiter ) {
1248 $this->delimiter = false;
1249 }
1250 else {
1251 $this->delimiter = ';';
1252 }
1253 }
1254 return parent::streamStatementEnd( $sql, $newLine );
1255 }
1256 } // end DatabasePostgres class