SPB Git

Repository Public License

SQLiteDatabase.swift 6.8 KB 152 lines swift

1import Foundation2import Synchronization34/// Owns one connection and runs every use of it on a private serial queue.5///6/// The custom executor keeps blocking SQLite calls off the Swift cooperative thread pool (and off the main7/// thread): awaiting this actor parks the caller, it never blocks one of the pool's threads on disk I/O.8actor ConnectionActor {9    private nonisolated let queue: DispatchSerialQueue10    private var connection: SQLiteConnection?1112    nonisolated var unownedExecutor: UnownedSerialExecutor { queue.asUnownedSerialExecutor() }1314    init(label: String) {15        queue = DispatchSerialQueue(label: label, qos: .userInitiated)16    }1718    /// Opens the connection on the actor's own queue, so `sqlite3_open` never runs on the caller's thread.19    func open(location: SQLiteConnection.Location, create: Bool) throws {20        connection = try SQLiteConnection(location: location, create: create)21    }2223    func run<T: Sendable>(_ body: @Sendable (SQLiteConnection) throws -> T) throws -> T {24        guard let connection else { throw PersistenceError.databaseClosed }25        return try body(connection)26    }2728    func transaction<T: Sendable>(_ body: @Sendable (SQLiteConnection) throws -> T) throws -> T {29        guard let connection else { throw PersistenceError.databaseClosed }30        return try connection.transaction { try body(connection) }31    }3233    /// Read-only snapshot: every statement of `body` sees the same committed state.34    func snapshot<T: Sendable>(_ body: @Sendable (SQLiteConnection) throws -> T) throws -> T {35        guard let connection else { throw PersistenceError.databaseClosed }36        try connection.executeScript("BEGIN DEFERRED")37        defer { try? connection.executeScript("COMMIT") }38        return try body(connection)39    }4041    func close() {42        connection?.close()43        connection = nil44    }45}4647/// The connection set of one database: a single writer and, for file databases, a small pool of read-only48/// connections.49///50/// In WAL mode readers do not block the writer and the writer does not block readers, so list queries and51/// omnibox suggestions keep running while a session save is committing. An in-memory database has exactly one52/// connection (a private in-memory database cannot be shared between connections), so reads are simply53/// serialised with writes there.54///55/// Read-your-writes holds: a `read` that starts after a `write`/`transaction` call returned sees its effects,56/// because each read opens a fresh snapshot.57public final class SQLiteDatabase: Sendable {58    public struct Configuration: Sendable {59        /// Number of read-only connections for a file database. `0` routes reads through the writer.60        public var readerCount: Int61        public var busyTimeoutMilliseconds: Int326263        public init(readerCount: Int = 3, busyTimeoutMilliseconds: Int32 = 5_000) {64            self.readerCount = max(0, readerCount)65            self.busyTimeoutMilliseconds = busyTimeoutMilliseconds66        }67    }6869    public let location: SQLiteConnection.Location70    private let writer: ConnectionActor71    private let readers: [ConnectionActor]72    private let cursor = Mutex<Int>(0)7374    /// Opens the writer, applies the connection pragmas, then opens the readers. Readers may be opened before75    /// the schema exists: migrations commit atomically, so a reader sees either no table or the full version.76    init(location: SQLiteConnection.Location, configuration: Configuration) async throws {77        self.location = location78        let writer = ConnectionActor(label: "dev.orixlab.navigator.sqlite.writer")79        let timeout = configuration.busyTimeoutMilliseconds80        let isFile = location != .memory81        do {82            try await writer.open(location: location, create: true)83            try await writer.run { connection in84                try connection.setBusyTimeout(milliseconds: timeout)85                if isFile {86                    // The first statement that touches the file: a non-database fails here with SQLITE_NOTADB.87                    _ = try connection.query("PRAGMA journal_mode = WAL")88                    // NORMAL in WAL: a committed transaction survives an app crash; only an OS crash or power89                    // loss can drop the last commits, and never corrupts the file.90                    try connection.executeScript("PRAGMA synchronous = NORMAL; PRAGMA journal_size_limit = 67108864;")91                }92                try connection.executeScript("""93                PRAGMA foreign_keys = ON;94                PRAGMA temp_store = MEMORY;95                PRAGMA secure_delete = ON;96                """)97            }98        } catch {99            await writer.close()100            throw error101        }102        self.writer = writer103        var readers: [ConnectionActor] = []104        if isFile {105            do {106                for index in 0..<configuration.readerCount {107                    let reader = ConnectionActor(label: "dev.orixlab.navigator.sqlite.reader.\(index)")108                    readers.append(reader)109                    try await reader.open(location: location, create: false)110                    try await reader.run { connection in111                        try connection.setBusyTimeout(milliseconds: timeout)112                        try connection.executeScript("PRAGMA query_only = ON; PRAGMA temp_store = MEMORY;")113                    }114                }115            } catch {116                for reader in readers { await reader.close() }117                await writer.close()118                throw error119            }120        }121        self.readers = readers122    }123124    /// Runs a read-only closure on a pooled reader (or on the writer when there is no pool).125    public func read<T: Sendable>(_ body: @Sendable (SQLiteConnection) throws -> T) async throws -> T {126        guard !readers.isEmpty else { return try await writer.run(body) }127        let index = cursor.withLock { value -> Int in128            value = (value + 1) % readers.count129            return value130        }131        return try await readers[index].snapshot(body)132    }133134    /// Runs a closure on the writer in autocommit mode. Use `transaction` for anything with more than one statement.135    @discardableResult136    public func write<T: Sendable>(_ body: @Sendable (SQLiteConnection) throws -> T) async throws -> T {137        try await writer.run(body)138    }139140    /// Runs a closure on the writer inside one atomic transaction; a throw rolls back and is rethrown.141    @discardableResult142    public func transaction<T: Sendable>(_ body: @Sendable (SQLiteConnection) throws -> T) async throws -> T {143        try await writer.transaction(body)144    }145146    /// Closes every connection. Later calls throw `PersistenceError.databaseClosed`.147    public func close() async {148        for reader in readers { await reader.close() }149        await writer.close()150    }151}152
Files main
Menu

Theme