Clear ORM
Search…
Transaction & Savepoints
Transaction are safeguard to ensure than a list of operation on a database are only permanent if they can all succeed as atomic action.
In Clear, the usage of transaction is simple:
1
Clear::SQL.transaction do
2
yacine.withdraw(100)
3
mary.deposit(100)
4
end
Copied!
In the example above, if one of the method fail, the whole transaction block will be reverted to initial state.

Rollback

You can manually rollback a transaction if something went wrong:
1
Clear::SQL.transaction do
2
yacine.withdraw(100)
3
Clear::SQL.rollback if mary.is_suspicious?
4
mary.deposit(100)
5
end
Copied!
In this case, the block will be returned, nothing will be committed in the database and no error will be thrown

Nested transaction

Nested transaction are not working, but save points are used for that. Let's take an example:
1
Clear::SQL.transaction do
2
puts "I do something"
3
Clear::SQL.transaction do
4
puts "I do another thing"
5
Clear::SQL.rollback
6
puts "This should not print"
7
end
8
puts "This will never reach too."
9
end
Copied!
In this case, the output will be:
1
# BEGIN
2
I do something
3
I do another thing
4
# ROLLBACK
Copied!
Since nested transaction are not permitted, rollback will rollback the top-most transaction. Any nested transaction block will perform SQL-wise, only the block content will be executed.

Savepoints

For nested transaction, you may want to use save points:
1
Clear::SQL.with_savepoint do
2
puts "I do something"
3
Clear::SQL.with_savepoint do
4
puts "I do another thing"
5
Clear::SQL.rollback
6
puts "This should not print"
7
end
8
puts "Eventually, I do something else"
9
end
Copied!
In this case, the output will be:
1
# BEGIN
2
# SAVEPOINT xxx1
3
I do something
4
# SAVEPOINT xxx2
5
I do another thing
6
# ROLLBACK TO SAVEPOINT xxx2
7
Eventually, I do something else
8
# RELEASE SAVEPOINT xxx1
9
# COMMIT
Copied!
As you can see, save points are backed by a transaction block; rollback inside a save point block will rollback the block only and not all the transaction. Any unhandled exception will still rollback the full transaction.
Last modified 2yr ago