Database Reference
In-Depth Information
# roll back within eval to prevent rollback
# failure from terminating the script
eval { $dbh -> rollback (); };
}
# restore error-handling and auto-commit attributes
$dbh -> { AutoCommit } = $attr_ref -> { AutoCommit };
$dbh -> { PrintError } = $attr_ref -> { PrintError };
$dbh -> { RaiseError } = $attr_ref -> { RaiseError };
}
By using those two functions, our sample transaction can be performed easily as follows:
$ref = transaction_init ( $dbh );
eval
{
# move some money from one person to the other
$dbh -> do ( "UPDATE money SET amt = amt - 6 WHERE name = 'Eve'" );
$dbh -> do ( "UPDATE money SET amt = amt + 6 WHERE name = 'Ida'" );
# all statements succeeded; commit transaction
$dbh -> commit ();
};
transaction_finish ( $dbh , $ref , $@ );
In Perl DBI, an alternative to manipulating the AutoCommit attribute manually is to
begin a transaction by invoking begin_work() . This method disables AutoCommit and
causes it to be enabled again automatically when you invoke commit() or rollback()
later.
17.5. Using Transactions in Ruby Programs
Problem
You want to perform a transaction in a Ruby DBI script.
Solution
Use the standard DBI transaction support mechanism. Actually, Ruby provides two
mechanisms.
Discussion
The Ruby DBI module provides two ways to perform transactions, although both of
them rely on manipulation of auto-commit mode. One approach uses a begin/
rescue block, and you invoke the commit and rollback methods explicitly:
begin
dbh [ 'AutoCommit' ] = false
dbh . do ( "UPDATE money SET amt = amt - 6 WHERE name = 'Eve'" )
dbh . do ( "UPDATE money SET amt = amt + 6 WHERE name = 'Ida'" )
Search WWH ::




Custom Search