Humphrey
01/31/2022, 5:24 PMdatabase.Schema.create(driver)
. I'm using a file based database. Second time I start my application the database already exists. I don't want it to recreate the tables. What is a good approach for that?Humphrey
01/31/2022, 8:45 PMmbonnin
01/31/2022, 9:02 PMmbonnin
01/31/2022, 9:06 PMuser_version
already and instead of creating the DB, you update itHumphrey
02/01/2022, 6:40 PMjw
02/01/2022, 6:58 PMHumphrey
02/01/2022, 7:44 PMjw
02/01/2022, 9:16 PMHumphrey
02/02/2022, 4:36 AMjw
02/02/2022, 5:01 AMHumphrey
02/02/2022, 10:30 PMimport com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver
const val VERSION_PRAGMA = "user_version"
class DbHelper(path: String = "") {
private val driver by lazy { JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY + path) }
private var version: Int
get() {
driver.executeQuery(null, "PRAGMA $VERSION_PRAGMA", 0).use {
if (it.next()) {
return it.getLong(0)?.toInt() ?: 0
}
return 0
}
}
set(version) {
driver.execute(null, "PRAGMA $VERSION_PRAGMA = $version;)", 0)
}
val database by lazy {
val currentVersion = version
if (currentVersion == 0) {
Database.Schema.create(driver)
version = 1
println("init: created tables, setVersion to 1")
} else {
val schemaVersion = Database.Schema.version
if (currentVersion < schemaVersion) {
Database.Schema.migrate(driver, currentVersion, schemaVersion)
version = schemaVersion
println("init: migrated from $currentVersion to $schemaVersion")
}
}
Database(driver)
}
}
Humphrey
02/02/2022, 11:06 PM