【Compose Multiplatform】Implementing SqlDelight Database
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
目錄
- 【Compose Multiplatform】專案轉移探討與開發指南
- 【Compose Multiplatform】手機使用依賴注入Koin
- 【Compose Multiplatform 】跨平台App但Android需要context作法並搭配Koin
- 【Compose Multiplatform】手機本地持久化儲存DataStore實作
- 【Compose Multiplatform】手機資料庫SqlDelight實作
- 【Compose Multiplatform】CMP中使用ROOM開發資料庫 - [KSP2] Annotation value is missing in nested annotations
- 【Compose Multiplatform】CMP專案中導入CocoaPods及無CocoaPods情況下使用IOS Swift/Obj-C
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 calledAppDatabase
in thetest.your.package.db
package
-
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 - (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
- 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
Create DatabaseDriverFactory for different platforms:
Implement business logic using the generated DB class:
If you use Koin for dependency injection
you can do it like this
- 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 - 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
- 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