Fork me on GitHub

Migrating database from previous version

Most apps go through database schema changes as they grow and release multiple revisions. Sugar provides an easy way to upgrade the database. The inspiration is again from the way Rails migrations work. Here's how you'd do it:

  • Create a folder named sugar_upgrades in your assets folder.

  • Create a file named <version>.sql in that folder, which corresponds to the database version. eg. 1.sql, 2.sql This file would contain all the update/alter queries for that particular version.

  • Change the VERSION metadata field in AndroidManifest.xml to the appropriate version.

    <application android:label="@string/app_name" android:icon="@drawable/icon"
    android:name="com.orm.SugarApp">
      .
      .
      <meta-data android:name="DATABASE" android:value="sugar_example.db" />
      <meta-data android:name="VERSION" android:value="2" />
      .
      .
    </application>
  • Sugar takes care of upgrading the database from its present version to the upgraded version. For eg: if the database is currently at version 1 and the upgraded version is 4, it'd look for 2.sql, 3.sql and 4.sql and execute all of the present files in that order.

  • Note that Sugar will automatically create tables for new entities, so your migration script only needs to cater for alterations to existing tables.

This is a normal sql script file. You can add all your alter and insert/update queries, one line at a time. Each line is terminated by a ; (semicolon).

2.sql
alter table NOTE add NAME TEXT;