3 * This is the Postgres database abstraction layer.
9 class PostgresField
implements Field
{
10 private $name, $tablename, $type, $nullable, $max_length, $deferred, $deferrable, $conname;
13 * @param $db DatabaseBase
16 * @return null|PostgresField
18 static function fromText( $db, $table, $field ) {
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
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')
42 $table = $db->tableName( $table, false );
45 $db->addQuotes( $wgDBmwschema ),
46 $db->addQuotes( $table ),
47 $db->addQuotes( $field )
50 $row = $db->fetchObject( $res );
54 $n = new PostgresField
;
55 $n->type
= $row->typname
;
56 $n->nullable
= ( $row->attnotnull
== 'f' );
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
;
70 function tableName() {
71 return $this->tablename
;
78 function isNullable() {
79 return $this->nullable
;
82 function maxLength() {
83 return $this->max_length
;
86 function is_deferrable() {
87 return $this->deferrable
;
90 function is_deferred() {
91 return $this->deferred
;
95 return $this->conname
;
103 class DatabasePostgres
extends DatabaseBase
{
104 var $mInsertId = null;
105 var $mLastResult = null;
106 var $numeric_version = null;
107 var $mAffectedRows = null;
113 function cascadingDeletes() {
116 function cleanupTriggers() {
119 function strictIPs() {
122 function realTimestamps() {
125 function implicitGroupby() {
128 function implicitOrderby() {
131 function searchableIPs() {
134 function functionalIndexes() {
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 );
147 * Usually aborts on failure
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" );
157 if ( !strlen( $user ) ) { # e.g. the class is being loaded
162 $this->mServer
= $server;
164 $this->mUser
= $user;
165 $this->mPassword
= $password;
166 $this->mDBname
= $dbName;
168 $connectVars = array(
171 'password' => $password
173 if ( $server != false && $server != '' ) {
174 $connectVars['host'] = $server;
176 if ( $port != false && $port != '' ) {
177 $connectVars['port'] = $port;
179 $connectString = $this->makeConnectionString( $connectVars, PGSQL_CONNECT_FORCE_NEW
);
181 $this->installErrorHandler();
182 $this->mConn
= pg_connect( $connectString );
183 $phpError = $this->restoreErrorHandler();
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, $phpError );
192 $this->mOpened
= true;
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'" );
200 $this->query( "SET client_encoding='UTF8'", __METHOD__
);
201 $this->query( "SET datestyle = 'ISO, YMD'", __METHOD__
);
202 $this->query( "SET timezone = 'GMT'", __METHOD__
);
204 global $wgDBmwschema;
205 if ( $this->schemaExists( $wgDBmwschema ) ) {
206 $safeschema = $this->addIdentifierQuotes( $wgDBmwschema );
207 $this->doQuery( "SET search_path = $safeschema" );
209 $this->doQuery( "SET search_path = public" );
216 * Postgres doesn't support selectDB in the same way MySQL does. So if the
217 * DB name doesn't match the open connection, open a new one
220 function selectDB( $db ) {
221 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
224 function makeConnectionString( $vars ) {
226 foreach ( $vars as $name => $value ) {
227 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
233 * Closes a database connection, if it is open
234 * Returns success, true if already closed
237 $this->mOpened
= false;
238 if ( $this->mConn
) {
239 return pg_close( $this->mConn
);
245 function doQuery( $sql ) {
246 if ( function_exists( 'mb_convert_encoding' ) ) {
247 $sql = mb_convert_encoding( $sql, 'UTF-8' );
249 $this->mLastResult
= pg_query( $this->mConn
, $sql );
250 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
251 return $this->mLastResult
;
254 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
255 return $this->query( $sql, $fname, true );
258 function freeResult( $res ) {
259 if ( $res instanceof ResultWrapper
) {
262 if ( !@pg_free_result
( $res ) ) {
263 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
267 function fetchObject( $res ) {
268 if ( $res instanceof ResultWrapper
) {
271 @$row = pg_fetch_object( $res );
272 # @todo FIXME: HACK HACK HACK HACK debug
274 # @todo hashar: not sure if the following test really trigger if the object
276 if( pg_last_error( $this->mConn
) ) {
277 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
282 function fetchRow( $res ) {
283 if ( $res instanceof ResultWrapper
) {
286 @$row = pg_fetch_array( $res );
287 if( pg_last_error( $this->mConn
) ) {
288 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
293 function numRows( $res ) {
294 if ( $res instanceof ResultWrapper
) {
297 @$n = pg_num_rows( $res );
298 if( pg_last_error( $this->mConn
) ) {
299 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
304 function numFields( $res ) {
305 if ( $res instanceof ResultWrapper
) {
308 return pg_num_fields( $res );
311 function fieldName( $res, $n ) {
312 if ( $res instanceof ResultWrapper
) {
315 return pg_field_name( $res, $n );
319 * This must be called after nextSequenceVal
321 function insertId() {
322 return $this->mInsertId
;
325 function dataSeek( $res, $row ) {
326 if ( $res instanceof ResultWrapper
) {
329 return pg_result_seek( $res, $row );
332 function lastError() {
333 if ( $this->mConn
) {
334 return pg_last_error();
336 return 'No database connection';
339 function lastErrno() {
340 return pg_last_error() ?
1 : 0;
343 function affectedRows() {
344 if ( !is_null( $this->mAffectedRows
) ) {
345 // Forced result for simulated queries
346 return $this->mAffectedRows
;
348 if( empty( $this->mLastResult
) ) {
351 return pg_affected_rows( $this->mLastResult
);
355 * Estimate rows in dataset
356 * Returns estimated count, based on EXPLAIN output
357 * This is not necessarily an accurate estimate, so use sparingly
358 * Returns -1 if count cannot be found
359 * Takes same arguments as Database::select()
361 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
362 $options['EXPLAIN'] = true;
363 $res = $this->select( $table, $vars, $conds, $fname, $options );
366 $row = $this->fetchRow( $res );
368 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
376 * Returns information about an index
377 * If errors are explicitly ignored, returns NULL on failure
379 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
380 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
381 $res = $this->query( $sql, $fname );
385 foreach ( $res as $row ) {
386 if ( $row->indexname
== $this->indexName( $index ) ) {
393 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
394 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
395 " AND indexdef LIKE 'CREATE UNIQUE%(" .
396 $this->strencode( $this->indexName( $index ) ) .
398 $res = $this->query( $sql, $fname );
402 foreach ( $res as $row ) {
409 * INSERT wrapper, inserts an array into a table
411 * $args may be a single associative array, or an array of these with numeric keys,
412 * for multi-row insert (Postgres version 8.2 and above only).
414 * @param $table String: Name of the table to insert to.
415 * @param $args Array: Items to insert into the table.
416 * @param $fname String: Name of the function, for profiling
417 * @param $options String or Array. Valid options: IGNORE
419 * @return bool Success of insert operation. IGNORE always returns true.
421 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
422 if ( !count( $args ) ) {
426 $table = $this->tableName( $table );
427 if (! isset( $this->numeric_version
) ) {
428 $this->getServerVersion();
431 if ( !is_array( $options ) ) {
432 $options = array( $options );
435 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
437 $keys = array_keys( $args[0] );
440 $keys = array_keys( $args );
443 // If IGNORE is set, we use savepoints to emulate mysql's behavior
444 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
446 // If we are not in a transaction, we need to be for savepoint trickery
449 if ( !$this->mTrxLevel
) {
453 $olde = error_reporting( 0 );
454 // For future use, we may want to track the number of actual inserts
455 // Right now, insert (all writes) simply return true/false
456 $numrowsinserted = 0;
459 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
462 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
464 foreach ( $args as $row ) {
470 $sql .= '(' . $this->makeList( $row ) . ')';
472 $res = (bool)$this->query( $sql, $fname, $ignore );
476 foreach ( $args as $row ) {
478 $tempsql .= '(' . $this->makeList( $row ) . ')';
481 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
484 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
487 $bar = pg_last_error();
488 if ( $bar != false ) {
489 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
491 pg_query( $this->mConn
, "RELEASE $ignore" );
496 // If any of them fail, we fail overall for this function call
497 // Note that this will be ignored if IGNORE is set
504 // Not multi, just a lone insert
506 pg_query($this->mConn
, "SAVEPOINT $ignore");
509 $sql .= '(' . $this->makeList( $args ) . ')';
510 $res = (bool)$this->query( $sql, $fname, $ignore );
512 $bar = pg_last_error();
513 if ( $bar != false ) {
514 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
516 pg_query( $this->mConn
, "RELEASE $ignore" );
522 $olde = error_reporting( $olde );
527 // Set the affected row count for the whole operation
528 $this->mAffectedRows
= $numrowsinserted;
530 // IGNORE always returns true
538 * INSERT SELECT wrapper
539 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
540 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
541 * $conds may be "*" to copy the whole table
542 * srcTable may be an array of tables.
543 * @todo FIXME: Implement this a little better (seperate select/insert)?
545 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
546 $insertOptions = array(), $selectOptions = array() )
548 $destTable = $this->tableName( $destTable );
550 // If IGNORE is set, we use savepoints to emulate mysql's behavior
551 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
553 if( is_array( $insertOptions ) ) {
554 $insertOptions = implode( ' ', $insertOptions );
556 if( !is_array( $selectOptions ) ) {
557 $selectOptions = array( $selectOptions );
559 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
560 if( is_array( $srcTable ) ) {
561 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
563 $srcTable = $this->tableName( $srcTable );
566 // If we are not in a transaction, we need to be for savepoint trickery
569 if( !$this->mTrxLevel
) {
573 $olde = error_reporting( 0 );
574 $numrowsinserted = 0;
575 pg_query( $this->mConn
, "SAVEPOINT $ignore");
578 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
579 " SELECT $startOpts " . implode( ',', $varMap ) .
580 " FROM $srcTable $useIndex";
582 if ( $conds != '*' ) {
583 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
586 $sql .= " $tailOpts";
588 $res = (bool)$this->query( $sql, $fname, $ignore );
590 $bar = pg_last_error();
591 if( $bar != false ) {
592 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
594 pg_query( $this->mConn
, "RELEASE $ignore" );
597 $olde = error_reporting( $olde );
602 // Set the affected row count for the whole operation
603 $this->mAffectedRows
= $numrowsinserted;
605 // IGNORE always returns true
612 function tableName( $name, $quoted = true ) {
613 # Replace reserved words with better ones
618 return 'pagecontent';
620 return parent
::tableName( $name, $quoted );
625 * Return the next in a sequence, save the value for retrieval via insertId()
627 function nextSequenceValue( $seqName ) {
628 $safeseq = str_replace( "'", "''", $seqName );
629 $res = $this->query( "SELECT nextval('$safeseq')" );
630 $row = $this->fetchRow( $res );
631 $this->mInsertId
= $row[0];
632 return $this->mInsertId
;
636 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
638 function currentSequenceValue( $seqName ) {
639 $safeseq = str_replace( "'", "''", $seqName );
640 $res = $this->query( "SELECT currval('$safeseq')" );
641 $row = $this->fetchRow( $res );
647 * REPLACE query wrapper
648 * Postgres simulates this with a DELETE followed by INSERT
649 * $row is the row to insert, an associative array
650 * $uniqueIndexes is an array of indexes. Each element may be either a
651 * field name or an array of field names
653 * It may be more efficient to leave off unique indexes which are unlikely to collide.
654 * However if you do this, you run the risk of encountering errors which wouldn't have
657 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
658 $table = $this->tableName( $table );
660 if ( count( $rows ) == 0 ) {
665 if ( !is_array( reset( $rows ) ) ) {
666 $rows = array( $rows );
669 foreach( $rows as $row ) {
670 # Delete rows which collide
671 if ( $uniqueIndexes ) {
672 $sql = "DELETE FROM $table WHERE ";
674 foreach ( $uniqueIndexes as $index ) {
681 if ( is_array( $index ) ) {
683 foreach ( $index as $col ) {
689 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
692 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
696 $this->query( $sql, $fname );
700 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
701 $this->makeList( $row, LIST_COMMA
) . ')';
702 $this->query( $sql, $fname );
706 # DELETE where the condition is a join
707 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
709 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
712 $delTable = $this->tableName( $delTable );
713 $joinTable = $this->tableName( $joinTable );
714 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
715 if ( $conds != '*' ) {
716 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
720 $this->query( $sql, $fname );
723 # Returns the size of a text field, or -1 for "unlimited"
724 function textFieldSize( $table, $field ) {
725 $table = $this->tableName( $table );
726 $sql = "SELECT t.typname as ftype,a.atttypmod as size
727 FROM pg_class c, pg_attribute a, pg_type t
728 WHERE relname='$table' AND a.attrelid=c.oid AND
729 a.atttypid=t.oid and a.attname='$field'";
730 $res =$this->query( $sql );
731 $row = $this->fetchObject( $res );
732 if ( $row->ftype
== 'varchar' ) {
733 $size = $row->size
- 4;
740 function limitResult( $sql, $limit, $offset = false ) {
741 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
744 function wasDeadlock() {
745 return $this->lastErrno() == '40P01';
748 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
749 $newName = $this->addIdentifierQuotes( $newName );
750 $oldName = $this->addIdentifierQuotes( $oldName );
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, false );
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 $gb = is_array( $options['GROUP BY'] )
1005 ?
implode( ',', $options['GROUP BY'] )
1006 : $options['GROUP BY'];
1007 $preLimitTail .= " GROUP BY {$gb}";
1010 if ( isset( $options['HAVING'] ) ) {
1011 $preLimitTail .= " HAVING {$options['HAVING']}";
1014 if ( isset( $options['ORDER BY'] ) ) {
1015 $ob = is_array( $options['ORDER BY'] )
1016 ?
implode( ',', $options['ORDER BY'] )
1017 : $options['ORDER BY'];
1018 $preLimitTail .= " ORDER BY {$ob}";
1021 //if ( isset( $options['LIMIT'] ) ) {
1022 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1023 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1027 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1028 $postLimitTail .= ' FOR UPDATE';
1030 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1031 $postLimitTail .= ' LOCK IN SHARE MODE';
1033 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1034 $startOpts .= 'DISTINCT';
1037 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1040 function setFakeMaster( $enabled = true ) {}
1042 function getDBname() {
1043 return $this->mDBname
;
1046 function getServer() {
1047 return $this->mServer
;
1050 function buildConcat( $stringList ) {
1051 return implode( ' || ', $stringList );
1054 public function getSearchEngine() {
1055 return 'SearchPostgres';
1057 } // end DatabasePostgres class