Skip to content
clientdb

Search the docs

Find a page or section

Guides

Swift client

A native client for iOS 17 and macOS 14+: SwiftPM codegen from your schema, @Observable models, live queries, SQLite storage and SwiftUI helpers.

The Swift client syncs with the same server as your web app. Each device keeps its own copy in SQLite, so the app opens instantly, works offline, and shows a change from another device as soon as it's saved. Its core is a Swift port of the same replica state machine and passes every conformance vector in spec/vectors/. Swift 6; Linux builds and tests everything except the SwiftUI helpers. The examples use the todo app from the quick start.

ModuleWhat
ClientDBThe app-facing database: typed entities, live queries, writes, undo, sync over HTTP and WebSocket. Observation-based.
ClientDBSQLiteSQLite storage on GRDB: rows, sync state, and the queue of unsent changes
ClientDBPluginSwiftPM build-tool plugin that generates the model classes from clientdb.schema.json
ClientDBCoreThe platform-neutral replica; comes with ClientDB

Setup

  1. Export the schema from the server project (the Prisma generator writes it too):
scripts/export-schema.ts
import { writeFileSync } from "node:fs";
import { exportSchema } from "@clientdb/schema";
import { schema } from "../src/sync/schema";

writeFileSync("clientdb.schema.json", JSON.stringify(exportSchema(schema)));
  1. Put clientdb.schema.json in your app target's sources and add the plugin:
Package.swift
.target(
  name: "App",
  dependencies: [
    .product(name: "ClientDB", package: "clientdb"),
    .product(name: "ClientDBSQLite", package: "clientdb"),
  ],
  plugins: [.plugin(name: "ClientDBPlugin", package: "clientdb")]
)

In an Xcode project, add the package and enable the plugin under the target's Build Phases → Run Build Tool Plug-ins. Headless CI builds pass -skipPackagePluginValidation to xcodebuild.

Every build regenerates the models: one class per model with typed fields, nested enums, forward relations (todo.project), inverse relations as live queries (project.todos), and Insert / Changes structs. Never edit them; add app logic in extensions:

Swift
extension Todo {
  func rename(_ title: String) throws {
    try update { $0.title = title.trimmingCharacters(in: .whitespaces) }
  }
}

Open the database

Swift
let db = try await ClientDB.open(
  schema: .generated,
  storage: SQLiteStorage(applicationSupport: "clientdb.sqlite"),
  sync: SyncOptions(
    url: URL(string: "https://app.example.com/api/sync")!,
    realtime: true,
    token: { await Session.current.token() } // your auth
  )
)
try await db.ready() // eager models usable, from SQLite or the network

The server decides who the user is from the token (its session() callback); the client never sends a user id of its own. Stored data belongs to the signed-in user: when the server reports a different one, the device copy is deleted and loaded again. await db.clear() does the same on sign-out.

ClientDB.open also takes load: .lazy (every model loads when read, for admin tools), eviction: .maxRows(5_000) (see Lazy models) and readOnly: true.

Reads

Entities are Observable per field; queries are maintained incrementally.

Swift
let open = db.todos.where(\.projectId == projectID, \.done == false).sorted(by: \.updatedAt, .descending).limit(50)
open.rows      // [Todo]
open.count     // ignoring the limit
project.todos  // the same kind of query, shared per project

Lazy models load when read

Models are eager (loaded at sign-in) or lazy (the default), as on the web. A lazy model fetches its rows by the key a read uses, such as todo.comments, or whole on other reads. Reads in the same main-actor turn, such as one SwiftUI render of a list whose rows each read todo.comments.count, share one request, and each set of rows is fetched once:

Swift
todo.comments.count                  // 0 at first; updates when the comments arrive
todo.comments.status                 // .partial, .loading, .complete or .failed(reason)
try await todo.comments.preload()    // optional: fetch early, e.g. before navigating to the todo

A failed fetch isn't retried on every read; preload() tries again.

With eviction: .maxRows(n), the loads used longest ago (a todo's comments, a server query's pages) are dropped whole once the device holds more rows; a query over them reads .partial and loads again when read. What the app still holds stays: a LiveQuery, a ServerQuery or an entity keeps the loads it reads. Eager models and rows with unsent writes or drafts always stay.

Server queries

To search rows that aren't on the device, ask the server. The model's query rules on the server say which fields and operators are allowed:

Swift
let results = db.comments.query(
  where: .contains(\.body, "launch", caseInsensitive: true),
  sortedBy: \.createdAt, .descending,
  limit: 20
)
results.rows       // the rows so far
results.status     // .loading, then .complete
results.hasMore
try await results.loadMore()

Writes

Writes are visible at once and sent in the background.

Swift
let todo = try db.todos.create(.init(title: "New", projectId: projectID, authorId: db.session.viewerId!))
try todo.update { $0.title = "Renamed" }
try await todo.delete().confirmed()    // throws the TransactionRejection if the server refuses

try db.transaction { tx in
  let second = try tx.create(Todo.self, .init(title: "Second", projectId: projectID, authorId: db.session.viewerId!))
  try tx.update(second) { $0.done = true }
}

try db.undo()                          // reports fields someone else changed meanwhile

Insert has every field the client may write, including authorId: pass db.session.viewerId yourself. The server's rules check the value (enforce: ($) => ({ authorId: $.viewer.id })) and reject a write that names someone else; they never fill it in. Generated fields aren't in Insert and are read-only.

Server logic

Logic that runs on your server (an API call that writes with Prisma) goes through db.action, which calls it and then waits for a sync, so its rows are on the device when it returns. optimistic shows the result before the server answers, and is dropped once the server's own write has synced:

Swift
try await db.action(optimistic: { db in
  try db.todos[todoID]!.update { $0.done = true }
}) {
  try await api.completeTodo(todoID)
}

Forms: drafts

Swift
try todo.edit { $0.title = "Typing…" }   // unsaved edit on top of the row
try todo.save()                          // or todo.revert()

Session and restricted fields

db.session is what the server verified: viewer, viewerId, claims (db.session.hasClaim("staff")) and readOnly. db.viewer(User.self) is the viewer's row. Writes in a read-only session, or on a database opened with readOnly: true, throw CoreError .readOnly.

A restricted field the viewer may not read is nil; user.isHidden(\.email) tells it apart from a field that is empty.

SwiftUI

Put the database in the environment and use @Live:

Swift
ContentView()
  .environment(db)
  .syncsOnForeground(db)

struct TodosView: View {
  @Live(.where(\.done == false).sorted(by: \.createdAt)) var todos: [Todo]

  var body: some View {
    List(todos) { todo in
      Text(todo.title)
    }
  }
}

Status and concurrency

db.syncStatus is idle, bootstrapping, syncing, online, offline(reason) (retried with backoff), outdated(reason) (the server runs another protocol or schema version; update the app) or closed. try await db.sync() returns once the device has everything the server had when it was called.

The database and entities live on the main actor; network IO and JSON decoding run off it.

Tests

Terminal
swift test                                         # vectors, codegen golden files, client, storage, sync (fake server)
CLIENTDB_TEST_PG=postgres://… swift/E2E/run.sh     # against the real server
CLIENTDB_UPDATE_GOLDEN=1 swift test --filter Golden # after a generator change

On Linux, URLSession WebSockets need a libcurl built with WebSocket support (Ubuntu's isn't); without one, realtime falls back to polling. CI builds one so the end-to-end job covers the live path.