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, 'raw' );
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, str_replace( "\n", ' ', $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__
);
203 $this->query( "SET standard_conforming_strings = on", __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 if ( $this->mDBname
!== $db ) {
223 return (bool)$this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $db );
229 function makeConnectionString( $vars ) {
231 foreach ( $vars as $name => $value ) {
232 $s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
238 * Closes a database connection, if it is open
239 * Returns success, true if already closed
242 $this->mOpened
= false;
243 if ( $this->mConn
) {
244 return pg_close( $this->mConn
);
250 protected function doQuery( $sql ) {
251 if ( function_exists( 'mb_convert_encoding' ) ) {
252 $sql = mb_convert_encoding( $sql, 'UTF-8' );
254 $this->mLastResult
= pg_query( $this->mConn
, $sql );
255 $this->mAffectedRows
= null; // use pg_affected_rows(mLastResult)
256 return $this->mLastResult
;
259 function queryIgnore( $sql, $fname = 'DatabasePostgres::queryIgnore' ) {
260 return $this->query( $sql, $fname, true );
263 function freeResult( $res ) {
264 if ( $res instanceof ResultWrapper
) {
267 wfSuppressWarnings();
268 $ok = pg_free_result( $res );
271 throw new DBUnexpectedError( $this, "Unable to free Postgres result\n" );
275 function fetchObject( $res ) {
276 if ( $res instanceof ResultWrapper
) {
279 wfSuppressWarnings();
280 $row = pg_fetch_object( $res );
282 # @todo FIXME: HACK HACK HACK HACK debug
284 # @todo hashar: not sure if the following test really trigger if the object
286 if( pg_last_error( $this->mConn
) ) {
287 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
292 function fetchRow( $res ) {
293 if ( $res instanceof ResultWrapper
) {
296 wfSuppressWarnings();
297 $row = pg_fetch_array( $res );
299 if( pg_last_error( $this->mConn
) ) {
300 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
305 function numRows( $res ) {
306 if ( $res instanceof ResultWrapper
) {
309 wfSuppressWarnings();
310 $n = pg_num_rows( $res );
312 if( pg_last_error( $this->mConn
) ) {
313 throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn
) ) );
318 function numFields( $res ) {
319 if ( $res instanceof ResultWrapper
) {
322 return pg_num_fields( $res );
325 function fieldName( $res, $n ) {
326 if ( $res instanceof ResultWrapper
) {
329 return pg_field_name( $res, $n );
333 * This must be called after nextSequenceVal
335 function insertId() {
336 return $this->mInsertId
;
339 function dataSeek( $res, $row ) {
340 if ( $res instanceof ResultWrapper
) {
343 return pg_result_seek( $res, $row );
346 function lastError() {
347 if ( $this->mConn
) {
348 return pg_last_error();
350 return 'No database connection';
353 function lastErrno() {
354 return pg_last_error() ?
1 : 0;
357 function affectedRows() {
358 if ( !is_null( $this->mAffectedRows
) ) {
359 // Forced result for simulated queries
360 return $this->mAffectedRows
;
362 if( empty( $this->mLastResult
) ) {
365 return pg_affected_rows( $this->mLastResult
);
369 * Estimate rows in dataset
370 * Returns estimated count, based on EXPLAIN output
371 * This is not necessarily an accurate estimate, so use sparingly
372 * Returns -1 if count cannot be found
373 * Takes same arguments as Database::select()
375 function estimateRowCount( $table, $vars = '*', $conds='', $fname = 'DatabasePostgres::estimateRowCount', $options = array() ) {
376 $options['EXPLAIN'] = true;
377 $res = $this->select( $table, $vars, $conds, $fname, $options );
380 $row = $this->fetchRow( $res );
382 if( preg_match( '/rows=(\d+)/', $row[0], $count ) ) {
390 * Returns information about an index
391 * If errors are explicitly ignored, returns NULL on failure
393 function indexInfo( $table, $index, $fname = 'DatabasePostgres::indexInfo' ) {
394 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='$table'";
395 $res = $this->query( $sql, $fname );
399 foreach ( $res as $row ) {
400 if ( $row->indexname
== $this->indexName( $index ) ) {
407 function indexUnique( $table, $index, $fname = 'DatabasePostgres::indexUnique' ) {
408 $sql = "SELECT indexname FROM pg_indexes WHERE tablename='{$table}'".
409 " AND indexdef LIKE 'CREATE UNIQUE%(" .
410 $this->strencode( $this->indexName( $index ) ) .
412 $res = $this->query( $sql, $fname );
416 foreach ( $res as $row ) {
423 * INSERT wrapper, inserts an array into a table
425 * $args may be a single associative array, or an array of these with numeric keys,
426 * for multi-row insert (Postgres version 8.2 and above only).
428 * @param $table String: Name of the table to insert to.
429 * @param $args Array: Items to insert into the table.
430 * @param $fname String: Name of the function, for profiling
431 * @param $options String or Array. Valid options: IGNORE
433 * @return bool Success of insert operation. IGNORE always returns true.
435 function insert( $table, $args, $fname = 'DatabasePostgres::insert', $options = array() ) {
436 if ( !count( $args ) ) {
440 $table = $this->tableName( $table );
441 if (! isset( $this->numeric_version
) ) {
442 $this->getServerVersion();
445 if ( !is_array( $options ) ) {
446 $options = array( $options );
449 if ( isset( $args[0] ) && is_array( $args[0] ) ) {
451 $keys = array_keys( $args[0] );
454 $keys = array_keys( $args );
457 // If IGNORE is set, we use savepoints to emulate mysql's behavior
458 $ignore = in_array( 'IGNORE', $options ) ?
'mw' : '';
460 // If we are not in a transaction, we need to be for savepoint trickery
463 if ( !$this->mTrxLevel
) {
467 $olde = error_reporting( 0 );
468 // For future use, we may want to track the number of actual inserts
469 // Right now, insert (all writes) simply return true/false
470 $numrowsinserted = 0;
473 $sql = "INSERT INTO $table (" . implode( ',', $keys ) . ') VALUES ';
476 if ( $this->numeric_version
>= 8.2 && !$ignore ) {
478 foreach ( $args as $row ) {
484 $sql .= '(' . $this->makeList( $row ) . ')';
486 $res = (bool)$this->query( $sql, $fname, $ignore );
490 foreach ( $args as $row ) {
492 $tempsql .= '(' . $this->makeList( $row ) . ')';
495 pg_query( $this->mConn
, "SAVEPOINT $ignore" );
498 $tempres = (bool)$this->query( $tempsql, $fname, $ignore );
501 $bar = pg_last_error();
502 if ( $bar != false ) {
503 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
505 pg_query( $this->mConn
, "RELEASE $ignore" );
510 // If any of them fail, we fail overall for this function call
511 // Note that this will be ignored if IGNORE is set
518 // Not multi, just a lone insert
520 pg_query($this->mConn
, "SAVEPOINT $ignore");
523 $sql .= '(' . $this->makeList( $args ) . ')';
524 $res = (bool)$this->query( $sql, $fname, $ignore );
526 $bar = pg_last_error();
527 if ( $bar != false ) {
528 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
530 pg_query( $this->mConn
, "RELEASE $ignore" );
536 $olde = error_reporting( $olde );
541 // Set the affected row count for the whole operation
542 $this->mAffectedRows
= $numrowsinserted;
544 // IGNORE always returns true
552 * INSERT SELECT wrapper
553 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
554 * Source items may be literals rather then field names, but strings should be quoted with Database::addQuotes()
555 * $conds may be "*" to copy the whole table
556 * srcTable may be an array of tables.
557 * @todo FIXME: Implement this a little better (seperate select/insert)?
559 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabasePostgres::insertSelect',
560 $insertOptions = array(), $selectOptions = array() )
562 $destTable = $this->tableName( $destTable );
564 // If IGNORE is set, we use savepoints to emulate mysql's behavior
565 $ignore = in_array( 'IGNORE', $insertOptions ) ?
'mw' : '';
567 if( is_array( $insertOptions ) ) {
568 $insertOptions = implode( ' ', $insertOptions ); // FIXME: This is unused
570 if( !is_array( $selectOptions ) ) {
571 $selectOptions = array( $selectOptions );
573 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
574 if( is_array( $srcTable ) ) {
575 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
577 $srcTable = $this->tableName( $srcTable );
580 // If we are not in a transaction, we need to be for savepoint trickery
583 if( !$this->mTrxLevel
) {
587 $olde = error_reporting( 0 );
588 $numrowsinserted = 0;
589 pg_query( $this->mConn
, "SAVEPOINT $ignore");
592 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
593 " SELECT $startOpts " . implode( ',', $varMap ) .
594 " FROM $srcTable $useIndex";
596 if ( $conds != '*' ) {
597 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
600 $sql .= " $tailOpts";
602 $res = (bool)$this->query( $sql, $fname, $ignore );
604 $bar = pg_last_error();
605 if( $bar != false ) {
606 pg_query( $this->mConn
, "ROLLBACK TO $ignore" );
608 pg_query( $this->mConn
, "RELEASE $ignore" );
611 $olde = error_reporting( $olde );
616 // Set the affected row count for the whole operation
617 $this->mAffectedRows
= $numrowsinserted;
619 // IGNORE always returns true
626 function tableName( $name, $format = 'quoted' ) {
627 global $wgSharedDB, $wgSharedTables, $wgDBmwschema;
628 # Skip quoted tablenames.
629 if ( $this->isQuotedIdentifier( $name ) ) {
632 # Lets test for any bits of text that should never show up in a table
633 # name. Basically anything like JOIN or ON which are actually part of
634 # SQL queries, but may end up inside of the table value to combine
635 # sql. Such as how the API is doing.
636 # Note that we use a whitespace test rather than a \b test to avoid
637 # any remote case where a word like on may be inside of a table name
638 # surrounded by symbols which may be considered word breaks.
639 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
642 # Split database and table into proper variables.
643 # We reverse the explode so that schema.table and table both output
645 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
646 if ( isset( $dbDetails[1] ) ) {
647 list( $table, $schema ) = $dbDetails;
649 list( $table ) = $dbDetails;
651 if ( $format != 'quoted' ) {
656 return 'pagecontent';
661 if ( !isset( $schema )) {
662 $schema = "\"{$wgDBmwschema}\".";
664 # keep old schema, but quote it.
665 $schema = "\"{$schema}\".";
667 # during installation wgDBmwschema is not set, so we would end up quering
668 # ""."table" => error. Erase the first part if wgDBmwschema is empty
669 if ( $schema == "\"\"." ) {
672 if ( isset( $wgSharedDB ) # We have a shared database (=> schema)
673 && isset( $wgSharedTables )
674 && is_array( $wgSharedTables )
675 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
676 $schema = "\"{$wgSharedDB}\".";
680 $table = "{$schema}\"mwuser\"";
683 $table = "{$schema}\"pagecontent\"";
686 $table = "{$schema}\"$table\"";
693 * Return the next in a sequence, save the value for retrieval via insertId()
695 function nextSequenceValue( $seqName ) {
696 $safeseq = str_replace( "'", "''", $seqName );
697 $res = $this->query( "SELECT nextval('$safeseq')" );
698 $row = $this->fetchRow( $res );
699 $this->mInsertId
= $row[0];
700 return $this->mInsertId
;
704 * Return the current value of a sequence. Assumes it has been nextval'ed in this session.
706 function currentSequenceValue( $seqName ) {
707 $safeseq = str_replace( "'", "''", $seqName );
708 $res = $this->query( "SELECT currval('$safeseq')" );
709 $row = $this->fetchRow( $res );
714 # Returns the size of a text field, or -1 for "unlimited"
715 function textFieldSize( $table, $field ) {
716 $table = $this->tableName( $table );
717 $sql = "SELECT t.typname as ftype,a.atttypmod as size
718 FROM pg_class c, pg_attribute a, pg_type t
719 WHERE relname='$table' AND a.attrelid=c.oid AND
720 a.atttypid=t.oid and a.attname='$field'";
721 $res =$this->query( $sql );
722 $row = $this->fetchObject( $res );
723 if ( $row->ftype
== 'varchar' ) {
724 $size = $row->size
- 4;
731 function limitResult( $sql, $limit, $offset = false ) {
732 return "$sql LIMIT $limit " . ( is_numeric( $offset ) ?
" OFFSET {$offset} " : '' );
735 function wasDeadlock() {
736 return $this->lastErrno() == '40P01';
739 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabasePostgres::duplicateTableStructure' ) {
740 $newName = $this->addIdentifierQuotes( $newName );
741 $oldName = $this->addIdentifierQuotes( $oldName );
742 return $this->query( 'CREATE ' . ( $temporary ?
'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
745 function listTables( $prefix = null, $fname = 'DatabasePostgres::listTables' ) {
746 global $wgDBmwschema;
747 $eschema = $this->addQuotes( $wgDBmwschema );
748 $result = $this->query( "SELECT tablename FROM pg_tables WHERE schemaname = $eschema", $fname );
752 foreach( $result as $table ) {
753 $vars = get_object_vars($table);
754 $table = array_pop( $vars );
755 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
756 $endArray[] = $table;
763 function timestamp( $ts = 0 ) {
764 return wfTimestamp( TS_POSTGRES
, $ts );
768 * Return aggregated value function call
770 function aggregateValue( $valuedata, $valuename = 'value' ) {
775 * @return string wikitext of a link to the server software's web site
777 public static function getSoftwareLink() {
778 return '[http://www.postgresql.org/ PostgreSQL]';
782 * @return string Version information from the database
784 function getServerVersion() {
785 if ( !isset( $this->numeric_version
) ) {
786 $versionInfo = pg_version( $this->mConn
);
787 if ( version_compare( $versionInfo['client'], '7.4.0', 'lt' ) ) {
788 // Old client, abort install
789 $this->numeric_version
= '7.3 or earlier';
790 } elseif ( isset( $versionInfo['server'] ) ) {
792 $this->numeric_version
= $versionInfo['server'];
794 // Bug 16937: broken pgsql extension from PHP<5.3
795 $this->numeric_version
= pg_parameter_status( $this->mConn
, 'server_version' );
798 return $this->numeric_version
;
802 * Query whether a given relation exists (in the given schema, or the
803 * default mw one if not given)
805 function relationExists( $table, $types, $schema = false ) {
806 global $wgDBmwschema;
807 if ( !is_array( $types ) ) {
808 $types = array( $types );
811 $schema = $wgDBmwschema;
813 $table = $this->tableName( $table, 'raw' );
814 $etable = $this->addQuotes( $table );
815 $eschema = $this->addQuotes( $schema );
816 $SQL = "SELECT 1 FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n "
817 . "WHERE c.relnamespace = n.oid AND c.relname = $etable AND n.nspname = $eschema "
818 . "AND c.relkind IN ('" . implode( "','", $types ) . "')";
819 $res = $this->query( $SQL );
820 $count = $res ?
$res->numRows() : 0;
825 * For backward compatibility, this function checks both tables and
828 function tableExists( $table, $fname = __METHOD__
, $schema = false ) {
829 return $this->relationExists( $table, array( 'r', 'v' ), $schema );
832 function sequenceExists( $sequence, $schema = false ) {
833 return $this->relationExists( $sequence, 'S', $schema );
836 function triggerExists( $table, $trigger ) {
837 global $wgDBmwschema;
840 SELECT 1 FROM pg_class, pg_namespace, pg_trigger
841 WHERE relnamespace=pg_namespace.oid AND relkind='r'
842 AND tgrelid=pg_class.oid
843 AND nspname=%s AND relname=%s AND tgname=%s
848 $this->addQuotes( $wgDBmwschema ),
849 $this->addQuotes( $table ),
850 $this->addQuotes( $trigger )
856 $rows = $res->numRows();
860 function ruleExists( $table, $rule ) {
861 global $wgDBmwschema;
862 $exists = $this->selectField( 'pg_rules', 'rulename',
865 'tablename' => $table,
866 'schemaname' => $wgDBmwschema
869 return $exists === $rule;
872 function constraintExists( $table, $constraint ) {
873 global $wgDBmwschema;
874 $SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints ".
875 "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
876 $this->addQuotes( $wgDBmwschema ),
877 $this->addQuotes( $table ),
878 $this->addQuotes( $constraint )
880 $res = $this->query( $SQL );
884 $rows = $res->numRows();
889 * Query whether a given schema exists. Returns true if it does, false if it doesn't.
891 function schemaExists( $schema ) {
892 $exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
893 array( 'nspname' => $schema ), __METHOD__
);
894 return (bool)$exists;
898 * Returns true if a given role (i.e. user) exists, false otherwise.
900 function roleExists( $roleName ) {
901 $exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
902 array( 'rolname' => $roleName ), __METHOD__
);
903 return (bool)$exists;
906 function fieldInfo( $table, $field ) {
907 return PostgresField
::fromText( $this, $table, $field );
911 * pg_field_type() wrapper
913 function fieldType( $res, $index ) {
914 if ( $res instanceof ResultWrapper
) {
917 return pg_field_type( $res, $index );
920 /* Not even sure why this is used in the main codebase... */
921 function limitResultForUpdate( $sql, $num ) {
929 function encodeBlob( $b ) {
930 return new Blob( pg_escape_bytea( $this->mConn
, $b ) );
933 function decodeBlob( $b ) {
934 if ( $b instanceof Blob
) {
937 return pg_unescape_bytea( $b );
940 function strencode( $s ) { # Should not be called by us
941 return pg_escape_string( $this->mConn
, $s );
945 * @param $s null|bool|Blob
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