本文整理汇总了PHP中Doctrine\ORM\EntityManager::rollback方法的典型用法代码示例。如果您正苦于以下问题:PHP EntityManager::rollback方法的具体用法?PHP EntityManager::rollback怎么用?PHP EntityManager::rollback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Doctrine\ORM\EntityManager
的用法示例。
在下文中一共展示了EntityManager::rollback方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
public function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Migrating translations...');
$this->setEntityManager($this->getContainer()->get('doctrine.orm.entity_manager'));
/* @var EntityRepository $repo */
$repo = $this->em->getRepository('KunstmaanTranslatorBundle:Translation');
/**
* @var QueryBuilder $qb
*/
$qb = $repo->createQueryBuilder('t');
$uniqueTranslations = $qb->select('t.domain,t.keyword')->distinct()->where('t.translationId IS NULL')->getQuery()->getArrayResult();
$this->em->beginTransaction();
try {
foreach ($uniqueTranslations as $uniqueTranslation) {
// Fetch new unique translation ID & update records
$newId = $repo->getUniqueTranslationId();
// Update translations...
$qb->update()->set('t.translationId', $newId)->where('t.domain = :domain')->andWhere('t.keyword = :keyword')->setParameter('domain', $uniqueTranslation['domain'])->setParameter('keyword', $uniqueTranslation['keyword'])->getQuery()->execute();
}
$this->em->commit();
$output->writeln('<info>' . count($uniqueTranslations) . ' translations have been migrated.</info>');
} catch (\Exception $e) {
$this->em->rollback();
$output->writeln('An error occured while migrating translations : <error>' . $e->getMessage() . '</error>');
}
}
示例2: persist
/**
* Persists data into DB in single transaction
*
* @param string $locale
* @param array $data translations strings, format same as MassageCatalog::all() returns
*
* @throws \Exception
*/
public function persist($locale, array $data)
{
$writeCount = 0;
try {
$this->em->beginTransaction();
foreach ($data as $domain => $domainData) {
foreach ($domainData as $key => $translation) {
if (strlen($key) > MySqlPlatform::LENGTH_LIMIT_TINYTEXT) {
continue;
}
$writeCount++;
$this->toWrite[] = $this->getTranslationObject($key, $locale, $domain, $translation);
if (0 === $writeCount % $this->batchSize) {
$this->write($this->toWrite);
$this->toWrite = [];
}
}
}
if (count($this->toWrite) > 0) {
$this->write($this->toWrite);
}
$this->em->commit();
} catch (\Exception $exception) {
$this->em->rollback();
throw $exception;
}
// update timestamp in case when persist succeed
$this->metadataCache->updateTimestamp($locale);
}
示例3: fillChannelToEntity
/**
* @param Channel $channel
* @param string $entity
*
* @throws \Exception
*/
protected function fillChannelToEntity(Channel $channel, $entity)
{
$interfaces = class_implements($entity) ?: [];
if (!in_array('OroCRM\\Bundle\\ChannelBundle\\Model\\ChannelAwareInterface', $interfaces)) {
return;
}
/** @var QueryBuilder $qb */
$qb = $this->em->getRepository($entity)->createQueryBuilder('e');
$iterator = new BufferedQueryResultIterator($qb);
$writeCount = 0;
$toWrite = [];
try {
$this->em->beginTransaction();
/** @var ChannelAwareInterface $data */
foreach ($iterator as $data) {
$writeCount++;
if (!$data->getDataChannel()) {
$channelReference = $this->em->getReference(ClassUtils::getClass($channel), $channel->getId());
$data->setDataChannel($channelReference);
$toWrite[] = $data;
}
if (0 === $writeCount % static::BATCH_SIZE) {
$this->write($toWrite);
$toWrite = [];
}
}
if (count($toWrite) > 0) {
$this->write($toWrite);
}
$this->em->commit();
} catch (\Exception $exception) {
$this->em->rollback();
throw $exception;
}
}
示例4: groupMembershipAction
public function groupMembershipAction()
{
/** @var AccountInterface $account */
$account = $this->entityManager->getRepository(AccountInterface::class)->find($this->bodyParam('account'));
if (!$account) {
return new ApiProblem(404, 'The account could not be found.');
}
/** @var Group $group */
$group = $this->entityManager->getRepository(Group::class)->find($this->bodyParam('group'));
if (!$group) {
return new ApiProblem(404, 'The group could not be found.');
}
if ($this->getRequest()->getMethod() === 'POST' && !$account->getGroups()->contains($group)) {
$account->getGroups()->add($group);
} elseif ($this->getRequest()->getMethod() === 'DELETE' && $account->getGroups()->contains($group)) {
$account->getGroups()->removeElement($group);
}
try {
$this->entityManager->beginTransaction();
$this->entityManager->persist($account);
$this->entityManager->flush();
$this->entityManager->commit();
} catch (Exception $e) {
$this->entityManager->rollback();
return new ApiProblemResponse(new ApiProblem(500, $e->getMessage(), null, null, ['exception' => $e]));
}
return new ViewModel(['group' => $group->getId(), 'account' => $account->getId()]);
}
示例5: executeJob
/**
* @param string $jobType
* @param string $jobName
* @param array $configuration
* @return JobResult
*/
public function executeJob($jobType, $jobName, array $configuration = array())
{
// create and persist job instance and job execution
$jobInstance = new JobInstance(self::CONNECTOR_NAME, $jobType, $jobName);
$jobInstance->setCode($this->generateJobCode($jobName));
$jobInstance->setLabel(sprintf('%s.%s', $jobType, $jobName));
$jobInstance->setRawConfiguration($configuration);
$jobExecution = new JobExecution();
$jobExecution->setJobInstance($jobInstance);
$jobResult = new JobResult();
$jobResult->setSuccessful(false);
$this->entityManager->beginTransaction();
try {
$job = $this->jobRegistry->getJob($jobInstance);
if (!$job) {
throw new RuntimeException(sprintf('Can\'t find job "%s"', $jobName));
}
// TODO: Refactor whole logic of job execution to perform actions in transactions
$job->execute($jobExecution);
$failureExceptions = $this->collectFailureExceptions($jobExecution);
if ($jobExecution->getStatus()->getValue() == BatchStatus::COMPLETED && !$failureExceptions) {
$this->entityManager->commit();
$jobResult->setSuccessful(true);
} else {
$this->entityManager->rollback();
foreach ($failureExceptions as $failureException) {
$jobResult->addFailureException($failureException);
}
}
} catch (\Exception $exception) {
$this->entityManager->rollback();
$jobExecution->addFailureException($exception);
$jobResult->addFailureException($exception->getMessage());
}
// save job instance
$this->entityManager->persist($jobInstance);
$this->entityManager->flush($jobInstance);
// set data to JobResult
$jobResult->setJobId($jobInstance->getId());
$jobResult->setJobCode($jobInstance->getCode());
/** @var JobExecution $jobExecution */
$jobExecution = $jobInstance->getJobExecutions()->first();
if ($jobExecution) {
$stepExecution = $jobExecution->getStepExecutions()->first();
if ($stepExecution) {
$context = $this->contextRegistry->getByStepExecution($stepExecution);
$jobResult->setContext($context);
}
}
return $jobResult;
}
示例6: updateActivityDescription
/**
* @param EmailBodyAdded $event
*
* @throws \Exception
*/
public function updateActivityDescription(EmailBodyAdded $event)
{
$this->entityManager->beginTransaction();
try {
$email = $event->getEmail();
$activityList = $this->chainProvider->getUpdatedActivityList($email, $this->entityManager);
if ($activityList) {
$this->entityManager->persist($activityList);
$this->entityManager->flush();
}
$this->entityManager->commit();
} catch (\Exception $e) {
$this->entityManager->rollback();
throw $e;
}
}
示例7: insertUpdateProcessing
public function insertUpdateProcessing(EntityManager $em, $data, $id = null)
{
$update = !is_null($id);
try {
$em->beginTransaction();
if ($update) {
$language = $em->find('Model\\Language', $id);
} else {
$language = new Language();
}
$language->setCode($data['code']);
$language->setDescription($data['description']);
$language->setFlagImageURL($data['flagimageurl']);
$menu = $em->find('Model\\Menu', $data['menuid']);
$language->setMenu($menu);
if ($update) {
$em->merge($language);
} else {
$em->persist($language);
}
$em->flush();
$em->commit();
} catch (\Exception $e) {
$em->rollback();
throw $e;
}
return $language->getId();
}
示例8: doJob
/**
* @param JobExecution $jobExecution
* @param JobInstance $jobInstance
* @return JobResult
*/
protected function doJob(JobInstance $jobInstance, JobExecution $jobExecution)
{
$jobResult = new JobResult();
$jobResult->setSuccessful(false);
$isTransactionRunning = $this->isTransactionRunning();
if (!$isTransactionRunning) {
$this->entityManager->beginTransaction();
}
try {
$job = $this->batchJobRegistry->getJob($jobInstance);
if (!$job) {
throw new RuntimeException(sprintf('Can\'t find job "%s"', $jobInstance->getAlias()));
}
$job->execute($jobExecution);
$isSuccessful = $this->handleJobResult($jobExecution, $jobResult);
if (!$isTransactionRunning && $isSuccessful && !$this->validationMode) {
$this->entityManager->commit();
} elseif (!$isTransactionRunning) {
$this->entityManager->rollback();
}
// trigger save of JobExecution and JobInstance
$this->batchJobRepository->getJobManager()->flush();
if (!$this->isClearSkipped($jobExecution)) {
$this->batchJobRepository->getJobManager()->clear();
}
} catch (\Exception $exception) {
if (!$isTransactionRunning) {
$this->entityManager->rollback();
}
$jobExecution->addFailureException($exception);
$jobResult->addFailureException($exception->getMessage());
$this->saveFailedJobExecution($jobExecution);
}
return $jobResult;
}
示例9: doJob
/**
* @param JobExecution $jobExecution
* @param JobInstance $jobInstance
* @return JobResult
*/
protected function doJob(JobInstance $jobInstance, JobExecution $jobExecution)
{
$jobResult = new JobResult();
$jobResult->setSuccessful(false);
$this->entityManager->beginTransaction();
try {
$job = $this->batchJobRegistry->getJob($jobInstance);
if (!$job) {
throw new RuntimeException(sprintf('Can\'t find job "%s"', $jobInstance->getAlias()));
}
$job->execute($jobExecution);
$failureExceptions = $this->collectFailureExceptions($jobExecution);
if ($jobExecution->getStatus()->getValue() == BatchStatus::COMPLETED && !$failureExceptions) {
$this->entityManager->commit();
$jobResult->setSuccessful(true);
} else {
$this->entityManager->rollback();
foreach ($failureExceptions as $failureException) {
$jobResult->addFailureException($failureException);
}
}
} catch (\Exception $exception) {
$this->entityManager->rollback();
$jobExecution->addFailureException($exception);
$jobResult->addFailureException($exception->getMessage());
}
return $jobResult;
}
示例10: rollback
public static function rollback(EntityManager $entityManager)
{
if ($entityManager->getConnection()->isTransactionActive()) {
//This place tried to commit without an active transaction
$entityManager->rollback();
$entityManager->beginTransaction();
}
}
示例11: handle
/**
* {@inheritDoc}
*/
public function handle(MassActionHandlerArgs $args)
{
$data = $args->getData();
$massAction = $args->getMassAction();
$options = $massAction->getOptions()->toArray();
$this->entityManager->beginTransaction();
try {
set_time_limit(0);
$iteration = $this->handleHeadEmails($options, $data);
$this->handleThreadEmails($options);
$this->entityManager->commit();
} catch (\Exception $e) {
$this->entityManager->rollback();
throw $e;
}
return $this->getResponse($args, $iteration);
}
示例12: handle
/**
* {@inheritDoc}
*/
public function handle(MassActionHandlerArgs $args)
{
$iteration = 0;
$entityName = null;
$entityIdentifiedField = null;
$results = new DeletionIterableResult($args->getResults()->getSource());
$results->setBufferSize(self::FLUSH_BATCH_SIZE);
// batch remove should be processed in transaction
$this->entityManager->beginTransaction();
try {
// if huge amount data must be deleted
set_time_limit(0);
foreach ($results as $result) {
/** @var $result ResultRecordInterface */
$entity = $result->getRootEntity();
if (!$entity) {
// no entity in result record, it should be extracted from DB
if (!$entityName) {
$entityName = $this->getEntityName($args);
}
if (!$entityIdentifiedField) {
$entityIdentifiedField = $this->getEntityIdentifierField($args);
}
$entity = $this->getEntity($entityName, $result->getValue($entityIdentifiedField));
}
if ($entity) {
if ($this->securityFacade->isGranted('DELETE', $entity)) {
$this->entityManager->remove($entity);
$iteration++;
}
if ($iteration % self::FLUSH_BATCH_SIZE == 0) {
$this->finishBatch();
}
}
}
if ($iteration % self::FLUSH_BATCH_SIZE > 0) {
$this->finishBatch();
}
$this->entityManager->commit();
} catch (\Exception $e) {
$this->entityManager->rollback();
throw $e;
}
return $this->getResponse($args, $iteration);
}
示例13: handle
/**
* {@inheritDoc}
*/
public function handle(MassActionMediatorInterface $mediator)
{
$iteration = 0;
$entityName = null;
$entityIdentifiedField = null;
$results = $this->prepareIterableResult($mediator->getResults());
$results->setBufferSize(self::FLUSH_BATCH_SIZE);
// batch remove should be processed in transaction
$this->entityManager->beginTransaction();
try {
foreach ($results as $result) {
/** @var $result ResultRecordInterface */
$entity = $result->getRootEntity();
if (!$entity) {
// no entity in result record, it should be extracted from DB
if (!$entityName) {
$entityName = $this->getEntityName($mediator);
}
if (!$entityIdentifiedField) {
$entityIdentifiedField = $this->getEntityIdentifierField($mediator);
}
$entity = $this->getEntity($entityName, $result->getValue($entityIdentifiedField));
}
if ($entity) {
$this->entityManager->remove($entity);
$iteration++;
if ($iteration % self::FLUSH_BATCH_SIZE == 0) {
$this->entityManager->flush();
$this->entityManager->clear();
}
}
}
if ($iteration % self::FLUSH_BATCH_SIZE > 0) {
$this->entityManager->flush();
$this->entityManager->clear();
}
$this->entityManager->commit();
} catch (\Exception $e) {
$this->entityManager->rollback();
throw $e;
}
return $this->getResponse($mediator, $iteration);
}
示例14: run
/**
* Runs static repository restriction query and stores it state into snapshot entity
* Doctrine does not supports insert in DQL. To increase the speed of query here uses plain sql query.
*
* @param Segment $segment
*
* @throws \LogicException
* @throws \Exception
*/
public function run(Segment $segment)
{
if ($segment->getType()->getName() !== SegmentType::TYPE_STATIC) {
throw new \LogicException('Only static segments could have snapshots.');
}
$entityMetadata = $this->em->getClassMetadata($segment->getEntity());
if (count($entityMetadata->getIdentifierFieldNames()) > 1) {
throw new \LogicException('Only entities with single identifier supports.');
}
$this->em->getRepository('OroSegmentBundle:SegmentSnapshot')->removeBySegment($segment);
try {
$this->em->beginTransaction();
$date = new \DateTime('now', new \DateTimeZone('UTC'));
$dateString = '\'' . $date->format('Y-m-d H:i:s') . '\'';
if ($this->em->getConnection()->getDriver()->getName() === DatabaseDriverInterface::DRIVER_POSTGRESQL) {
$dateString = sprintf('TIMESTAMP %s', $dateString);
}
$insertString = sprintf(', %d, %s ', $segment->getId(), $dateString);
$qb = $this->dynamicSegmentQB->getQueryBuilder($segment);
$this->applyOrganizationLimit($segment, $qb);
$query = $qb->getQuery();
$segmentQuery = $query->getSQL();
$segmentQuery = substr_replace($segmentQuery, $insertString, stripos($segmentQuery, 'from'), 0);
$fieldToSelect = 'entity_id';
if ($entityMetadata->getTypeOfField($entityMetadata->getSingleIdentifierFieldName()) === 'integer') {
$fieldToSelect = 'integer_entity_id';
}
$dbQuery = 'INSERT INTO oro_segment_snapshot (' . $fieldToSelect . ', segment_id, createdat) (%s)';
$dbQuery = sprintf($dbQuery, $segmentQuery);
$statement = $this->em->getConnection()->prepare($dbQuery);
$this->bindParameters($statement, $query->getParameters());
$statement->execute();
$this->em->commit();
} catch (\Exception $exception) {
$this->em->rollback();
throw $exception;
}
$segment = $this->em->merge($segment);
$segment->setLastRun(new \DateTime('now', new \DateTimeZone('UTC')));
$this->em->persist($segment);
$this->em->flush();
}
示例15: bind
/**
* @param ImageResourceInterface $resource
* @param ImageBindInterface $binder
* @throws \Exception
*/
public function bind(ImageResourceInterface $resource, ImageBindInterface $binder)
{
try {
$this->entityManager->beginTransaction();
$imageEntity = $resource->getEntity();
$this->entityManager->persist($imageEntity);
$this->entityManager->persist($binder);
if (is_null($resource->getEntity())) {
throw new DomainException("Could not get entity from resource,\n resource not loaded correctly");
}
$imageEntity->setTemporary(false);
$binder->addImage($imageEntity);
$this->entityManager->flush($binder);
$this->entityManager->flush($imageEntity);
$this->entityManager->commit();
} catch (\Exception $e) {
$this->entityManager->rollback();
throw $e;
}
}