You are here

public function Insert::execute in Drupal 10

Same name in this branch
  1. 10 core/lib/Drupal/Core/Database/Query/Insert.php \Drupal\Core\Database\Query\Insert::execute()
  2. 10 core/modules/sqlite/src/Driver/Database/sqlite/Insert.php \Drupal\sqlite\Driver\Database\sqlite\Insert::execute()
  3. 10 core/modules/pgsql/src/Driver/Database/pgsql/Insert.php \Drupal\pgsql\Driver\Database\pgsql\Insert::execute()
  4. 10 core/modules/mysql/src/Driver/Database/mysql/Insert.php \Drupal\mysql\Driver\Database\mysql\Insert::execute()

Executes the insert query.

Return value

The last insert ID of the query, if one exists. If the query was given multiple sets of values to insert, the return value is undefined. If no fields are specified, this method will do nothing and return NULL. That That makes it safe to use in multi-insert loops.

Overrides Insert::execute

File

core/modules/sqlite/src/Driver/Database/sqlite/Insert.php, line 26

Class

Insert
SQLite implementation of \Drupal\Core\Database\Query\Insert.

Namespace

Drupal\sqlite\Driver\Database\sqlite

Code

public function execute() {
  if (!$this
    ->preExecute()) {
    return NULL;
  }

  // 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)) {

    // The SelectQuery may contain arguments, load and pass them through.
    return $this->connection
      ->query((string) $this, $this->fromQuery
      ->getArguments(), $this->queryOptions);
  }

  // We wrap the insert in a transaction so that it is atomic where possible.
  // In SQLite, this is also a notable performance boost.
  $transaction = $this->connection
    ->startTransaction();
  if (count($this->insertFields)) {

    // Each insert happens in its own query.
    $stmt = $this->connection
      ->prepareStatement((string) $this, $this->queryOptions);
    foreach ($this->insertValues as $insert_values) {
      try {
        $stmt
          ->execute($insert_values, $this->queryOptions);
      } catch (\Exception $e) {

        // One of the INSERTs failed, rollback the whole batch.
        $transaction
          ->rollBack();
        $this->connection
          ->exceptionHandler()
          ->handleExecutionException($e, $stmt, $insert_values, $this->queryOptions);
      }
    }

    // Re-initialize the values array so that we can re-use this query.
    $this->insertValues = [];
  }
  else {
    $stmt = $this->connection
      ->prepareStatement("INSERT INTO {{$this->table}} DEFAULT VALUES", $this->queryOptions);
    try {
      $stmt
        ->execute(NULL, $this->queryOptions);
    } catch (\Exception $e) {
      $transaction
        ->rollBack();
      $this->connection
        ->exceptionHandler()
        ->handleExecutionException($e, $stmt, [], $this->queryOptions);
    }
  }

  // Transaction commits here when $transaction looses scope.
  return $this->connection
    ->lastInsertId();
}