Search code examples
androidkotlinsqldelight

Can I create an in-memory database with SqlDelight for running in Android?


I have a SqlDelight database that is working nicely. I create it like this:

Database(AndroidSqliteDriver(Database.Schema, context, DatabaseName)

For unit-tests, I create an in-memory database like this:

Database(JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY).apply { 
        Database.Schema.create(this) 
})

I wanted to do the same for androidTests that run on the emulator or on a physical device, but JdbcSqliteDriver doesn't work in Android, presumably because Android doesn't have that package installed by default.

How do I run an in-memory database in AndroidTest (or in production)?


Solution

  • It turns out if you don't name your database, it creates an in-memory version:

    Database(AndroidSqliteDriver(Database.Schema, context, null)
    

    Because AndroidSqliteDriver uses SupportSQLiteOpenHelper.Builder which has this in the documentation:

        /**
         * @param name Name of the database file, or null for an in-memory database.
         * @return This
         */
        @NonNull
        public Builder name(@Nullable String name) {
            mName = name;
            return this;
        }