You are here

class InsertQuery_sqlsrv in Drupal driver for SQL Server and SQL Azure 7.3

Same name and namespace in other branches
  1. 7 sqlsrv/query.inc \InsertQuery_sqlsrv
  2. 7.2 sqlsrv/query.inc \InsertQuery_sqlsrv

SQL Server-specific implementation of INSERT.

SQL Server doesn't supports multi-insert queries, and needs special handling for binary columns.

Hierarchy

Expanded class hierarchy of InsertQuery_sqlsrv

File

sqlsrv/query.inc, line 9

View source
class InsertQuery_sqlsrv extends InsertQuery {

  /**
   * Wether or not to use OUTPUT to obtains inserted identifiers.
   */
  protected $use_output = TRUE;
  public function __construct($connection, $table, array $options = []) {
    global $conf;
    if (isset($conf['MSSQL_INSERT_DISABLE_OUTPUT']) && $conf['MSSQL_INSERT_DISABLE_OUTPUT'] === TRUE) {
      $this->use_output = FALSE;
    }
    if (!isset($options['return'])) {
      $options['return'] = Database::RETURN_NULL;
    }
    parent::__construct($connection, $table, $options);
  }
  public function execute() {
    if (!$this
      ->preExecute()) {
      return NULL;
    }

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

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

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

    #region Select Based Insert
    if (!empty($this->fromQuery)) {

      // Re-initialize the values array so that we can re-use this query.
      $this->insertValues = array();
      $stmt = $this->connection
        ->prepareQuery((string) $this);

      // Handle the case of SELECT-based INSERT queries first.
      $arguments = $this->fromQuery
        ->getArguments();
      DatabaseUtils::BindArguments($stmt, $arguments);

      // Run the query
      $this->connection
        ->query($stmt, array(), $options);
      if ($this->use_output) {

        // We can only have 1 identity column per table (or none, where fetchColumn will fail)
        try {
          return $stmt
            ->fetchColumn(0);
        } catch (\PDOException $e) {
          return NULL;
        }
      }
      else {
        return $this->connection
          ->lastInsertId();
      }
    }

    #endregion

    #region Inserts with no values (full defaults)

    // Handle the case of full-default queries.
    if (empty($this->fromQuery) && (empty($this->insertFields) || empty($this->insertValues))) {

      // Re-initialize the values array so that we can re-use this query.
      $this->insertValues = array();
      $stmt = $this->connection
        ->prepareQuery((string) $this);

      // Run the query
      $this->connection
        ->query($stmt, array(), $options);
      if ($this->use_output) {

        // We can only have 1 identity column per table (or none, where fetchColumn will fail)
        try {
          return $stmt
            ->fetchColumn(0);
        } catch (\PDOException $e) {
          return NULL;
        }
      }
      else {
        return $this->connection
          ->lastInsertId();
      }
    }

    #endregion

    #region Regular Inserts

    // Each insert happens in its own query. However, we wrap it in a transaction
    // so that it is atomic where possible.
    $transaction = NULL;
    $batch_size = 200;

    // At most we can process in batches of 250 elements.
    $batch = array_splice($this->insertValues, 0, $batch_size);

    // If we are going to need more than one batch for this... start a transaction.
    if (empty($this->queryOptions['sqlsrv_skip_transactions']) && !empty($this->insertValues)) {
      $transaction = $this->connection
        ->startTransaction('', DatabaseTransactionSettings::GetBetterDefaults());
    }
    while (!empty($batch)) {

      // Give me a query with the amount of batch inserts.
      $query = (string) $this
        ->__toString2(count($batch));

      // Prepare the query.
      $stmt = $this->connection
        ->prepareQuery($query);

      // We use this array to store references to the blob handles.
      // This is necessary because the PDO will otherwise messes up with references.
      $blobs = array();
      $max_placeholder = 0;
      foreach ($batch as $insert_index => $insert_values) {
        $values = array_combine($this->insertFields, $insert_values);
        DatabaseUtils::BindValues($stmt, $values, $blobs, ':db_insert', $columnInformation, $max_placeholder, $insert_index);
      }

      // Run the query
      $this->connection
        ->query($stmt, [], array_merge($options, [
        'fetch' => PDO::FETCH_ASSOC,
      ]));

      // We can only have 1 identity column per table (or none, where fetchColumn will fail)
      // When the column does not have an identity column, no results are thrown back.
      if ($this->use_output) {
        foreach ($stmt as $insert) {
          try {
            $this->inserted_keys[] = $insert[$identity];
          } catch (\Exception $e) {
            $this->inserted_keys[] = NULL;
          }
        }
      }
      else {
        $this->inserted_keys[] = $this->connection
          ->lastInsertId();
      }

      // Fetch the next batch.
      $batch = array_splice($this->insertValues, 0, $batch_size);
    }

    // If we started a transaction, commit it.
    if ($transaction) {
      $transaction
        ->commit();
    }

    // Re-initialize the values array so that we can re-use this query.
    $this->insertValues = array();

    // Return the last inserted key.
    return empty($this->inserted_keys) ? NULL : end($this->inserted_keys);

    #endregion
  }

  // Because we can handle multiple inserts, give
  // an option to retrieve all keys.
  public $inserted_keys = array();
  public function __toString() {
    return $this
      ->__toString2(1);
  }

  /**
   * The aspect of the query depends on the batch size...
   *
   * @param mixed $batch_size
   * @throws Exception
   * @return string
   */
  private function __toString2($batch_size) {

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

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

    // Create a sanitized comment string to prepend to the query.
    $prefix = $this->connection
      ->makeComment($this->comments);
    $output = NULL;

    // Enable direct insertion to identity columns if necessary.
    if (!empty($this->setIdentity)) {
      $prefix .= 'SET IDENTITY_INSERT {' . $this->table . '} ON;';
    }

    // Using PDO->lastInsertId() is not reliable on highly concurrent scenarios.
    // It is much better to use the OUTPUT option of SQL Server.
    if (isset($columnInformation['identities']) && !empty($columnInformation['identities'])) {
      $identities = array_keys($columnInformation['identities']);
      $identity = reset($identities);
      $output = "OUTPUT (Inserted.{$identity})";
    }
    else {

      // Empty is the default for
      // a missing lastInsertId()
      $output = "OUTPUT ('')";
    }
    if ($this->use_output === FALSE) {
      $output = '';
    }

    // If we're selecting from a SelectQuery, finish building the query and
    // pass it back, as any remaining options are irrelevant.
    if (!empty($this->fromQuery)) {
      if (empty($this->insertFields)) {
        return $prefix . "INSERT INTO {{$this->table}} {$output}" . $this->fromQuery;
      }
      else {
        $fields_csv = implode(', ', $this->connection
          ->quoteIdentifiers($this->insertFields));
        return $prefix . "INSERT INTO {{$this->table}} ({$fields_csv}) {$output} " . $this->fromQuery;
      }
    }

    // Full default insert
    if (empty($this->insertFields)) {
      return $prefix . "INSERT INTO {{$this->table}} {$output} DEFAULT VALUES";
    }

    // Build the list of placeholders, a set of placeholders
    // for each element in the batch.
    $placeholders = array();
    $field_count = count($this->insertFields);
    for ($j = 0; $j < $batch_size; $j++) {
      $batch_placeholders = array();
      for ($i = 0; $i < $field_count; ++$i) {
        $batch_placeholders[] = ':db_insert' . ($field_count * $j + $i);
      }
      $placeholders[] = '(' . implode(', ', $batch_placeholders) . ')';
    }
    $sql = $prefix . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $this->connection
      ->quoteIdentifiers($this->insertFields)) . ') ' . $output . ' VALUES ' . PHP_EOL;
    $sql .= implode(', ', $placeholders) . PHP_EOL;
    return $sql;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
InsertQuery::$defaultFields protected property An array of fields that should be set to their database-defined defaults.
InsertQuery::$fromQuery protected property A SelectQuery object to fetch the rows that should be inserted.
InsertQuery::$insertFields protected property An array of fields on which to insert.
InsertQuery::$insertValues protected property A nested array of values to insert.
InsertQuery::$table protected property The table on which to insert.
InsertQuery::fields public function Adds a set of field->value pairs to be inserted.
InsertQuery::from public function Sets the fromQuery on this InsertQuery object.
InsertQuery::preExecute public function Preprocesses and validates the query.
InsertQuery::useDefaults public function Specifies fields for which the database defaults should be used.
InsertQuery::values public function Adds another set of values to the query to be inserted.
InsertQuery_sqlsrv::$inserted_keys public property
InsertQuery_sqlsrv::$use_output protected property Wether or not to use OUTPUT to obtains inserted identifiers.
InsertQuery_sqlsrv::execute public function Executes the insert query. Overrides InsertQuery::execute
InsertQuery_sqlsrv::__construct public function Constructs an InsertQuery object. Overrides InsertQuery::__construct
InsertQuery_sqlsrv::__toString public function Implements PHP magic __toString method to convert the query to a string. Overrides InsertQuery::__toString
InsertQuery_sqlsrv::__toString2 private function The aspect of the query depends on the batch size...
Query::$comments protected property An array of comments that can be prepended to a query.
Query::$connection protected property The connection object on which to run this query.
Query::$connectionKey protected property The key of the connection object.
Query::$connectionTarget protected property The target of the connection object.
Query::$nextPlaceholder protected property The placeholder counter.
Query::$queryOptions protected property The query options to pass on to the connection object.
Query::$uniqueIdentifier protected property A unique identifier for this query object.
Query::comment public function Adds a comment to the query.
Query::getComments public function Returns a reference to the comments array for the query.
Query::nextPlaceholder public function Gets the next placeholder value for this query object. Overrides QueryPlaceholderInterface::nextPlaceholder
Query::uniqueIdentifier public function Returns a unique identifier for this object. Overrides QueryPlaceholderInterface::uniqueIdentifier
Query::__clone public function Implements the magic __clone function. 1
Query::__sleep public function Implements the magic __sleep function to disconnect from the database.
Query::__wakeup public function Implements the magic __wakeup function to reconnect to the database.