Search code examples
kotlin-multiplatformsqldelight

SQLDelight: how to create table dynamically?


I saw examples where we can create a table with fixed name using sq file like that

CREATE TABLE hockeyPlayer (
  player_number INTEGER NOT NULL,
  full_name TEXT NOT NULL
);

I need to create tables with arbitrary names at runtime, how could I achieve this?

UPD

It seems I have to execute all queries manually in this case (like it's done in generated classes)

val driver = DatabaseDriverFactory().createDriver(databaseName)
val tableName = "table2"
driver.execute(null, "CREATE TABLE IF NOT EXISTS $tableName (player_number INTEGER NOT NULL, full_name TEXT NOT NULL", 0, null)

Solution

  • Here is an example of manual/dynamic table creation & operations

        fun test(databaseName: String, key: String?) {
            val driver = DatabaseDriverFactory().createDriver(databaseName, key)
            val tableName = "table2"
            val identifier = 1
    
            // identifier here must be null to avoid SQLiteBindOrColumnIndexOutOfRangeException
            // in INSERT statements below
            driver.execute(null, "CREATE TABLE IF NOT EXISTS $tableName (player_number INTEGER NOT NULL, full_name TEXT NOT NULL)", 0, null)
            var cursor = driver.executeQuery(identifier, "SELECT * FROM $tableName", 0, null)
    
            if (!cursor.next()) {
                Napier.i("EMPTY TEST DB")
                driver.execute(identifier, "INSERT INTO $tableName (player_number, full_name) VALUES (?, ?)", 2) {
                    // indices start here from 1
                    bindLong(1, 1)
                    bindString(2, "John")
                }
                driver.execute(identifier, "INSERT INTO $tableName (player_number, full_name) VALUES (?, ?)", 2) {
                    bindLong(1, 2)
                    bindString(2, "Mike")
                }
            }
    
            cursor = driver.executeQuery(identifier, "SELECT * FROM $tableName", 0, null)
    
            while (cursor.next()) {
                // indices start here from 0
                val number = cursor.getLong(0)
                val name = cursor.getString(1)
                Napier.i("Player #$number $name")
            }
    
        }