/** * Starts a new transactional block, if none is open, or silently completes, if the transaction * is already opened. */ public function requestTransaction() { if (!$this->inTransaction) { $this->conn->beginTransaction(); $this->inTransaction = true; } }
protected function performBeginTransaction($identifier = NULL) { if ($identifier === NULL) { return $this->conn->beginTransaction(); } $this->conn->createSavepoint($identifier); }
protected function execute(InputInterface $input, OutputInterface $output) { $file = $input->getArgument('file'); if (!is_file($file)) { throw new RuntimeException('File does not exists'); } $verbose = $output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL; if (!$verbose) { $this->logger->pushHandler(new NullHandler()); } try { $this->connection->beginTransaction(); $result = $this->importService->import(file_get_contents($file)); $this->connection->commit(); $output->writeln('Import successful!'); $output->writeln('The following actions were done:'); $output->writeln(''); foreach ($result as $message) { $output->writeln('- ' . $message); } } catch (\Exception $e) { $this->connection->rollback(); $output->writeln('An exception occured during import. No changes are applied to the database.'); $output->writeln(''); $output->writeln('Message: ' . $e->getMessage()); $output->writeln('Trace: ' . $e->getTraceAsString()); } if (!$verbose) { $this->logger->popHandler(); } }
public function exportData($export, $reporter) { $this->conn->beginTransaction(); try { $lastExportedAt = (int) $export['lastExportedAt']; $areas = $this->conn->fetchAll('SELECT a.`id`, a.`name`, t.`id` AS `territoryId`, t.`name` AS `territoryName`, a.`customData`, a.`lastUpdatedAt` ' . 'FROM `' . CoreTables::AREA_TBL . '` a ' . 'INNER JOIN `' . CoreTables::TERRITORY_TBL . '` t ON t.`id` = a.`territoryId` ' . 'WHERE a.`projectId` = :projectId AND a.`statusId` = :statusId', [':projectId' => $export['projectId'], ':statusId' => $export['areaStatusId']]); $block = new ExportBlock(); foreach ($areas as $area) { $block->addId($area['id']); if ($area['lastUpdatedAt'] > $lastExportedAt) { $area['customData'] = json_decode($area['customData']); $block->addUpdatedId($area['id']); $block->addUpdate($area); } } $event = new ExportEvent($export['projectId'], $export['lastExportedAt'], $reporter); $event->addBlock('area', $block); $event = $this->eventDispatcher->dispatch(ExportEvents::EXPORT_ONGOING, $event); $this->conn->executeQuery('UPDATE `' . ExportTables::DATA_EXPORT_TBL . '` SET `lastExportedAt` = :time WHERE `id` = :id', [':time' => time(), ':id' => $export['id']]); $this->conn->commit(); return $event->output(); } catch (Exception $ex) { $this->conn->rollBack(); throw $ex; } }
/** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { parent::setUp(); $this->entityManager = $this->container->getBean("em"); $this->albumRepository = $this->container->getBean("albumRepository"); $this->connection = $this->entityManager->getConnection(); $this->connection->beginTransaction(); }
/** * Persists task * * @param Task $task * @return Task */ public function save(Task $task) { $this->connection->beginTransaction(); $this->_em->persist($task); $this->_em->flush(); $this->_em->commit(); return $task; }
public function push(array $list) { $this->create(); $this->connection->beginTransaction(); $statement = $this->connection->prepare("\n INSERT INTO `{$this->table}`(`path`)\n VALUES (:path)\n "); foreach ($list as $path) { $statement->execute(compact('path')); } $this->connection->commit(); }
/** * Begin transaction */ public function beginTransaction() { if (0 != $this->connection->getTransactionNestingLevel()) { throw new \RuntimeException('Transaction already started'); } $this->connection->beginTransaction(); }
/** * Rolls back the transaction. * It makes sure that the connection is in the correct state regardless of what happened before. * Correct state means that connection is not rollback only and does not have a transaction nesting level > 0 * * @throws \Exception */ public function rollBack() { try { /** * Roll back all the way as this is supposed to be the top level transaction and we want to reset * the nesting level */ $transactionNestingLevel = $this->connection->getTransactionNestingLevel(); for ($i = 0; $i < $transactionNestingLevel - 1; $i++) { $this->connection->rollBack(); } $this->connection->rollBack(); } catch (\Exception $e) { $rethrowable = $this->attemptToReconnectPresumedLostConnection($e); /** * If connection is functional we need to make sure the connection is not rollback only. * This can only be achieved by starting a transaction and rolling it back (the "why" is found in * lines 1277-1279 of Doctrine\DBAL\Connection). */ if ($rethrowable === $e) { $this->connection->beginTransaction(); $this->connection->rollBack(); } throw $rethrowable; } }
/** * Insert multiple rows, if a row with a duplicate key is found will update the row * This function assumes that 'id' is the primary key, and is used as a fallback for databases that don't support real upserts * * @param string $table * @param array $rows array of column => value * @param null $lastInsertId Optional reference to populate with the last auto increment id * @return int The number of affected rows * * @throws \Doctrine\DBAL\ConnectionException * @throws \Exception */ public function massUpsert($table, array $rows, &$lastInsertId = null) { if (empty($rows)) { return 0; } $rowsToInsert = []; $rowsToUpdate = []; foreach ($rows as $row) { if (!empty($row['id'])) { $rowsToUpdate[] = $row; } else { $rowsToInsert[] = $row; } } $this->db->beginTransaction(); try { $effected = $this->massInsert($table, $rowsToInsert); $lastInsertId = $this->getLastInsertId($table) - (count($rowsToInsert) - 1); foreach ($rowsToUpdate as $row) { $id = $row['id']; unset($row['id']); $effected += $this->db->update($this->db->quoteIdentifier($table), $this->quoteIdentifiers($row), ['id' => $id]); } $this->db->commit(); } catch (\Exception $e) { $this->db->rollBack(); throw $e; } return $effected; }
/** * @inheritdoc */ public function performInitialSetup() { $manager = $this->connection->getSchemaManager(); $from = $manager->createSchema(); $to = clone $from; $table = $to->createTable($this->getQueueTableName()); $to->createSequence('job_seq'); $table->addColumn($this->columns[JobReflector::PROPERTY_ID], 'integer', ['autoincrement' => true]); $table->addColumn($this->columns[JobReflector::PROPERTY_QUEUE], 'string'); $table->addColumn($this->columns[JobReflector::PROPERTY_CREATED], 'datetime'); $table->addColumn($this->columns[JobReflector::PROPERTY_SCHEDULE], 'datetime'); $table->addColumn($this->columns[JobReflector::PROPERTY_FAILED], 'boolean', ['notnull' => true, 'default' => false]); $table->addColumn($this->columns[JobReflector::PROPERTY_FINISHED], 'datetime', ['notnull' => false, 'default' => null]); $table->addColumn($this->columns[JobReflector::PROPERTY_RESULT], 'text', ['notnull' => false, 'default' => null]); $table->addColumn($this->columns[JobReflector::PROPERTY_PROGRESS], 'decimal', ['notnull' => false, 'default' => null, 'precision' => 5, 'scale' => 2]); $table->addColumn($this->columns[JobReflector::PROPERTY_LAST_ATTEMPT], 'datetime', ['notnull' => false, 'default' => null]); $table->addColumn($this->columns[JobReflector::PROPERTY_TIMEOUT], 'datetime', ['notnull' => false, 'default' => null]); $table->addColumn($this->columns[JobReflector::PROPERTY_RETRY_COUNT], 'integer'); $table->addColumn($this->columns[JobReflector::PROPERTY_RETRY], 'boolean', ['notnull' => true, 'default' => false]); $table->addColumn($this->columns[JobReflector::PROPERTY_PARAMETERS], 'text', ['notnull' => false, 'default' => null]); $table->addColumn($this->columns[JobReflector::PROPERTY_VERSION], 'integer'); $table->addColumn($this->columns['__CLASS__'], 'string'); $table->setPrimaryKey(array($this->columns[JobReflector::PROPERTY_ID])); $sql = $from->getMigrateToSql($to, $this->connection->getDatabasePlatform()); $this->connection->beginTransaction(); foreach ($sql as $query) { $this->connection->exec($query); } $this->connection->commit(); return; }
/** * Convert the tables in the current database to use given character set and collation. * * @param string $characterSet Character set to convert to * @param string $collation Collation to set, must be compatible with the character set * @param string $outputPathAndFilename * @param boolean $verbose * @throws ConnectionException * @throws DBALException */ protected function convertToCharacterSetAndCollation($characterSet = 'utf8', $collation = 'utf8_unicode_ci', $outputPathAndFilename = null, $verbose = false) { $statements = ['SET foreign_key_checks = 0']; $statements[] = 'ALTER DATABASE ' . $this->connection->quoteIdentifier($this->persistenceSettings['backendOptions']['dbname']) . ' CHARACTER SET ' . $characterSet . ' COLLATE ' . $collation; $tableNames = $this->connection->getSchemaManager()->listTableNames(); foreach ($tableNames as $tableName) { $statements[] = 'ALTER TABLE ' . $this->connection->quoteIdentifier($tableName) . ' DEFAULT CHARACTER SET ' . $characterSet . ' COLLATE ' . $collation; $statements[] = 'ALTER TABLE ' . $this->connection->quoteIdentifier($tableName) . ' CONVERT TO CHARACTER SET ' . $characterSet . ' COLLATE ' . $collation; } $statements[] = 'SET foreign_key_checks = 1'; if ($outputPathAndFilename === null) { try { $this->connection->beginTransaction(); foreach ($statements as $statement) { if ($verbose) { $this->outputLine($statement); } $this->connection->exec($statement); } $this->connection->commit(); } catch (\Exception $exception) { $this->connection->rollBack(); $this->outputLine($exception->getMessage()); $this->outputLine('[ERROR] The transaction was rolled back.'); } } else { file_put_contents($outputPathAndFilename, implode(';' . PHP_EOL, $statements) . ';'); } }
/** * @param string $version * @param \DateTime $apply_at * @throws \Exception */ public function fixVersion($version, \DateTime $apply_at = null) { if ($apply_at === null) { $apply_at = new \DateTime(); } $this->createTable(); $this->doctrine->beginTransaction(); try { $this->doctrine->delete(self::TABLE_NAME, array('version' => $version)); $this->doctrine->insert(self::TABLE_NAME, array('version' => $version, 'apply_at' => $apply_at->format('Y-m-d\\TH:i:s'))); $this->doctrine->commit(); } catch (\Exception $ex) { $this->doctrine->rollBack(); throw $ex; } }
/** * @param CommitId $commitId * @param Contract $streamContract * @param Identifier $streamId * @param $expectedStreamRevision * @param EventEnvelope[] $eventEnvelopes * @throws \Doctrine\DBAL\ConnectionException * @throws \Exception * @return void */ public function commit(CommitId $commitId, Contract $streamContract, Identifier $streamId, $expectedStreamRevision, array $eventEnvelopes) { $this->connection->beginTransaction(); $now = (new DateTimeImmutable('now', new DateTimeZone('UTC')))->format("Y-m-d H:i:s"); try { $this->controlOptimisticConcurrency($streamContract, $streamId, $expectedStreamRevision); $nextStreamRevision = $expectedStreamRevision; foreach ($eventEnvelopes as $eventEnvelope) { $this->connection->executeQuery(Insert::into(self::TABLE_NAME), ['streamContract' => (string) $streamContract, 'streamId' => (string) $streamId, 'streamRevision' => ++$nextStreamRevision, 'eventContract' => (string) $eventEnvelope->getEventContract(), 'eventPayload' => (string) $eventEnvelope->getEventPayload(), 'eventId' => (string) $eventEnvelope->getEventId(), 'commitId' => $commitId, 'utcCommittedTime' => $now]); } $this->connection->commit(); } catch (Exception $exception) { $this->connection->rollback(); throw $exception; } }
/** * Runs the changes to the schema */ public function commit() { $this->connection->beginTransaction(); foreach ($this->getChanges() as $sql) { $this->connection->query($sql); } $this->connection->commit(); }
/** * Update Website SQL entry according to the BackBee installation. * * @param array Website configuration, must contains 'domain' and 'label' keys * @return array|InvalidArgumentException Returns domain and label set up in database or an Exception */ public function updateWebsite($configuration) { if (!is_array($configuration) || !isset($configuration['domain']) || !isset($configuration['label'])) { throw new \InvalidArgumentException('array expected with domain and label keyes'); } $domain = $configuration['domain']; $label = $configuration['label']; try { $this->connection->beginTransaction(); $stmt = $this->connection->executeUpdate('UPDATE site SET server_name = ? , label = ?', array($domain, $label)); $this->connection->commit(); } catch (\PDOException $e) { $this->connection->rollback(); throw new \RuntimeException($e->getMessage(), (int) $e->getCode(), $e); } return $configuration; }
/** * Begin a transaction. * * @return void */ public function beginTransaction() { try { $this->connection->beginTransaction(); } catch (DBALException $e) { throw new QueryException($e->getMessage(), $e->getCode(), $e); } }
/** * {@inheritdoc} */ public function register(EventDispatcher $dispatcher) { $dispatcher->addListener(RouteMatchedEvent::class, function (RouteMatchedEvent $event) { $annotation = $this->getTransactionalAnnotation($event->getRouteMatch()); if ($annotation) { $this->connection->setTransactionIsolation($annotation->getIsolationLevel()); $this->connection->beginTransaction(); } }); $dispatcher->addListener(ControllerInvocatedEvent::class, function (ControllerInvocatedEvent $event) { $annotation = $this->getTransactionalAnnotation($event->getRouteMatch()); if ($annotation) { if ($this->connection->isTransactionActive()) { $this->connection->rollback(); } } }); }
/** * {@inheritdoc} */ public function flush() { if (!$this->data) { return; } try { $this->conn->beginTransaction(); $stmt = $this->conn->prepare('INSERT INTO metrics (metric, measurement, created) VALUES (?, ?, ?)'); foreach ($this->data as $measurement) { $stmt->bindParam(1, $measurement[0]); $stmt->bindParam(2, $measurement[1]); $stmt->bindParam(3, $measurement[2]); $stmt->execute(); } $this->conn->commit(); } catch (Exception $e) { $this->conn->rollback(); } $this->data = array(); }
/** * Delete a workflow by its ID * * @param int $workflowId * @return void */ public function delete($workflowId) { $this->conn->beginTransaction(); try { // delete only those two, the rest should be deleted automatically through cascading foreign keys $this->conn->delete($this->options->variableHandlerTable(), array('workflow_id' => $workflowId)); $this->conn->delete($this->options->workflowTable(), array('workflow_id' => $workflowId)); $this->conn->commit(); } catch (\Exception $e) { $this->conn->rollback(); } }
/** * @param array $data * @param string $namespace * @param int $localeId * @param int $shopId * @throws \Exception */ public function write($data, $namespace, $localeId, $shopId) { if (empty($data)) { throw new \Exception('You called write() but provided no data to be written'); } if (!isset($this->db)) { throw new \Exception('Required database connection is missing'); } $this->db->beginTransaction(); try { // If no update are allowed, we can speed up using INSERT IGNORE if (!$this->update) { $this->insertBatch($data, $namespace, $localeId, $shopId); } else { $rows = $this->db->fetchAll('SELECT * FROM s_core_snippets WHERE shopID = :shopId AND localeID = :localeId AND namespace = :namespace', array('shopId' => $shopId, 'localeId' => $localeId, 'namespace' => $namespace)); foreach ($data as $name => $value) { $row = null; // Find the matching value in db, if it exists foreach ($rows as $key => $values) { if ($values['name'] == $name) { $row = $values; unset($rows[$key]); break; } } if ($row !== null) { // Found a matching value, try update $this->updateRecord($value, $row); } else { // No matching value, just insert a new one $this->insertRecord($name, $value, $namespace, $localeId, $shopId); } } } $this->db->commit(); } catch (\Exception $e) { $this->db->rollBack(); throw new \Exception(sprintf('An error occurred when importing namespace "%s" for locale "%s"', $namespace, $localeId), 0, $e); } }
/** * @param callable $callback * * @return bool|int * @throws \Doctrine\DBAL\ConnectionException */ public function executeTransactionalQuery(callable $callback) { $this->connection->beginTransaction(); try { $result = $callback(); $this->connection->commit(); } catch (\Exception $e) { $this->connection->rollBack(); $this->logger->error('database', $e); $result = false; } return $result; }
protected function testInsertGeometry(Connection $connection) { $i = 0; $connection->beginTransaction(); $collection = \geoPHP::load(file_get_contents(self::$kml), 'kml'); $collection->setSRID(4326); $connection->insert('test_table', array('id' => $i++, 'name' => 'test_' . $i, 'geometry' => $collection), array('integer', 'string', 'geometry')); $connection->commit(); $data = $connection->fetchAll('SELECT * FROM test_table'); $this->assertEquals(1, count($data)); $this->assertEquals(0, $data[0]['id']); $this->assertEquals('test_1', $data[0]['name']); }
/** * Executes an insert into the database * * @param array $updateData * @param $id * @return int * @throws Exception * @throws \Doctrine\DBAL\ConnectionException * @throws \Exception */ public function executeUpdate(array $updateData, $id) { $this->connection->beginTransaction(); try { $primaryKey = ['id' => $id]; $rows = $this->connection->update($this->table, $updateData, $primaryKey); $this->connection->commit(); return $rows; } catch (\Exception $exception) { $this->connection->rollback(); throw $exception; } }
/** * Executes a function in a transaction. * * The function gets passed this EntityManager instance as an (optional) parameter. * * {@link flush} is invoked prior to transaction commit. * * If an exception occurs during execution of the function or flushing or transaction commit, * the transaction is rolled back, the EntityManager closed and the exception re-thrown. * * @param Closure $func The function to execute transactionally. */ public function transactional(Closure $func) { $this->_conn->beginTransaction(); try { $func($this); $this->flush(); $this->_conn->commit(); } catch (Exception $e) { $this->close(); $this->_conn->rollback(); throw $e; } }
/** * @param iterable $metadatas list of \Doctrine\ORM\Mapping\ClassMetadata * * @throws \Exception */ public function truncateMetadatas($metadatas) { $this->reset(); $this->connection->beginTransaction(); try { $this->disableDatabaseForeignKeyChecks(); /* @var $classMetadata \Doctrine\ORM\Mapping\ClassMetadata */ foreach ($metadatas as $classMetadata) { if ($classMetadata->isMappedSuperclass === false) { $this->truncateTable($classMetadata->getTableName()); foreach ($classMetadata->getAssociationMappings() as $field) { if (isset($field['joinTable']) && isset($field['joinTable']['name'])) { $this->truncateTable($field['joinTable']['name']); } } } } $this->enableDatabaseForeignKeyChecks(); $this->connection->commit(); } catch (\Exception $e) { $this->connection->rollback(); throw $e; } }
/** * Salva a lista de presença (salva as faltas) de uma data específica no banco de dados. * * @param Connection $conn * @param DateTime $date Data da lista de presença * @param array $types Tipos de presença * @param array $students Alunos * @throws Exception */ public static function insertNewList(Connection $conn, DateTime $date, array $types, array $students = []) { $conn->beginTransaction(); try { foreach ($types as $type) { $conn->delete('attendance', ['attendance_date' => $date, 'attendance_type_id' => $type], ['date', PDO::PARAM_INT]); } foreach ($students as $student) { $conn->insert('attendance', ['enrollment_id' => $student['id'], 'attendance_type_id' => $student['type'], 'attendance_date' => $date], [PDO::PARAM_INT, PDO::PARAM_INT, 'date']); } $conn->commit(); } catch (Exception $ex) { $conn->rollBack(); throw $ex; } }
/** * @param DBPatcher\PatchFile $patchFile * @param \Doctrine\DBAL\Connection $connection * @return DBPatcher\PatchFile */ function applySqlPatch($patchFile, $connection) { if ($patchFile->extension === 'sql') { $sqlCommands = file_get_contents($patchFile->filename); $connection->beginTransaction(); try { $connection->exec($sqlCommands); } catch (\Doctrine\DBAL\DBALException $e) { $connection->rollBack(); return array(DBPatcher\PatchFile::copyWithNewStatus($patchFile, DBPatcher\PatchFile::STATUS_ERROR), $e->getMessage()); } $connection->commit(); return array(DBPatcher\PatchFile::copyWithNewStatus($patchFile, DBPatcher\PatchFile::STATUS_INSTALLED)); } return array(DBPatcher\PatchFile::copyWithNewStatus($patchFile, DBPatcher\PatchFile::STATUS_ERROR)); }
/** * {@inheritDoc} */ public function transactional($func) { if (!is_callable($func)) { throw new \InvalidArgumentException('Expected argument of type "callable", got "' . gettype($func) . '"'); } $this->conn->beginTransaction(); try { $return = call_user_func($func, $this); $this->flush(); $this->conn->commit(); return $return ?: true; } catch (Exception $e) { $this->close(); $this->conn->rollback(); throw $e; } }
/** * Deletes all nodes with edges from database * * @throws DatabaseErrorException */ public function delete() { try { $this->dbal->setAutoCommit(false); $this->dbal->beginTransaction(); $this->dbal->executeQuery('DELETE FROM relations'); $this->dbal->executeQuery('DELETE FROM organizations'); $this->dbal->commit(); $this->dbal->setAutoCommit(true); } catch (\Doctrine\DBAL\ConnectionException $exception) { throw new DatabaseErrorException($exception); } catch (\Doctrine\DBAL\DBALException $exception) { $this->dbal->rollBack(); $this->dbal->setAutoCommit(true); throw new DatabaseErrorException($exception); } }