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 # FIXME: HACK HACK HACK HACK debug
275 # hashar : not sure if the following test really trigger if the object
277 if( pg_last_error( $this->mConn
) ) {
278 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
283 function fetchRow( $res ) {
284 if ( $res instanceof ResultWrapper
) {
287 @$row = pg_fetch_array( $res );
288 if( pg_last_error( $this->mConn
) ) {
289 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
294 function numRows( $res ) {
295 if ( $res instanceof ResultWrapper
) {
298 @$n = pg_num_rows( $res );
299 if( pg_last_error( $this->mConn
) ) {
300 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
305 function numFields( $res ) {
306 if ( $res instanceof ResultWrapper
) {
309 return pg_num_fields( $res );
312 function fieldName( $res, $n ) {
313 if ( $res instanceof ResultWrapper
) {
316 return pg_field_name( $res, $n );
320 * This must be called after nextSequenceVal
322 function insertId() {
323 return $this->mInsertId
;
326 function dataSeek( $res, $row ) {
327 if ( $res instanceof ResultWrapper
) {
330 return pg_result_seek( $res, $row );
333 function lastError() {
334 if ( $this->mConn
) {
335 return pg_last_error();
337 return 'No database connection';
340 function lastErrno() {
341 return pg_last_error() ?
1 : 0;
344 function affectedRows() {
345 if ( !is_null( $this->mAffectedRows
) ) {
346 // Forced result for simulated queries
347 return $this->mAffectedRows
;
349 if( empty( $this->mLastResult
) ) {
352 return pg_affected_rows( $this->mLastResult
);
356 * Estimate rows in dataset
357 * Returns estimated count, based on EXPLAIN output
358 * This is not necessarily an accurate estimate, so use sparingly
359 * Returns -1 if count cannot be found
360 * Takes same arguments as Database::select()
362 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
363 $options['EXPLAIN'] = true;
364 $res = $this->select( $table, $vars, $conds, $fname, $options );
367 $row = $this->fetchRow( $res );
369 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
377 * Returns information about an index
378 * If errors are explicitly ignored, returns NULL on failure
380 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
381 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
382 $res = $this->query( $sql, $fname );
386 foreach ( $res as $row ) {
387 if ( $row->indexname
== $this->indexName( $index ) ) {
394 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
395 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
396 " AND indexdef LIKE 'CREATE UNIQUE%(" .
397 $this->strencode( $this->indexName( $index ) ) .
399 $res = $this->query( $sql, $fname );
403 foreach ( $res as $row ) {
410 * INSERT wrapper, inserts an array into a table
412 * $args may be a single associative array, or an array of these with numeric keys,
413 * for multi-row insert (Postgres version 8.2 and above only).
415 * @param $table String: Name of the table to insert to.
416 * @param $args Array: Items to insert into the table.
417 * @param $fname String: Name of the function, for profiling
418 * @param $options String or Array. Valid options: IGNORE
420 * @return bool Success of insert operation. IGNORE always returns true.
422 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
423 if ( !count( $args ) ) {
427 $table = $this->tableName( $table );
428 if (! isset( $this->numeric_version
) ) {
429 $this->getServerVersion();
432 if ( !is_array( $options ) ) {
433 $options = array( $options );
436 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
438 $keys = array_keys( $args[0] );
441 $keys = array_keys( $args );
444 // If IGNORE is set, we use savepoints to emulate mysql's behavior
445 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
447 // If we are not in a transaction, we need to be for savepoint trickery
450 if ( !$this->mTrxLevel
) {
454 $olde = error_reporting( 0 );
455 // For future use, we may want to track the number of actual inserts
456 // Right now, insert (all writes) simply return true/false
457 $numrowsinserted = 0;
460 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
463 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
465 foreach ( $args as $row ) {
471 $sql .= '(' . $this->makeList( $row ) . ')';
473 $res = (bool)$this->query( $sql, $fname, $ignore );
477 foreach ( $args as $row ) {
479 $tempsql .= '(' . $this->makeList( $row ) . ')';
482 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
485 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
488 $bar = pg_last_error();
489 if ( $bar != false ) {
490 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
492 pg_query( $this->mConn
, "RELEASE $ignore" );
497 // If any of them fail, we fail overall for this function call
498 // Note that this will be ignored if IGNORE is set
505 // Not multi, just a lone insert
507 pg_query($this->mConn
, "SAVEPOINT $ignore");
510 $sql .= '(' . $this->makeList( $args ) . ')';
511 $res = (bool)$this->query( $sql, $fname, $ignore );
513 $bar = pg_last_error();
514 if ( $bar != false ) {
515 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
517 pg_query( $this->mConn
, "RELEASE $ignore" );
523 $olde = error_reporting( $olde );
528 // Set the affected row count for the whole operation
529 $this->mAffectedRows
= $numrowsinserted;
531 // IGNORE always returns true
539 * INSERT SELECT wrapper
540 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
541 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
542 * $conds may be "*" to copy the whole table
543 * srcTable may be an array of tables.
544 * @todo FIXME: implement this a little better (seperate select/insert)?
546 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
547 $insertOptions = array(), $selectOptions = array() )
549 $destTable = $this->tableName( $destTable );
551 // If IGNORE is set, we use savepoints to emulate mysql's behavior
552 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
554 if( is_array( $insertOptions ) ) {
555 $insertOptions = implode( ' ', $insertOptions );
557 if( !is_array( $selectOptions ) ) {
558 $selectOptions = array( $selectOptions );
560 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
561 if( is_array( $srcTable ) ) {
562 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
564 $srcTable = $this->tableName( $srcTable );
567 // If we are not in a transaction, we need to be for savepoint trickery
570 if( !$this->mTrxLevel
) {
574 $olde = error_reporting( 0 );
575 $numrowsinserted = 0;
576 pg_query( $this->mConn
, "SAVEPOINT $ignore");
579 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
580 " SELECT $startOpts " . implode( ',', $varMap ) .
581 " FROM $srcTable $useIndex";
583 if ( $conds != '*' ) {
584 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
587 $sql .= " $tailOpts";
589 $res = (bool)$this->query( $sql, $fname, $ignore );
591 $bar = pg_last_error();
592 if( $bar != false ) {
593 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
595 pg_query( $this->mConn
, "RELEASE $ignore" );
598 $olde = error_reporting( $olde );
603 // Set the affected row count for the whole operation
604 $this->mAffectedRows
= $numrowsinserted;
606 // IGNORE always returns true
613 function tableName( $name, $quoted = true ) {
614 # Replace reserved words with better ones
619 return 'pagecontent';
621 return parent
::tableName( $name, $quoted );
626 * Return the next in a sequence, save the value for retrieval via insertId()
628 function nextSequenceValue( $seqName ) {
629 $safeseq = str_replace( "'", "''", $seqName );
630 $res = $this->query( "SELECT nextval('$safeseq')" );
631 $row = $this->fetchRow( $res );
632 $this->mInsertId
= $row[0];
633 return $this->mInsertId
;
637 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
639 function currentSequenceValue( $seqName ) {
640 $safeseq = str_replace( "'", "''", $seqName );
641 $res = $this->query( "SELECT currval('$safeseq')" );
642 $row = $this->fetchRow( $res );
648 * REPLACE query wrapper
649 * Postgres simulates this with a DELETE followed by INSERT
650 * $row is the row to insert, an associative array
651 * $uniqueIndexes is an array of indexes. Each element may be either a
652 * field name or an array of field names
654 * It may be more efficient to leave off unique indexes which are unlikely to collide.
655 * However if you do this, you run the risk of encountering errors which wouldn't have
658 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabasePostgres::replace' ) {
659 $table = $this->tableName( $table );
661 if ( count( $rows ) == 0 ) {
666 if ( !is_array( reset( $rows ) ) ) {
667 $rows = array( $rows );
670 foreach( $rows as $row ) {
671 # Delete rows which collide
672 if ( $uniqueIndexes ) {
673 $sql = "DELETE FROM $table WHERE ";
675 foreach ( $uniqueIndexes as $index ) {
682 if ( is_array( $index ) ) {
684 foreach ( $index as $col ) {
690 $sql .= $col.'=' . $this->addQuotes( $row[$col] );
693 $sql .= $index.'=' . $this->addQuotes( $row[$index] );
697 $this->query( $sql, $fname );
701 $sql = "INSERT INTO $table (" . $this->makeList( array_keys( $row ), LIST_NAMES
) .') VALUES (' .
702 $this->makeList( $row, LIST_COMMA
) . ')';
703 $this->query( $sql, $fname );
707 # DELETE where the condition is a join
708 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabasePostgres::deleteJoin' ) {
710 throw new DBUnexpectedError( $this, 'DatabasePostgres::deleteJoin() called with empty $conds' );
713 $delTable = $this->tableName( $delTable );
714 $joinTable = $this->tableName( $joinTable );
715 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
716 if ( $conds != '*' ) {
717 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
721 $this->query( $sql, $fname );
724 # Returns the size of a text field, or -1 for "unlimited"
725 function textFieldSize( $table, $field ) {
726 $table = $this->tableName( $table );
727 $sql = "SELECT t.typname as ftype,a.atttypmod as size
728 FROM pg_class c, pg_attribute a, pg_type t
729 WHERE relname='$table' AND a.attrelid=c.oid AND
730 a.atttypid=t.oid and a.attname='$field'";
731 $res =$this->query( $sql );
732 $row = $this->fetchObject( $res );
733 if ( $row->ftype
== 'varchar' ) {
734 $size = $row->size
- 4;
741 function limitResult( $sql, $limit, $offset = false ) {
742 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
745 function wasDeadlock() {
746 return $this->lastErrno() == '40P01';
749 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
750 $newName = $this->addIdentifierQuotes( $newName );
751 $oldName = $this->addIdentifierQuotes( $oldName );
752 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
755 function timestamp( $ts = 0 ) {
756 return wfTimestamp( TS_POSTGRES
, $ts );
760 * Return aggregated value function call
762 function aggregateValue( $valuedata, $valuename = 'value' ) {
766 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
767 // Ignore errors during error handling to avoid infinite recursion
768 $ignore = $this->ignoreErrors( true );
769 $this->mErrorCount++
;
771 if ( $ignore ||
$tempIgnore ) {
772 wfDebug( "SQL ERROR (ignored): $error\n" );
773 $this->ignoreErrors( $ignore );
775 $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" .
777 "Function: $fname\n" .
778 "Error: $errno $error\n";
779 throw new DBUnexpectedError( $this, $message );
784 * @return string wikitext of a link to the server software's web site
786 public static function getSoftwareLink() {
787 return '[http://www.postgresql.org/ PostgreSQL]';
791 * @return string Version information from the database
793 function getServerVersion() {
794 if ( !isset( $this->numeric_version
) ) {
795 $versionInfo = pg_version( $this->mConn
);
796 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
797 // Old client, abort install
798 $this->numeric_version
= '7.3 or earlier';
799 } elseif ( isset( $versionInfo['server'] ) ) {
801 $this->numeric_version
= $versionInfo['server'];
803 // Bug 16937: broken pgsql extension from PHP<5.3
804 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
807 return $this->numeric_version
;
811 * Query whether a given relation exists (in the given schema, or the
812 * default mw one if not given)
814 function relationExists( $table, $types, $schema = false ) {
815 global $wgDBmwschema;
816 if ( !is_array( $types ) ) {
817 $types = array( $types );
820 $schema = $wgDBmwschema;
822 $table = $this->tableName( $table, false );
823 $etable = $this->addQuotes( $table );
824 $eschema = $this->addQuotes( $schema );
825 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
826 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
827 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
828 $res = $this->query( $SQL );
829 $count = $res ?
$res->numRows() : 0;
834 * For backward compatibility, this function checks both tables and
837 function tableExists( $table, $schema = false ) {
838 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
841 function sequenceExists( $sequence, $schema = false ) {
842 return $this->relationExists( $sequence, 'S', $schema );
845 function triggerExists( $table, $trigger ) {
846 global $wgDBmwschema;
849 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
850 WHERE relnamespace=pg_namespace.oid AND relkind='r'
851 AND tgrelid=pg_class.oid
852 AND nspname=%s AND relname=%s AND tgname=%s
857 $this->addQuotes( $wgDBmwschema ),
858 $this->addQuotes( $table ),
859 $this->addQuotes( $trigger )
865 $rows = $res->numRows();
869 function ruleExists( $table, $rule ) {
870 global $wgDBmwschema;
871 $exists = $this->selectField( 'pg_rules', 'rulename',
874 'tablename' => $table,
875 'schemaname' => $wgDBmwschema
878 return $exists === $rule;
881 function constraintExists( $table, $constraint ) {
882 global $wgDBmwschema;
883 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
884 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
885 $this->addQuotes( $wgDBmwschema ),
886 $this->addQuotes( $table ),
887 $this->addQuotes( $constraint )
889 $res = $this->query( $SQL );
893 $rows = $res->numRows();
898 * Query whether a given schema exists. Returns the name of the owner
900 function schemaExists( $schema ) {
901 $eschema = str_replace( "'", "''", $schema );
902 $SQL = "SELECT rolname FROM pg_catalog.pg_namespace n, pg_catalog.pg_roles r "
903 ."WHERE n.nspowner=r.oid AND n.nspname = '$eschema'";
904 $res = $this->query( $SQL );
905 if ( $res && $res->numRows() ) {
906 $row = $res->fetchObject();
907 $owner = $row->rolname
;
914 function fieldInfo( $table, $field ) {
915 return PostgresField
::fromText( $this, $table, $field );
919 * pg_field_type() wrapper
921 function fieldType( $res, $index ) {
922 if ( $res instanceof ResultWrapper
) {
925 return pg_field_type( $res, $index );
928 /* Not even sure why this is used in the main codebase... */
929 function limitResultForUpdate( $sql, $num ) {
933 function encodeBlob( $b ) {
934 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
937 function decodeBlob( $b ) {
938 if ( $b instanceof Blob
) {
941 return pg_unescape_bytea( $b );
944 function strencode( $s ) { # Should not be called by us
945 return pg_escape_string( $this->mConn
, $s );
948 function addQuotes( $s ) {
949 if ( is_null( $s ) ) {
951 } elseif ( is_bool( $s ) ) {
953 } elseif ( $s instanceof Blob
) {
954 return "'" . $s->fetch( $s ) . "'";
956 return "'" . pg_escape_string( $this->mConn
, $s ) . "'";
960 * Postgres specific version of replaceVars.
961 * Calls the parent version in Database.php
965 * @param $ins String: SQL string, read from a stream (usually tables.sql)
967 * @return string SQL string
969 protected function replaceVars( $ins ) {
970 $ins = parent
::replaceVars( $ins );
972 if ( $this->numeric_version
>= 8.3 ) {
973 // Thanks for not providing backwards-compatibility, 8.3
974 $ins = preg_replace( "/to_tsvector\s*\(\s*'default'\s*,/", 'to_tsvector(', $ins );
977 if ( $this->numeric_version
<= 8.1 ) { // Our minimum version
978 $ins = str_replace( 'USING gin', 'USING gist', $ins );
985 * Various select options
989 * @param $options Array: an associative array of options to be turned into
990 * an SQL query, valid keys are listed in the function.
993 function makeSelectOptions( $options ) {
994 $preLimitTail = $postLimitTail = '';
995 $startOpts = $useIndex = '';
997 $noKeyOptions = array();
998 foreach ( $options as $key => $option ) {
999 if ( is_numeric( $key ) ) {
1000 $noKeyOptions[$option] = true;
1004 if ( isset( $options['GROUP BY'] ) ) {
1005 $gb = is_array( $options['GROUP BY'] )
1006 ?
implode( ',', $options['GROUP BY'] )
1007 : $options['GROUP BY'];
1008 $preLimitTail .= " GROUP BY {$gb}";
1011 if ( isset( $options['HAVING'] ) ) {
1012 $preLimitTail .= " HAVING {$options['HAVING']}";
1015 if ( isset( $options['ORDER BY'] ) ) {
1016 $ob = is_array( $options['ORDER BY'] )
1017 ?
implode( ',', $options['ORDER BY'] )
1018 : $options['ORDER BY'];
1019 $preLimitTail .= " ORDER BY {$ob}";
1022 //if ( isset( $options['LIMIT'] ) ) {
1023 // $tailOpts .= $this->limitResult( '', $options['LIMIT'],
1024 // isset( $options['OFFSET'] ) ? $options['OFFSET']
1028 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1029 $postLimitTail .= ' FOR UPDATE';
1031 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1032 $postLimitTail .= ' LOCK IN SHARE MODE';
1034 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1035 $startOpts .= 'DISTINCT';
1038 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1041 function setFakeMaster( $enabled = true ) {}
1043 function getDBname() {
1044 return $this->mDBname
;
1047 function getServer() {
1048 return $this->mServer
;
1051 function buildConcat( $stringList ) {
1052 return implode( ' || ', $stringList );
1055 public function getSearchEngine() {
1056 return 'SearchPostgres';
1058 } // end DatabasePostgres class