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