SPB Git

Repository Public

SQLite.swift 5.0 KB 120 lines swift

1// SP Music iOS2// File: Core/Sources/SPMusicCore/Persistence/SQLite.swift3// Description: Thin wrapper over the system SQLite.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation9import SQLite31011public struct SQLiteError: Error, CustomStringConvertible, Sendable {12    public var code: Int3213    public var message: String14    public var description: String { "SQLite \(code): \(message)" }15}1617public enum SQLValue: Sendable, Equatable {18    case null, int(Int64), double(Double), text(String), blob(Data)19    public static func t(_ s: String?) -> SQLValue { s.map { .text($0) } ?? .null }20    public static func i(_ n: Int?) -> SQLValue { n.map { .int(Int64($0)) } ?? .null }21    public static func i(_ n: Int64?) -> SQLValue { n.map { .int($0) } ?? .null }22    public static func b(_ v: Bool) -> SQLValue { .int(v ? 1 : 0) }23    public static func d(_ d: Date?) -> SQLValue { d.map { .double($0.timeIntervalSince1970) } ?? .null }24}2526/// One row of a result, read by column index.27public struct SQLRow {28    let stmt: OpaquePointer29    public func isNull(_ i: Int32) -> Bool { sqlite3_column_type(stmt, i) == SQLITE_NULL }30    public func text(_ i: Int32) -> String { sqlite3_column_text(stmt, i).map { String(cString: $0) } ?? "" }31    public func optText(_ i: Int32) -> String? { isNull(i) ? nil : text(i) }32    public func int(_ i: Int32) -> Int { Int(sqlite3_column_int64(stmt, i)) }33    public func int64(_ i: Int32) -> Int64 { sqlite3_column_int64(stmt, i) }34    public func optInt(_ i: Int32) -> Int? { isNull(i) ? nil : int(i) }35    public func bool(_ i: Int32) -> Bool { sqlite3_column_int64(stmt, i) != 0 }36    public func double(_ i: Int32) -> Double { sqlite3_column_double(stmt, i) }37    public func optDate(_ i: Int32) -> Date? { isNull(i) ? nil : Date(timeIntervalSince1970: double(i)) }38    public func blob(_ i: Int32) -> Data? {39        guard let p = sqlite3_column_blob(stmt, i) else { return nil }40        return Data(bytes: p, count: Int(sqlite3_column_bytes(stmt, i)))41    }42}4344/// Thin wrapper over the system SQLite. Not thread-safe by itself: it lives inside the `Database` actor.45final class SQLite {46    private var db: OpaquePointer?47    private var cache: [String: OpaquePointer] = [:]48    private static let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)4950    init(path: String) throws {51        let flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX52        guard sqlite3_open_v2(path, &db, flags, nil) == SQLITE_OK else {53            let e = error(); sqlite3_close(db); throw e54        }55        try exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = OFF; PRAGMA busy_timeout = 5000;")56    }57    deinit {58        for s in cache.values { sqlite3_finalize(s) }59        sqlite3_close(db)60    }6162    private func error() -> SQLiteError { SQLiteError(code: sqlite3_errcode(db), message: String(cString: sqlite3_errmsg(db))) }6364    func exec(_ sql: String) throws {65        guard sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK else { throw error() }66    }6768    private func prepared(_ sql: String, _ params: [SQLValue]) throws -> OpaquePointer {69        let stmt: OpaquePointer70        if let s = cache[sql] { stmt = s; sqlite3_reset(s); sqlite3_clear_bindings(s) }71        else {72            var s: OpaquePointer?73            guard sqlite3_prepare_v2(db, sql, -1, &s, nil) == SQLITE_OK, let s else { throw error() }74            cache[sql] = s; stmt = s75        }76        for (k, v) in params.enumerated() {77            let i = Int32(k + 1)78            let rc: Int32 = switch v {79            case .null: sqlite3_bind_null(stmt, i)80            case .int(let n): sqlite3_bind_int64(stmt, i, n)81            case .double(let d): sqlite3_bind_double(stmt, i, d)82            case .text(let s): sqlite3_bind_text(stmt, i, s, -1, Self.transient)83            case .blob(let d): d.withUnsafeBytes { sqlite3_bind_blob(stmt, i, $0.baseAddress, Int32(d.count), Self.transient) }84            }85            guard rc == SQLITE_OK else { throw error() }86        }87        return stmt88    }8990    func run(_ sql: String, _ params: [SQLValue] = []) throws {91        let stmt = try prepared(sql, params)92        defer { sqlite3_reset(stmt) }93        while true {94            let rc = sqlite3_step(stmt)95            if rc == SQLITE_DONE { return }96            if rc != SQLITE_ROW { throw error() }97        }98    }99100    func query<T>(_ sql: String, _ params: [SQLValue] = [], _ map: (SQLRow) -> T) throws -> [T] {101        let stmt = try prepared(sql, params)102        defer { sqlite3_reset(stmt) }103        var out: [T] = []104        while true {105            let rc = sqlite3_step(stmt)106            if rc == SQLITE_DONE { return out }107            if rc != SQLITE_ROW { throw error() }108            out.append(map(SQLRow(stmt: stmt)))109        }110    }111112    var changes: Int { Int(sqlite3_changes(db)) }113114    func transaction<T>(_ body: () throws -> T) throws -> T {115        try exec("BEGIN IMMEDIATE")116        do { let r = try body(); try exec("COMMIT"); return r }117        catch { try? exec("ROLLBACK"); throw error }118    }119}120
Files main
Menu

Theme