transaction.cc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (c) 2011 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "sql/transaction.h"
  5. #include "base/check.h"
  6. #include "base/sequence_checker.h"
  7. #include "sql/database.h"
  8. namespace sql {
  9. Transaction::Transaction(Database* database) : database_(*database) {
  10. DCHECK(database);
  11. }
  12. Transaction::~Transaction() {
  13. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  14. #if DCHECK_IS_ON()
  15. DCHECK(begin_called_)
  16. << "Begin() not called immediately after Transaction creation";
  17. #endif // DCHECK_IS_ON()
  18. if (is_active_)
  19. database_.RollbackTransaction();
  20. }
  21. bool Transaction::Begin() {
  22. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  23. #if DCHECK_IS_ON()
  24. DCHECK(!begin_called_) << __func__ << " already called";
  25. begin_called_ = true;
  26. #endif // DCHECK_IS_ON()
  27. DCHECK(!is_active_);
  28. is_active_ = database_.BeginTransaction();
  29. return is_active_;
  30. }
  31. void Transaction::Rollback() {
  32. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  33. #if DCHECK_IS_ON()
  34. DCHECK(begin_called_) << __func__ << " called before Begin()";
  35. DCHECK(!commit_called_) << __func__ << " called after Commit()";
  36. DCHECK(!rollback_called_) << __func__ << " called twice";
  37. rollback_called_ = true;
  38. #endif // DCHECK_IS_ON()
  39. DCHECK(is_active_) << __func__ << " called after Begin() failed";
  40. is_active_ = false;
  41. database_.RollbackTransaction();
  42. }
  43. bool Transaction::Commit() {
  44. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  45. #if DCHECK_IS_ON()
  46. DCHECK(begin_called_) << __func__ << " called before Begin()";
  47. DCHECK(!rollback_called_) << __func__ << " called after Rollback()";
  48. DCHECK(!commit_called_) << __func__ << " called after Commit()";
  49. commit_called_ = true;
  50. #endif // DCHECK_IS_ON()
  51. DCHECK(is_active_) << __func__ << " called after Begin() failed";
  52. is_active_ = false;
  53. return database_.CommitTransaction();
  54. }
  55. } // namespace sql