I know that to create create your database you have to create it for each platform as indicated on the documentation:
val driver: SqlDriver = AndroidSqliteDriver(Database.Schema, context, "test.db")val driver: SqlDriver = NativeSqliteDriver(Database.Schema, "test.db")But I have the problem that on AndroidMain code we don't have access to the context.
How can I create the SqlDriver on AndroidMain or access to context?
I imagine this a comment on multiplatform, would something like this work for you?
// common
expect interface DbArgs
expect fun createDriver(dbArgs: DbArgs): SqlDriver
// androidMain
actual interface DbArgs {
val context: Context
}
actual fun createDb(dbArgs: DbArgs): SqlDriver {
//
}
But I imagine it'll be easier for you if your common code depended on the actual class generated for your database rather than the SqlDriver.
Thank you @nabrozidhs, your comment give me an idea. Yes, this is a problem related with multiplatform.
I had this problem because I wanted to move to common code all the usecases that were be related with SqlDelight, but I had the problem that I needed the AndroidContext.
Finally I did:
// Common Code
expect class DbArgs
expect fun getSqlDriver(dbArgs: DbArgs): SqlDriver
object DatabaseCreator {
fun getDataBase(dbArgs: DbArgs): Database {
return Database(getSqlDriver(dbArgs))
}
}
// Android Main
actual class DbArgs(
var context: Context
)
actual fun getSqlDriver(dbArgs: DbArgs): SqlDriver {
val driver: SqlDriver = AndroidSqliteDriver(Database.Schema, dbArgs.context, "test.db")
return driver
}
And from the Android App I inject the DBArgs with the context.
Most helpful comment
Thank you @nabrozidhs, your comment give me an idea. Yes, this is a problem related with multiplatform.
I had this problem because I wanted to move to common code all the usecases that were be related with SqlDelight, but I had the problem that I needed the AndroidContext.
Finally I did:
And from the Android App I inject the DBArgs with the context.