On Tue, 30 Jan 2007 [email protected] wrote:
already existing, and if not, to have a set of SQLite statements create it,
which I probably place in their own class, as the SQL can change, and this
would provide easier maintenance, and a better re-usability of the code,
hopefully you realize this code contains a race condition. if you use a
step process to check that the database is created and, if not, to
create it -
you risk that another process might create it in between those two
cleaner way to do it is to use execptions:
harp:~ > cat a.rb
SCHEMA = <<-SCHEMA
create table t(
def initialize path
@path = path
@db = SQLite::Database.new @path
@db.execute SCHEMA rescue nil
@db.execute 'select * from t limit 1'
here, the db is always created and initialized with the SCHEMA.
trying to create the table twice would throw an error, which is ingored.
because ignoring this error might mask a real failure to set the db a
simplistic method, in this case, is used to make sure the database looks
it’s supposed to. note that this whole thing is based on the knowledge
sqlite uses it’s own locking to ensure atmoicity.
in any case, the pattern of
“try it and recover if it blows up”
is often a good solution where testing a condition and then acting on it
cannot be done in one step to avoid a race condition.
btw. sqlite and ruby are a good combination - i use them heavily in my