You are here

public function Merge::execute in Drupal driver for SQL Server and SQL Azure 8.2

Same name and namespace in other branches
  1. 8 drivers/lib/Drupal/Driver/Database/sqlsrv/Merge.php \Drupal\Driver\Database\sqlsrv\Merge::execute()
  2. 3.0.x drivers/lib/Drupal/Driver/Database/sqlsrv/Merge.php \Drupal\Driver\Database\sqlsrv\Merge::execute()

Runs the query against the database.

Return value

\Drupal\Core\Database\StatementInterface|null A prepared statement, or NULL if the query is not valid.

Overrides Merge::execute

File

drivers/lib/Drupal/Driver/Database/sqlsrv/Merge.php, line 35

Class

Merge

Namespace

Drupal\Driver\Database\sqlsrv

Code

public function execute() {
  if (!count($this->condition)) {
    throw new InvalidMergeQueryException(t('Invalid merge query: no conditions'));
  }

  // Check that the table does exist.
  if (!$this->connection
    ->schema()
    ->tableExists($this->table)) {
    throw new \Drupal\Core\Database\SchemaObjectDoesNotExistException("Table {$this->table} does not exist.");
  }

  // Retrieve query options.
  $options = $this->queryOptions;

  // Keep a reference to the blobs.
  $blobs = [];

  // Fetch the list of blobs and sequences used on that table.
  $columnInformation = $this->connection
    ->schema()
    ->getTableIntrospection($this->table);

  // Find out if there is an identity field set in this insert.
  $this->setIdentity = !empty($columnInformation['identity']) && in_array($columnInformation['identity'], array_keys($this->insertFields));

  // Initialize placeholder count.
  $max_placeholder = 0;

  // Stringify the query
  $query = $this
    ->__toString();

  // Build the query, ensure that we have retries for concurrency control
  $options['integrityretry'] = true;
  if ($this->totalPlaceholders >= 2100) {
    $options['insecure'] = true;
  }
  $stmt = $this->connection
    ->prepareQuery($query, $options);

  // Build the arguments: 1. condition.
  $arguments = $this->condition
    ->arguments();
  $stmt
    ->BindArguments($arguments);

  // 2. When matched part.
  $fields = $this->updateFields;
  $stmt
    ->BindExpressions($this->expressionFields, $fields);
  $stmt
    ->BindValues($fields, $blobs, ':db_merge_placeholder_', $columnInformation, $max_placeholder);

  // 3. When not matched part.
  $stmt
    ->BindValues($this->insertFields, $blobs, ':db_merge_placeholder_', $columnInformation, $max_placeholder);

  // 4. Run the query, this will return UPDATE or INSERT
  $this->connection
    ->query($stmt, []);
  $result = null;
  foreach ($stmt as $value) {
    $result = $value->{'$action'};
  }
  switch ($result) {
    case 'UPDATE':
      return static::STATUS_UPDATE;
    case 'INSERT':
      return static::STATUS_INSERT;
    default:
      if (!empty($this->expressionFields)) {
        throw new InvalidMergeQueryException(t('Invalid merge query: no results.'));
      }
      else {
        return static::STATUS_NONE;
      }
  }
}