Module: Simple::SQL::Transactions

Included in:
Simple::SQL
Defined in:
lib/simple/sql/transactions.rb

Overview

private

Constant Summary collapse

SELF =
self

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.nesting_levelObject



5
6
7
# File 'lib/simple/sql/transactions.rb', line 5

def self.nesting_level
  Thread.current[:nesting_level] ||= 0
end

.nesting_level=(nesting_level) ⇒ Object



9
10
11
# File 'lib/simple/sql/transactions.rb', line 9

def self.nesting_level=(nesting_level)
  Thread.current[:nesting_level] = nesting_level
end

Instance Method Details

#transaction(&block) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/simple/sql/transactions.rb', line 13

def transaction(&block)
  # Notes: by using "ensure" (as opposed to rescue) we are rolling back 
  # both when an exception was raised and when a value was thrown. This 
  # also means we have to track whether or not to rollback. i.e. do roll
  # back when we yielded to &block but not otherwise.
  #
  # Also the transaction support is a bit limited: you cannot rollback.
  # Rolling back from inside a nested transaction would require SAVEPOINT
  # support; without the code is simpler at least :)
  if SELF.nesting_level == 0
    transaction_started = true
    ask "BEGIN"
  end

  SELF.nesting_level += 1

  return_value = yield

  # Only commit if we started a transaction here.
  if transaction_started
    ask "COMMIT"
    transaction_committed = true
  end

  return_value
ensure
  SELF.nesting_level -= 1
  if transaction_started && !transaction_committed
    ask "ROLLBACK"
  end
end