You are here

private function Upsert::buildQuery in Drupal driver for SQL Server and SQL Azure 8

Same name and namespace in other branches
  1. 3.0.x drivers/lib/Drupal/Driver/Database/sqlsrv/Upsert.php \Drupal\Driver\Database\sqlsrv\Upsert::buildQuery()

The aspect of the query depends on the batch size...

Parameters

int $batch_size: The number of inserts to perform on a single statement.

Return value

string SQL Statement.

Throws

\Exception

2 calls to Upsert::buildQuery()
Upsert::execute in drivers/lib/Drupal/Driver/Database/sqlsrv/Upsert.php
Runs the query against the database.
Upsert::__toString in drivers/lib/Drupal/Driver/Database/sqlsrv/Upsert.php
Implements PHP magic __toString method to convert the query to a string.

File

drivers/lib/Drupal/Driver/Database/sqlsrv/Upsert.php, line 100

Class

Upsert
Implements Native Upsert queries for MSSQL.

Namespace

Drupal\Driver\Database\sqlsrv

Code

private function buildQuery($batch_size) {

  // Make sure we don't go crazy with this numbers.
  if ($batch_size > self::MAX_BATCH_SIZE) {
    throw new \Exception("MSSQL Native Batch Insert limited to 250.");
  }

  // Do we to escape fields?
  $key = $this->connection
    ->escapeField($this->key);
  $all_fields = array_merge($this->defaultFields, $this->insertFields);
  $placeholders = [];
  $row = [];
  $max_placeholder = -1;
  $field_count = count($this->insertFields);
  for ($i = 0; $i < $batch_size; $i++) {
    for ($j = 0; $j < $field_count; $j++) {
      $row[] = ':db_upsert_placeholder_' . ++$max_placeholder;
    }
    $placeholders[] = '(' . implode(', ', $row) . ')';
    $row = [];
  }
  $placeholder_list = implode(', ', $placeholders);
  $insert_count = count($this->insertValues);
  $field_count = count($all_fields);
  $insert_fields = [];
  $update_fields = [];
  $all_fields_escaped = [];
  foreach ($all_fields as $field) {
    $field = $this->connection
      ->escapeField($field);
    $all_fields_escaped[] = $field;
    $insert_fields[] = 'src.' . $field;
    $update_fields[] = $field . '=src.' . $field;
  }
  $insert_list = '(' . implode(', ', $insert_fields) . ')';
  $update_list = implode(', ', $update_fields);
  $field_list = '(' . implode(', ', $all_fields_escaped) . ')';
  $values_string = 'VALUES ' . $placeholder_list;
  $update_string = 'UPDATE SET ' . $update_list;
  $insert_string = 'INSERT ' . $field_list . ' VALUES ' . $insert_list;
  $query = 'MERGE {' . $this->table . '} AS tgt USING(' . $values_string . ')';
  $query .= ' AS src ' . $field_list . ' ON tgt.' . $key . '=src.' . $key;
  $query .= ' WHEN MATCHED THEN ' . $update_string;
  $query .= ' WHEN NOT MATCHED THEN ' . $insert_string . ';';
  return $query;
}