Kotlin Multiplatform (Alpha)

SDK Features

  • Provides real-time streaming of database changes.

  • Offers direct access to the SQLite database, enabling the use of SQL on both client and server sides.

  • Operations are asynchronous by default, ensuring the user interface remains unblocked.

  • Supports concurrent database operations, allowing one write and multiple reads simultaneously.

  • Enables subscription to queries for receiving live updates.

  • Eliminates the need for client-side database migrations as these are managed automatically.

Supported targets: Android and iOS.

Installation

See the SDK's README for installation instructions.

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

// Inject the Schema you defined in the previous step and the database directory
val database = PowerSyncBuilder.from(driverFactory, schema).build()

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 connectors/supabase/src/commonMain/kotlin/com/powersync/connector/supabase/SupabaseConnector.kt
    }

    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/usage/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(0)!!,
            name = cursor.getString(1)!!,
            email = cursor.getString(2)!!
        )
    })
}

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 {
        database.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 {
        database.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.

Source Code

To access the source code for this SDK, refer to powersync-kotlin repo on GitHub.

Last updated