/** * Выполняет запрос миграцию. * @param string $migrationName имя миграции * @param string $query запрос * @param string $type тип миграции * @return bool|\Exception|\PDOException * @throw \RuntimeException в случае, если не удалось применить */ protected function runMigration($migrationName, $query, $type = 'up') { if (empty($query)) { throw new \RuntimeException('В миграции отсутствует запрос'); } try { $this->db->beginTransaction(); $statement = $this->db->prepare($query); $result = $statement->execute(); if (!$result) { throw new \RuntimeException('Запрос не был выполнен'); } $statement->closeCursor(); if ($type == 'up') { $this->addMigrationInfo($migrationName); } else { $this->removeMigrationInfo($migrationName); } $this->db->commit(); } catch (\PDOException $e) { $this->db->rollBack(); throw $e; } return true; }
public function commitTransaction() { if (!$this->pdo->inTransaction()) { throw new \RuntimeException('PDO is not in a transaction.'); } $this->pdo->commit(); }
public function commit() { if (--$this->transactionCounter === 0) { return $this->pdo->commit(); } return $this->transactionCounter >= 0; }
/** * {@inheritdoc} */ public function commit() { $this->profiler->startQuery("COMMIT;"); $result = $this->pdo->commit(); $this->profiler->stopQuery(); return $result; }
private function _logCompletedJob(array $job) { $this->_pdo->beginTransaction(); $this->_pdo->prepare("INSERT INTO {$this->_table_log} (id,app_id,metric,value,distinct_id,created_at,sent_at) VALUES(?,?,?,?,?,?,?)")->execute(array($job['id'], $job['app_id'], $job['metric'], $job['value'], $job['distinct_id'], $job['created_at'], date("Y-m-d H:i:s"))); $this->_pdo->prepare("DELETE FROM {$this->_table_jobs} WHERE id = ? LIMIT 1")->execute(array($job['id'])); $this->_pdo->commit(); }
public function commit() { if ($this->transactionsCount == 1) { $this->pdo->commit(); } --$this->transactionsCount; }
/** * Ends a transaction with the server. * * @param bool $commit * @return void */ public function endTransaction($commit = false) { if ($commit) { $this->connection->commit(); } else { $this->connection->rollBack(); } }
public function commit() { $this->transLevel--; if (!$this->transactionNestable() || $this->transLevel == 0) { $this->dbh->commit(); } else { $this->dbh->exec(sprintf("RELEASE SAVEPOINT LEVEL%d", $this->transLevel)); } }
public function close() { if (isset($this->dbh)) { $options = $this->getOptions(); if ($options['transaction']) { $this->dbh->commit(); } unset($this->dbh); } }
/** * @param string $script */ public function run($script) { try { $this->pdo->beginTransaction(); $this->pdo->query($script); $this->pdo->commit(); } catch (\PDOException $e) { $this->pdo->rollBack(); } }
/** * Valide la transaction ou bien libére le point de sauvegarde courant * @return bool */ private function commit() { if (!--$this->transactionCounter) { return $this->pdolink->commit(); } else{ $this->pdolink->exec('RELEASE SAVEPOINT trans'.($this->transactionCounter + 1)); return true; } }
/** * @param \Closure $queries * @return bool */ public function transaction(\Closure $queries) { $this->connection->beginTransaction(); try { $queries($this); $this->connection->commit(); return true; } catch (Exception $e) { $this->connection->rollback(); return false; } }
/** * Replace current token after successful authentication * @param $credential * @param $token * @param $persistentToken * @param int $expire */ public function replaceTriplet($credential, $token, $persistentToken, $expire = 0) { try { $this->connection->beginTransaction(); $this->cleanTriplet($credential, $persistentToken); $this->storeTriplet($credential, $token, $persistentToken, $expire); $this->connection->commit(); } catch (\PDOException $e) { $this->connection->rollBack(); throw $e; } }
/** * This is run after each unit test. It empties the database. */ protected function tearDown() { // Only commit if the transaction hasn't failed. // This is because tearDown() is also executed on a failed tests, // and we don't want to call ConnectionInterface::commit() in that case // since it will trigger an exception on its own // ('Cannot commit because a nested transaction was rolled back') if ($this->con->isCommitable()) { $this->con->commit(); } $this->con = null; }
/** * @param $post * @return false|Post */ public function create($post) { $sql = "INSERT INTO posts (user_id, message , created_at ,updated_at) values (:user_id, :message, now(), now())"; $stmt = $this->dbh->prepare($sql); $stmt->bindParam(':user_id', $post['user_id']); $stmt->bindParam(':message', $post['message']); $this->dbh->beginTransaction(); $stmt->execute(); $post = $this->findByID($this->dbh->lastInsertId()); $this->dbh->commit(); return $post; }
/** * Executes a function in a transaction. * * @param callable $callable The function to execute transactionally * * @return mixed The non-empty value returned from the closure or true instead. * * @throws \Exception during execution of the function or transaction commit, * the transaction is rolled back and the exception re-thrown */ public function transactional(callable $callable) { $this->pdo->beginTransaction(); try { $return = call_user_func($callable, $this); $this->pdo->commit(); return $return ?: true; } catch (\Exception $exception) { $this->pdo->rollback(); throw $exception; } }
public function update(ConfigCollection $collection) { $this->pdo->beginTransaction(); try { $this->updateItems($collection); $this->objectRepository->update(ConfigCollection::TYPE, $collection->getUuid()); $collection->metaDataSetUpdateTimestamp(new \DateTimeImmutable()); $this->pdo->commit(); } catch (\Throwable $exception) { $this->pdo->rollBack(); throw $exception; } }
/** * Materialize a view and then replace the view by its materialized version in the same schema * @param $view_name the name of the view to materialize */ public function materializeInPlace($view_name) { $materialized_view_name = $view_name . "_materialized"; // select * into materialize_tmp $materialize_sql = "select * into " . $materialized_view_name . " from " . $view_name; $this->pdo->exec($materialize_sql); // swap the materialized view for original view $this->pdo->beginTransaction(); $this->pdo->exec("drop view {$view_name}"); $rename_sql = "alter table {$materialized_view_name} rename to {$view_name}"; $this->pdo->exec($rename_sql); $this->pdo->commit(); }
public function flush() { $this->pdo->beginTransaction(); try { foreach ($this->stack as $data) { $this->statement->execute($data); } $this->stack = []; $this->pdo->commit(); } catch (\PDOException $e) { throw new WriterException('Failed to write to database', null, $e); } }
public function it_can_update_a_user(User $user, \PDOStatement $statement) { $user->getUuid()->willReturn($uuid = Uuid::uuid4()); $user->getEmailAddress()->willReturn(EmailAddress::get($email = '*****@*****.**')); $user->getPassword()->willReturn($password = password_hash('no.jedi.please', PASSWORD_BCRYPT)); $user->getDisplayName()->willReturn($displayName = 'Nute Gunray'); $user->metaDataSetUpdateTimestamp(new Argument\Token\TypeToken(\DateTimeInterface::class))->shouldBeCalled(); $this->pdo->beginTransaction()->shouldBeCalled(); $this->pdo->prepare(new Argument\Token\StringContainsToken('UPDATE users'))->willReturn($statement); $statement->execute(['user_uuid' => $uuid->getBytes(), 'email_address' => $email, 'password' => $password, 'display_name' => $displayName])->shouldBeCalled(); $statement->rowCount()->willReturn(1); $this->objectRepository->update(User::TYPE, $uuid)->shouldBeCalled(); $this->pdo->commit()->shouldBeCalled(); $this->update($user); }
public function it_can_update_a_collection(ConfigCollection $collection, \PDOStatement $itemStatement1, \PDOStatement $itemStatement2) { $uuid = Uuid::uuid4(); $items = ['k1' => 'v1', 'k2' => 'v2']; $collection->getUuid()->willReturn($uuid); $collection->getItems()->willReturn($items); $collection->metaDataSetUpdateTimestamp(new Argument\Token\TypeToken(\DateTimeImmutable::class))->willReturn($collection); $this->pdo->beginTransaction()->shouldBeCalled(); $this->objectRepository->update(ConfigCollection::TYPE, $uuid)->shouldBeCalled(); $this->pdo->prepare(new Argument\Token\StringContainsToken('UPDATE config_items'))->willReturn($itemStatement1, $itemStatement2, false); $itemStatement1->execute(['config_collection_uuid' => $uuid->getBytes(), 'name' => 'k1', 'value' => json_encode('v1')])->shouldBeCalled(); $itemStatement2->execute(['config_collection_uuid' => $uuid->getBytes(), 'name' => 'k2', 'value' => json_encode('v2')])->shouldBeCalled(); $this->pdo->commit()->shouldBeCalled(); $this->update($collection); }
/** * @param $primaryPid * @param $transferPid * * @return bool */ public function merge($primaryPid, $transferPid) { try { $this->conn->beginTransaction(); foreach ($this->tables as $t) { $this->conn->exec("UPDATE `{$t}` SET `pid` = '{$primaryPid}' WHERE `pid` = '{$transferPid}'"); } $this->conn->exec("DELETE FROM `patient` WHERE `pid` = '{$transferPid}'"); $this->conn->commit(); return true; } catch (Exception $e) { error_log($e->getMessage()); $this->conn->rollBack(); return false; } }
public function commit() { $this->transactionNestingLevel--; if ($this->transactionNestingLevel == 0 && $this->db->inTransaction()) { $this->db->commit(); } }
public function commit() { $start = millitime(); $ret = parent::commit(); function_log('PDO->commit()', millitime() - $start); return $ret; }
function commit() { if (!--$this->transactionCounter) { return parent::commit(); } return $this->transactionCounter >= 0; }
/** * Execulta sentenças sql do tipo UPDATE, DELETE, INSERT, CREATE TABLE, etc. * * @param string $slq * @return true - sucesso | false - falha */ public function executaSqlRetornoID($sql) { $this->ultimoID = null; if (!$this->conectarNoBancoDeDados()) { return false; } try { $this->conexao->beginTransaction(); $this->resultado = $this->conexao->prepare($sql); $this->resultado->execute(); if (!$this->resultado) { $this->conexao->rollBack(); $this->desconectar(); return false; } } catch (PDOException $erro) { $this->conexao->rollBack(); $this->desconectar(); return false; } $this->ultimoID = $this->conexao->lastInsertId(); $this->conexao->commit(); $this->desconectar(); return true; }
public function updateBlockForPage(PageBlock $block, Page $page) { if (!$page->getUuid()->equals($block->getPage()->getUuid())) { throw new \OutOfBoundsException('PageBlock must belong to page to be added to it.'); } $this->pdo->beginTransaction(); try { $query = $this->executeSql(' UPDATE page_blocks SET parameters = :parameters, sort_order = :sort_order, status = :status WHERE page_block_uuid = :page_block_uuid ', ['page_block_uuid' => $block->getUuid()->getBytes(), 'parameters' => json_encode($block->getParameters()), 'sort_order' => $block->getSortOrder(), 'status' => $block->getStatus()->toString()]); // When at least one of the fields changes, the rowCount will be 1 and an update occurred if ($query->rowCount() === 1) { $this->objectRepository->update(Page::TYPE, $page->getUuid()); $page->metaDataSetUpdateTimestamp(new \DateTimeImmutable()); $this->objectRepository->update(PageBlock::TYPE, $block->getUuid()); $block->metaDataSetUpdateTimestamp(new \DateTimeImmutable()); } $this->pdo->commit(); } catch (\Throwable $exception) { $this->pdo->rollBack(); throw $exception; } }
/** * Seed database from configuration * * @return void */ public function seedFromConfig() { // Begin transation $this->pdo->beginTransaction(); // Seed tables foreach ($this->schema['seed'] as $schema) { if (isset($this->tables[$schema['table']])) { $table = $this->tables[$schema['table']]; if (isset($schema['truncate']) && ($sql = $this->getTruncate($table))) { $this->pdo->exec($sql); } if (isset($schema['values'])) { $sql = $this->getInsert($table, $schema['values']); $stm = $this->pdo->prepare($sql); $values = array(); foreach ($schema['values'] as $k => $v) { $values[] = $this->parseValue($v); } $stm->execute($values); } } } // Commit changes $this->pdo->commit(); }
/** * Executes the critical code within a transaction. * * It's up to the user to set the correct transaction isolation level. * However if the transaction fails, the code will be executed again in a * new transaction. Therefore the code must not have any side effects * besides SQL statements. Also the isolation level should be conserved for * the repeated transaction. * * A transaction is considered as failed if a PDOException or an exception * which has a PDOException as any previous exception was raised. * * If the code throws any other exception, the transaction is rolled back * and won't be replayed. * * @param callable $code The synchronized execution block. * @return mixed The return value of the execution block. * @SuppressWarnings(PHPMD) * * @throws \Exception The execution block threw an exception. * @throws LockAcquireException The transaction was not commited. */ public function synchronized(callable $code) { return $this->loop->execute(function () use($code) { try { // BEGIN $this->pdo->beginTransaction(); } catch (\PDOException $e) { throw new LockAcquireException("Could not begin transaction.", 0, $e); } try { // Unit of work $result = call_user_func($code); $this->pdo->commit(); $this->loop->end(); return $result; } catch (\Exception $e) { $this->rollBack($e); if ($this->hasPDOException($e)) { return; // Replay } else { throw $e; } } }); }