1. drupal
    1. 8
    2. 7



DatabaseConnection::$connectionOptionsThe connection information for this connection object.
DatabaseConnection::$driverClassesIndex of what driver-specific class to use for various operations.
DatabaseConnection::$keyThe key representing this connection.
DatabaseConnection::$loggerThe current database logging object for this connection.
DatabaseConnection::$prefixesThe prefixes used by this database connection.
DatabaseConnection::$prefixReplaceList of replacement values for use in prefixTables().
DatabaseConnection::$prefixSearchList of search values for use in prefixTables().
DatabaseConnection::$statementClassThe name of the Statement class for this connection.
DatabaseConnection::$targetThe database target this connection is for.
DatabaseConnection::$temporaryNameIndexAn index used to generate unique temporary table names.
DatabaseConnection::$transactionalDDLSupportWhether this database connection supports transactional DDL.
DatabaseConnection::$transactionLayersTracks the number of "layers" of transactions currently active.
DatabaseConnection::$transactionSupportWhether this database connection supports transactions.

Functions & methods

DatabaseConnection::commitThrows an exception to deny direct access to transaction commits.
DatabaseConnection::defaultOptionsReturns the default query options for any given query.
DatabaseConnection::deletePrepares and returns a DELETE query object.
DatabaseConnection::escapeAliasEscapes an alias name string.
DatabaseConnection::escapeFieldEscapes a field name string.
DatabaseConnection::escapeLikeEscapes characters that work as wildcard characters in a LIKE pattern.
DatabaseConnection::escapeTableEscapes a table name string.
DatabaseConnection::expandArgumentsExpands out shorthand placeholders.
DatabaseConnection::filterCommentSanitize a query comment string.
DatabaseConnection::generateTemporaryTableNameGenerates a temporary table name.
DatabaseConnection::getConnectionOptionsReturns the connection information for this connection object.
DatabaseConnection::getDriverClassGets the driver-specific override class if any for the specified class.
DatabaseConnection::getKeyReturns the key this connection is associated with.
DatabaseConnection::getLoggerGets the current logging object for this connection.
DatabaseConnection::getTargetReturns the target this connection is associated with.
DatabaseConnection::insertPrepares and returns an INSERT query object.
DatabaseConnection::inTransactionDetermines if there is an active transaction open.
DatabaseConnection::makeCommentFlatten an array of query comments into a single comment string.
DatabaseConnection::makeSequenceNameCreates the appropriate sequence name for a given table and serial field.
DatabaseConnection::mergePrepares and returns a MERGE query object.
DatabaseConnection::popCommittableTransactionsInternal function: commit all the transaction layers that can commit.
DatabaseConnection::popTransactionDecreases the depth of transaction nesting.
DatabaseConnection::prefixTablesAppends a database prefix to all tables in a query.
DatabaseConnection::prepareQueryPrepares a query string and returns the prepared statement.
DatabaseConnection::pushTransactionIncreases the depth of transaction nesting.
DatabaseConnection::rollbackRolls back the transaction entirely or to a named savepoint.
DatabaseConnection::schemaReturns a DatabaseSchema object for manipulating the schema.
DatabaseConnection::selectPrepares and returns a SELECT query object.
DatabaseConnection::setKeyTells this connection object what its key is.
DatabaseConnection::setLoggerAssociates a logging object with this connection.
DatabaseConnection::setPrefixSet the list of prefixes used by this database connection.
DatabaseConnection::setTargetTells this connection object what its target value is.
DatabaseConnection::startTransactionReturns a new DatabaseTransaction object on this connection.
DatabaseConnection::supportsTransactionalDDLDetermines if this driver supports transactional DDL.
DatabaseConnection::supportsTransactionsDetermines if this driver supports transactions.
DatabaseConnection::tablePrefixFind the prefix for a table.
DatabaseConnection::transactionDepthDetermines current transaction depth.
DatabaseConnection::truncatePrepares and returns a TRUNCATE query object.
DatabaseConnection::updatePrepares and returns an UPDATE query object.
DatabaseConnection::versionReturns the version of the database server.
DatabaseConnection_pgsql::databaseTypeReturns the name of the PDO driver for this connection. Overrides DatabaseConnection::databaseType
DatabaseConnection_pgsql::driverReturns the type of database driver. Overrides DatabaseConnection::driver
DatabaseConnection_pgsql::mapConditionOperatorGets any special processing requirements for the condition operator. Overrides DatabaseConnection::mapConditionOperator
DatabaseConnection_pgsql::nextIdRetrive a the next id in a sequence. Overrides DatabaseConnection::nextId
DatabaseConnection_pgsql::queryExecutes a query string against the database. Overrides DatabaseConnection::query
DatabaseConnection_pgsql::queryRangeRuns a limited-range query on this database object. Overrides DatabaseConnection::queryRange
DatabaseConnection_pgsql::queryTemporaryRuns a SELECT query and stores its results in a temporary table. Overrides DatabaseConnection::queryTemporary
DatabaseConnection_pgsql::__construct Overrides DatabaseConnection::__construct

includes/database/pgsql/, line 18

View source
class DatabaseConnection_pgsql extends DatabaseConnection {

  public function __construct(array $connection_options = array()) {
    // This driver defaults to transaction support, except if explicitly passed FALSE.
    $this->transactionSupport = !isset($connection_options['transactions']) || ($connection_options['transactions'] !== FALSE);

    // Transactional DDL is always available in PostgreSQL,
    // but we'll only enable it if standard transactions are.
    $this->transactionalDDLSupport = $this->transactionSupport;

    // Default to TCP connection on port 5432.
    if (empty($connection_options['port'])) {
      $connection_options['port'] = 5432;

    // PostgreSQL in trust mode doesn't require a password to be supplied.
    if (empty($connection_options['password'])) {
      $connection_options['password'] = NULL;
    // If the password contains a backslash it is treated as an escape character
    // so backslashes in the password need to be doubled up.
    // The bug was reported against pdo_pgsql 1.0.2, backslashes in passwords
    // will break on this doubling up when the bug is fixed, so check the version
    //elseif (phpversion('pdo_pgsql') < 'version_this_was_fixed_in') {
    else {
      $connection_options['password'] = str_replace('\\', '\\\\', $connection_options['password']);

    $this->connectionOptions = $connection_options;

    $dsn = 'pgsql:host=' . $connection_options['host'] . ' dbname=' . $connection_options['database'] . ' port=' . $connection_options['port'];
    parent::__construct($dsn, $connection_options['username'], $connection_options['password'], array(
      // Prepared statements are most effective for performance when queries
      // are recycled (used several times). However, if they are not re-used,
      // prepared statements become ineffecient. Since most of Drupal's
      // prepared queries are not re-used, it should be faster to emulate
      // the preparation than to actually ready statements for re-use. If in
      // doubt, reset to FALSE and measure performance.
      // Convert numeric values to strings when fetching. 
      // Force column names to lower case. 

    // Force PostgreSQL to use the UTF-8 character set by default.
    $this->exec("SET NAMES 'UTF8'");

  public function query($query, array $args = array(), $options = array()) {

    $options += $this->defaultOptions();

    // The PDO PostgreSQL driver has a bug which
    // doesn't type cast booleans correctly when
    // parameters are bound using associative
    // arrays.
    // See
    foreach ($args as &$value) {
      if (is_bool($value)) {
        $value = (int) $value;

    try {
      if ($query instanceof DatabaseStatementInterface) {
        $stmt = $query;
        $stmt->execute(NULL, $options);
      else {
        $this->expandArguments($query, $args);
        $stmt = $this->prepareQuery($query);
        $stmt->execute($args, $options);

      switch ($options['return']) {
        case Database::RETURN_STATEMENT:
          return $stmt;
        case Database::RETURN_AFFECTED:
          return $stmt->rowCount();
        case Database::RETURN_INSERT_ID:
          return $this->lastInsertId($options['sequence_name']);
        case Database::RETURN_NULL:
          throw new PDOException('Invalid return directive: ' . $options['return']);
    catch (PDOException $e) {
      if ($options['throw_exception']) {
        // Add additional debug information.
        if ($query instanceof DatabaseStatementInterface) {
          $e->query_string = $stmt->getQueryString();
        else {
          $e->query_string = $query;
        $e->args = $args;
        throw $e;
      return NULL;

  public function queryRange($query, $from, $count, array $args = array(), array $options = array()) {
    return $this->query($query . ' LIMIT ' . (int) $count . ' OFFSET ' . (int) $from, $args, $options);

  public function queryTemporary($query, array $args = array(), array $options = array()) {
    $tablename = $this->generateTemporaryTableName();
    $this->query(preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE {' . $tablename . '} AS SELECT', $query), $args, $options);
    return $tablename;

  public function driver() {
    return 'pgsql';

  public function databaseType() {
    return 'pgsql';

  public function mapConditionOperator($operator) {
    static $specials;

    // Function calls not allowed in static declarations, thus this method.
    if (!isset($specials)) {
      $specials = array(
        // In PostgreSQL, 'LIKE' is case-sensitive. For case-insensitive LIKE
        // statements, we need to use ILIKE instead.
        'LIKE' => array('operator' => 'ILIKE'), 
        'NOT LIKE' => array('operator' => 'NOT ILIKE'),

    return isset($specials[$operator]) ? $specials[$operator] : NULL;

   * Retrive a the next id in a sequence.
   * PostgreSQL has built in sequences. We'll use these instead of inserting
   * and updating a sequences table.
  public function nextId($existing = 0) {

    // Retrive the name of the sequence. This information cannot be cached
    // because the prefix may change, for example, like it does in simpletests.
    $sequence_name = $this->makeSequenceName('sequences', 'value');

    // When PostgreSQL gets a value too small then it will lock the table,
    // retry the INSERT and if it's still too small then alter the sequence.
    $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
    if ($id > $existing) {
      return $id;

    // PostgreSQL advisory locks are simply locks to be used by an
    // application such as Drupal. This will prevent other Drupal proccesses
    // from altering the sequence while we are.
    $this->query("SELECT pg_advisory_lock(" . POSTGRESQL_NEXTID_LOCK . ")");

    // While waiting to obtain the lock, the sequence may have been altered
    // so lets try again to obtain an adequate value.
    $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();
    if ($id > $existing) {
      $this->query("SELECT pg_advisory_unlock(" . POSTGRESQL_NEXTID_LOCK . ")");
      return $id;

    // Reset the sequence to a higher value than the existing id.
    $this->query("ALTER SEQUENCE " . $sequence_name . " RESTART WITH " . ($existing + 1));

    // Retrive the next id. We know this will be as high as we want it.
    $id = $this->query("SELECT nextval('" . $sequence_name . "')")->fetchField();

    $this->query("SELECT pg_advisory_unlock(" . POSTGRESQL_NEXTID_LOCK . ")");

    return $id;

Related topics