> ## Documentation Index
> Fetch the complete documentation index at: https://powersync-update-diagrams.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Kotlin SDK

> Use PowerSync in Kotlin Multiplatform apps.

```text Build with AI icon="sparkles" wrap theme={null}
Install the PowerSync Agent Skills with: npx skills add powersync-ja/agent-skills. Then follow the skills to onboard this project to PowerSync using the Kotlin Multiplatform SDK.
```

<CardGroup cols={3}>
  <Card title="PowerSync SDK on Maven Central" icon="https://mintcdn.com/powersync-update-diagrams/Je_fR1YF8Djv7OT8/logo/maven.svg?fit=max&auto=format&n=Je_fR1YF8Djv7OT8&q=85&s=f144172c03f0ac0b607eb3ee34aba826" href="https://central.sonatype.com/artifact/com.powersync/core" width="128" height="128" data-path="logo/maven.svg">
    The PowerSync Kotlin SDK is distributed via Maven Central
  </Card>

  <Card title="Source Code" icon="github" href="https://github.com/powersync-ja/powersync-kotlin/">
    Refer to the `powersync-kotlin` repo on GitHub
  </Card>

  <Card title="API Reference" icon="book" href="https://powersync-ja.github.io/powersync-kotlin">
    Full API reference for the SDK
  </Card>

  <Card title="Example Projects" icon="code" href="/intro/examples#kotlin">
    Gallery of example projects/demo apps built with Kotlin and PowerSync.
  </Card>

  <Card title="Changelog" icon="megaphone" href="https://releases.powersync.com/announcements/powersync-kotlin-sdk">
    Changelog for the SDK
  </Card>
</CardGroup>

## SDK Features

* **Real-time streaming of database changes**: Changes made by one user are instantly streamed to all other users with access to that data. This keeps clients automatically in sync without manual polling or refresh logic.
* **Direct access to a local SQLite database**: Data is stored locally, so apps can read and write instantly without network calls. This enables offline support and faster user interactions.
* **Asynchronous background execution**: The SDK performs database operations in the background to avoid blocking the application’s main thread. This means that apps stay responsive, even during heavy data activity.
* **Query subscriptions for live updates**: The SDK supports query subscriptions that automatically push real-time updates to client applications as data changes, keeping your UI reactive and up to date.
* **Automatic schema management**: PowerSync syncs schemaless data and applies a client-defined schema using SQLite views. This architecture means that PowerSync SDKs handle schema changes without explicit migrations on the client side.

## Installation

Add the [PowerSync SDK](https://central.sonatype.com/artifact/com.powersync/core) to your project by adding the following to your `build.gradle.kts` file:

<Tabs sync={false}>
  <Tab title="With Version catalog">
    ```toml gradle/libs.versions.toml theme={null}
    [versions]
    # Please check the latest version at https://github.com/powersync-ja/powersync-kotlin/releases/
    powersync = "1.12.0"

    [libraries]
    powersync-core = { module = "com.powersync:core", version.ref = "powersync" }
    powersync-integration-supabase = { module = "com.powersync:connector-supabase", version.ref = "powersync" }
    ```

    ```Kotlin build.gradle.kts icon="https://mintcdn.com/powersync-update-diagrams/Je_fR1YF8Djv7OT8/logo/gradle.svg?fit=max&auto=format&n=Je_fR1YF8Djv7OT8&q=85&s=18fd34e4fda83fb91a7425eb99a933ec" theme={null}
    kotlin {
        //...
        sourceSets {
            commonMain.dependencies {
                implementation(libs.powersync.core)
                // If you want to use the Supabase Connector, also add the following:
                implementation(libs.powersync.integration.supabase)
            }
            //...
        }
    }
    ```
  </Tab>

  <Tab title="Direct dependency">
    ```Kotlin build.gradle.kts icon="https://mintcdn.com/powersync-update-diagrams/Je_fR1YF8Djv7OT8/logo/gradle.svg?fit=max&auto=format&n=Je_fR1YF8Djv7OT8&q=85&s=18fd34e4fda83fb91a7425eb99a933ec" theme={null}
    kotlin {
        //...
        sourceSets {
            commonMain.dependencies {
                implementation("com.powersync:core:$powersyncVersion")
                // If you want to use the Supabase Connector, also add the following:
                implementation("com.powersync:connector-supabase:$powersyncVersion")
            }
            //...
        }
    }
    ```
  </Tab>
</Tabs>

On Kotlin SDK v1.12.0 and later, the [PowerSync SQLite core extension](https://github.com/powersync-ja/powersync-sqlite-core) is statically linked into `com.powersync:core` for Apple targets (iOS, macOS, tvOS, and watchOS), consistent with Android and JVM. Use the Gradle dependencies above only. When you upgrade from an older SDK, remove any Swift package dependency on [`powersync-sqlite-core-swift`](https://github.com/powersync-ja/powersync-sqlite-core-swift) and any `powersync-sqlite-core` CocoaPod from your Xcode or CocoaPods setup.

<Note>
  **Supported platforms**

  * PowerSync supports Android, JVM and Apple (iOS, macOS, tvOS, watchOS) targets through Kotlin Multiplatform.
  * On the JVM, the following platforms are supported: Linux AArch64, Linux X64, macOS AArch64, macOS X64, Windows X64.
  * Web (JS and WebAssembly) targets have experimental support. See [Experimental Web Support](#experimental-web-support).
</Note>

## Getting Started

**Prerequisites:** Before you start, connect your source database to the PowerSync Service and deploy Sync Streams. These are steps 1-4 in the [Setup Guide](/intro/setup-guide).

### 1. Define the Client-Side Schema

The client-side schema defines the tables and columns of the SQLite database that the PowerSync client SDK manages and that your app reads from and writes to. It is usually derived from your backend database schema and your [Sync Streams](/sync/streams/overview), and it can also include [local-only tables](/client-sdks/advanced/local-only-usage). You apply the schema when you instantiate the database in the next step.

Schema migrations are not required. The SDK syncs schemaless data and applies the schema to that data with SQLite views. The exception is [raw tables](/client-sdks/advanced/raw-tables), which you create and migrate yourself.

<Tip>
  **Generate schema automatically**

  In the [PowerSync Dashboard](https://dashboard.powersync.com/), select your project and instance and click the **Connect** button in the top bar to generate the client-side schema in your preferred language. The schema is generated from your Sync Streams. The [CLI](/tools/cli) offers the same function.

  The generated schema does not include an `id` column. The client SDK creates an `id` column of type `text` automatically, so you do not need to declare it. See [Client ID](/sync/advanced/client-id) for details.
</Tip>

The available column types are `text`, `integer`, and `real`. These should match the values produced by your Sync Streams. If a value does not match, it is cast automatically. For details on how source database types map to SQLite types, see [Types](/sync/types).

**Example:**

```kotlin theme={null}
// AppSchema.kt
import com.powersync.db.schema.Column
import com.powersync.db.schema.Index
import com.powersync.db.schema.IndexedColumn
import com.powersync.db.schema.Schema
import com.powersync.db.schema.Table

val AppSchema: Schema = Schema(
    listOf(
        Table(
            name = "todos",
            columns = listOf(
                Column.text("list_id"),
                Column.text("created_at"),
                Column.text("completed_at"),
                Column.text("description"),
                Column.integer("completed"),
                Column.text("created_by"),
                Column.text("completed_by")
            ),
            // Index to allow efficient lookup within a list
            indexes = listOf(
                Index("list", listOf(IndexedColumn.descending("list_id")))
            )
        ),
        Table(
            name = "lists",
            columns = listOf(
                Column.text("created_at"),
                Column.text("name"),
                Column.text("owner_id")
            )
        )
    )
)
```

<Note>
  You do not need to declare an `id` column. PowerSync creates it automatically.
</Note>

### 2. Instantiate the PowerSync Database

Next, instantiate the PowerSync database. PowerSync streams changes from your backend source database into the client-side SQLite database, based on your Sync Streams. Your app reads from and writes to this local database whether the user is online or offline.

**Example:**

a. Create a platform-specific `DatabaseDriverFactory` to be used by the `PowerSyncBuilder` to create the SQLite database driver.

```kotlin theme={null}
// commonMain

import com.powersync.DatabaseDriverFactory
import com.powersync.PowerSyncDatabase

// Android
val driverFactory = DatabaseDriverFactory(this)
// iOS & Desktop
val driverFactory = DatabaseDriverFactory()
```

b. Build a `PowerSyncDatabase` instance using the `PowerSyncBuilder` and the `DatabaseDriverFactory`. The schema you created in a previous step is provided as a parameter:

```kotlin theme={null}
// commonMain

val database = PowerSyncDatabase(
  factory = driverFactory, // The factory you defined above
  schema = AppSchema, // The schema you defined in the previous step
  dbFilename = "powersync.db",
  // logger = YourLogger, // Optional. Your own Kermit Logger.
  // dbDirectory = "path/to/directory", // Optional. Directory for the database file. Ignored on iOS.
)
```

c. Connect the `PowerSyncDatabase` to sync data with your backend:

<Tip>
  This section assumes that you use PowerSync to sync your backend source database with SQLite in your app. To manage a local SQLite database without sync, instantiate the PowerSync database without calling `connect()` and see the [Local-Only](/client-sdks/advanced/local-only-usage) guide.
</Tip>

```kotlin theme={null}
// commonMain

// Uses the backend connector that you create in the next step
database.connect(MyConnector())
```

**Special case: Compose Multiplatform**

The artifact `com.powersync:powersync-compose` provides a simpler API:

```kotlin theme={null}
// commonMain
val database = rememberPowerSyncDatabase(schema)
remember {
    database.connect(MyConnector())
}
```

### 3. Integrate with Your Backend

The backend connector connects the PowerSync client SDK to your application backend. The SDK uses it to:

1. Get an auth token to connect to the PowerSync instance.
2. Upload client-side writes to your backend API. The SDK places every write to the SQLite database in an upload queue and uploads the queue to your backend when the user is connected. Your backend then applies the changes to the source database.

The connector must implement two methods:

1. `PowerSyncBackendConnector.fetchCredentials` - The SDK calls this method to get authentication credentials. It caches the credentials and calls the method again only when needed, for example on the first connection or when the token is near expiry. See [When `fetchCredentials()` is Called](/configuration/app-backend/client-side-integration#when-fetchcredentials-is-called) for details and [Authentication Setup](/configuration/auth/overview) for how to generate credentials.
2. `PowerSyncBackendConnector.uploadData` - The SDK calls this method whenever it has client-side writes to upload to your backend API. Implement how those writes are processed and uploaded. See [When `uploadData()` is Called](/configuration/app-backend/client-side-integration#when-uploaddata-is-called) for triggers, throttling, and retry behavior, and [Writing Client Changes](/handling-writes/writing-client-changes) for the app backend implementation.

**Example:**

```kotlin theme={null}
// PowerSync.kt
import com.powersync.DatabaseDriverFactory
import com.powersync.PowerSyncDatabase

class MyConnector : PowerSyncBackendConnector() {
    override suspend fun fetchCredentials(): PowerSyncCredentials {
        // implement fetchCredentials to obtain the necessary credentials to connect to your backend
        // See an example implementation in https://github.com/powersync-ja/powersync-kotlin/blob/main/integrations/supabase/src/commonMain/kotlin/com/powersync/connector/supabase/SupabaseConnector.kt

        return PowerSyncCredentials(
            endpoint = "[Your PowerSync instance URL or self-hosted endpoint]",
            // Use a development token (see Authentication Setup https://docs.powersync.com/configuration/auth/development-tokens) to get up and running quickly
            token = "An authentication token"
        )
    }

    override suspend fun uploadData(database: PowerSyncDatabase) {
        // Implement uploadData to send local changes to your backend service
        // You can omit this method if you only want to sync data from the server to the client
        // See an example implementation under Usage Examples (sub-page)
        // See https://docs.powersync.com/handling-writes/writing-client-changes for considerations.
    }
}
```

If you use Supabase, you can use [SupabaseConnector.kt](https://github.com/powersync-ja/powersync-kotlin/blob/main/integrations/supabase/src/commonMain/kotlin/com/powersync/connector/supabase/SupabaseConnector.kt) as a starting point.

### 4. Subscribe to Sync Streams

Streams defined with `auto_subscribe: true` start syncing as soon as the client connects. For all other streams, your app must subscribe before their data downloads. The basic pattern is: subscribe to a stream, wait for its data to sync, then unsubscribe when the data is no longer needed.

```kotlin theme={null}
// Subscribe to a stream with parameters
val sub = database.syncStream("list_todos", mapOf("list_id" to JsonParam.String("abc123")))
  .subscribe()

// Wait for the initial data to sync
sub.waitForFirstSync()

// The stream's rows are now in the local SQLite database.
// TODO: Read the todos for this list with a local query.

// When the data is no longer needed
sub.unsubscribe()
```

After you unsubscribe, the synced data stays in the local database for the stream's time-to-live (TTL), which is 24 hours by default. If the app subscribes again within that time, the data is already available. See [Client-Side Usage](/sync/streams/client-usage) for framework hooks, per-subscription sync status, custom TTLs, priority overrides, and connection parameters.

## Using PowerSync: CRUD Functions

Once the PowerSync database is connected and your streams have synced, the data is in the local SQLite database.

The most commonly used CRUD functions to interact with your SQLite data are:

* [PowerSyncDatabase.get](/client-sdks/reference/kotlin#fetching-a-single-item) - get (`SELECT`) a single row from a table.
* [PowerSyncDatabase.getAll](/client-sdks/reference/kotlin#querying-items-powersync-getall) - get (`SELECT`) a set of rows from a table.
* [PowerSyncDatabase.watch](/client-sdks/reference/kotlin#watching-queries-powersync-watch) - execute a read query every time a dependent table changes.
* [PowerSyncDatabase.execute](/client-sdks/reference/kotlin#mutations-powersync-execute) - execute a write (`INSERT`/`UPDATE`/`DELETE`) query.

### Fetching a Single Item

The `get` method executes a read-only (SELECT) query and returns a single result. It throws an exception if no result is found. Use `getOptional` to return a single optional result (returns `null` if no result is found).

```kotlin theme={null}
// Find a list item by ID
suspend fun find(id: Any): TodoList {
    return database.get(
                "SELECT * FROM lists WHERE id = ?", 
                listOf(id)
            ) { cursor ->
                TodoList.fromCursor(cursor)
            }
}
```

### Querying Items (PowerSync.getAll)

The `getAll` method executes a read-only (SELECT) query and returns a set of rows.

```kotlin theme={null}
// Get all list IDs
suspend fun getLists(): List<String> {
    return database.getAll(
                "SELECT id FROM lists WHERE id IS NOT NULL"
            ) { cursor ->
                cursor.getString("id")
            }
}
```

### Watching Queries (PowerSync.watch)

The `watch` method executes a read query whenever a change to a dependent table is made.

```kotlin theme={null}
fun watchPendingLists(): Flow<List<ListItem>> =
    db.watch(
        "SELECT * FROM lists WHERE state = ?",
        listOf("pending"),
    ) { cursor ->
        ListItem(
            id = cursor.getString("id"),
            name = cursor.getString("name"),
        )
    }
```

### Mutations (PowerSync.execute)

The `execute` method executes a write query (INSERT, UPDATE, DELETE) and returns the results (if any).

```kotlin theme={null}
suspend fun insertCustomer(name: String, email: String) {
    database.writeTransaction { tx ->
        tx.execute(
            sql = "INSERT INTO customers (id, name, email) VALUES (uuid(), ?, ?)",
            parameters = listOf(name, email)
        )
    }
}

suspend fun updateCustomer(id: String, name: String, email: String) {
    database.execute(
        sql = "UPDATE customers SET name = ? WHERE email = ?",
        parameters = listOf(name, email)
    )
}

suspend fun deleteCustomer(id: String? = null) {
    // If no id is provided, delete the first customer in the database
    val targetId =
        id ?: database.getOptional(
            sql = "SELECT id FROM customers LIMIT 1",
            mapper = { cursor ->
                cursor.getString(0)!!
            }
        ) ?: return

    database.writeTransaction { tx ->
        tx.execute(
            sql = "DELETE FROM customers WHERE id = ?",
            parameters = listOf(targetId)
        )
    }
}
```

## Configure Logging

You can supply your own logger. It must conform to the [Kermit Logger](https://kermit.touchlab.co/docs/):

```kotlin theme={null}
PowerSyncDatabase(
  ...
  logger: Logger? = YourLogger
)
```

If you do not supply a logger, the SDK creates a default Kermit Logger. It shows `Warn` and above in release builds and `Verbose` in debug builds:

```kotlin theme={null}
val defaultLogger: Logger = Logger

// Severity is set to Verbose in Debug and Warn in Release
if(BuildConfig.isDebug) {
    Logger.setMinSeverity(Severity.Verbose)
} else {
    Logger.setMinSeverity(Severity.Warn)
}

return defaultLogger
```

You can use the logger anywhere in your code:

```kotlin theme={null}
import co.touchlab.kermit.Logger

Logger.i("Some information");
Logger.e("Some error");
...
```

## Custom HTTP Clients and Headers

PowerSync uses streaming HTTP responses or WebSockets to connect to the PowerSync Service. The SDK uses
[ktor](https://ktor.io/) as a cross-platform HTTP client. `com.powersync:core` depends on an OkHttp-based
implementation on Android and JVM targets, and on the Darwin engine for native Apple targets.

Configure how the PowerSync SDK sets up client engines by passing an instance of `SyncClientConfiguration.ExtendedConfig`
in `SyncOptions`:

```kotlin theme={null}
import com.powersync.sync.SyncClientConfiguration
import com.powersync.sync.SyncOptions
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.request.header

db.connect(
    connector,
    options = SyncOptions(
        clientConfiguration = SyncClientConfiguration.ExtendedConfig {
            // For more options, see https://ktor.io/docs/client-create-and-configure.html#plugins
            defaultRequest {
                header("X-Custom-Header", "Used by PowerSync")
            }
        }
    )
)
```

If you want to use a custom HTTP client engine instead, use `SyncClientConfiguration.ExistingClient`:

```kotlin theme={null}
import com.powersync.sync.configureSyncHttpClient

db.connect(
    connector,
    options = SyncOptions(
        clientConfiguration = SyncClientConfiguration.ExistingClient(HttpClient(YourPreferredClientEngine) {
            // Important: This configures a minimal set of plugins required by the PowerSync sync client.
            configureSyncHttpClient()
        })
    )
)
```

## Additional Usage Examples

For more usage examples including accessing connection status, monitoring sync progress, and waiting for initial sync, see the [Usage Examples](/client-sdks/usage-examples) page.

## ORM / SQL Library Support

You can use the Kotlin SDK with the SQLDelight and Room libraries to define and run SQL queries.
For details, see the [SQL Library Support](/client-sdks/orms/kotlin/overview) page.

## Experimental Web Support

Version 1.14.1 of the SDK adds initial support for web targets (JS and WebAssembly). Use `WebConnectionFactory` to open a PowerSync database on the web.

<Warning>
  Web support is experimental and incomplete. We are sharing it for early testing and prototyping purposes, and it is not ready for production use. The main limitation is that multi-tab support is not functional in this version: tabs don't coordinate sync connections or share update notifications, so use the database from a single tab only.

  If you try web support, test it thoroughly and report any issues on [GitHub](https://github.com/powersync-ja/powersync-kotlin/issues). Follow the [tracking issue](https://github.com/powersync-ja/powersync-kotlin/issues/362) for progress on stabilizing web support.
</Warning>

For a working example, see the web target of the [Supabase To-Do List demo](https://github.com/powersync-ja/powersync-kotlin/tree/main/demos/supabase-todolist).

## Troubleshooting

See [Troubleshooting](/debugging/troubleshooting) for pointers to debug common issues.

## Supported Platforms

See [Supported Platforms -> Kotlin SDK](/resources/supported-platforms#kotlin).

## Upgrading the SDK

Update your project's Gradle file (`build.gradle.kts`) with the latest version of the [SDK](https://central.sonatype.com/artifact/com.powersync/core).
