Skip to content

Class

SQLiteConnection

Represents a single open connection to an SQLite database, either on disk or in memory.
final class SQLiteConnection

Overview

SQLiteConnection wraps a single sqlite3* handle and provides fully asynchronous, Swift-concurrency–friendly access to SQLite, as well as a multiplexed hook API that lets you register many Swift observers even though SQLite exposes only one slot per hook in C.

Storage

Choose how the underlying database is created when opening a connection via SQLiteConnection.Storage:

  • SQLiteConnection.Storage.memory – transient; lives only as long as the connection. Not shareable across processes (and, with SQLITE_OMIT_SHARED_CACHE, not across multiple connections in-process). Great for unit tests and scratch work.

  • SQLiteConnection.Storage.file(path:) – persisted on disk; can be opened by multiple connections/processes subject to SQLite locking rules. Prefer absolute paths.

Observable Hooks

Each connection can fan out these SQLite hooks to multiple callbacks:

Observer Registration Styles

Style

API

Lifetime

Cleanup

Notes

Token-Based (Scoped)

add…Observer(lifetime: .scoped)

Until SQLiteHookToken deallocated

Auto on token dealloc

Use for temporary observation.

Token-Based (Pinned)

add…Observer(lifetime: .pinned)

Until SQLiteHookToken canceled

token.cancel()

Use for long-lived observation.

Scoped

with…Observer

Active only for closure duration

Auto

Handy for tests / temporary instrumentation.

Threading

Registration is thread-safe. Callbacks run on SQLite’s internal thread, not your event loop or actor. Hop if needed:

let token = try await db.addUpdateObserver(lifetime: .pinned) { [weak self] event in
    Task { await self?.myActor.handle(event) }   // hop to actor
}

Cleanup

  • Dropping a SQLiteHookToken with SQLObserverLifetime/scoped lifetime auto-cancels on deallocation.

  • Dropping a SQLiteHookToken with SQLObserverLifetime/pinned lifetime triggers a debug assertion but leaves the observer active.

  • Call cancel() to stop an observer early (works for both lifetimes).

  • All observers are torn down automatically when the connection closes; later cancels are safe.

  • See SQLiteObserverLifetime for detailed lifetime behavior.

Topics

Instance Properties

  • eventLoop
    The event loop on which operations on the connection execute.
  • isClosed
    false if the connection is valid, true if not.
  • logger
    The logger used by the connection.

Instance Methods

Type Aliases

Type Methods

Enumerations

Relationships

Conforms To