Israel,

On Mar 17, 2011, at 4:48 PM, Xavier (DBIYF) wrote:

> On 18/03/11 10:26 AM, Israel Ben Guilherme Fonseca wrote:
>> Why the transaction is attached to the instance?
> just as a convenience, especially inside your model code.

The key point to keep in mind is that transactions are tied to /repositories/, 
not models or instances.  If all the models you are operating with are located 
inside the same repository (specified in database.yml), then a new transaction 
on that repository will apply to *all of them*.

So: AnyOfYourModel.transaction is equivalent to 
AnyOfYourModel.repository.transaction is equivalent to 
::DataMapper.repository(AnyOfYourModel.repository.name).transaction.  If the 
repository name is unspecified in your database.yml, OR if it is specified in 
your database.yml and named "default", then ::DataMapper.repository.transaction 
also works (because repository defaults to "default" name).

There are a few other ways to get at the transaction method for convenience, 
but the key conceptual point to remember is that transactions are tied to 
repositories (which, in an RDBMS/SQL context, is a database instance).

>> The "link" API is very
>> weird.
> I don't know what this is but I've never used it

I've never seen the link() usage, and I would definitely recommend avoiding it. 
 I use transactions heavily and have never seen it or needed it.

>> Wouldn't be nicier a global method to start/commit/rollback
>> transactions?And how can I force a rollback?
> 
> AnyOfYourModel.transaction do |t|
>  t.rollback
> end

Exceptions also result in a ROLLBACK: 

begin
        AnyOfYourModel.transaction do 
                do_stuff
                if something_broke
                        raise some_exception
                end
        end
rescue some_exception
end

Also, any non-exceptional exit from a transactional block results in a COMMIT:

AnyOfYourModel.transaction do
        next # leaves block immediately, calls commit
        return # due to a special hack in the code, this too exits the block 
and calls commit
end

And finally, if you're using MySQL or PostgreSQL, as of 1.1 you can use nested 
transactions within the same repository (just nest transaction blocks, and 
after the first one, SAVEPOINTs will be employed instead).

cheers,
--jordan

-- 
You received this message because you are subscribed to the Google Groups 
"DataMapper" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/datamapper?hl=en.

Reply via email to