Module: Simple::SQL::SimpleTransactions

Included in:
Connection::PgConnection
Defined in:
lib/simple/sql/simple_transactions.rb

Overview

private

Instance Method Summary collapse

Instance Method Details

#transaction(&_block) ⇒ Object



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
44
45
# File 'lib/simple/sql/simple_transactions.rb', line 14

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 tx_nesting_level == 0
    exec "BEGIN"
    tx_started = true
  end

  self.tx_nesting_level += 1

  return_value = yield

  # Only commit if we started a transaction here.
  if tx_started
    exec "COMMIT"
    tx_committed = true
  end

  return_value
ensure
  self.tx_nesting_level -= 1
  if tx_started && !tx_committed
    exec "ROLLBACK"
  end
end

#tx_nesting_levelObject



6
7
8
# File 'lib/simple/sql/simple_transactions.rb', line 6

def tx_nesting_level
  @tx_nesting_level ||= 0
end

#tx_nesting_level=(tx_nesting_level) ⇒ Object



10
11
12
# File 'lib/simple/sql/simple_transactions.rb', line 10

def tx_nesting_level=(tx_nesting_level)
  @tx_nesting_level = tx_nesting_level
end