This SDK is currently in a beta release. It is suitable for production use provided you’ve tested your specific use cases.

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.

Supported targets: Android, iOS and Desktop.

Installation

Add the PowerSync SDK to your project by adding the following to your build.gradle.kts file:

kotlin {
    //...
    sourceSets {
        commonMain.dependencies {
            api("com.powersync:core:$powersyncVersion")
            // If you want to use the Supabase Connector, also add the following:
            implementation("com.powersync:connectors:$powersyncVersion")
        }
        //...
    }
}

Cocoapods configuration (recommended for iOS)

Add the following to the cocoapods config in your build.gradle.kts:

cocoapods {
    //...
    pod("powersync-sqlite-core") {
        linkOnly = true
    }

    framework {
        isStatic = true
        export("com.powersync:core")
    }
    //...
}

The linkOnly = true attribute and isStatic = true framework setting ensure that the powersync-sqlite-core binaries are statically linked.

JVM compatibility for Desktop

  • The following platforms are supported: Linux AArch64, Linux X64, MacOS AArch64, MacOS X64, Windows X64.
  • See this example build.gradle file for the relevant JVM config.

Getting Started

Before implementing the PowerSync SDK in your project, make sure you have completed these steps:

1. Define the Schema

The first step is defining the schema for the local SQLite database, which is provided to the PowerSyncDatabase constructor via the schema parameter. This schema represents a “view” of the downloaded data. No migrations are required — the schema is applied directly when the PowerSync database is constructed.

The types available are text, integer and real. These should map directly to the values produced by the Sync Rules. If a value doesn’t match, it is cast automatically.

Example:

// 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: No need to declare a primary key id column, as PowerSync will automatically create this.

2. Instantiate the PowerSync Database

Next, you need to instantiate the PowerSync database — this is the core managed database.

Its primary functions are to record all changes in the local database, whether online or offline. In addition, it automatically uploads changes to your app backend when connected.

Example:

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

// 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:

// 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 the backend connector:

// 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:

// 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. Apply local changes on your backend application server (and from there, to Postgres)

Accordingly, the connector must implement two methods:

  1. PowerSyncBackendConnector.fetchCredentials - This is called every couple of minutes and is used to obtain credentials for your app backend API. -> See Authentication Setup for instructions on how the credentials should be generated.
  2. PowerSyncBackendConnector.uploadData - Use this to upload client-side changes to your app backend. -> See Writing Client Changes for considerations on the app backend implementation.

Example:

// 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/installation/authentication-setup/development-tokens) to get up and running quickly) 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/installation/app-backend-setup/writing-client-changes for considerations.
    }
}

Note: If you are using Supabase, you can use 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:

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

// Find a list item by ID
suspend fun find(id: Any): TodoList {
    val results = db.get("SELECT * FROM lists WHERE id = ?", listOf(id))
    return TodoList.fromRow(results)
}

Querying Items (PowerSync.getAll)

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

// Get all list IDs
suspend fun getLists(): List<String> {
    val results = db.getAll("SELECT id FROM lists WHERE id IS NOT NULL")
    return results.map { row -> row["id"] as String }.toList()
}

Watching Queries (PowerSync.watch)

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

// You can watch any SQL query
fun watchCustomers(): Flow<List<User>> {
    // TODO: implement your UI based on the result set
    return database.watch("SELECT * FROM customers", mapper = { cursor ->
        User(
            id = cursor.getString("id"),
            name = cursor.getString("name"),
            email = cursor.getString("email")
        )
    })
}

Mutations (PowerSync.execute)

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

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)
        )
    }
}

Additional Usage Examples

See Usage Examples for further examples of the SDK.

ORM Support

ORM support is not yet available, we are still investigating options. Please let us know what your needs around ORMs are.

Troubleshooting

See Troubleshooting for pointers to debug common issues.