3 * This is the Postgres database abstraction layer.
9 class PostgresField
implements Field
{
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
14 * @param $db DatabaseBase
17 * @return null|PostgresField
19 static function fromText( $db, $table, $field ) {
24 attnotnull, attlen, COALESCE(conname, '') AS conname,
25 COALESCE(condeferred, 'f') AS deferred,
26 COALESCE(condeferrable, 'f') AS deferrable,
27 CASE WHEN typname = 'int2' THEN 'smallint'
28 WHEN typname = 'int4' THEN 'integer'
29 WHEN typname = 'int8' THEN 'bigint'
30 WHEN typname = 'bpchar' THEN 'char'
31 ELSE typname END AS typname
33 JOIN pg_namespace n ON (n.oid = c.relnamespace)
34 JOIN pg_attribute a ON (a.attrelid = c.oid)
35 JOIN pg_type t ON (t.oid = a.atttypid)
36 LEFT JOIN pg_constraint o ON (o.conrelid = c.oid AND a.attnum = ANY(o.conkey) AND o.contype = 'f')
43 $table = $db->tableName( $table );
46 $db->addQuotes( $wgDBmwschema ),
47 $db->addQuotes( $table ),
48 $db->addQuotes( $field )
51 $row = $db->fetchObject( $res );
55 $n = new PostgresField
;
56 $n->type
= $row->typname
;
57 $n->nullable
= ( $row->attnotnull
== 'f' );
59 $n->tablename
= $table;
60 $n->max_length
= $row->attlen
;
61 $n->deferrable
= ( $row->deferrable
== 't' );
62 $n->deferred
= ( $row->deferred
== 't' );
63 $n->conname
= $row->conname
;
71 function tableName() {
72 return $this->tablename
;
79 function isNullable() {
80 return $this->nullable
;
83 function maxLength() {
84 return $this->max_length
;
87 function is_deferrable() {
88 return $this->deferrable
;
91 function is_deferred() {
92 return $this->deferred
;
96 return $this->conname
;
104 class DatabasePostgres
extends DatabaseBase
{
105 var $mInsertId = null;
106 var $mLastResult = null;
107 var $numeric_version = null;
108 var $mAffectedRows = null;
114 function cascadingDeletes() {
117 function cleanupTriggers() {
120 function strictIPs() {
123 function realTimestamps() {
126 function implicitGroupby() {
129 function implicitOrderby() {
132 function searchableIPs() {
135 function functionalIndexes() {
139 function hasConstraint( $name ) {
140 global $wgDBmwschema;
141 $SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
142 pg_escape_string( $this->mConn
, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn
, $wgDBmwschema ) ."'";
143 $res = $this->doQuery( $SQL );
144 return $this->numRows( $res );
148 * Usually aborts on failure
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" );
158 if ( !strlen( $user ) ) { # e.g. the class is being loaded
163 $this->mServer
= $server;
165 $this->mUser
= $user;
166 $this->mPassword
= $password;
167 $this->mDBname
= $dbName;
169 $connectVars = array(
172 'password' => $password
174 if ( $server != false && $server != '' ) {
175 $connectVars['host'] = $server;
177 if ( $port != false && $port != '' ) {
178 $connectVars['port'] = $port;
180 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
182 $this->installErrorHandler();
183 $this->mConn
= pg_connect( $connectString );
184 $phpError = $this->restoreErrorHandler();
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, $phpError );
193 $this->mOpened
= true;
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'" );
201 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
202 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
203 $this->query( "SET timezone = 'GMT'", __METHOD__
);
205 global $wgDBmwschema;
206 if ( $this->schemaExists( $wgDBmwschema ) ) {
207 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
208 $this->doQuery( "SET search_path = $safeschema" );
210 $this->doQuery( "SET search_path = public" );
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
221 function selectDB( $db ) {
222 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
225 function makeConnectionString( $vars ) {
227 foreach ( $vars as $name => $value ) {
228 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
234 * Closes a database connection, if it is open
235 * Returns success, true if already closed
238 $this->mOpened
= false;
239 if ( $this->mConn
) {
240 return pg_close( $this->mConn
);
246 function doQuery( $sql ) {
247 if ( function_exists( 'mb_convert_encoding' ) ) {
248 $sql = mb_convert_encoding( $sql, 'UTF-8' );
250 $this->mLastResult
= pg_query( $this->mConn
, $sql );
251 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
252 return $this->mLastResult
;
255 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
256 return $this->query( $sql, $fname, true );
259 function freeResult( $res ) {
260 if ( $res instanceof ResultWrapper
) {
263 if ( !@pg_free_result
( $res ) ) {
264 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
268 function fetchObject( $res ) {
269 if ( $res instanceof ResultWrapper
) {
272 @$row = pg_fetch_object( $res );
273 # FIXME: HACK HACK HACK HACK debug
276 # hashar : not sure if the following test really trigger if the object
278 if( pg_last_error( $this->mConn
) ) {
279 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
284 function fetchRow( $res ) {
285 if ( $res instanceof ResultWrapper
) {
288 @$row = pg_fetch_array( $res );
289 if( pg_last_error( $this->mConn
) ) {
290 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
295 function numRows( $res ) {
296 if ( $res instanceof ResultWrapper
) {
299 @$n = pg_num_rows( $res );
300 if( pg_last_error( $this->mConn
) ) {
301 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
306 function numFields( $res ) {
307 if ( $res instanceof ResultWrapper
) {
310 return pg_num_fields( $res );
313 function fieldName( $res, $n ) {
314 if ( $res instanceof ResultWrapper
) {
317 return pg_field_name( $res, $n );
321 * This must be called after nextSequenceVal
323 function insertId() {
324 return $this->mInsertId
;
327 function dataSeek( $res, $row ) {
328 if ( $res instanceof ResultWrapper
) {
331 return pg_result_seek( $res, $row );
334 function lastError() {
335 if ( $this->mConn
) {
336 return pg_last_error();
338 return 'No database connection';
341 function lastErrno() {
342 return pg_last_error() ?
1 : 0;
345 function affectedRows() {
346 if ( !is_null( $this->mAffectedRows
) ) {
347 // Forced result for simulated queries
348 return $this->mAffectedRows
;
350 if( empty( $this->mLastResult
) ) {
353 return pg_affected_rows( $this->mLastResult
);
357 * Estimate rows in dataset
358 * Returns estimated count, based on EXPLAIN output
359 * This is not necessarily an accurate estimate, so use sparingly
360 * Returns -1 if count cannot be found
361 * Takes same arguments as Database::select()
363 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
364 $options['EXPLAIN'] = true;
365 $res = $this->select( $table, $vars, $conds, $fname, $options );
368 $row = $this->fetchRow( $res );
370 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
378 * Returns information about an index
379 * If errors are explicitly ignored, returns NULL on failure
381 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
382 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
383 $res = $this->query( $sql, $fname );
387 foreach ( $res as $row ) {
388 if ( $row->indexname
== $this->indexName( $index ) ) {
395 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
396 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
397 " AND indexdef LIKE 'CREATE UNIQUE%(" .
398 $this->strencode( $this->indexName( $index ) ) .
400 $res = $this->query( $sql, $fname );
404 foreach ( $res as $row ) {
411 * INSERT wrapper, inserts an array into a table
413 * $args may be a single associative array, or an array of these with numeric keys,
414 * for multi-row insert (Postgres version 8.2 and above only).
416 * @param $table String: Name of the table to insert to.
417 * @param $args Array: Items to insert into the table.
418 * @param $fname String: Name of the function, for profiling
419 * @param $options String or Array. Valid options: IGNORE
421 * @return bool Success of insert operation. IGNORE always returns true.
423 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
424 if ( !count( $args ) ) {
428 $table = $this->tableName( $table );
429 if (! isset( $this->numeric_version
) ) {
430 $this->getServerVersion();
433 if ( !is_array( $options ) ) {
434 $options = array( $options );
437 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
439 $keys = array_keys( $args[0] );
442 $keys = array_keys( $args );
445 // If IGNORE is set, we use savepoints to emulate mysql's behavior
446 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
448 // If we are not in a transaction, we need to be for savepoint trickery
451 if ( !$this->mTrxLevel
) {
455 $olde = error_reporting( 0 );
456 // For future use, we may want to track the number of actual inserts
457 // Right now, insert (all writes) simply return true/false
458 $numrowsinserted = 0;
461 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
464 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
466 foreach ( $args as $row ) {
472 $sql .= '(' . $this->makeList( $row ) . ')';
474 $res = (bool)$this->query( $sql, $fname, $ignore );
478 foreach ( $args as $row ) {
480 $tempsql .= '(' . $this->makeList( $row ) . ')';
483 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
486 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
489 $bar = pg_last_error();
490 if ( $bar != false ) {
491 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
493 pg_query( $this->mConn
, "RELEASE $ignore" );
498 // If any of them fail, we fail overall for this function call
499 // Note that this will be ignored if IGNORE is set
506 // Not multi, just a lone insert
508 pg_query($this->mConn
, "SAVEPOINT $ignore");
511 $sql .= '(' . $this->makeList( $args ) . ')';
512 $res = (bool)$this->query( $sql, $fname, $ignore );
514 $bar = pg_last_error();
515 if ( $bar != false ) {
516 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
518 pg_query( $this->mConn
, "RELEASE $ignore" );
524 $olde = error_reporting( $olde );
529 // Set the affected row count for the whole operation
530 $this->mAffectedRows
= $numrowsinserted;
532 // IGNORE always returns true
540 * INSERT SELECT wrapper
541 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
542 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
543 * $conds may be "*" to copy the whole table
544 * srcTable may be an array of tables.
545 * @todo FIXME: implement this a little better (seperate select/insert)?
547 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
548 $insertOptions = array(), $selectOptions = array() )
550 $destTable = $this->tableName( $destTable );
552 // If IGNORE is set, we use savepoints to emulate mysql's behavior
553 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
555 if( is_array( $insertOptions ) ) {
556 $insertOptions = implode( ' ', $insertOptions );
558 if( !is_array( $selectOptions ) ) {
559 $selectOptions = array( $selectOptions );
561 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
562 if( is_array( $srcTable ) ) {
563 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
565 $srcTable = $this->tableName( $srcTable );
568 // If we are not in a transaction, we need to be for savepoint trickery
571 if( !$this->mTrxLevel
) {
575 $olde = error_reporting( 0 );
576 $numrowsinserted = 0;
577 pg_query( $this->mConn
, "SAVEPOINT $ignore");
580 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
581 " SELECT $startOpts " . implode( ',', $varMap ) .
582 " FROM $srcTable $useIndex";
584 if ( $conds != '*' ) {
585 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
588 $sql .= " $tailOpts";
590 $res = (bool)$this->query( $sql, $fname, $ignore );
592 $bar = pg_last_error();
593 if( $bar != false ) {
594 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
596 pg_query( $this->mConn
, "RELEASE $ignore" );
599 $olde = error_reporting( $olde );
604 // Set the affected row count for the whole operation
605 $this->mAffectedRows
= $numrowsinserted;
607 // IGNORE always returns true
614 function tableName( $name ) {
615 # Replace reserved words with better ones
620 return 'pagecontent';
627 * Return the next in a sequence, save the value for retrieval via insertId()
629 function nextSequenceValue( $seqName ) {
630 $safeseq = str_replace( "'", "''", $seqName );
631 $res = $this->query( "SELECT nextval('$safeseq')" );
632 $row = $this->fetchRow( $res );
633 $this->mInsertId
= $row[0];
634 return $this->mInsertId
;
638 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
640 function currentSequenceValue( $seqName ) {
641 $safeseq = str_replace( "'", "''", $seqName );
642 $res = $this->query( "SELECT currval('$safeseq')" );
643 $row = $this->fetchRow( $res );
649 * REPLACE query wrapper
650 * Postgres simulates this with a DELETE followed by INSERT
651 * $row is the row to insert, an associative array
652 * $uniqueIndexes is an array of indexes. Each element may be either a
653 * field name or an array of field names
655 * It may be more efficient to leave off unique indexes which are unlikely to collide.
656 * However if you do this, you run the risk of encountering errors which wouldn't have
659 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
660 $table = $this->tableName( $table );
662 if ( count( $rows ) == 0 ) {
667 if ( !is_array( reset( $rows ) ) ) {
668 $rows = array( $rows );
671 foreach( $rows as $row ) {
672 # Delete rows which collide
673 if ( $uniqueIndexes ) {
674 $sql = "DELETE FROM $table WHERE ";
676 foreach ( $uniqueIndexes as $index ) {
683 if ( is_array( $index ) ) {
685 foreach ( $index as $col ) {
691 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
694 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
698 $this->query( $sql, $fname );
702 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
703 $this->makeList( $row, LIST_COMMA
) . ')';
704 $this->query( $sql, $fname );
708 # DELETE where the condition is a join
709 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
711 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
714 $delTable = $this->tableName( $delTable );
715 $joinTable = $this->tableName( $joinTable );
716 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
717 if ( $conds != '*' ) {
718 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
722 $this->query( $sql, $fname );
725 # Returns the size of a text field, or -1 for "unlimited"
726 function textFieldSize( $table, $field ) {
727 $table = $this->tableName( $table );
728 $sql = "SELECT t.typname as ftype,a.atttypmod as size
729 FROM pg_class c, pg_attribute a, pg_type t
730 WHERE relname='$table' AND a.attrelid=c.oid AND
731 a.atttypid=t.oid and a.attname='$field'";
732 $res =$this->query( $sql );
733 $row = $this->fetchObject( $res );
734 if ( $row->ftype
== 'varchar' ) {
735 $size = $row->size
- 4;
742 function limitResult( $sql, $limit, $offset = false ) {
743 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
746 function wasDeadlock() {
747 return $this->lastErrno() == '40P01';
750 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
751 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
754 function timestamp( $ts = 0 ) {
755 return wfTimestamp( TS_POSTGRES
, $ts );
759 * Return aggregated value function call
761 function aggregateValue( $valuedata, $valuename = 'value' ) {
765 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
766 // Ignore errors during error handling to avoid infinite recursion
767 $ignore = $this->ignoreErrors( true );
768 $this->mErrorCount++
;
770 if ( $ignore ||
$tempIgnore ) {
771 wfDebug( "SQL ERROR (ignored): $error\n" );
772 $this->ignoreErrors( $ignore );
774 $message = "A database error has occurred. Did you forget to run maintenance/update.php after upgrading? See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
776 "Function: $fname\n" .
777 "Error: $errno $error\n";
778 throw new DBUnexpectedError( $this, $message );
783 * @return string wikitext of a link to the server software's web site
785 public static function getSoftwareLink() {
786 return '[http://www.postgresql.org/ PostgreSQL]';
790 * @return string Version information from the database
792 function getServerVersion() {
793 if ( !isset( $this->numeric_version
) ) {
794 $versionInfo = pg_version( $this->mConn
);
795 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
796 // Old client, abort install
797 $this->numeric_version
= '7.3 or earlier';
798 } elseif ( isset( $versionInfo['server'] ) ) {
800 $this->numeric_version
= $versionInfo['server'];
802 // Bug 16937: broken pgsql extension from PHP<5.3
803 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
806 return $this->numeric_version
;
810 * Query whether a given relation exists (in the given schema, or the
811 * default mw one if not given)
813 function relationExists( $table, $types, $schema = false ) {
814 global $wgDBmwschema;
815 if ( !is_array( $types ) ) {
816 $types = array( $types );
819 $schema = $wgDBmwschema;
821 $table = $this->tableName( $table );
822 $etable = $this->addQuotes( $table );
823 $eschema = $this->addQuotes( $schema );
824 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
825 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
826 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
827 $res = $this->query( $SQL );
828 $count = $res ?
$res->numRows() : 0;
833 * For backward compatibility, this function checks both tables and
836 function tableExists( $table, $schema = false ) {
837 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
840 function sequenceExists( $sequence, $schema = false ) {
841 return $this->relationExists( $sequence, 'S', $schema );
844 function triggerExists( $table, $trigger ) {
845 global $wgDBmwschema;
848 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
849 WHERE relnamespace=pg_namespace.oid AND relkind='r'
850 AND tgrelid=pg_class.oid
851 AND nspname=%s AND relname=%s AND tgname=%s
856 $this->addQuotes( $wgDBmwschema ),
857 $this->addQuotes( $table ),
858 $this->addQuotes( $trigger )
864 $rows = $res->numRows();
868 function ruleExists( $table, $rule ) {
869 global $wgDBmwschema;
870 $exists = $this->selectField( 'pg_rules', 'rulename',
873 'tablename' => $table,
874 'schemaname' => $wgDBmwschema
877 return $exists === $rule;
880 function constraintExists( $table, $constraint ) {
881 global $wgDBmwschema;
882 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
883 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
884 $this->addQuotes( $wgDBmwschema ),
885 $this->addQuotes( $table ),
886 $this->addQuotes( $constraint )
888 $res = $this->query( $SQL );
892 $rows = $res->numRows();
897 * Query whether a given schema exists. Returns the name of the owner
899 function schemaExists( $schema ) {
900 $eschema = str_replace( "'", "''", $schema );
901 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
902 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
903 $res = $this->query( $SQL );
904 if ( $res && $res->numRows() ) {
905 $row = $res->fetchObject();
906 $owner = $row->rolname
;
913 function fieldInfo( $table, $field ) {
914 return PostgresField
::fromText( $this, $table, $field );
918 * pg_field_type() wrapper
920 function fieldType( $res, $index ) {
921 if ( $res instanceof ResultWrapper
) {
924 return pg_field_type( $res, $index );
927 /* Not even sure why this is used in the main codebase... */
928 function limitResultForUpdate( $sql, $num ) {
932 function encodeBlob( $b ) {
933 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
936 function decodeBlob( $b ) {
937 if ( $b instanceof Blob
) {
940 return pg_unescape_bytea( $b );
943 function strencode( $s ) { # Should not be called by us
944 return pg_escape_string( $this->mConn
, $s );
947 function addQuotes( $s ) {
948 if ( is_null( $s ) ) {
950 } elseif ( is_bool( $s ) ) {
952 } elseif ( $s instanceof Blob
) {
953 return "'" . $s->fetch( $s ) . "'";
955 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
959 * Postgres specific version of replaceVars.
960 * Calls the parent version in Database.php
964 * @param $ins String: SQL string, read from a stream (usually tables.sql)
966 * @return string SQL string
968 protected function replaceVars( $ins ) {
969 $ins = parent
::replaceVars( $ins );
971 if ( $this->numeric_version
>= 8.3 ) {
972 // Thanks for not providing backwards-compatibility, 8.3
973 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
976 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
977 $ins = str_replace( 'USING gin', 'USING gist', $ins );
984 * Various select options
988 * @param $options Array: an associative array of options to be turned into
989 * an SQL query, valid keys are listed in the function.
992 function makeSelectOptions( $options ) {
993 $preLimitTail = $postLimitTail = '';
994 $startOpts = $useIndex = '';
996 $noKeyOptions = array();
997 foreach ( $options as $key => $option ) {
998 if ( is_numeric( $key ) ) {
999 $noKeyOptions[$option] = true;
1003 if ( isset( $options['GROUP BY'] ) ) {
1004 $preLimitTail .= ' GROUP BY ' . $options['GROUP BY'];
1006 if ( isset( $options['HAVING'] ) ) {
1007 $preLimitTail .= " HAVING {$options['HAVING']}";
1009 if ( isset( $options['ORDER BY'] ) ) {
1010 $preLimitTail .= ' ORDER BY ' . $options['ORDER BY'];
1013 //if ( isset( $options['LIMIT'] ) ) {
1014 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1015 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1019 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1020 $postLimitTail .= ' FOR UPDATE';
1022 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1023 $postLimitTail .= ' LOCK IN SHARE MODE';
1025 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1026 $startOpts .= 'DISTINCT';
1029 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1032 function setFakeMaster( $enabled = true ) {}
1034 function getDBname() {
1035 return $this->mDBname
;
1038 function getServer() {
1039 return $this->mServer
;
1042 function buildConcat( $stringList ) {
1043 return implode( ' || ', $stringList );
1046 public function getSearchEngine() {
1047 return 'SearchPostgres';
1049 } // end DatabasePostgres class