I'm using SQLdelight in a multiplatform project an...
# squarelibraries
a
I'm using SQLdelight in a multiplatform project and the migrations seems to work properly in Android but in desktop is executing all the migrations every time and crashes trying to add a existing column, What am I doing wrong?
I have the .sq files in sqldelight-> com.mypackage and my .sqm files in sqldelight->migrations, and my build.gradle looks like:
Copy code
sqldelight {
        databases {
            create("Database") {
                packageName.set("com.mypackage")
                verifyMigrations.set(true)
                deriveSchemaFromMigrations.set(true)
                version = 2
            }
        }
    }
After some research seems that changing the driver creation from this:
Copy code
fun provideDriverFactory(): SqlDriver {
    val dbPath = File(getAppDataFolder())
    if (!dbPath.exists()) {
        dbPath.mkdirs()
    }
    val dbFile = File(dbPath, "${NexplayConfig.appName.toLowerCase(Locale("en")).replace(" ","-")}.db")
    val driver: SqlDriver = JdbcSqliteDriver("jdbc:sqlite:${dbFile.absolutePath}")
    Database.Schema.create(driver)
    return driver
}
to this:
Copy code
fun provideDriverFactory(): SqlDriver {
    val dbPath = File(getAppDataFolder())
    if (!dbPath.exists()) {
        dbPath.mkdirs()
    }
    val dbFile = File(dbPath, "${NexplayConfig.appName.toLowerCase(Locale("en")).replace(" ","-")}.db")
    val driver = JdbcSqliteDriver("jdbc:sqlite:${dbFile.absolutePath}")

    val transacter = object : TransacterImpl(driver) {}

    transacter.transaction {
        val version = driver.getVersion()
        if (version == 0L) {
            Database.Schema.create(driver).value
            driver.setVersion(Database.Schema.version)
        } else if (version < Database.Schema.version) {
            Database.Schema.migrate(driver, version, Database.Schema.version).value
            driver.setVersion(Database.Schema.version)
        }
    }

    return driver
}

private fun JdbcSqliteDriver.getVersion(): Long {
    val mapper = { cursor: SqlCursor ->
        QueryResult.Value(if (cursor.next().value) cursor.getLong(0) else null)
    }
    return executeQuery(null, "PRAGMA user_version", mapper, 0, null).value ?: 0L
}

private fun JdbcSqliteDriver.setVersion(version: Long) {
    execute(null, "PRAGMA user_version = $version", 0, null)
}
it's works, but I'm not really sure if this is the correct way to achieve that