Multiplatform Persistence with SQLDelight
SQLDelight
SQLDelight provides libraries and drivers to generate typesafe Kotlin classes from SQL statements that verifies database schemas, statements, and migrations at compile time. This post will step through the basics of getting started with SQLDelight for Android and iOS using the kotlin-mulitplatform-template I referenced in a previous post, a project that started out as a template for getting your development environment started with Kotlin Multiplatform.
Dependency setup
First we will get started adding the most basic dependencies, adding the plugin classpath to the project, the common library dependencies, and Android app dependencies.
1 | buildscript { |
In your common gradle build file apply the plugin and add platform dependencies.
1 | // apply plugin |
In your Android app gradle build file.
1 | implementation (com.squareup.sqldelight:android-driver:${Versions.SQLDELIGHT}) |
Databse schema setup
Setup your database schema dependencies. Generically this looks for a database named MyDatabase
in com.example.package
package directory structure. More on this in the next section.
1 | sqldelight { |
And that’s it for a very basic setup, check out this commit for reference.
Implementation
SQLDelight generates Kotlin source files which can be used to create and interact with the database. Create your initial database schema with a *.sq
file. This file always represents the latest schema for an empty database. You need to create the SQL source file in the package defined above in the commonMain
sourceset, e.g. common/src/commonMain/sqldelight/com/example/package. In this example we will be persisting some weather station data.
1 | CREATE TABLE Weather ( |
Drivers
Implement the platform driver factories to create the database on both Android and iOS platforms. Include the following inside common/src/commonMain/kotlin/ source set:
1 | expect class KmpDriverFactory { |
Implement the Android actual
in common/src/AndroidMain/kotlin:
1 | actual class KmpDriverFactory(private val appContext: Context) { |
Implement the iOS actual
in common/src/iosMain/kotlin:
1 | actual class KmpDriverFactory { |
Client access
In order to show interacting with the SQLite database we add code in MainActivity
, which is not where this would typically go but it validates the process. The insertWeather
and selectAll
methods are generated for us.
1 | val driver = KmpDriverFactory(this) |
Swift code for iOS can be used to call Kotlin KmpDriverFactory()
and createDb
to create the database and validate the process on iOS.
1 | let driver = KmpDriverFactory() |
And that’s it for a very basic implementation, check out this commit for reference.
Resources
SQLDelight IntelliJ PLugin is available from within Android Studio by navigating to Preferences > Plugins > Marketplace > Search for SQLDelight