(bug 34762) Calling close() on a DatabaseBase object now clears the connection. Based...
[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 global $wgDBmwschema;
20
21 $q = <<<SQL
22 SELECT
23 attnotnull, attlen, COALESCE(conname, '') AS conname,
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( $wgDBmwschema ),
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 * @ingroup Database
102 */
103 class DatabasePostgres extends DatabaseBase {
104 var $mInsertId = null;
105 var $mLastResult = null;
106 var $numeric_version = null;
107 var $mAffectedRows = null;
108
109 function getType() {
110 return 'postgres';
111 }
112
113 function cascadingDeletes() {
114 return true;
115 }
116 function cleanupTriggers() {
117 return true;
118 }
119 function strictIPs() {
120 return true;
121 }
122 function realTimestamps() {
123 return true;
124 }
125 function implicitGroupby() {
126 return false;
127 }
128 function implicitOrderby() {
129 return false;
130 }
131 function searchableIPs() {
132 return true;
133 }
134 function functionalIndexes() {
135 return true;
136 }
137
138 function hasConstraint( $name ) {
139 global $wgDBmwschema;
140 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
141 pg_escape_string( $this->mConn, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn, $wgDBmwschema ) ."'";
142 $res = $this->doQuery( $SQL );
143 return $this->numRows( $res );
144 }
145
146 /**
147 * Usually aborts on failure
148 * @return DatabaseBase|null
149 */
150 function open( $server, $user, $password, $dbName ) {
151 # Test for Postgres support, to avoid suppressed fatal error
152 if ( !function_exists( 'pg_connect' ) ) {
153 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" );
154 }
155
156 global $wgDBport;
157
158 if ( !strlen( $user ) ) { # e.g. the class is being loaded
159 return;
160 }
161
162 $this->close();
163 $this->mServer = $server;
164 $port = $wgDBport;
165 $this->mUser = $user;
166 $this->mPassword = $password;
167 $this->mDBname = $dbName;
168
169 $connectVars = array(
170 'dbname' => $dbName,
171 'user' => $user,
172 'password' => $password
173 );
174 if ( $server != false && $server != '' ) {
175 $connectVars['host'] = $server;
176 }
177 if ( $port != false && $port != '' ) {
178 $connectVars['port'] = $port;
179 }
180 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW );
181
182 $this->installErrorHandler();
183 $this->mConn = pg_connect( $connectString );
184 $phpError = $this->restoreErrorHandler();
185
186 if ( !$this->mConn ) {
187 wfDebug( "DB connection error\n" );
188 wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
189 wfDebug( $this->lastError() . "\n" );
190 throw new DBConnectionError( $this, str_replace( "\n", ' ', $phpError ) );
191 }
192
193 $this->mOpened = true;
194
195 global $wgCommandLineMode;
196 # If called from the command-line (e.g. importDump), only show errors
197 if ( $wgCommandLineMode ) {
198 $this->doQuery( "SET client_min_messages = 'ERROR'" );
199 }
200
201 $this->query( "SET client_encoding='UTF8'", __METHOD__ );
202 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__ );
203 $this->query( "SET timezone = 'GMT'", __METHOD__ );
204 $this->query( "SET standard_conforming_strings = on", __METHOD__ );
205
206 global $wgDBmwschema;
207 if ( $this->schemaExists( $wgDBmwschema ) ) {
208 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
209 $this->doQuery( "SET search_path = $safeschema" );
210 } else {
211 $this->doQuery( "SET search_path = public" );
212 }
213
214 return $this->mConn;
215 }
216
217 /**
218 * Postgres doesn't support selectDB in the same way MySQL does. So if the
219 * DB name doesn't match the open connection, open a new one
220 * @return
221 */
222 function selectDB( $db ) {
223 if ( $this->mDBname !== $db ) {
224 return (bool)$this->open( $this->mServer, $this->mUser, $this->mPassword, $db );
225 } else {
226 return true;
227 }
228 }
229
230 function makeConnectionString( $vars ) {
231 $s = '';
232 foreach ( $vars as $name => $value ) {
233 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
234 }
235 return $s;
236 }
237
238 /**
239 * Closes a database connection, if it is open
240 * Returns success, true if already closed
241 * @return bool
242 */
243 function close() {
244 $this->mOpened = false;
245 if ( $this->mConn ) {
246 $ret = pg_close( $this->mConn );
247 $this->mConn = null;
248 return $ret;
249 } else {
250 return true;
251 }
252 }
253
254 protected function doQuery( $sql ) {
255 if ( function_exists( 'mb_convert_encoding' ) ) {
256 $sql = mb_convert_encoding( $sql, 'UTF-8' );
257 }
258 $this->mLastResult = pg_query( $this->mConn, $sql );
259 $this->mAffectedRows = null; // use pg_affected_rows(mLastResult)
260 return $this->mLastResult;
261 }
262
263 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
264 return $this->query( $sql, $fname, true );
265 }
266
267 function freeResult( $res ) {
268 if ( $res instanceof ResultWrapper ) {
269 $res = $res->result;
270 }
271 wfSuppressWarnings();
272 $ok = pg_free_result( $res );
273 wfRestoreWarnings();
274 if ( !$ok ) {
275 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
276 }
277 }
278
279 function fetchObject( $res ) {
280 if ( $res instanceof ResultWrapper ) {
281 $res = $res->result;
282 }
283 wfSuppressWarnings();
284 $row = pg_fetch_object( $res );
285 wfRestoreWarnings();
286 # @todo FIXME: HACK HACK HACK HACK debug
287
288 # @todo hashar: not sure if the following test really trigger if the object
289 # fetching failed.
290 if( pg_last_error( $this->mConn ) ) {
291 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
292 }
293 return $row;
294 }
295
296 function fetchRow( $res ) {
297 if ( $res instanceof ResultWrapper ) {
298 $res = $res->result;
299 }
300 wfSuppressWarnings();
301 $row = pg_fetch_array( $res );
302 wfRestoreWarnings();
303 if( pg_last_error( $this->mConn ) ) {
304 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
305 }
306 return $row;
307 }
308
309 function numRows( $res ) {
310 if ( $res instanceof ResultWrapper ) {
311 $res = $res->result;
312 }
313 wfSuppressWarnings();
314 $n = pg_num_rows( $res );
315 wfRestoreWarnings();
316 if( pg_last_error( $this->mConn ) ) {
317 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
318 }
319 return $n;
320 }
321
322 function numFields( $res ) {
323 if ( $res instanceof ResultWrapper ) {
324 $res = $res->result;
325 }
326 return pg_num_fields( $res );
327 }
328
329 function fieldName( $res, $n ) {
330 if ( $res instanceof ResultWrapper ) {
331 $res = $res->result;
332 }
333 return pg_field_name( $res, $n );
334 }
335
336 /**
337 * This must be called after nextSequenceVal
338 * @return null
339 */
340 function insertId() {
341 return $this->mInsertId;
342 }
343
344 function dataSeek( $res, $row ) {
345 if ( $res instanceof ResultWrapper ) {
346 $res = $res->result;
347 }
348 return pg_result_seek( $res, $row );
349 }
350
351 function lastError() {
352 if ( $this->mConn ) {
353 return pg_last_error();
354 } else {
355 return 'No database connection';
356 }
357 }
358 function lastErrno() {
359 return pg_last_error() ? 1 : 0;
360 }
361
362 function affectedRows() {
363 if ( !is_null( $this->mAffectedRows ) ) {
364 // Forced result for simulated queries
365 return $this->mAffectedRows;
366 }
367 if( empty( $this->mLastResult ) ) {
368 return 0;
369 }
370 return pg_affected_rows( $this->mLastResult );
371 }
372
373 /**
374 * Estimate rows in dataset
375 * Returns estimated count, based on EXPLAIN output
376 * This is not necessarily an accurate estimate, so use sparingly
377 * Returns -1 if count cannot be found
378 * Takes same arguments as Database::select()
379 * @return int
380 */
381 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
382 $options['EXPLAIN'] = true;
383 $res = $this->select( $table, $vars, $conds, $fname, $options );
384 $rows = -1;
385 if ( $res ) {
386 $row = $this->fetchRow( $res );
387 $count = array();
388 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
389 $rows = $count[1];
390 }
391 }
392 return $rows;
393 }
394
395 /**
396 * Returns information about an index
397 * If errors are explicitly ignored, returns NULL on failure
398 * @return bool|null
399 */
400 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
401 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
402 $res = $this->query( $sql, $fname );
403 if ( !$res ) {
404 return null;
405 }
406 foreach ( $res as $row ) {
407 if ( $row->indexname == $this->indexName( $index ) ) {
408 return $row;
409 }
410 }
411 return false;
412 }
413
414 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
415 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
416 " AND indexdef LIKE 'CREATE UNIQUE%(" .
417 $this->strencode( $this->indexName( $index ) ) .
418 ")'";
419 $res = $this->query( $sql, $fname );
420 if ( !$res ) {
421 return null;
422 }
423 foreach ( $res as $row ) {
424 return true;
425 }
426 return false;
427 }
428
429 /**
430 * INSERT wrapper, inserts an array into a table
431 *
432 * $args may be a single associative array, or an array of these with numeric keys,
433 * for multi-row insert (Postgres version 8.2 and above only).
434 *
435 * @param $table String: Name of the table to insert to.
436 * @param $args Array: Items to insert into the table.
437 * @param $fname String: Name of the function, for profiling
438 * @param $options String or Array. Valid options: IGNORE
439 *
440 * @return bool Success of insert operation. IGNORE always returns true.
441 */
442 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
443 if ( !count( $args ) ) {
444 return true;
445 }
446
447 $table = $this->tableName( $table );
448 if (! isset( $this->numeric_version ) ) {
449 $this->getServerVersion();
450 }
451
452 if ( !is_array( $options ) ) {
453 $options = array( $options );
454 }
455
456 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
457 $multi = true;
458 $keys = array_keys( $args[0] );
459 } else {
460 $multi = false;
461 $keys = array_keys( $args );
462 }
463
464 // If IGNORE is set, we use savepoints to emulate mysql's behavior
465 $ignore = in_array( 'IGNORE', $options ) ? 'mw' : '';
466
467 // If we are not in a transaction, we need to be for savepoint trickery
468 $didbegin = 0;
469 if ( $ignore ) {
470 if ( !$this->mTrxLevel ) {
471 $this->begin( __METHOD__ );
472 $didbegin = 1;
473 }
474 $olde = error_reporting( 0 );
475 // For future use, we may want to track the number of actual inserts
476 // Right now, insert (all writes) simply return true/false
477 $numrowsinserted = 0;
478 }
479
480 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
481
482 if ( $multi ) {
483 if ( $this->numeric_version >= 8.2 && !$ignore ) {
484 $first = true;
485 foreach ( $args as $row ) {
486 if ( $first ) {
487 $first = false;
488 } else {
489 $sql .= ',';
490 }
491 $sql .= '(' . $this->makeList( $row ) . ')';
492 }
493 $res = (bool)$this->query( $sql, $fname, $ignore );
494 } else {
495 $res = true;
496 $origsql = $sql;
497 foreach ( $args as $row ) {
498 $tempsql = $origsql;
499 $tempsql .= '(' . $this->makeList( $row ) . ')';
500
501 if ( $ignore ) {
502 pg_query( $this->mConn, "SAVEPOINT $ignore" );
503 }
504
505 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
506
507 if ( $ignore ) {
508 $bar = pg_last_error();
509 if ( $bar != false ) {
510 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
511 } else {
512 pg_query( $this->mConn, "RELEASE $ignore" );
513 $numrowsinserted++;
514 }
515 }
516
517 // If any of them fail, we fail overall for this function call
518 // Note that this will be ignored if IGNORE is set
519 if ( !$tempres ) {
520 $res = false;
521 }
522 }
523 }
524 } else {
525 // Not multi, just a lone insert
526 if ( $ignore ) {
527 pg_query($this->mConn, "SAVEPOINT $ignore");
528 }
529
530 $sql .= '(' . $this->makeList( $args ) . ')';
531 $res = (bool)$this->query( $sql, $fname, $ignore );
532 if ( $ignore ) {
533 $bar = pg_last_error();
534 if ( $bar != false ) {
535 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
536 } else {
537 pg_query( $this->mConn, "RELEASE $ignore" );
538 $numrowsinserted++;
539 }
540 }
541 }
542 if ( $ignore ) {
543 $olde = error_reporting( $olde );
544 if ( $didbegin ) {
545 $this->commit( __METHOD__ );
546 }
547
548 // Set the affected row count for the whole operation
549 $this->mAffectedRows = $numrowsinserted;
550
551 // IGNORE always returns true
552 return true;
553 }
554
555 return $res;
556 }
557
558 /**
559 * INSERT SELECT wrapper
560 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
561 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
562 * $conds may be "*" to copy the whole table
563 * srcTable may be an array of tables.
564 * @todo FIXME: Implement this a little better (seperate select/insert)?
565 * @return bool
566 */
567 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
568 $insertOptions = array(), $selectOptions = array() )
569 {
570 $destTable = $this->tableName( $destTable );
571
572 // If IGNORE is set, we use savepoints to emulate mysql's behavior
573 $ignore = in_array( 'IGNORE', $insertOptions ) ? 'mw' : '';
574
575 if( is_array( $insertOptions ) ) {
576 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
577 }
578 if( !is_array( $selectOptions ) ) {
579 $selectOptions = array( $selectOptions );
580 }
581 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
582 if( is_array( $srcTable ) ) {
583 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
584 } else {
585 $srcTable = $this->tableName( $srcTable );
586 }
587
588 // If we are not in a transaction, we need to be for savepoint trickery
589 $didbegin = 0;
590 if ( $ignore ) {
591 if( !$this->mTrxLevel ) {
592 $this->begin( __METHOD__ );
593 $didbegin = 1;
594 }
595 $olde = error_reporting( 0 );
596 $numrowsinserted = 0;
597 pg_query( $this->mConn, "SAVEPOINT $ignore");
598 }
599
600 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
601 " SELECT $startOpts " . implode( ',', $varMap ) .
602 " FROM $srcTable $useIndex";
603
604 if ( $conds != '*' ) {
605 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
606 }
607
608 $sql .= " $tailOpts";
609
610 $res = (bool)$this->query( $sql, $fname, $ignore );
611 if( $ignore ) {
612 $bar = pg_last_error();
613 if( $bar != false ) {
614 pg_query( $this->mConn, "ROLLBACK TO $ignore" );
615 } else {
616 pg_query( $this->mConn, "RELEASE $ignore" );
617 $numrowsinserted++;
618 }
619 $olde = error_reporting( $olde );
620 if( $didbegin ) {
621 $this->commit( __METHOD__ );
622 }
623
624 // Set the affected row count for the whole operation
625 $this->mAffectedRows = $numrowsinserted;
626
627 // IGNORE always returns true
628 return true;
629 }
630
631 return $res;
632 }
633
634 function tableName( $name, $format = 'quoted' ) {
635 # Replace reserved words with better ones
636 switch( $name ) {
637 case 'user':
638 return 'mwuser';
639 case 'text':
640 return 'pagecontent';
641 default:
642 return parent::tableName( $name, $format );
643 }
644 }
645
646 /**
647 * Return the next in a sequence, save the value for retrieval via insertId()
648 * @return null
649 */
650 function nextSequenceValue( $seqName ) {
651 $safeseq = str_replace( "'", "''", $seqName );
652 $res = $this->query( "SELECT nextval('$safeseq')" );
653 $row = $this->fetchRow( $res );
654 $this->mInsertId = $row[0];
655 return $this->mInsertId;
656 }
657
658 /**
659 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
660 * @return
661 */
662 function currentSequenceValue( $seqName ) {
663 $safeseq = str_replace( "'", "''", $seqName );
664 $res = $this->query( "SELECT currval('$safeseq')" );
665 $row = $this->fetchRow( $res );
666 $currval = $row[0];
667 return $currval;
668 }
669
670 # Returns the size of a text field, or -1 for "unlimited"
671 function textFieldSize( $table, $field ) {
672 $table = $this->tableName( $table );
673 $sql = "SELECT t.typname as ftype,a.atttypmod as size
674 FROM pg_class c, pg_attribute a, pg_type t
675 WHERE relname='$table' AND a.attrelid=c.oid AND
676 a.atttypid=t.oid and a.attname='$field'";
677 $res =$this->query( $sql );
678 $row = $this->fetchObject( $res );
679 if ( $row->ftype == 'varchar' ) {
680 $size = $row->size - 4;
681 } else {
682 $size = $row->size;
683 }
684 return $size;
685 }
686
687 function limitResult( $sql, $limit, $offset = false ) {
688 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ? " OFFSET {$offset} " : '' );
689 }
690
691 function wasDeadlock() {
692 return $this->lastErrno() == '40P01';
693 }
694
695 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
696 $newName = $this->addIdentifierQuotes( $newName );
697 $oldName = $this->addIdentifierQuotes( $oldName );
698 return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
699 }
700
701 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
702 global $wgDBmwschema;
703 $eschema = $this->addQuotes( $wgDBmwschema );
704 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
705
706 $endArray = array();
707
708 foreach( $result as $table ) {
709 $vars = get_object_vars($table);
710 $table = array_pop( $vars );
711 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
712 $endArray[] = $table;
713 }
714 }
715
716 return $endArray;
717 }
718
719 function timestamp( $ts = 0 ) {
720 return wfTimestamp( TS_POSTGRES, $ts );
721 }
722
723 /**
724 * Return aggregated value function call
725 */
726 function aggregateValue( $valuedata, $valuename = 'value' ) {
727 return $valuedata;
728 }
729
730 /**
731 * @return string wikitext of a link to the server software's web site
732 */
733 public static function getSoftwareLink() {
734 return '[http://www.postgresql.org/ PostgreSQL]';
735 }
736
737 /**
738 * @return string Version information from the database
739 */
740 function getServerVersion() {
741 if ( !isset( $this->numeric_version ) ) {
742 $versionInfo = pg_version( $this->mConn );
743 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
744 // Old client, abort install
745 $this->numeric_version = '7.3 or earlier';
746 } elseif ( isset( $versionInfo['server'] ) ) {
747 // Normal client
748 $this->numeric_version = $versionInfo['server'];
749 } else {
750 // Bug 16937: broken pgsql extension from PHP<5.3
751 $this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
752 }
753 }
754 return $this->numeric_version;
755 }
756
757 /**
758 * Query whether a given relation exists (in the given schema, or the
759 * default mw one if not given)
760 * @return bool
761 */
762 function relationExists( $table, $types, $schema = false ) {
763 global $wgDBmwschema;
764 if ( !is_array( $types ) ) {
765 $types = array( $types );
766 }
767 if ( !$schema ) {
768 $schema = $wgDBmwschema;
769 }
770 $table = $this->tableName( $table, 'raw' );
771 $etable = $this->addQuotes( $table );
772 $eschema = $this->addQuotes( $schema );
773 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
774 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
775 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
776 $res = $this->query( $SQL );
777 $count = $res ? $res->numRows() : 0;
778 return (bool)$count;
779 }
780
781 /**
782 * For backward compatibility, this function checks both tables and
783 * views.
784 * @return bool
785 */
786 function tableExists( $table, $fname = __METHOD__, $schema = false ) {
787 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
788 }
789
790 function sequenceExists( $sequence, $schema = false ) {
791 return $this->relationExists( $sequence, 'S', $schema );
792 }
793
794 function triggerExists( $table, $trigger ) {
795 global $wgDBmwschema;
796
797 $q = <<<SQL
798 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
799 WHERE relnamespace=pg_namespace.oid AND relkind='r'
800 AND tgrelid=pg_class.oid
801 AND nspname=%s AND relname=%s AND tgname=%s
802 SQL;
803 $res = $this->query(
804 sprintf(
805 $q,
806 $this->addQuotes( $wgDBmwschema ),
807 $this->addQuotes( $table ),
808 $this->addQuotes( $trigger )
809 )
810 );
811 if ( !$res ) {
812 return null;
813 }
814 $rows = $res->numRows();
815 return $rows;
816 }
817
818 function ruleExists( $table, $rule ) {
819 global $wgDBmwschema;
820 $exists = $this->selectField( 'pg_rules', 'rulename',
821 array(
822 'rulename' => $rule,
823 'tablename' => $table,
824 'schemaname' => $wgDBmwschema
825 )
826 );
827 return $exists === $rule;
828 }
829
830 function constraintExists( $table, $constraint ) {
831 global $wgDBmwschema;
832 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
833 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
834 $this->addQuotes( $wgDBmwschema ),
835 $this->addQuotes( $table ),
836 $this->addQuotes( $constraint )
837 );
838 $res = $this->query( $SQL );
839 if ( !$res ) {
840 return null;
841 }
842 $rows = $res->numRows();
843 return $rows;
844 }
845
846 /**
847 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
848 * @return bool
849 */
850 function schemaExists( $schema ) {
851 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
852 array( 'nspname' => $schema ), __METHOD__ );
853 return (bool)$exists;
854 }
855
856 /**
857 * Returns true if a given role (i.e. user) exists, false otherwise.
858 * @return bool
859 */
860 function roleExists( $roleName ) {
861 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
862 array( 'rolname' => $roleName ), __METHOD__ );
863 return (bool)$exists;
864 }
865
866 function fieldInfo( $table, $field ) {
867 return PostgresField::fromText( $this, $table, $field );
868 }
869
870 /**
871 * pg_field_type() wrapper
872 * @return string
873 */
874 function fieldType( $res, $index ) {
875 if ( $res instanceof ResultWrapper ) {
876 $res = $res->result;
877 }
878 return pg_field_type( $res, $index );
879 }
880
881 /* Not even sure why this is used in the main codebase... */
882 function limitResultForUpdate( $sql, $num ) {
883 return $sql;
884 }
885
886 /**
887 * @param $b
888 * @return Blob
889 */
890 function encodeBlob( $b ) {
891 return new Blob( pg_escape_bytea( $this->mConn, $b ) );
892 }
893
894 function decodeBlob( $b ) {
895 if ( $b instanceof Blob ) {
896 $b = $b->fetch();
897 }
898 return pg_unescape_bytea( $b );
899 }
900
901 function strencode( $s ) { # Should not be called by us
902 return pg_escape_string( $this->mConn, $s );
903 }
904
905 /**
906 * @param $s null|bool|Blob
907 * @return int|string
908 */
909 function addQuotes( $s ) {
910 if ( is_null( $s ) ) {
911 return 'NULL';
912 } elseif ( is_bool( $s ) ) {
913 return intval( $s );
914 } elseif ( $s instanceof Blob ) {
915 return "'" . $s->fetch( $s ) . "'";
916 }
917 return "'" . pg_escape_string( $this->mConn, $s ) . "'";
918 }
919
920 /**
921 * Postgres specific version of replaceVars.
922 * Calls the parent version in Database.php
923 *
924 * @private
925 *
926 * @param $ins String: SQL string, read from a stream (usually tables.sql)
927 *
928 * @return string SQL string
929 */
930 protected function replaceVars( $ins ) {
931 $ins = parent::replaceVars( $ins );
932
933 if ( $this->numeric_version >= 8.3 ) {
934 // Thanks for not providing backwards-compatibility, 8.3
935 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
936 }
937
938 if ( $this->numeric_version <= 8.1 ) { // Our minimum version
939 $ins = str_replace( 'USING gin', 'USING gist', $ins );
940 }
941
942 return $ins;
943 }
944
945 /**
946 * Various select options
947 *
948 * @private
949 *
950 * @param $options Array: an associative array of options to be turned into
951 * an SQL query, valid keys are listed in the function.
952 * @return array
953 */
954 function makeSelectOptions( $options ) {
955 $preLimitTail = $postLimitTail = '';
956 $startOpts = $useIndex = '';
957
958 $noKeyOptions = array();
959 foreach ( $options as $key => $option ) {
960 if ( is_numeric( $key ) ) {
961 $noKeyOptions[$option] = true;
962 }
963 }
964
965 if ( isset( $options['GROUP BY'] ) ) {
966 $gb = is_array( $options['GROUP BY'] )
967 ? implode( ',', $options['GROUP BY'] )
968 : $options['GROUP BY'];
969 $preLimitTail .= " GROUP BY {$gb}";
970 }
971
972 if ( isset( $options['HAVING'] ) ) {
973 $preLimitTail .= " HAVING {$options['HAVING']}";
974 }
975
976 if ( isset( $options['ORDER BY'] ) ) {
977 $ob = is_array( $options['ORDER BY'] )
978 ? implode( ',', $options['ORDER BY'] )
979 : $options['ORDER BY'];
980 $preLimitTail .= " ORDER BY {$ob}";
981 }
982
983 //if ( isset( $options['LIMIT'] ) ) {
984 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
985 // isset( $options['OFFSET'] ) ? $options['OFFSET']
986 // : false );
987 //}
988
989 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
990 $postLimitTail .= ' FOR UPDATE';
991 }
992 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
993 $postLimitTail .= ' LOCK IN SHARE MODE';
994 }
995 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
996 $startOpts .= 'DISTINCT';
997 }
998
999 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1000 }
1001
1002 function setFakeMaster( $enabled = true ) {}
1003
1004 function getDBname() {
1005 return $this->mDBname;
1006 }
1007
1008 function getServer() {
1009 return $this->mServer;
1010 }
1011
1012 function buildConcat( $stringList ) {
1013 return implode( ' || ', $stringList );
1014 }
1015
1016 public function getSearchEngine() {
1017 return 'SearchPostgres';
1018 }
1019
1020 public function streamStatementEnd( &$sql, &$newLine ) {
1021 # Allow dollar quoting for function declarations
1022 if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
1023 if ( $this->delimiter ) {
1024 $this->delimiter = false;
1025 }
1026 else {
1027 $this->delimiter = ';';
1028 }
1029 }
1030 return parent::streamStatementEnd( $sql, $newLine );
1031 }
1032 } // end DatabasePostgres class