Sqldelight: Create AndroidSqliteDriver on AndroinMain

Created on 13 Jun 2019  路  2Comments  路  Source: cashapp/sqldelight

I know that to create create your database you have to create it for each platform as indicated on the documentation:

  • Android:
    val driver: SqlDriver = AndroidSqliteDriver(Database.Schema, context, "test.db")
  • iOS:
    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?

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:

// 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.

All 2 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kuhnroyal picture kuhnroyal  路  4Comments

treelzebub picture treelzebub  路  3Comments

tellypresence picture tellypresence  路  4Comments

LouisCAD picture LouisCAD  路  5Comments

Takhion picture Takhion  路  3Comments