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