commit() public method

Commits the current transaction.
public commit ( ) : void
return void
Exemplo n.º 1
0
 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;
     }
 }
Exemplo n.º 2
0
 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 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();
 }
Exemplo n.º 4
0
 /**
  * Closes the transaction. If the transaction has been marked to rollback, it is rolled back. Otherwise
  * it is committed. The method does nothing, if the transaction is not open.
  */
 public function closeTransaction()
 {
     if ($this->inTransaction) {
         $this->inTransaction = false;
         if ($this->shouldCommit) {
             $this->conn->commit();
         } else {
             $this->conn->rollBack();
         }
         $this->shouldCommit = true;
     }
 }
Exemplo n.º 5
0
 protected function performCommit($identifier = NULL)
 {
     if ($identifier === NULL) {
         return $this->conn->commit();
     }
     $this->conn->createSavepoint($identifier);
 }
Exemplo n.º 6
0
 /**
  * @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;
     }
 }
Exemplo n.º 8
0
 /**
  * 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;
 }
 /**
  * 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) . ';');
     }
 }
Exemplo n.º 10
0
 /**
  * @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;
 }
Exemplo n.º 11
0
 /**
  */
 private function completeTransaction()
 {
     $this->connection->commit();
     foreach ($this->stagedEvents as $event) {
         $this->publish(self::EVENT_STORED, $event);
     }
     $this->stagedEvents = [];
 }
Exemplo n.º 12
0
 /**
  * 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;
 }
Exemplo n.º 13
0
 /**
  * Runs the changes to the schema
  */
 public function commit()
 {
     $this->connection->beginTransaction();
     foreach ($this->getChanges() as $sql) {
         $this->connection->query($sql);
     }
     $this->connection->commit();
 }
Exemplo n.º 14
0
 /**
  * Commit a transaction.
  *
  * @return void
  */
 public function commit()
 {
     try {
         $this->connection->commit();
     } catch (DBALException $e) {
         throw new QueryException($e->getMessage(), $e->getCode(), $e);
     }
 }
 /**
  * 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();
     }
 }
Exemplo n.º 16
0
 /**
  * @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']);
 }
Exemplo n.º 18
0
 /**
  * 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;
     }
 }
Exemplo n.º 19
0
 /**
  * @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;
     }
 }
Exemplo n.º 21
0
/**
 * @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));
}
 /**
  * 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);
     }
 }
Exemplo n.º 23
0
 /**
  * Check the migration of a table on a copy so we can detect errors before messing with the real table
  *
  * @param \Doctrine\DBAL\Schema\Table $table
  * @throws \OC\DB\MigrationException
  */
 protected function checkTableMigrate(Table $table)
 {
     $name = $table->getName();
     $tmpName = $this->generateTemporaryTableName($name);
     $this->copyTable($name, $tmpName);
     //create the migration schema for the temporary table
     $tmpTable = $this->renameTableSchema($table, $tmpName);
     $schemaConfig = new SchemaConfig();
     $schemaConfig->setName($this->connection->getDatabase());
     $schema = new Schema(array($tmpTable), array(), $schemaConfig);
     try {
         $this->applySchema($schema);
         $this->dropTable($tmpName);
     } catch (DBALException $e) {
         // pgsql needs to commit it's failed transaction before doing anything else
         $this->connection->commit();
         $this->dropTable($tmpName);
         throw new MigrationException($table->getName(), $e->getMessage());
     }
 }
Exemplo n.º 24
0
 /**
  * {@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();
 }
Exemplo n.º 25
0
 public function updateStatisticsForPreviousDay($now)
 {
     $when = getdate($now - 86400);
     $upperBounds = mktime(23, 59, 59, $when['mon'], $when['mday'], $when['year']) + 1;
     $sqlDate = $when['year'] . '-' . $when['mon'] . '-' . $when['mday'];
     $projects = Project::fetchActiveIds($this->conn);
     foreach ($projects as $projectId) {
         $this->conn->beginTransaction();
         $counters = $this->conn->fetchAll('SELECT SUM(`peopleNum`) AS `sum`, a.`id` AS `areaId` ' . 'FROM `' . EdkTables::PARTICIPANT_TBL . '` p ' . 'INNER JOIN `' . CoreTables::AREA_TBL . '` a ON a.id = p.areaId ' . 'WHERE p.`createdAt` < :upperTime AND a.projectId = :projectId ' . 'GROUP BY a.`id`', [':upperTime' => $upperBounds, ':projectId' => $projectId]);
         $areas = [];
         $total = 0;
         foreach ($counters as $row) {
             $total += $row['sum'];
             $areas[$row['areaId']] = $row['areaId'];
         }
         $this->updateStatsFor($projectId, $sqlDate, $total);
         $this->updateAreaStatsFor($projectId, $sqlDate, $areas);
         $this->conn->commit();
     }
 }
Exemplo n.º 26
0
 /**
  * @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);
     }
 }
 /**
  * Generate the next unused value for the given sequence name
  *
  * @param string
  * @return int
  */
 public function nextValue($sequenceName)
 {
     if (isset($this->sequences[$sequenceName])) {
         $value = $this->sequences[$sequenceName]['value'];
         $this->sequences[$sequenceName]['value']++;
         if ($this->sequences[$sequenceName]['value'] >= $this->sequences[$sequenceName]['max']) {
             unset($this->sequences[$sequenceName]);
         }
         return $value;
     }
     $this->conn->beginTransaction();
     try {
         $platform = $this->conn->getDatabasePlatform();
         $sql = "SELECT sequence_value, sequence_increment_by " . "FROM " . $platform->appendLockHint($this->generatorTableName, \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE) . " " . "WHERE sequence_name = ? " . $platform->getWriteLockSQL();
         $stmt = $this->conn->executeQuery($sql, array($sequenceName));
         if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
             $row = array_change_key_case($row, CASE_LOWER);
             $value = $row['sequence_value'];
             $value++;
             if ($row['sequence_increment_by'] > 1) {
                 $this->sequences[$sequenceName] = array('value' => $value, 'max' => $row['sequence_value'] + $row['sequence_increment_by']);
             }
             $sql = "UPDATE " . $this->generatorTableName . " " . "SET sequence_value = sequence_value + sequence_increment_by " . "WHERE sequence_name = ? AND sequence_value = ?";
             $rows = $this->conn->executeUpdate($sql, array($sequenceName, $row['sequence_value']));
             if ($rows != 1) {
                 throw new \Doctrine\DBAL\DBALException("Race-condition detected while updating sequence. Aborting generation");
             }
         } else {
             $this->conn->insert($this->generatorTableName, array('sequence_name' => $sequenceName, 'sequence_value' => 1, 'sequence_increment_by' => 1));
             $value = 1;
         }
         $this->conn->commit();
     } catch (\Exception $e) {
         $this->conn->rollback();
         throw new \Doctrine\DBAL\DBALException("Error occured while generating ID with TableGenerator, aborted generation: " . $e->getMessage(), 0, $e);
     }
     return $value;
 }
Exemplo n.º 28
0
 /**
  * Delete entity from the database.
  *
  * @param \Lokhman\Silex\ARM\AbstractEntity $entity
  *
  * @throws \Exception
  * @return integer
  *         Number of affected rows
  */
 public function delete(AbstractEntity $entity)
 {
     $this->assert($entity);
     // check if primary key is defined and is not NULL
     $primary = $this->metadata->getPrimary();
     if (!isset($entity[$primary])) {
         self::raise('Primary key is required to update the entity.');
     }
     try {
         $this->db->beginTransaction();
         // pre-delete event
         $this->preDelete($entity);
         // update position indexes
         if ($this->metadata->hasPosition()) {
             $position = $entity[$this->metadata->getPosition()];
             $this->positionShift($entity, $position + 1, null, -1);
         }
         if ($this->translate) {
             // delete all translations for entity
             $this->db->delete($this->app['arm.trans'], ['_table' => $this->table, '_key' => $entity[$primary]]);
         }
         // attempt to delete entity
         $result = $this->db->delete($this->table, [$primary => $entity[$primary]]);
         // delete all files
         $this->unlink($entity);
         $this->db->commit();
         // unset primary key
         unset($entity[$primary]);
         // post-delete event
         $this->postDelete($entity);
     } catch (\Exception $ex) {
         $this->rollback();
         throw $ex;
     }
     return $result;
 }
Exemplo n.º 29
0
 /**
  * {@inheritdoc}
  */
 public function write($sessionId, $data)
 {
     // Session data can contain non binary safe characters so we need to encode it.
     $encoded = base64_encode($data);
     // We use a MERGE SQL query when supported by the database.
     // Otherwise we have to use a transactional DELETE followed by INSERT to prevent duplicate entries under high concurrency.
     try {
         $mergeSql = $this->getMergeSql();
         if (null !== $mergeSql) {
             $mergeStmt = $this->con->prepare($mergeSql);
             $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
             $mergeStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
             $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
             $mergeStmt->execute();
             return true;
         }
         $this->con->beginTransaction();
         try {
             $deleteStmt = $this->con->prepare("DELETE FROM {$this->table} WHERE {$this->idCol} = :id");
             $deleteStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
             $deleteStmt->execute();
             $insertStmt = $this->con->prepare("INSERT INTO {$this->table} ({$this->idCol}, {$this->dataCol}, {$this->timeCol}) VALUES (:id, :data, :time)");
             $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
             $insertStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
             $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
             $insertStmt->execute();
             $this->con->commit();
         } catch (\Exception $e) {
             $this->con->rollback();
             throw $e;
         }
     } catch (\Exception $e) {
         throw new \RuntimeException(sprintf('Exception was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
     }
     return true;
 }
 protected function doSuspend()
 {
     $platform = $this->conn->getDatabasePlatform();
     $variables = $this->variables;
     $executionNextPollDate = null;
     if (isset($variables['batchWaitInterval'])) {
         if (!$variables['batchWaitInterval'] instanceof \DateInterval) {
             throw new \ezcWorkflowExecutionException("Specified batch waiting interval has to be instance of DateInterval!");
         }
         $executionNextPollDate = new \DateTime("now");
         $executionNextPollDate->add($variables['batchWaitInterval']);
         $executionNextPollDate = $executionNextPollDate->format($platform->getDateTimeFormatString());
     }
     $serializer = $this->options->getSerializer();
     $now = new \DateTime("now");
     $data = array('execution_suspended' => $now->format($platform->getDateTimeFormatString()), 'execution_variables' => $serializer->serialize($variables), 'execution_waiting_for' => $serializer->serialize($this->waitingFor), 'execution_threads' => $serializer->serialize($this->threads), 'execution_next_thread_id' => (int) $this->nextThreadId, 'execution_next_poll_date' => $executionNextPollDate);
     $this->cleanUpExecutionStateTable();
     $this->conn->update($this->options->executionTable(), $data, array('execution_id' => (int) $this->id));
     foreach ($this->activatedNodes as $node) {
         $data = array('execution_id' => (int) $this->id, 'node_id' => (int) $node->getId(), 'node_state' => $serializer->serialize($node->getState()), 'node_activated_from' => $serializer->serialize($node->getActivatedFrom()), 'node_thread_id' => $node->getThreadId());
         $this->conn->insert($this->options->executionStateTable(), $data);
     }
     $this->conn->commit();
 }