SQLDelight for Kotlin: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course
\n

SQLDelight for Kotlin: Complete Guide with Examples

\n\n
\n

1. What It Is and Why You Need It

\n

SQLDelight is a library for Kotlin that generates type-safe Kotlin code from SQL queries. It was developed by Cash App (Square) and supports Kotlin Multiplatform (KMP), allowing you to use the same code for working with databases on Android, iOS, JVM, JS, and Native platforms.

\n

The main idea of SQLDelight is that you write SQL queries in .sq files, and the library automatically generates Kotlin classes, interfaces, and functions that fully correspond to your queries. This eliminates the need to write boilerplate code for mapping query results to objects and handles SQL injections at the compilation level.

\n

Why use SQLDelight? First, it provides full type checking at compile time: if you change the table structure, the compiler will immediately point out all places where queries need to be updated. Second, it supports migrations, transactions, asynchronous queries, and multi-platform work. Third, it integrates with popular frameworks such as Ktor, Koin, Dagger/Hilt, and others.

\n
\n\n
\n

2. Installation

\n

SQLDelight is installed via the Gradle build system. For Kotlin Multiplatform, add the following plugin to the root build.gradle.kts:

\n
// Root build.gradle.kts\nplugins {\n    id("app.cash.sqldelight") version "2.0.2" apply false\n}\n\n// In the module (e.g., :shared)\nplugins {\n    id("app.cash.sqldelight")\n}\n\nsqldelight {\n    databases {\n        create("MyDatabase") {\n            packageName.set("com.example.db")\n        }\n    }\n}\n\ndependencies {\n    implementation("app.cash.sqldelight:coroutines-extensions:2.0.2")\n    implementation("app.cash.sqldelight:runtime:2.0.2")\n    // For Android\n    implementation("app.cash.sqldelight:android-driver:2.0.2")\n    // For iOS\n    implementation("app.cash.sqldelight:native-driver:2.0.2")\n    // For JVM\n    implementation("app.cash.sqldelight:sqlite-driver:2.0.2")\n}\n
\n

After Gradle sync, create the file src/commonMain/sqldelight/com/example/db/MyDatabase.sq (the path must match the packageName).

\n
\n\n
\n

3. Quick Start — Minimal Working Example

\n

Create the file MyDatabase.sq:

\n
-- MyDatabase.sq\nCREATE TABLE Person (\n    id INTEGER PRIMARY KEY AUTOINCREMENT,\n    name TEXT NOT NULL,\n    age INTEGER NOT NULL\n);\n\nselectAll:\nSELECT * FROM Person;\n\ninsertPerson:\nINSERT INTO Person(name, age) VALUES (?, ?);\n
\n

Now in Kotlin code:

\n
import com.example.db.MyDatabase\nimport app.cash.sqldelight.db.SqlDriver\nimport app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver\n\nfun main() {\n    val driver: SqlDriver = JdbcSqliteDriver("jdbc:sqlite:test.db")\n    MyDatabase.Schema.create(driver)\n    \n    val database = MyDatabase(driver)\n    val queries = database.myDatabaseQueries\n    \n    // Insert\n    queries.insertPerson("Alice", 30)\n    queries.insertPerson("Bob", 25)\n    \n    // Select\n    val people = queries.selectAll().executeAsList()\n    people.forEach { person ->\n        println("${person.name} is ${person.age} years old")\n    }\n}\n
\n

This code will create the table, insert two records, and display them.

\n
\n\n
\n

4. Main Methods/Functions/Classes

\n\n

4.1 executeAsList()

\n

Signature: fun <T> executeAsList(): List<T>

\n

What it does: Executes a SELECT query and returns all result rows as a list of objects of the generated type.

\n
val allPeople: List<Person> = querie                    

Recommendations