Using a modern Sqlite version for Android in KMP

Easy to setup and use, it enforces the same Sqlite version across all Android versions, leveraging all modern features.

When you build a KMP library for use in both Android and iOS, you’ll probably need a SQLite database. SQLDelight being the most suitable SQLite ORM for KMP, we’ll use it. But the database runs in the apps, not (yet) directly in KMP. That’s why we need to construct platform dependent driver instances.

Plus, in Android, the SQLite versions are late and so different that you often consider the lowest version, which is usually several years old and lacks modern features. This is why the sqlite-android project appeared, to provide the latest SQLite version to Android. We’ll use it too.

To achieve this, we just need to set this library into both the KMP library and Android app.

Setting up a dedicated SQLite factory for Android in a KMP project

For this, you’ll need to include the sqlite-android dependency:

implementation("com.github.requery:sqlite-android:3.45.0")

and the jitpack repository:

maven { url = uri("https://jitpack.io") }

Then, when constructing the AndroidSqliteDriver for SQLDelight, just specify a not default factory:

AndroidSqliteDriver(
    schema = SqlDb.Schema,
    context = androidContext(),
    name = "database.db",
    factory = RequerySQLiteOpenHelperFactory()
)

Using the library in an Android app

The Android app that uses the KMP library also needs to use the sqlite-android library, instead of the embedded one. For that, just declare it as a dependency, exactly like in the library:

implementation("com.github.requery:sqlite-android:3.45.0")

with the same repository if you do not already have it:

maven { url = uri("https://jitpack.io") }

Yeah, it’s that simple!

Could not find any complete setup on any website, so here it is.