how to atomically move a file and update a database?

W

wrex

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.
 
R

Robert Klemme

wrex said:
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
 
W

wrex

Robert said:
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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top