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