Database migration is a headache for any developer working in an application with a non-trivial state. Whenever the state structure changes it must be depicted in the underlying database as well. Coming from a Java background I am used to having libraries to help me out with this problem, such as flyway or
Using sqflite plugin
The most common plugin to use for SQLopenDatabase
, you can spot onCreate
onUpgrade
option.
Using onCreate
and onUpgrade
In order to facilitate schema onCreate
(schema onUpgrade
(schema migration) options. Much like so:
Where initialSchema
migrationScript
db.execute()
call. This means that you have to separate multiple statements into different executions. Much like so:
Binding the version
This is all straight forward up to now, but what about version
Let’s say you have the following transition from migrationScripts1
to migrationScripts2
.
version
n
version
n
version: migrationScripts.length + 1
But what if you want to transition from following migrationScript1
migrationScript2
In this situation you want to migrate from version 2 to version 4. This is where the oldVersion
variable in the onUpgrade
callback comes to play. So, with some index manipulation you can end up to something like the following.
Using sqlite_migration library
I have used the above pattern way too many times so I decided to create a library out of it. The sqflite_migration library was created for my own sanity and it basically abstracts away all
You just have to use the `openDatabaseWithMigration` method and pass the migration configuration.
As you can see using sqflite_migration library simplifies things a lot, as you do not have to deal with index manipulation and script execution yourself.
Database migration is a very complex topic. More so when you have to do it in embedded applications such as mobile apps. sqflite_migration, was created as a very simple abstraction layer on top of sqflite functionality. Being simple though doesn’t mean it is not useful.