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