4

I'm building a small web app using sinatra + datamapper. The app is based on an sqlite database which contains a big number of records in table1 and nothing in table2.

My dir structure is the following:

total 32
-rw-r--r--   1 atma  staff  1895 31 Δεκ 21:35 application.rb
drwxr-xr-x   6 atma  staff   204 31 Δεκ 21:10 archive/
-rw-r--r--@  1 atma  staff    82 23 Δεκ 23:59 config.ru
drwxr-xr-x  10 atma  staff   340 31 Δεκ 21:38 lib/
drwxr-xr-x   4 atma  staff   136 27 Δεκ 20:01 public/
drwxr-xr-x   6 atma  staff   204 24 Δεκ 00:00 views/
ls -R lib
database.rb       db_scheme.rb      db_status.yaml    fileutils.rb      greek-dict.txt        greekcase.rb      rankmanager.rb    wodb_el_v0.0.1.db

The database is located in lib/wodb_el_v0.0.1.db. All these files contain classes.

When I run tests in rankmanager.rb or database.rb by calling the classes by adding lines like:

Class TestClass
[code goes here]
end
x = TestClass.new
x.test_class_method

When I do that everything runs fine. When I remove the lines to perform the test (where I create the object and run the method) and require_relative in my application.rb, it erases the database instead of using it. The database is handled by the db_scheme.rb which is loaded by database.rb.

My db_scheme.rb is the gist.

Any idea why datamapper behaves like that?

ps. I load data to the database by running a manually a method from database.rb which creates the database.

Best Regards and thanks for your time in advance!

patm
  • 1,420
  • 14
  • 19

1 Answers1

1

In your db_scheme.rb you have:

version = '0.0.1' # database version
db = 'wodb_el_v' + version + '.db' #db location

DataMapper.setup( :default, "sqlite3:///Users/atma/Dropbox/Programming/Projects/Local/HOWDB/lib/#{db}" )

...

if File.exists?(db)
    DataMapper.auto_upgrade!
else
    DataMapper.auto_migrate! # erases and creates the database. This needs run before any work is done with the database!
end

The line if File.exists?(db) checks to see if the file exists in the current working directory, i.e. the directory you start your program from. When you start Thin, that directory will be the parent directory, not the lib directory, so the file won’t be found and auto_migrate! will be run, erasing your data.

You should make sure you always deal with the absolute path to your database file:

version = '0.0.1' # database version
db = File.expand_path('../wodb_el_v#{version}.db', __FILE__)

DataMapper.setup(:default, "sqlite3:///#{db}" )

if File.exists?(db) #db is now the absolute path
  # as before...
matt
  • 78,533
  • 8
  • 163
  • 197