Repository Public License
1import Foundation2import SQLite334/// SQLite copies the bytes before `sqlite3_bind_*` returns.5private let transientDestructor = unsafeBitCast(-1, to: sqlite3_destructor_type.self)67/// One row of a result set, fully materialised (no statement stays stepped after a query returns, so a read8/// never pins a WAL snapshot longer than the call).9public struct SQLiteRow: Sendable {10 private let columns: [String: Int]11 public let values: [SQLiteValue]1213 init(columns: [String: Int], values: [SQLiteValue]) {14 self.columns = columns; self.values = values15 }1617 public subscript(index: Int) -> SQLiteValue { values[index] }1819 public subscript(column: String) -> SQLiteValue? { columns[column].map { values[$0] } }2021 /// Typed read. Throws `PersistenceError.invalidData` when the column is missing or holds another type.22 public func get<T: SQLiteConvertible>(_ column: String, as type: T.Type = T.self) throws -> T {23 guard let index = columns[column] else {24 throw PersistenceError.invalidData("no column named \(column)")25 }26 guard let value = T.fromSQLite(values[index]) else {27 throw PersistenceError.invalidData("column \(column) does not hold a \(T.self)")28 }29 return value30 }3132 /// Reads a `TEXT` column holding the raw value of an enum.33 public func raw<T: RawRepresentable>(_ column: String, as type: T.Type = T.self) throws -> T34 where T.RawValue == String {35 let text: String = try get(column)36 guard let value = T(rawValue: text) else {37 throw PersistenceError.invalidData("column \(column): unknown \(T.self) value")38 }39 return value40 }4142 public func rawIfPresent<T: RawRepresentable>(_ column: String, as type: T.Type = T.self) throws -> T?43 where T.RawValue == String {44 let text: String? = try get(column)45 guard let text else { return nil }46 guard let value = T(rawValue: text) else {47 throw PersistenceError.invalidData("column \(column): unknown \(T.self) value")48 }49 return value50 }51}5253/// A single SQLite connection with a prepared-statement cache.54///55/// Not `Sendable` on purpose: a connection is confined to the `ConnectionActor` that created it and is only56/// ever handed to synchronous closures running on that actor's serial queue.57public final class SQLiteConnection {58 public enum Location: Sendable, Equatable {59 case file(URL)60 case memory61 }6263 private static let statementCacheLimit = 2566465 private var handle: OpaquePointer?66 private var statements: [String: OpaquePointer] = [:]67 private var savepointDepth = 06869 /// - Parameter create: create the file when missing (writer); readers open an existing file.70 init(location: Location, create: Bool) throws {71 var flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_PRIVATECACHE72 if create { flags |= SQLITE_OPEN_CREATE }73 #if os(iOS)74 // Applies the protection class to the database and to the journal/WAL files SQLite creates.75 flags |= SQLITE_OPEN_FILEPROTECTION_COMPLETEUNTILFIRSTUSERAUTHENTICATION76 #endif77 let path: String78 switch location {79 case .file(let url): path = url.path80 case .memory: path = ":memory:"81 }82 var opened: OpaquePointer?83 let status = sqlite3_open_v2(path, &opened, flags, nil)84 guard status == SQLITE_OK, let opened else {85 let error = SQLiteError(code: status & 0xff, extendedCode: status,86 message: opened.map { String(cString: sqlite3_errmsg($0)) } ?? "cannot open database")87 sqlite3_close_v2(opened)88 throw error89 }90 handle = opened91 sqlite3_extended_result_codes(opened, 1)92 }9394 deinit { close() }9596 public var isOpen: Bool { handle != nil }9798 /// Finalises cached statements and closes the handle. Idempotent.99 func close() {100 for statement in statements.values { sqlite3_finalize(statement) }101 statements.removeAll()102 if let handle { sqlite3_close_v2(handle) }103 handle = nil104 }105106 func setBusyTimeout(milliseconds: Int32) throws {107 try check(sqlite3_busy_timeout(try openHandle(), milliseconds), sql: nil)108 }109110 // MARK: - Running SQL111112 /// Runs one statement and returns the number of rows it changed.113 @discardableResult114 public func execute(_ sql: String, _ parameters: [(any SQLiteConvertible)?] = []) throws -> Int {115 _ = try run(sql, parameters, collect: false)116 return Int(sqlite3_changes(try openHandle()))117 }118119 public func query(_ sql: String, _ parameters: [(any SQLiteConvertible)?] = []) throws -> [SQLiteRow] {120 try run(sql, parameters, collect: true)121 }122123 public func queryOne(_ sql: String, _ parameters: [(any SQLiteConvertible)?] = []) throws -> SQLiteRow? {124 try query(sql, parameters).first125 }126127 /// First column of the first row, or `nil` when there is no row or the value is NULL.128 public func scalar<T: SQLiteConvertible>(_ sql: String, _ parameters: [(any SQLiteConvertible)?] = [],129 as type: T.Type = T.self) throws -> T? {130 guard let value = try query(sql, parameters).first?.values.first, !value.isNull else { return nil }131 guard let typed = T.fromSQLite(value) else {132 throw PersistenceError.invalidData("scalar result is not a \(T.self)")133 }134 return typed135 }136137 /// Runs several `;`-separated statements without parameters (schema scripts, pragmas).138 public func executeScript(_ sql: String) throws {139 let handle = try openHandle()140 var message: UnsafeMutablePointer<CChar>?141 let status = sqlite3_exec(handle, sql, nil, nil, &message)142 if status != SQLITE_OK {143 let text = message.map { String(cString: $0) } ?? String(cString: sqlite3_errmsg(handle))144 sqlite3_free(message)145 throw SQLiteError(code: status & 0xff, extendedCode: sqlite3_extended_errcode(handle), message: text, sql: sql)146 }147 }148149 public var lastInsertRowID: Int64 { handle.map(sqlite3_last_insert_rowid) ?? 0 }150151 public var isInTransaction: Bool { handle.map { sqlite3_get_autocommit($0) == 0 } ?? false }152153 /// Runs `body` atomically. A throw rolls everything back and is rethrown. Nested calls use savepoints, so an154 /// inner failure that the outer body catches only undoes the inner work.155 public func transaction<T>(_ body: () throws -> T) throws -> T {156 if !isInTransaction {157 // IMMEDIATE takes the write lock up front: no lock-upgrade deadlock between two writers.158 try executeScript("BEGIN IMMEDIATE")159 do {160 let result = try body()161 try executeScript("COMMIT")162 return result163 } catch {164 // COMMIT itself can fail (deferred foreign key) and leave the transaction open.165 if isInTransaction { try? executeScript("ROLLBACK") }166 throw error167 }168 }169 savepointDepth += 1170 let name = "sp_\(savepointDepth)"171 defer { savepointDepth -= 1 }172 try executeScript("SAVEPOINT \(name)")173 do {174 let result = try body()175 try executeScript("RELEASE \(name)")176 return result177 } catch {178 try? executeScript("ROLLBACK TO \(name); RELEASE \(name)")179 throw error180 }181 }182183 /// Insert-or-update keyed on `key`. Never `INSERT OR REPLACE`: replacing deletes the row first and would184 /// fire `ON DELETE CASCADE` on its children.185 public func upsert(into table: String, key: String = "id",186 _ columns: KeyValuePairs<String, (any SQLiteConvertible)?>) throws {187 let names = columns.map(\.key)188 let updates = names.filter { $0 != key }.map { "\($0) = excluded.\($0)" }.joined(separator: ", ")189 let conflict = updates.isEmpty ? "DO NOTHING" : "DO UPDATE SET \(updates)"190 let sql = """191 INSERT INTO \(table) (\(names.joined(separator: ", "))) \192 VALUES (\(names.map { _ in "?" }.joined(separator: ", "))) ON CONFLICT(\(key)) \(conflict)193 """194 try execute(sql, columns.map(\.value))195 }196197 // MARK: - Internals198199 private func openHandle() throws -> OpaquePointer {200 guard let handle else { throw PersistenceError.databaseClosed }201 return handle202 }203204 private func check(_ status: Int32, sql: String?) throws {205 guard status != SQLITE_OK, status != SQLITE_DONE, status != SQLITE_ROW else { return }206 throw makeError(status, sql: sql)207 }208209 private func makeError(_ status: Int32, sql: String?) -> SQLiteError {210 guard let handle else {211 return SQLiteError(code: status & 0xff, extendedCode: status, message: "database closed", sql: sql)212 }213 return SQLiteError(code: status & 0xff, extendedCode: sqlite3_extended_errcode(handle),214 message: String(cString: sqlite3_errmsg(handle)), sql: sql)215 }216217 /// Returns a prepared statement and whether it lives in the cache (uncached ones are finalised by the caller).218 private func prepare(_ sql: String) throws -> (statement: OpaquePointer, cached: Bool) {219 let handle = try openHandle()220 if let cached = statements[sql] {221 if sqlite3_stmt_busy(cached) == 0 { return (cached, true) }222 }223 var statement: OpaquePointer?224 let status = sqlite3_prepare_v2(handle, sql, -1, &statement, nil)225 guard status == SQLITE_OK, let statement else {226 sqlite3_finalize(statement)227 throw makeError(status, sql: sql)228 }229 if statements[sql] != nil { return (statement, false) }230 if statements.count >= Self.statementCacheLimit {231 // Dynamic SQL (IN lists…) could grow the cache without bound; dropping it all is rare and cheap.232 var kept: [String: OpaquePointer] = [:]233 for (text, old) in statements {234 if sqlite3_stmt_busy(old) == 0 { sqlite3_finalize(old) } else { kept[text] = old }235 }236 statements = kept237 }238 statements[sql] = statement239 return (statement, true)240 }241242 private func bind(_ statement: OpaquePointer, _ parameters: [(any SQLiteConvertible)?], sql: String) throws {243 let expected = Int(sqlite3_bind_parameter_count(statement))244 guard expected == parameters.count else {245 throw SQLiteError(code: SQLITE_MISUSE, extendedCode: SQLITE_MISUSE,246 message: "statement expects \(expected) parameters, got \(parameters.count)", sql: sql)247 }248 for (offset, parameter) in parameters.enumerated() {249 let index = Int32(offset + 1)250 let status: Int32251 switch parameter?.sqliteValue ?? .null {252 case .null: status = sqlite3_bind_null(statement, index)253 case .integer(let value): status = sqlite3_bind_int64(statement, index, value)254 case .real(let value): status = sqlite3_bind_double(statement, index, value)255 case .text(let value):256 status = sqlite3_bind_text(statement, index, value, Int32(value.utf8.count), transientDestructor)257 case .blob(let value):258 status = value.withUnsafeBytes { buffer in259 // A zero-length blob has a nil base address; bind_zeroblob keeps it a BLOB instead of NULL.260 guard let base = buffer.baseAddress, buffer.count > 0 else {261 return sqlite3_bind_zeroblob(statement, index, 0)262 }263 return sqlite3_bind_blob64(statement, index, base, sqlite3_uint64(buffer.count), transientDestructor)264 }265 }266 try check(status, sql: sql)267 }268 }269270 private func run(_ sql: String, _ parameters: [(any SQLiteConvertible)?], collect: Bool) throws -> [SQLiteRow] {271 let (statement, cached) = try prepare(sql)272 defer {273 if cached {274 sqlite3_reset(statement)275 sqlite3_clear_bindings(statement)276 } else {277 sqlite3_finalize(statement)278 }279 }280 try bind(statement, parameters, sql: sql)281282 var rows: [SQLiteRow] = []283 var columns: [String: Int] = [:]284 let count = Int(sqlite3_column_count(statement))285 if collect {286 for index in 0..<count {287 columns[String(cString: sqlite3_column_name(statement, Int32(index)))] = index288 }289 }290 while true {291 let status = sqlite3_step(statement)292 if status == SQLITE_DONE { break }293 guard status == SQLITE_ROW else { throw makeError(status, sql: sql) }294 guard collect else { continue }295 var values: [SQLiteValue] = []296 values.reserveCapacity(count)297 for index in 0..<Int32(count) {298 switch sqlite3_column_type(statement, index) {299 case SQLITE_INTEGER: values.append(.integer(sqlite3_column_int64(statement, index)))300 case SQLITE_FLOAT: values.append(.real(sqlite3_column_double(statement, index)))301 case SQLITE_TEXT:302 let length = Int(sqlite3_column_bytes(statement, index))303 if let pointer = sqlite3_column_text(statement, index) {304 let buffer = UnsafeBufferPointer(start: pointer, count: length)305 values.append(.text(String(decoding: buffer, as: UTF8.self)))306 } else {307 values.append(.text(""))308 }309 case SQLITE_BLOB:310 let length = Int(sqlite3_column_bytes(statement, index))311 if let pointer = sqlite3_column_blob(statement, index), length > 0 {312 values.append(.blob(Data(bytes: pointer, count: length)))313 } else {314 values.append(.blob(Data()))315 }316 default: values.append(.null)317 }318 }319 rows.append(SQLiteRow(columns: columns, values: values))320 }321 return rows322 }323}324