/** * {@inheritdoc} */ public function rollBack() { $this->profiler->startQuery("ROLLBACK;"); $result = $this->pdo->rollBack(); $this->profiler->stopQuery(); return $result; }
/** * Выполняет запрос миграцию. * @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; }
/** * 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 rollBack() { $this->transLevel--; if (!$this->transactionNestable() || $this->transLevel == 0) { $this->dbh->rollBack(); } else { $this->dbh->exec(sprintf("ROLLBACK TO SAVEPOINT LEVEL%d", $this->transLevel)); } }
public function __destruct() { try { if (!is_null($this->_conn)) { $this->_conn->rollBack(); } } catch (Exception $e) { } }
public function rollBack() { if ($this->transactionsCount == 1) { $this->transactionsCount = 0; $this->pdo->rollBack(); } else { --$this->transactionsCount; } }
public function rollBack() { if ($this->transactionCounter >= 0) { $this->transactionCounter = 0; return $this->pdo->rollBack(); } $this->transactionCounter = 0; return false; }
/** * @param string $script */ public function run($script) { try { $this->pdo->beginTransaction(); $this->pdo->query($script); $this->pdo->commit(); } catch (\PDOException $e) { $this->pdo->rollBack(); } }
public function it_can_rollBack_on_error_during_update_user(User $user) { $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'); $this->pdo->beginTransaction()->shouldBeCalled(); $exception = new \RuntimeException(); $this->pdo->prepare(new Argument\Token\StringContainsToken('UPDATE users'))->willThrow($exception); $this->pdo->rollBack()->shouldBeCalled(); $this->shouldThrow($exception)->duringUpdate($user); }
/** * 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; } }
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; } }
/** * @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; } }
protected function doRollback( $fname = '' ) { if ( $this->mTrxLevel == 0 ) { return; } $this->mConn->rollBack(); $this->mTrxLevel = 0; }
/** * @param String $query * @param array $parameters * @return int|null|string */ public function execute(string $query, $parameters = array()) { try { $this->pdo->beginTransaction(); $stmt = $this->pdo->prepare($query); $stmt->execute($parameters); if ($stmt->errorCode() != 0) { $this->pdo->rollBack(); return 0; } $returnID = $this->pdo->lastInsertId(); $this->pdo->commit(); $stmt->closeCursor(); return $returnID; } catch (\Exception $e) { $this->log->addError("There was an error during a query: ", [$e->getMessage()]); try { $this->pdo = $this->connect(); } catch (\Exception $e2) { $this->log->addCritical("Couldn't reconnect to the database: " . $e->getMessage()); die(1); } } return null; }
/** * Rollback transaction */ public function transactionRollBack() { if (self::$transactionOngoing) { self::$conn->rollBack(); self::$transactionOngoing = false; } }
/** * 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; }
/** * Synchronize uploads. * * @param string $uploadsPath Path to the uploads. * * @throws Exception 'Репозиторий по такому пути не существует' * @throws Exception 'Странный какой то идентификатор родительский.' */ private function syncUploadsAction($uploadsPath = self::UPLOADS_PATH) { $this->checkDBConnection(); $this->title('Синхронизация папки с загрузками'); $this->dbConnect->beginTransaction(); if (substr($uploadsPath, -1) == '/') { $uploadsPath = substr($uploadsPath, 0, -1); } $r = $this->dbConnect->query('SELECT upl_id FROM ' . self::UPLOADS_TABLE . ' WHERE upl_path LIKE "' . $uploadsPath . '"'); if (!$r) { throw new \Exception('Репозиторий по такому пути не существует'); } $PID = $r->fetchColumn(); if (!$PID) { throw new \Exception('Странный какой то идентификатор родительский.'); } $uploadsPath .= '/'; try { $this->dbConnect->query('UPDATE ' . self::UPLOADS_TABLE . ' SET upl_is_active=0 WHERE upl_path LIKE "' . $uploadsPath . '%"'); $this->iterateUploads(implode(DIRECTORY_SEPARATOR, array(HTDOCS_DIR, $uploadsPath)), $PID); $this->dbConnect->commit(); } catch (\Exception $e) { $this->dbConnect->rollBack(); throw new \Exception($e->getMessage()); } }
/** * Saves a given entity or set of entities. * Use the returned instance for further operations as * the save operation might have changed the entity instance completely. * * Notice: In order to save entities, the $additionalColumns have to be set * @param MysqlEntity|MysqlEntity[] $param an entitiy or set of entities * @throws \Exception * @return MysqlEntity|MysqlEntity[] the saved entity or entities */ public function save($param) { try { $this->pdo->beginTransaction(); if (is_array($param)) { foreach ($param as $p) { if ($p instanceof MysqlEntity) { $this->save($p); } } } else { if ($param instanceof MysqlEntity) { if ($param->isPersisted()) { $this->updateEntity($param); } else { $this->insertNewEntity($param); } } } $this->pdo->commit(); return $param; } catch (\Exception $exc) { $this->pdo->rollBack(); throw $exc; } }
/** Database install */ private static function install_schema() { $data = $_SESSION; $sql = str_replace('[[now]]', time(), file_get_contents('assets/sql/anchor.sql')); $dsn = 'mysql:dbname=' . $data['db']['name'] . ';host=' . $data['db']['host'] . ';port=' . $data['db']['port']; $dbh = new PDO($dsn, $data['db']['user'], $data['db']['pass']); try { $dbh->beginTransaction(); $dbh->exec('SET NAMES `utf8`'); $dbh->exec($sql); // create metadata $sql = "INSERT INTO `meta` (`key`, `value`) VALUES ('sitename', ?), ('description', ?), ('theme', ?);"; $statement = $dbh->prepare($sql); $statement->execute(array($data['site']['site_name'], $data['site']['site_description'], $data['site']['theme'])); // create user account $sql = "INSERT INTO `users` (`username`, `password`, `email`, `real_name`, `bio`, `status`, `role`) VALUES (?, ?, ?, 'Administrator', 'Default account for Anchor.', 'active', 'administrator');"; $statement = $dbh->prepare($sql); $statement->execute(array($data['user']['username'], crypt($data['user']['password'], $_SESSION['key']), $data['user']['email'])); $dbh->commit(); } catch (PDOException $e) { Messages::add($e->getMessage()); // rollback any changes if ($dbh->inTransaction()) { $dbh->rollBack(); } } }
/** * Execute a query or a prepared statement with a params array values. * * @param string $queryString * @param array $queryValues in format [:placeholder => 'value'] * * @return mixed */ public function query($queryString, array $queryValues = []) { if (!is_string($queryString) || empty($queryString)) { throw new \InvalidArgumentException(__METHOD__ . ': The specified query is not valid.'); } $this->connect(); $this->resourceHandle = $this->dbConnection->prepare($queryString); try { // start transaction $this->dbConnection->beginTransaction(); // execute the query and return a status $this->executionStatus = $this->resourceHandle->execute($queryValues ?: null); // get last inserted id if present $this->lastInsertedId = $this->dbConnection->lastInsertId(); // finally execute the query $this->dbConnection->commit(); } catch (\PDOException $ex) { // If an error occurs, execute rollback $this->dbConnection->rollBack(); // Return execution status to false $this->executionStatus = false; $this->resourceHandle->closeCursor(); throw new \RuntimeException(__METHOD__ . ": {$ex->getMessage()}\nqueryString: {$queryString}"); } return $this->resourceHandle; }
/** * 回滚事务 */ public function roll_back() { if (!$this->pdo) { $this->connect(); } return $this->pdo->rollBack(); }
public function rollBack() { $start = millitime(); $ret = parent::rollBack(); function_log('PDO->rollBack()', millitime() - $start); return $ret; }
/** * executes all the update classes */ private function _performUpdates() { foreach ($this->_availableUpdates as $rev => $updateList) { foreach ($updateList as $u) { if (!empty($u[3]) && $this->_conn->getAttribute(PDO::ATTR_DRIVER_NAME) != $u[3]) { continue; } $updateFormat = $u[5]; $this->_conn->beginTransaction(); try { $instance = null; if ($updateFormat == 'sql') { require_once 'Indechse/Maintain/Update/SqlExecute.php'; $instance = new Indechse_Maintain_Update_SqlExecute($this->_conn, $rev); $instance->setSql(file_get_contents($this->_updateLocation . '/' . $u[0])); } else { $className = 'Update_' . $u[4]; require_once $this->_updateLocation . '/' . $u[0]; $instance = new $className($this->_conn, $rev); } $instance->update(); $this->_markUpdateComplete($rev, $u[4] . '.' . $u[5]); $this->_conn->commit(); } catch (Exception $ex) { $this->_conn->rollBack(); throw new Exception(sprintf("Update %s (%d) failed with message: %s", $u[0], $rev, $ex->getMessage()), $ex->getCode(), $ex); } } } }
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; } }
function executeQuery($sqlCommand, $parameters) { try { $connection = new PDO('mysql:dbname=taller;host=localhost', 'root', 'mysql'); $command = $connection->prepare($sqlCommand); if ($parameters != null) { foreach ($parameters as $key => $value) { $listaRetorno = array(); $command->bindValue($key, $value); //echo $key."=>".$value."<br>"; } } $command->execute(); $listaRetorno = array(); for ($i = 0; $row = $command->fetch(PDO::FETCH_ASSOC); $i++) { array_push($listaRetorno, $row); } return $listaRetorno; } catch (PDOException $ex) { echo $ex->getMessage(); if ($connection != null) { if ($connection->inTransaction()) { $connection->rollBack(); } } return array(); } finally { //UTILIZADO NA VERSAO DO PHP 5.6 NAS PREVIAS NAO É COMPATÍVEL if ($connection != null) { //FECHA A CONEXAO COM O BANCO DE DADOS $connection = null; } } }
/** * Rollback. * Provides a fluent interface. * * @return PDOMySQL */ public function rollback() { if (isset($this->link) && $this->link->inTransaction()) { $this->link->rollBack(); } return $this; }
public function rollback() { $this->transactionNestingLevel--; if ($this->transactionNestingLevel == 0 && $this->db->inTransaction()) { $this->db->rollBack(); } }
/** * Rolls back an active database transaction * * @return void * @throws ConnectionException */ public function transactionRollback() { if (!$this->connection) { throw new ConnectionException('No database connection'); } $this->connection->rollBack(); }