KC Blog

【Compose Multiplatform】Implementing SqlDelight Database

3 min read
CrossPlatform#CMP#Kotlin#SqlDelight

Introduction

In Compose Multiplatform projects

how can we implement cross-platform database operations?

SqlDelight provides a powerful solution

This article will introduce how to

use SqlDelight for database operations in a cross-platform environment

{% include table/compose-multiplatform-category.html %}

Implementation Steps

1. Import SqlDelight
First, import SqlDelight into your project:

Add to your .toml file:

Add plugins and dependencies to build.gradle.kts:

  • First add the plugin
  • Then add the corresponding libraries for each environment
  • Finally, add the SqlDelight configuration under kotlin

This can be understood as creating an operable class called AppDatabase in the test.your.package.db package

2. Implement Database Tables
- Create .sq files in the commonMain/`sqldelight`/database directory:

In the current version, I've verified that you need to add the sqldelight folder in the above path for the build process to successfully generate the operable class in the next step 截圖 2024-07-09 下午3.11.59.png

  • (Optional) You can download the SqlDelight plugin of the same name, so it can generate .sq files via right-click (available for download from the Marketplace)

Reference sqldelight

截圖 2024-07-09 下午3.11.59.png

  • As mentioned above, after configuration and building

    the corresponding class will be generated in the path /build/generated/sqldelight/code/..

  • Or you can use cmd to Build

    ./gradlew generateCommonMainAppDatabaseInterface

  • If you encounter iOS build failures, you can change isStatic to false in build.gradle.kts

3. Create Platform-specific Implementations
Create DatabaseDriverFactory for different platforms:
4. Practical Usage
Implement business logic using the generated DB class:
5. Koin Injection (Optional)
If you use Koin for dependency injection

you can do it like this

Considerations

  1. It is recommended to use SqlDelight version 2.0.1, to avoid known issues with iOS build failures in version 2.0.0

For details, see this discussion thread: Click here

  1. If you encounter iOS build failures, you can try setting isStatic to false

I can't find why this change is necessary

It might be an official workaround

The official documentation directly mentions this method

Conclusion

  • SqlDelight provides a powerful cross-platform database solution
  • Through proper encapsulation, you can use database APIs uniformly across different platforms
  • Combined with dependency injection frameworks like Koin, database instances can be better managed
  • Pay attention to version selection and platform-specific implementations to ensure cross-platform compatibility