KQLite Drivers
KQLiteDriver is the core abstraction responsible for executing SQL operations and managing database connections in KQLite. It acts as a bridge between KQLite and the underlying SQLite engine, ensuring consistent behavior across platforms in Kotlin Multiplatform (KMP) projects.
It is recommended to use BundledSQLiteDriver, which provides a reliable and consistent SQLite implementation across all supported platforms.
Adding dependency for driver
sourceSets {
commonMain.dependencies {
implementation("androidx.sqlite:sqlite-bundled:2.6.2")
}
}
Getting database absolute path
expect fun getDatabaseAbsolutePath(name: String): String
import android.content.Context
import org.koin.java.KoinJavaComponent.inject
private val context: Context by inject(Context::class.java)
actual fun getDatabaseAbsolutePath(name: String): String {
return context.getDatabasePath(name).absolutePath
}
import platform.Foundation.NSDocumentDirectory
import platform.Foundation.NSFileManager
import platform.Foundation.NSURL
import platform.Foundation.NSUserDomainMask
actual fun getDatabaseAbsolutePath(name: String): String {
val documents = NSFileManager.defaultManager.URLsForDirectory(
NSDocumentDirectory,
NSUserDomainMask
).firstOrNull()
val databaseUrl = (documents as? NSURL)?.URLByAppendingPathComponent(name)
return databaseUrl?.path ?: throw Exception("Failed to get database path")
}
import java.io.File
actual fun getDatabaseAbsolutePath(name: String): String {
val userHome = System.getProperty("user.home")
val databaseFolder = File(userHome, ".kqlite-contacts")
if (!databaseFolder.exists()) {
databaseFolder.mkdirs()
}
return File(databaseFolder, name).absolutePath
}
Creating KQLiteDriver
KQLite is independent of underlying driver implementation. Any SQLite driver that can open a compatible SQLiteConnection works.
class ContactsDbDriver(filePath: String) : KQLiteDriver {
override val dbFile: String = filePath
override val version: Int = ContactsDatabase.VERSION
private val sqliteDriver = BundledSQLiteDriver()
override fun open(flags: Int?): SQLiteConnection {
return if (flags == null) {
sqliteDriver.open(dbFile)
} else {
sqliteDriver.open(dbFile, flags)
}
}
}