Datamapper erases sqlite db when accessing through thin (sinatra)

I am creating a small web application using synatra + datamapper. The application is based on the sqlite database, which contains a large number of records in table1 and nothing in table2.

The structure of my file is as follows:

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 of these files contain classes.

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

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

When I do, everything works fine. When I delete the lines to run the test (where I create the object and run the method) and require_relative in my application.rb , it deletes the database instead of using it . The database is processed by db_scheme.rb , which is loaded by database.rb .

My db_scheme.rb - gist .

Any idea why datamapper is behaving like this?

ps. I load the data into the database by manually running the method from database.rb that creates the database.

Best wishes and thanks for your time in advance!

+4
source share
1 answer

In 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 if the file exists in the current working directory, that is, in the directory from which you run your program. When you start Thin, this directory will be the parent directory, not the lib directory, so the file will not be found and auto_migrate! will be started by erasing your data.

You must ensure that you are always dealing with an absolute path to the 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... 
+1
source

All Articles