LoginSignup
21
14

More than 5 years have passed since last update.

おまえ、もしかしてまだ、beginTransactionが死なないとでも思ってるんじゃないかね?

Last updated at Posted at 2017-11-28

ほんぺ

try {
    $dbh->beginTransaction();

    // この間に色々処理が書いてある。

    $dbh->commit();
} catch (Exception $e) {
    $dbh->rollBack();
    log::write('ダメみたいですね…');
    log::write($e);
    throw $e;
}

っていう感じでPDOを操作しているPHPの処理があったんですが、
beginTransactionが失敗していてまともにログ出力出来ていなくて久々にキレそうになったので、怒りの殴り書きヽ(`Д´)ノプンプン


beginTransaction()が失敗していた場合、commit()を実行する際に有効なトランザクションが存在しないため、PDOExceptionがスローされます。

その後、catch処理に入った後、rollBack()が呼ばれますがここでも有効なトランザクションが存在しないため、PDOExceptionがスローされます。
どうなるかというとrollBack()以下の処理が一切実行されずに本来スローしたい例外がPDOExceptionに置き換わります。

beginTransaction()からcommit()までの間に何も無ければ被害は少ないですが、その間で例外が発生した場合は例外がPDOExceptionに置き換わっているばかりかログに何も記載されておらず死が見えますよ…。

$dbh->beginTransaction();

if (!$dbh->inTransaction()) {
    throw new \Exception('あ、おい待てい!');
}

try {
    // この間に色々処理が書いてある。

    $dbh->commit();
} catch (Exception $e) {
    $dbh->rollBack();
    log::write('ダメみたいですね…');
    log::write($e);
    throw $e;
}

ちょー適当だけど、コレだけでも最悪の事態は防げる。
ちゃんと適切な処理になっているか確認しましょう。というお話。

蛇足

トランザクションが必要な処理はトランザクションにちゃんと入っているか確認してほしい。
こんなウンコードでもいいからさ書いておくと違うんだしさ。頼むよ〜。


function oreoreBeginTransaction($dbh){
    $dbh->beginTransaction();

    if (!$dbh->inTransaction()) {
        log::write('何か足んねぇよなぁ?');
        throw new Exception();
    }
}

function oreoreCommit($dbh){
    if (!$dbh->inTransaction()) {
        log::write('ファッ!?');
        throw new Exception();
    }
    $dbh->commit();
}

function oreoreRollBack($dbh){
    if (!$dbh->inTransaction()) {
        log::write('あのさぁ・・・');
        throw new Exception();
    }
    $dbh->rollBack();
}
21
14
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
14