Skip to content

Local Application Database & Storages

Benjamin Eder edited this page Dec 17, 2018 · 4 revisions

We needed a way to cache resources (like notice board entries) locally. Thus a class called AppDatabase has been created which will give you access to an SQLite database via AppDatabase.getDatabase(). For more information on how to use the Database see here.

For each resource there should be an instance of the Storage interface, which provides basic methods write, read and clear. The NoticeBoardStorage has already been implemented and serves as an example.

Database Patches

Sometimes we need to create new tables, update tables, ... In order to provide an easy way to extend the database there are DatabasePatch classes. Each database patch has as version (to which the database will be upgraded after the patch), a upgrade and a downgrade method. For example you create a patch to create a new table called EXAMPLE, you will create a new Patch class called PATCH{VERSION} where {VERSION} will be the patch version. Then you implement the getVersion method which returns the version number, the upgrade method where you create the table like so:

  @override
  Future<void> upgrade(Database db, int currentVersion) async {
    await db.transaction((transaction) async {
      await transaction.execute("""
      CREATE TABLE EXAMPLE (
        id INTEGER,
        PRIMARY KEY (id)
      )
      """);
    });
  }

and finally the downgrade method:

  @override
  Future<void> downgrade(Database db, int currentVersion) async {
    await db.transaction((transaction) async {
      await transaction.execute("""
      DROP TABLE EXAMPLE
      """);
    });
  }

The patches will only be executed if the currentVersion is not higher (in case of upgrade) than the patch version or not lower (in case of downgrade) than the patch version.

As last step update AppDatabase._databaseVersion to the new patch version, so that the database will be patched!

Clone this wiki locally