本文整理汇总了PHP中PDO::beginTransaction方法的典型用法代码示例。如果您正苦于以下问题:PHP PDO::beginTransaction方法的具体用法?PHP PDO::beginTransaction怎么用?PHP PDO::beginTransaction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PDO
的用法示例。
在下文中一共展示了PDO::beginTransaction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: beginTransaction
public function beginTransaction()
{
if (!$this->transactionCounter++) {
return $this->pdo->beginTransaction();
}
return $this->transactionCounter >= 0;
}
示例2: _logCompletedJob
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();
}
示例3: synchronized
/**
* 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;
}
}
});
}
示例4: runMigration
/**
* Выполняет запрос миграцию.
* @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;
}
示例5: beginTransaction
/**
* {@inheritdoc}
*/
public function beginTransaction()
{
$this->profiler->startQuery("START TRANSACTION;");
$result = $this->pdo->beginTransaction();
$this->profiler->stopQuery();
return $result;
}
示例6: getInstance
/**
* Creates, when necessary, and returns a PDO instance
* @return PDO
*/
public static function getInstance($usesTransaction = false) {
try {
if (!self::$instance) {
self::$instance = new \PDO(
\core\Config::DATABASE_ADDRESS,
\core\Config::DATABASE_USERNAME,
\core\Config::DATABASE_PASSWORD,
array(
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
\PDO::ATTR_PERSISTENT => true
)
);
self::$instance->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
if ($usesTransaction && !self::$openTransaction) {
self::$instance->beginTransaction();
self::$openTransaction = true;
}
return self::$instance;
} catch (\Exception $e) {
$ex = new RepositoryException($e);
$ex->setFatal(true);
throw $ex;
}
}
示例7: _performUpdates
/**
* 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);
}
}
}
}
示例8: processEntity
/**
* Process an entity by reading / writing to the DB
*
* @param string $table
* @param callable|null $callback
* @param bool $pretend
* @param bool $returnResult
*
* @return void|array
*/
public function processEntity($table, $callback = null, $pretend = true, $returnResult = false)
{
$queries = array();
$actionsOnThatEntity = $this->whatToDoWithEntity($table);
if ($actionsOnThatEntity & self::TRUNCATE_TABLE) {
$where = $this->getWhereConditionInConfig($table);
$query = $this->runDelete($table, $where, $pretend);
$returnResult === true ? array_push($queries, $query) : '';
}
if ($actionsOnThatEntity & self::UPDATE_TABLE) {
// I need to read line by line if I have to update the table
// to make sure I do update by update (slower but no other choice for now)
$i = 0;
$this->preparedStmt = null;
$key = $this->getPrimaryKey($table);
$res = $this->pdo->query("SELECT {$key} FROM {$table}");
$res->setFetchMode(\PDO::FETCH_ASSOC);
$this->pdo->beginTransaction();
while ($row = $res->fetch()) {
$val = $row['id'];
$data = $this->generateFakeData($table);
if ($pretend === false) {
$this->runUpdate($table, $data, $key, $val);
}
$returnResult === true ? array_push($queries, $this->buildUpdateSQL($table, $data, "{$key} = '{$val}'")) : '';
if (!is_null($callback)) {
$callback(++$i);
}
}
// Commit, even if I am in pretend (that will do ... nothing)
$this->pdo->commit();
}
return $queries;
}
示例9: startTransaction
public function startTransaction()
{
if ($this->pdo->inTransaction()) {
throw new \RuntimeException('PDO is already in a transaction. Nested transactions are not supported.');
}
$this->pdo->beginTransaction();
}
示例10: beginTransaction
public function beginTransaction()
{
++$this->transactionsCount;
if ($this->transactionsCount == 1) {
$this->pdo->beginTransaction();
}
}
示例11: beginTransaction
/**
* Démarre une transaction ou créer un point de sauvegarde dans la transaction courante
* @return bool
*/
private function beginTransaction()
{
if (!$this->transactionCounter++) {
return $this->pdolink->beginTransaction();
}
$this->pdolink->exec('SAVEPOINT trans'.$this->transactionCounter);
return true;
}
示例12: beginTransaction
public function beginTransaction()
{
if (!$this->transactionNestable() || $this->transLevel == 0) {
$this->dbh->beginTransaction();
} else {
$this->dbh->exec(sprintf('SAVEPOINT LEVEL%d', $this->transLevel));
}
$this->transLevel++;
}
示例13: __construct
/**
* @param string $file
*/
public function __construct($file)
{
$this->db = new \PDO('sqlite:' . $file);
$this->db->exec('CREATE TABLE metadata (name TEXT, value TEXT);');
$this->db->exec('CREATE TABLE tiles (zoom_level INTEGER, tile_column INTEGER, tile_row INTEGER, tile_data BLOB);');
$this->db->exec('CREATE UNIQUE INDEX tile_index ON tiles (zoom_level, tile_column, tile_row);');
$this->db->beginTransaction();
$this->addMetaStmt = $this->db->prepare('INSERT INTO metadata (name, value) VALUES (:name, :value)');
$this->addTileStmt = $this->db->prepare('INSERT INTO tiles (zoom_level, tile_column, tile_row, tile_data) VALUES (:z, :x, :y, :data)');
}
示例14: beginTransaction
/**
* starts transaction
*/
public function beginTransaction()
{
$this->checkConnection();
try {
$this->_pdo->beginTransaction();
$this->_lastCheckTime = time();
} catch (\PDOException $e) {
$this->_error($e->getMessage(), FQDBException::PDO_CODE, $e);
}
}
示例15: run
/**
* @param string $script
*/
public function run($script)
{
try {
$this->pdo->beginTransaction();
$this->pdo->query($script);
$this->pdo->commit();
} catch (\PDOException $e) {
$this->pdo->rollBack();
}
}