Search code examples
kotlincompose-desktopsqldelight

Sqldelight not creating database tables


I am using sqldelight to persist items locally. This is the error i get when i run the test org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: LocalMember) It worked perfectly until now. I really should have learnt to write test earlier, maybe would have caught the problem sooner. I created a new project, without any of the other stuff going on just to test this and it still gave the same error.

class LocalDataTest {
    private lateinit var db: database
    private lateinit var localData: LocalData

    @BeforeEach
    fun setUp() {
        val driver: SqlDriver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY) //actual implementation uses a file db with dependency injection using koin, but the same error though
        database.Schema.create(driver)
        db = database(driver)
        localData = LocalData(db)
    }

    @Test
    fun addMember() {
        runBlocking {
            localData.addMember(LocalMember("1", "test"))
            val member = db.dataQueries.selectAll().executeAsOne()
            assertEquals("test", member.name)
        }
    }
}
CREATE TABLE IF NOT EXISTS LocalMember (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL
);


selectAll:
SELECT * FROM LocalMember;

upsert:
-- Insert or ignore the record
INSERT OR IGNORE INTO LocalMember (id, name)
VALUES (?, ?);

-- Then update the record assuming it exists
UPDATE LocalMember
SET
    name = COALESCE(?, name)
WHERE id = ?;
//settings.gradle.kts
pluginManagement {
    repositories {
        gradlePluginPortal()
        maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
        mavenCentral()
    }

    plugins {
        kotlin("jvm").version(extra["kotlin.version"] as String)
        kotlin("plugin.serialization").version(extra["kotlin.version"] as String)
        id("org.jetbrains.compose").version(extra["compose.version"] as String)
        id("app.cash.sqldelight").version("2.0.0") apply false
    }
}
//build.gradle.kts
dependencies {
 implementation("app.cash.sqldelight:sqlite-driver:2.0.0")
}

sqldelight {
    databases {
        create("database") {
            packageName.set("com.ayitinya.data")
            generateAsync.set(true)
        }
    }
}

Solution

  • call await() method for database.Schema.create(driver)