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