Repository Public License
1import Foundation2import PrismCore3import PrismObjectModel45/// The per-app SQLite store: schema kept in step with the blueprint, CRUD, transactions.6public final class AppDataStore: @unchecked Sendable {7 public let db: SQLiteDatabase8 public private(set) var tables: [String: TableSchema] = [:]9 private let lock = NSLock()10 private var _revision = 01112 /// Bumped on every write; views and caches key on it.13 public var revision: Int { lock.withLock { _revision } }14 private func bump() { lock.withLock { _revision += 1 } }1516 public struct MigrationReport: Sendable, Equatable {17 public var createdTables: [String] = []18 public var addedColumns: [String] = []19 /// Columns or tables that exist in the database but are no longer declared. They are kept: nothing is dropped.20 public var retained: [String] = []21 public init() {}22 }2324 public init(url: URL?) throws {25 db = try SQLiteDatabase(url: url)26 try db.execute("CREATE TABLE IF NOT EXISTS _prism_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")27 }2829 public convenience init(url: URL?, blueprint: AppBlueprint) throws {30 try self.init(url: url)31 try sync(with: blueprint)32 }3334 public func close() { db.close() }3536 /// Plans the schema change without touching the database.37 public func plan(for blueprint: AppBlueprint) throws -> MigrationReport {38 try migrate(blueprint, apply: false)39 }4041 /// Additive, transactional migration: creates missing tables and columns, never drops data.42 @discardableResult43 public func sync(with blueprint: AppBlueprint) throws -> MigrationReport {44 try migrate(blueprint, apply: true)45 }4647 private func migrate(_ blueprint: AppBlueprint, apply: Bool) throws -> MigrationReport {48 let schemas = try blueprint.tables.map(TableSchema.init(object:))49 var report = MigrationReport()50 var seeds: [String] = []51 let work = {52 let existing = Set(try self.db.query("SELECT name FROM sqlite_master WHERE type='table'").compactMap { $0["name"]?.stringValue })53 for schema in schemas {54 let table = try SQLiteDatabase.quote(schema.name)55 if !existing.contains(schema.name) {56 report.createdTables.append(schema.name)57 if apply {58 let cols = try schema.columns.map { "\(try SQLiteDatabase.quote($0.name)) \($0.type.sqlType)" }59 try self.db.execute("CREATE TABLE \(table) (id INTEGER PRIMARY KEY AUTOINCREMENT, \(cols.joined(separator: ", ")))")60 seeds.append(schema.name)61 }62 continue63 }64 let present = try self.db.query("PRAGMA table_info(\(table))").compactMap { $0["name"]?.stringValue }65 for c in schema.columns where !present.contains(where: { $0.lowercased() == c.name.lowercased() }) {66 report.addedColumns.append("\(schema.name).\(c.name)")67 if apply { try self.db.execute("ALTER TABLE \(table) ADD COLUMN \(try SQLiteDatabase.quote(c.name)) \(c.type.sqlType)") }68 }69 for p in present where p != "id" && schema.column(p) == nil { report.retained.append("\(schema.name).\(p)") }70 }71 for name in existing where !name.hasPrefix("_prism_") && !name.hasPrefix("sqlite_") && !schemas.contains(where: { $0.name == name }) {72 report.retained.append(name)73 }74 if apply {75 try self.db.execute(76 "INSERT INTO _prism_meta (key, value) VALUES ('blueprintVersion', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",77 [.string(String(blueprint.version))]78 )79 }80 }81 if apply {82 try db.transaction(work)83 tables = Dictionary(schemas.map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a })84 // Sample rows declared by the blueprint (`props.seed`) fill a table only when it is first created.85 for name in seeds {86 let rows = (blueprint.object(name)?.props["seed"]?.arrayValue ?? []).compactMap(\.objectValue)87 if !rows.isEmpty { try? insertAll(into: name, rows: rows) }88 }89 bump()90 } else {91 try work()92 }93 report.createdTables.sort(); report.addedColumns.sort(); report.retained.sort()94 return report95 }9697 public func schema(_ table: String) throws -> TableSchema {98 guard let s = tables[table] else { throw DataError("There is no table `\(table)`.") }99 return s100 }101102 private func coerced(_ values: [String: JSONValue], schema: TableSchema, requireAll: Bool) throws -> [(String, JSONValue)] {103 var out: [(String, JSONValue)] = []104 for key in values.keys where schema.column(key) == nil && key != "id" {105 throw DataError("Table `\(schema.name)` has no column `\(key)`.")106 }107 for column in schema.columns {108 if let v = values[column.name] {109 out.append((column.name, try schema.coerce(v, for: column)))110 } else if requireAll {111 let fallback = column.defaultValue ?? .null112 out.append((column.name, try schema.coerce(fallback, for: column)))113 }114 }115 return out116 }117118 @discardableResult119 public func insert(into table: String, values: [String: JSONValue]) throws -> Int {120 let schema = try schema(table)121 let pairs = try coerced(values, schema: schema, requireAll: true)122 let cols = try pairs.map { try SQLiteDatabase.quote($0.0) }.joined(separator: ", ")123 let marks = pairs.map { _ in "?" }.joined(separator: ", ")124 let id = try db.transaction {125 try db.execute("INSERT INTO \(try SQLiteDatabase.quote(table)) (\(cols)) VALUES (\(marks))", pairs.map(\.1))126 return db.lastInsertRowID127 }128 bump()129 return id130 }131132 /// Inserts many rows in one transaction; either all are stored or none.133 public func insertAll(into table: String, rows: [[String: JSONValue]]) throws {134 let schema = try schema(table)135 try db.transaction {136 for row in rows {137 let pairs = try coerced(row, schema: schema, requireAll: true)138 let cols = try pairs.map { try SQLiteDatabase.quote($0.0) }.joined(separator: ", ")139 try db.execute(140 "INSERT INTO \(try SQLiteDatabase.quote(table)) (\(cols)) VALUES (\(pairs.map { _ in "?" }.joined(separator: ", ")))",141 pairs.map(\.1)142 )143 }144 }145 bump()146 }147148 public func update(_ table: String, id: Int, values: [String: JSONValue]) throws {149 let schema = try schema(table)150 let pairs = try coerced(values, schema: schema, requireAll: false)151 guard !pairs.isEmpty else { return }152 let sets = try pairs.map { "\(try SQLiteDatabase.quote($0.0)) = ?" }.joined(separator: ", ")153 try db.execute("UPDATE \(try SQLiteDatabase.quote(table)) SET \(sets) WHERE id = ?", pairs.map(\.1) + [.int(id)])154 guard db.changes > 0 else { throw DataError("That record no longer exists.") }155 bump()156 }157158 public func delete(from table: String, id: Int) throws {159 _ = try schema(table)160 try db.execute("DELETE FROM \(try SQLiteDatabase.quote(table)) WHERE id = ?", [.int(id)])161 bump()162 }163164 public func deleteAll(from table: String) throws {165 _ = try schema(table)166 try db.execute("DELETE FROM \(try SQLiteDatabase.quote(table))")167 bump()168 }169170 public func record(_ table: String, id: Int) throws -> [String: JSONValue]? {171 _ = try schema(table)172 return try db.query("SELECT * FROM \(try SQLiteDatabase.quote(table)) WHERE id = ?", [.int(id)]).first173 }174175 public func count(_ table: String) throws -> Int {176 _ = try schema(table)177 return try db.query("SELECT COUNT(*) AS n FROM \(try SQLiteDatabase.quote(table))").first?["n"]?.intValue ?? 0178 }179180 /// Distinct non-empty values of a column, sorted: the options of a filter dropdown.181 public func distinctValues(_ table: String, column: String) throws -> [JSONValue] {182 let schema = try schema(table)183 guard schema.column(column) != nil else { throw DataError("Table `\(table)` has no column `\(column)`.") }184 let c = try SQLiteDatabase.quote(column)185 return try db.query("SELECT DISTINCT \(c) AS v FROM \(try SQLiteDatabase.quote(table)) WHERE \(c) IS NOT NULL AND \(c) <> '' ORDER BY \(c) LIMIT 500")186 .compactMap { $0["v"] }187 }188189 // MARK: Small key/value area for app state and bookkeeping190191 public func meta(_ key: String) -> String? {192 (try? db.query("SELECT value FROM _prism_meta WHERE key = ?", [.string(key)]))?.first?["value"]?.stringValue193 }194195 public func setMeta(_ key: String, _ value: String) throws {196 try db.execute("INSERT INTO _prism_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", [.string(key), .string(value)])197 }198}199