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

# Kotlin SDK

> Use PowerSync in Kotlin Multiplatform apps.

<CardGroup cols={3}>
  <Card title="PowerSync SDK on Maven Central" icon="https://mintcdn.com/powersync/tPs7iOuh1Kx4X1r7/logo/maven.svg?fit=max&auto=format&n=tPs7iOuh1Kx4X1r7&q=85&s=cfad4e6e8aea487603e81a03919ed2dd" 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 can handle schema changes gracefully without requiring 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/GTJdSKFSfUc2Sxtc/logo/gradle.svg?fit=max&auto=format&n=GTJdSKFSfUc2Sxtc&q=85&s=bb14bd89bac7520f103a2ad2abc17053" 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/GTJdSKFSfUc2Sxtc/logo/gradle.svg?fit=max&auto=format&n=GTJdSKFSfUc2Sxtc&q=85&s=bb14bd89bac7520f103a2ad2abc17053" 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.
</Note>

## Getting Started

**Prerequisites**: To sync data between your client-side app and your backend source database, you must have completed the necessary setup for PowerSync, which includes connecting your source database to the PowerSync Service and deploying Sync Streams (or legacy Sync Rules) (steps 1-4 in the [Setup Guide](/intro/setup-guide)).

### 1. Define the Client-Side Schema

The first step is to define the client-side schema, which refers to the schema for the managed SQLite database exposed by the PowerSync Client SDKs, that your app can read from and write to. The client-side schema is typically mainly derived from your backend source database schema and your [Sync Streams](/sync/streams/overview) (or legacy [Sync Rules](/sync/rules/overview)), but can also include other tables such as local-only tables. Note that schema migrations are not required on the SQLite database due to the schemaless nature of the [PowerSync protocol](/architecture/powersync-protocol): schemaless data is synced to the client-side SQLite database, and the client-side schema is then applied to that data using *SQLite views* to allow for structured querying of the data. The schema is applied when the local PowerSync database is constructed (as we'll show in the next step).

<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 will be generated based off your Sync Streams/Rules.

  Similar functionality exists in the [CLI](/tools/cli).

  **Note:** The generated schema will not include an `id` column, as the client SDK automatically creates an `id` column of type `text`. Consequently, it is not necessary to specify an `id` column in your schema. For additional information on IDs, refer to [Client ID](/sync/advanced/client-id).
</Tip>

The types available are `text`, `integer` and `real`. These should map directly to the values produced by your [Sync Streams](/sync/streams/overview) (or legacy [Sync Rules](/sync/rules/overview)). If a value doesn't match, it is cast automatically. For details on how backend source database types are mapped to the 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>
  **Note**: No need to declare a primary key `id` column, as PowerSync will automatically create this.
</Note>

### 2. Instantiate the PowerSync Database

Next, you need to instantiate the PowerSync database. PowerSync streams changes from your backend source database into the client-side SQLite database, based on your [Sync Streams](/sync/streams/overview) (or legacy [Sync Rules](/sync/rules/overview)). In your client-side app, you can read from and write to the local SQLite database, whether the user is online or offline.

**Example**:

a. Create 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 // Optionally include your own Logger that must conform to Kermit Logger
  // dbDirectory: "path/to/directory" // Optional. Directory path where the database file is located. This parameter is ignored for iOS.
});
```

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

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

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

// Uses the backend connector that will be created 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

Create a connector to integrate with your backend. The PowerSync backend connector provides the connection between your application backend and the PowerSync managed database. It is used to:

1. Retrieve an auth token to connect to the PowerSync instance.
2. Upload client-side writes to your backend API. Any writes that are made to the SQLite database are placed into an upload queue by the PowerSync Client SDK and automatically uploaded to your app backend (where you apply those changes to the backend source database) when the user is connected.

Accordingly, the connector must implement two methods:

1. `PowerSyncBackendConnector.fetchCredentials` - This method is automatically invoked by the PowerSync Client SDK to obtain authentication credentials. The SDK caches credentials internally and only calls this method when needed (e.g. on initial 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 instructions on how the credentials should be generated.
2. `PowerSyncBackendConnector.uploadData` - This method will be automatically invoked by the PowerSync Client SDK whenever it needs to upload client-side writes to your app's backend API. You need to implement how those writes are processed and uploaded in this method. See [When `uploadData()` is Called](/configuration/app-backend/client-side-integration#when-uploaddata-is-called) for details on triggers, throttling, and retry behavior, and [Writing Client Changes](/handling-writes/writing-client-changes) for considerations on 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/connectors/supabase/src/commonMain/kotlin/com/powersync/connector/supabase/SupabaseConnector.kt

        return {
            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.
    }
}
```

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

## Using PowerSync: CRUD functions

Once the PowerSync instance is configured you can start using the SQLite DB functions.

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 source tables are modified.
* [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 include your own Logger that must conform to the [Kermit Logger](https://kermit.touchlab.co/docs/) as shown here.

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

If you don't supply a Logger then a default Kermit Logger is created with settings to only show `Warnings` in release and `Verbose` in debug as follows:

```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 are able to use the Logger anywhere in your code as follows to debug:

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

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

## 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

The PowerSync SDK for Kotlin can be used with the SQLDelight and Room libraries, making it easier to define and
run SQL queries.
For details, see the [SQL Library Support](/client-sdks/orms/kotlin/overview) page.

## Troubleshooting

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

## Supported Platforms

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

## 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).
