Repository Public License
1import Foundation2import PrismCore3import PrismLogicRuntime4import PrismObjectModel56/// A declarative query (ADR 0003). It is compiled to parameterized SQL over validated identifiers;7/// blueprints and expressions never contain SQL.8public struct DataQuery: Sendable, Hashable {9 public struct Filter: Sendable, Hashable {10 public var column: String11 public var op: String12 public var value: DynamicValue13 /// When this evaluates truthy the filter is skipped (e.g. the "All" choice of a category picker).14 public var unless: DynamicValue?15 }16 public struct Sort: Sendable, Hashable {17 public var column: String18 public var descending: Bool19 public init(column: String, descending: Bool) { self.column = column; self.descending = descending }20 }21 public struct Group: Sendable, Hashable { public var column: String; public var bucket: String; public var alias: String }22 public struct Aggregate: Sendable, Hashable { public var fn: String; public var column: String?; public var alias: String }2324 public var table: String25 public var filters: [Filter] = []26 public var searchColumns: [String] = []27 public var searchText: DynamicValue?28 public var sort: [Sort] = []29 public var group: Group?30 public var aggregates: [Aggregate] = []31 public var limit: Int?3233 public static let operators: Set<String> = ["eq", "ne", "lt", "lte", "gt", "gte", "contains", "startsWith", "in"]34 public static let aggregateFunctions: Set<String> = ["sum", "count", "avg", "min", "max"]35 public static let buckets: Set<String> = ["none", "month", "year"]36 public static let maxRows = 50_0003738 public init(table: String) { self.table = table }3940 public init(json: JSONValue) throws {41 guard let o = json.objectValue else { throw DataError("A query must be an object.") }42 let known: Set<String> = ["table", "filters", "search", "sort", "groupBy", "aggregates", "limit"]43 if let unknown = o.keys.first(where: { !known.contains($0) }) { throw DataError("Unknown query field `\(unknown)`.") }44 guard let table = o["table"]?.stringValue else { throw DataError("A query needs a `table`.") }45 self.table = table46 for f in o["filters"]?.arrayValue ?? [] {47 guard let column = f["column"]?.stringValue else { throw DataError("A filter needs a `column`.") }48 let op = f["op"]?.stringValue ?? "eq"49 guard Self.operators.contains(op) else { throw DataError("Unknown filter operator `\(op)`.") }50 guard let value = f["value"] else { throw DataError("The filter on `\(column)` needs a `value`.") }51 filters.append(Filter(column: column, op: op, value: DynamicValue(value), unless: f["unless"].map(DynamicValue.init)))52 }53 if let s = o["search"] {54 searchColumns = (s["columns"]?.arrayValue ?? []).compactMap(\.stringValue)55 guard !searchColumns.isEmpty, let text = s["text"] else { throw DataError("`search` needs `columns` and `text`.") }56 searchText = DynamicValue(text)57 }58 for s in o["sort"]?.arrayValue ?? [] {59 guard let column = s["column"]?.stringValue else { throw DataError("A sort needs a `column`.") }60 sort.append(Sort(column: column, descending: s["descending"]?.boolValue ?? false))61 }62 if let g = o["groupBy"] {63 guard let column = g["column"]?.stringValue else { throw DataError("`groupBy` needs a `column`.") }64 let bucket = g["bucket"]?.stringValue ?? "none"65 guard Self.buckets.contains(bucket) else { throw DataError("Unknown bucket `\(bucket)`.") }66 group = Group(column: column, bucket: bucket, alias: g["as"]?.stringValue ?? column)67 }68 for a in o["aggregates"]?.arrayValue ?? [] {69 guard let fn = a["fn"]?.stringValue, Self.aggregateFunctions.contains(fn) else {70 throw DataError("An aggregate needs `fn`: \(Self.aggregateFunctions.sorted().joined(separator: ", ")).")71 }72 let column = a["column"]?.stringValue73 guard fn == "count" || column != nil else { throw DataError("`\(fn)` needs a `column`.") }74 aggregates.append(Aggregate(fn: fn, column: column, alias: a["as"]?.stringValue ?? (column.map { "\(fn)_\($0)" } ?? "count")))75 }76 if let l = o["limit"] {77 guard let n = l.intValue, n > 0 else { throw DataError("`limit` must be a positive whole number.") }78 limit = n79 }80 if group != nil && aggregates.isEmpty { throw DataError("`groupBy` needs at least one aggregate.") }81 }8283 /// Names produced by this query, used to validate what components read from it.84 public func outputColumns(schema: TableSchema) -> [String] {85 if aggregates.isEmpty { return ["id"] + schema.columns.map(\.name) }86 return (group.map { [$0.alias] } ?? []) + aggregates.map(\.alias)87 }8889 /// Checks identifiers against the schema. Returns human-readable problems.90 public func problems(schema: TableSchema) -> [String] {91 var out: [String] = []92 func check(_ column: String, _ what: String) {93 if column != "id" && schema.column(column) == nil { out.append("\(what) uses unknown column `\(column)` of `\(schema.name)`.") }94 }95 filters.forEach { check($0.column, "A filter") }96 searchColumns.forEach { check($0, "Search") }97 if let group { check(group.column, "Grouping") }98 for a in aggregates {99 if let c = a.column {100 check(c, "An aggregate")101 if a.fn != "count", a.fn != "min", a.fn != "max", let col = schema.column(c), !col.type.isNumeric {102 out.append("`\(a.fn)` needs a numeric column; `\(c)` is \(col.type.rawValue).")103 }104 }105 if !PrismID.isValid(a.alias) { out.append("`\(a.alias)` is not a valid result name.") }106 }107 let outputs = Set(outputColumns(schema: schema))108 for s in sort where !outputs.contains(s.column) { out.append("Sorting uses `\(s.column)`, which this query does not produce.") }109 if let group, !PrismID.isValid(group.alias) { out.append("`\(group.alias)` is not a valid result name.") }110 if let group, group.bucket != "none", let c = schema.column(group.column), c.type != .date {111 out.append("Bucketing by \(group.bucket) needs a date column; `\(group.column)` is \(c.type.rawValue).")112 }113 return out114 }115116 public struct Compiled: Sendable, Equatable { public var sql: String; public var params: [JSONValue] }117118 public func compile(schema: TableSchema, scope: ExpressionScope) throws -> Compiled {119 if let problem = problems(schema: schema).first { throw DataError(problem) }120 let q = SQLiteDatabase.quote121 var params: [JSONValue] = []122 var wheres: [String] = []123 func like(_ text: String) -> String {124 text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "%", with: "\\%").replacingOccurrences(of: "_", with: "\\_")125 }126 for f in filters {127 if let unless = f.unless, try unless.resolve(in: scope).isTruthy { continue }128 let value = try f.value.resolve(in: scope)129 let col = try q(f.column)130 switch f.op {131 case "contains", "startsWith":132 let text = value.displayString133 if text.isEmpty { continue }134 wheres.append("\(col) LIKE ? ESCAPE '\\'")135 params.append(.string((f.op == "contains" ? "%" : "") + like(text) + "%"))136 case "in":137 guard let list = value.arrayValue, !list.isEmpty else { continue }138 wheres.append("\(col) IN (\(list.map { _ in "?" }.joined(separator: ", ")))")139 params += list140 default:141 if value.isNull {142 wheres.append(f.op == "ne" ? "\(col) IS NOT NULL" : "\(col) IS NULL")143 } else {144 let op = ["eq": "=", "ne": "<>", "lt": "<", "lte": "<=", "gt": ">", "gte": ">="][f.op]!145 wheres.append("\(col) \(op) ?")146 params.append(value)147 }148 }149 }150 if let searchText, case let text = try searchText.resolve(in: scope).displayString.trimmingCharacters(in: .whitespaces), !text.isEmpty {151 let parts = try searchColumns.map { "CAST(\(try q($0)) AS TEXT) LIKE ? ESCAPE '\\'" }152 wheres.append("(" + parts.joined(separator: " OR ") + ")")153 params += searchColumns.map { _ in .string("%" + like(text) + "%") }154 }155156 var selects: [String] = []157 var groupSQL: String?158 if aggregates.isEmpty {159 selects.append("*")160 } else {161 if let group {162 let col = try q(group.column)163 let expr = group.bucket == "month" ? "substr(\(col), 1, 7)" : group.bucket == "year" ? "substr(\(col), 1, 4)" : col164 selects.append("\(expr) AS \(try q(group.alias))")165 groupSQL = expr166 }167 for a in aggregates {168 let target = try a.column.map { try q($0) } ?? "*"169 let fn = a.fn.uppercased()170 let expr = a.fn == "sum" ? "COALESCE(SUM(\(target)), 0)" : "\(fn)(\(target))"171 selects.append("\(expr) AS \(try q(a.alias))")172 }173 }174 var sql = "SELECT \(selects.joined(separator: ", ")) FROM \(try q(table))"175 if !wheres.isEmpty { sql += " WHERE " + wheres.joined(separator: " AND ") }176 if let groupSQL { sql += " GROUP BY \(groupSQL)" }177 var orders = try sort.map { "\(try q($0.column)) \($0.descending ? "DESC" : "ASC")" }178 if orders.isEmpty, let group { orders = ["\(try q(group.alias)) ASC"] }179 if orders.isEmpty, aggregates.isEmpty { orders = ["id ASC"] }180 if !orders.isEmpty { sql += " ORDER BY " + orders.joined(separator: ", ") }181 sql += " LIMIT \(min(limit ?? Self.maxRows, Self.maxRows))"182 return Compiled(sql: sql, params: params)183 }184}185186extension AppDataStore {187 public func run(_ query: DataQuery, scope: ExpressionScope = ExpressionScope()) throws -> [[String: JSONValue]] {188 let compiled = try query.compile(schema: try schema(query.table), scope: scope)189 return try db.query(compiled.sql, compiled.params)190 }191}192