[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

how to atomically move a file and update a database?

wrex

6/3/2006 6:38:00 AM

I've got an application where I need to do three things in an atomic
transaction:

1) move a file from one subdirectory to another (in the same
filesystem)

2) update an activerecord object with the resulting path to the the
new location

3) call the save method on the activerecord object.

If any one of these three operations fails, I need to ensure the file
remains in it's original location (or is moved back to it's original
location) and that the database remains in it's original state.

What's a clean, idiomatic, and robust method in ruby to accomplish
this? (My table supports transactions, but how do I make the file
move/rename part of the transaction?)

Many thanks for any help.
--
Rex

2 Answers

Robert Klemme

6/3/2006 7:46:00 AM

0

wrex wrote:
> I've got an application where I need to do three things in an atomic
> transaction:
>
> 1) move a file from one subdirectory to another (in the same
> filesystem)
>
> 2) update an activerecord object with the resulting path to the the
> new location
>
> 3) call the save method on the activerecord object.
>
> If any one of these three operations fails, I need to ensure the file
> remains in it's original location (or is moved back to it's original
> location) and that the database remains in it's original state.
>
> What's a clean, idiomatic, and robust method in ruby to accomplish
> this? (My table supports transactions, but how do I make the file
> move/rename part of the transaction?)
>
> Many thanks for any help.

I don't think there is an easy way to do it really transactional (there
would probably be if you stored your files in the DB, say in a BLOB).

You might get close by doing

open DB TX
update record
create hard link in filesystem on new location to old file location
commit DB TX
remove link to file in old location

rescue if anything fails
remove new link
TX rollback

This works only when files are moved inside the same filesystem.

HTH

robert

wrex

6/4/2006 3:39:00 AM

0


Robert Klemme wrote:

> open DB TX
> update record
> create hard link in filesystem on new location to old file location
> commit DB TX
> remove link to file in old location
>
> rescue if anything fails
> remove new link
> TX rollback

Thanks -- this is close enough for my needs.

I was trying something similar using rename, but I like the two-phase
nature of link/unlink better (for one thing I can at least detect
problems if any file in the source directory ever has more than one
link after the script runs).

Regards,
--
Rex