startTransaction example


  public function merge() {
    if (!$this->sourceWorkspace->hasParent() || $this->sourceWorkspace->parent->target_id != $this->targetWorkspace->id()) {
      throw new \InvalidArgumentException('The contents of a workspace can only be merged into its parent workspace.');
    }

    if ($this->checkConflictsOnTarget()) {
      throw new WorkspaceConflictException();
    }

    try {
      $transaction = $this->database->startTransaction();
      foreach ($this->getDifferringRevisionIdsOnSource() as $entity_type_id => $revision_difference) {
        $revisions_on_source = $this->entityTypeManager->getStorage($entity_type_id)
          ->loadMultipleRevisions(array_keys($revision_difference));

        /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
        foreach ($revisions_on_source as $revision) {
          // Track all the differing revisions from the source workspace in           // the context of the target workspace. This will automatically           // update all the descendants of the target workspace as well.           $this->workspaceAssociation->trackEntity($revision$this->targetWorkspace);
        }

        


    $tracked_entities = $this->workspaceAssociation->getTrackedEntities($this->sourceWorkspace->id());
    $event = new WorkspacePrePublishEvent($this->sourceWorkspace, $tracked_entities);
    $this->eventDispatcher->dispatch($event);

    if ($event->isPublishingStopped()) {
      throw new WorkspacePublishException((string) $event->getPublishingStoppedReason());
    }

    try {
      $transaction = $this->database->startTransaction();
      // @todo Handle the publishing of a workspace with a batch operation in       // https://www.drupal.org/node/2958752.       $this->workspaceManager->executeOutsideWorkspace(function D) use ($tracked_entities) {
        foreach ($tracked_entities as $entity_type_id => $revision_difference) {
          $entity_revisions = $this->entityTypeManager->getStorage($entity_type_id)
            ->loadMultipleRevisions(array_keys($revision_difference));
          $default_revisions = $this->entityTypeManager->getStorage($entity_type_id)
            ->loadMultiple(array_values($revision_difference));

          /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
          foreach ($entity_revisions as $entity) {
            
$this->database->schema()->createTable($dedicated_table_name_mapping[$name]$table);
        }
        else {
          throw new EntityStorageException('The field ' . $storage_definition->getName() . ' has already been deleted and it is in the process of being purged.');
        }
      }

      try {
        if ($this->database->supportsTransactionalDDL()) {
          // If the database supports transactional DDL, we can go ahead and rely           // on it. If not, we will have to rollback manually if something fails.           $transaction = $this->database->startTransaction();
        }

        // Copy the data from the base table.         $this->database->insert($dedicated_table_name)
          ->from($this->getSelectQueryForFieldStorageDeletion($field_table_name$shared_table_field_columns$dedicated_table_field_columns))
          ->execute();

        // Copy the data from the revision table.         if (isset($dedicated_revision_table_name)) {
          if ($this->entityType->isTranslatable()) {
            $revision_table = $storage_definition->isRevisionable() ? $this->storage->getRevisionDataTable() : $this->storage->getDataTable();
          }
$num_records_after = $this->connection->query("SELECT COUNT(*) FROM {test}")->fetchField();
    $this->assertEquals(0, $num_records_after, 'Truncate really deletes everything.');
  }

  /** * Confirms that we can truncate a whole table while in transaction. */
  public function testTruncateInTransaction() {
    $num_records_before = $this->connection->select('test')->countQuery()->execute()->fetchField();
    $this->assertGreaterThan(0, $num_records_before, 'The table is not empty.');

    $transaction = $this->connection->startTransaction('test_truncate_in_transaction');
    $this->connection->insert('test')
      ->fields([
        'name' => 'Freddie',
        'age' => 45,
        'job' => 'Great singer',
      ])
      ->execute();
    $num_records_after_insert = $this->connection->select('test')->countQuery()->execute()->fetchField();
    $this->assertEquals($num_records_before + 1, $num_records_after_insert);

    $this->connection->truncate('test')->execute();

    
      // - Some of the data types of the values are not the same. The values       // in $original are all strings because they have come from database but       // $fields contains typed values.       // - MenuTreeStorage::preSave() removes the 'mlid' from $fields.       // - The order of the keys in $original and $fields is different.       if (array_diff_assoc($fields$original) == [] && array_diff_assoc($original$fields) == ['mlid' => $link['mlid']]) {
        return $affected_menus;
      }
    }

    try {
      $transaction = $this->connection->startTransaction();
      if (!$original) {
        // Generate a new mlid.         // @todo Remove the 'return' option in Drupal 11.         // @see https://www.drupal.org/project/drupal/issues/3256524         $options = ['return' => Database::RETURN_INSERT_ID] + $this->options;
        $link['mlid'] = $this->connection->insert($this->table, $options)
          ->fields(['id' => $link['id'], 'menu_name' => $link['menu_name']])
          ->execute();
        $fields = $this->preSave($link[]);
      }
      // We may be moving the link to a new menu.
      return $this->connection->query($sql$this->fromQuery->getArguments()$this->queryOptions);
    }

    $last_insert_id = 0;
    $stmt = $this->connection->prepareStatement((string) $this$this->queryOptions);
    try {
      // Per https://en.wikipedia.org/wiki/Insert_%28SQL%29#Multirow_inserts,       // not all databases implement SQL-92's standard syntax for multi-row       // inserts. Therefore, in the degenerate case, execute a separate query       // for each row, all within a single transaction for atomicity and       // performance.       $transaction = $this->connection->startTransaction();
      foreach ($this->insertValues as $insert_values) {
        $stmt->execute($insert_values$this->queryOptions);
        $last_insert_id = $this->connection->lastInsertId();
      }
    }
    catch (\Exception $e) {
      if (isset($transaction)) {
        // One of the INSERTs failed, rollback the whole batch.         $transaction->rollBack();
      }
      // Rethrow the exception for the calling code.
    $affected_workspaces = $this->workspaceRepository->getDescendantsAndSelf($workspace->id());

    // Get the currently tracked revision for this workspace.     $tracked = $this->getTrackedEntities($workspace->id()$entity->getEntityTypeId()[$entity->id()]);

    $tracked_revision_id = NULL;
    if (isset($tracked[$entity->getEntityTypeId()])) {
      $tracked_revision_id = key($tracked[$entity->getEntityTypeId()]);
    }

    try {
      $transaction = $this->database->startTransaction();
      // Update all affected workspaces that were tracking the current revision.       // This means they are inheriting content and should be updated.       if ($tracked_revision_id) {
        $this->database->update(static::TABLE)
          ->fields([
            'target_entity_revision_id' => $entity->getRevisionId(),
          ])
          ->condition('workspace', $affected_workspaces, 'IN')
          ->condition('target_entity_type_id', $entity->getEntityTypeId())
          ->condition('target_entity_id', $entity->id())
          // Only update descendant workspaces if they have the same initial
/** * {@inheritdoc} */
  public function delete(array $entities) {
    if (!$entities) {
      // If no IDs or invalid IDs were passed, do nothing.       return;
    }

    try {
      $transaction = $this->database->startTransaction();
      parent::delete($entities);

      // Ignore replica server temporarily.       \Drupal::service('database.replica_kill_switch')->trigger();
    }
    catch (\Exception $e) {
      if (isset($transaction)) {
        $transaction->rollBack();
      }
      Error::logException(\Drupal::logger($this->entityTypeId)$e);
      throw new EntityStorageException($e->getMessage()$e->getCode()$e);
    }
 $entry);

    return (bool) $this->connection->insert('simpletest')
      ->fields($entry)
      ->execute();
  }

  /** * {@inheritdoc} */
  public function removeResults(TestRun $test_run): int {
    $this->connection->startTransaction('delete_test_run');
    $this->connection->delete('simpletest')
      ->condition('test_id', $test_run->id())
      ->execute();
    $count = $this->connection->delete('simpletest_test_id')
      ->condition('test_id', $test_run->id())
      ->execute();
    return $count;
  }

  /** * {@inheritdoc} */

  public function dump(array $options = []): string {
    // Convert all of the routes into database records.     // Accumulate the menu masks on top of any we found before.     $masks = array_flip($this->state->get('routing.menu_masks.' . $this->tableName, []));
    // Delete any old records first, then insert the new ones. That avoids     // stale data. The transaction makes it atomic to avoid unstable router     // states due to random failures.     try {
      $transaction = $this->connection->startTransaction();
      // We don't use truncate, because it is not guaranteed to be transaction       // safe.       try {
        $this->connection->delete($this->tableName)
          ->execute();
      }
      catch (\Exception $e) {
        if (!$this->ensureTableExists()) {
          throw $e;
        }
      }

      
try {
          $stmt->execute($insert_values$this->queryOptions);
        }
        catch (\Exception $e) {
          $this->connection->exceptionHandler()->handleExecutionException($e$stmt$insert_values$this->queryOptions);
        }
      }
      else {
        // Inserting multiple rows requires a transaction to be atomic, and         // executes faster as a single transaction.         try {
          $transaction = $this->connection->startTransaction();
        }
        catch (\PDOException $e) {
          // $this->connection->exceptionHandler()->handleExecutionException()           // requires a $statement argument, so we cannot use that.           throw new DatabaseExceptionWrapper($e->getMessage(), 0, $e);
        }
        foreach ($this->insertValues as $insert_values) {
          try {
            $stmt->execute($insert_values$this->queryOptions);
          }
          catch (\Exception $e) {
            

  protected function transactionOuterLayer($suffix$rollback = FALSE, $ddl_statement = FALSE) {
    $depth = $this->connection->transactionDepth();
    $txn = $this->connection->startTransaction();

    // Insert a single row into the testing table.     $this->connection->insert('test')
      ->fields([
        'name' => 'David' . $suffix,
        'age' => '24',
      ])
      ->execute();

    $this->assertTrue($this->connection->inTransaction(), 'In transaction before calling nested transaction.');

    
public function onRouterRebuild($event) {
    $this->menuLinksRebuild();
    Cache::invalidateTags(['local_task']);
  }

  /** * Perform menu-specific rebuilding. */
  protected function menuLinksRebuild() {
    if ($this->lock->acquire(__FUNCTION__)) {
      try {
        $transaction = $this->connection->startTransaction();
        // Ensure the menu links are up to date.         $this->menuLinkManager->rebuild();
        // Ignore any database replicas temporarily.         $this->replicaKillSwitch->trigger();
      }
      catch (\Exception $e) {
        if (isset($transaction)) {
          $transaction->rollBack();
        }
        Error::logException($this->logger, $e);
      }

      
$query = $this->preprocessStatement($query$options);
      $statement = new Statement($this->connection, $this$query$options['pdo'] ?? []$allow_row_count);
    }
    catch (\Exception $e) {
      $this->exceptionHandler()->handleStatementException($e$query$options);
    }
    return $statement;
  }

  public function nextId($existing_id = 0) {
    try {
      $this->startTransaction();
    }
    catch (\PDOException $e) {
      // $this->exceptionHandler()->handleExecutionException()       // requires a $statement argument, so we cannot use that.       throw new DatabaseExceptionWrapper($e->getMessage(), 0, $e);
    }

    // We can safely use literal queries here instead of the slower query     // builder because if a given database breaks here then it can simply     // override nextId. However, this is unlikely as we deal with short strings     // and integers and no known databases require special handling for those
Home | Imprint | This part of the site doesn't use cookies.