Class: SqlPostgres::Transaction
- Inherits:
-
Object
- Object
- SqlPostgres::Transaction
- Defined in:
- lib/sqlpostgres/Transaction.rb
Overview
Instance Method Summary collapse
-
#abort ⇒ Object
Abort this transaction.
-
#commit ⇒ Object
Commit this transaction.
-
#initialize(connection = Connection.default) ⇒ Transaction
constructor
Create an SQL transaction, yield, and then end the transaction.
Constructor Details
#initialize(connection = Connection.default) ⇒ Transaction
Create an SQL transaction, yield, and then end the transaction. If an exception occurs, the transaction is aborted.
If no connection is given, then the default connection is used.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/sqlpostgres/Transaction.rb', line 27 def initialize(connection = Connection.default) @state = :open @finished = false @connection = connection @connection.exec("begin transaction") begin result = yield(self) commit result rescue Exception abort raise end end |
Instance Method Details
#abort ⇒ Object
Abort this transaction. This is done for you when an exception occurs within the block you passed to “new”. Call this when you want to abort a transaction without throwing an exception.
Example:
** example: transaction_abort
Transaction.new(connection) do |transaction|
insert = Insert.new('foo', connection)
insert.insert('i', 1)
insert.exec
transaction.abort
end
select = Select.new(connection)
select.select('i')
select.from('foo')
p select.exec # []
**
94 95 96 97 98 |
# File 'lib/sqlpostgres/Transaction.rb', line 94 def abort unless @finished do_abort end end |
#commit ⇒ Object
Commit this transaction. This is done for you unless an exception occurs within the block you passed to “new”. Call this when you want to commit the transaction before raising an exception – in other words, when you want to keep your database changes even though an exception is about to occur.
Example:
** example: transaction_commit
begin
Transaction.new(connection) do |transaction|
insert = Insert.new('foo', connection)
insert.insert('i', 1)
insert.exec
transaction.commit
raise
end
rescue Exception => e
end
select = Select.new(connection)
select.select('i')
select.from('foo')
p select.exec # [{"i"=>1}]
**
68 69 70 71 72 |
# File 'lib/sqlpostgres/Transaction.rb', line 68 def commit unless @finished do_commit end end |