Infant Dev
Infant Dev

Reputation: 1749

How to use sugar orm to run migrations

I have an existing Android application which pre packages a database called app.db . The app.db file resides in src/main/res/raw . On starting the application it gets copied over to data/data/app/databases.

The current version of db is 2, which was set using SQLiteOpenHelper. I don't want to bind this db to any model object but only add or delete rows from it by running some dmls.

The Manifest looks like this:

<application
   android:label="@string/app_name"
   android:icon="@drawable/launcher"
   android:name="MyApplication">
   ...
 <meta-data android:name="DATABASE" android:value="app.db" />
 <meta-data android:name="VERSION" android:value="3" />
 <meta-data android:name="QUERY_LOG" android:value="true" />
</application>

MyAppplication class extends SugarApp. I created a folder called sugar_upgrades in assets and created a file in it called 3.sql. This file contains a script like:

DELETE FROM images WHERE id = 53;

But after running the application this script never runs. I think the issue is Sugar is expecting the db to be present in /data folder. But in the start of the application it is present in res/raw and that is why it is not able to pick it up. Any way that I can achieve this?

Upvotes: 3

Views: 1242

Answers (1)

Andrea Thacker
Andrea Thacker

Reputation: 3470

I decided to write an answer rather than a comment because I needed some extra formatting help. I will update this post as needed.

First of all, you should look at the SchemaGenerator class here. You will notice that there are a couple of log statements that could help narrow down your issue. Here is one for example:

Log.i("Sugar", "not a sugar script. ignored." + file);

So I would suggest searching your logcat output for the "Sugar" tag and see if there is any useful information that is shown.

A second place that would be valuable to debug would be the SugarDb class found here. This class extends SQLiteOpenHelper and implements the onUpgrade method:

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
    schemaGenerator.doUpgrade(sqLiteDatabase, oldVersion, newVersion);
}

It might be helpful to clone the Sugar source code and compile the project manually and add it as a dependency. Then you will be able testing your SQL query directly on the SQLite database like so:

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
    schemaGenerator.doUpgrade(sqLiteDatabase, oldVersion, newVersion);

    sqLiteDatabase.rawQuery("DELETE FROM images WHERE id = ?", new String[]{"53"});
}

Finally, if you discover the the data is not available like you suspect in the /data folder at startup you would have to modify the Sugar source code to alter the data once it has been loaded.

Upvotes: 0

Related Questions