Repository Public License
1import Foundation2import PrismCore3import PrismLogicRuntime4import PrismObjectModel56public enum ColumnType: String, Sendable, CaseIterable {7 case text, number, integer, currency, date, boolean89 var sqlType: String {10 switch self {11 case .text, .date: "TEXT"12 case .number, .currency: "REAL"13 case .integer, .boolean: "INTEGER"14 }15 }1617 public var isNumeric: Bool { self == .number || self == .integer || self == .currency }18}1920public struct ColumnSchema: Sendable, Hashable {21 public var name: String22 public var type: ColumnType23 public var label: String24 public var required: Bool25 public var options: [String]26 public var defaultValue: JSONValue?2728 public init(name: String, type: ColumnType, label: String? = nil, required: Bool = false, options: [String] = [], defaultValue: JSONValue? = nil) {29 self.name = name; self.type = type; self.label = label ?? name.prefix(1).uppercased() + name.dropFirst()30 self.required = required; self.options = options; self.defaultValue = defaultValue31 }32}3334/// A data table declared by a `prism.data.table` object. The SQL table name is the object id.35public struct TableSchema: Sendable, Hashable {36 public var name: String37 public var title: String38 public var columns: [ColumnSchema]3940 public init(name: String, title: String = "", columns: [ColumnSchema]) {41 self.name = name; self.title = title.isEmpty ? name : title; self.columns = columns42 }4344 public static let reservedColumns: Set<String> = ["id", "rowid", "oid", "_rowid_"]4546 public init(object: PrismObject) throws {47 guard object.isTable else { throw DataError("`\(object.id)` is not a data table.") }48 guard PrismID.isValid(object.id) else { throw DataError("`\(object.id)` is not a valid table name.") }49 guard let list = object.props["columns"]?.arrayValue, !list.isEmpty else {50 throw DataError("Table `\(object.id)` declares no columns.")51 }52 var columns: [ColumnSchema] = []53 for c in list {54 guard let name = c["name"]?.stringValue, PrismID.isValid(name) else {55 throw DataError("Table `\(object.id)` has a column without a valid name.")56 }57 guard !Self.reservedColumns.contains(name.lowercased()) else {58 throw DataError("`\(name)` is reserved; every table already has an `id` column.")59 }60 guard !columns.contains(where: { $0.name.lowercased() == name.lowercased() }) else {61 throw DataError("Table `\(object.id)` declares column `\(name)` twice.")62 }63 let typeName = c["type"]?.stringValue ?? "text"64 guard let type = ColumnType(rawValue: typeName) else {65 throw DataError("Column `\(name)` has unknown type `\(typeName)`. Use one of: \(ColumnType.allCases.map(\.rawValue).joined(separator: ", ")).")66 }67 columns.append(ColumnSchema(68 name: name, type: type, label: c["label"]?.stringValue, required: c["required"]?.boolValue ?? false,69 options: (c["options"]?.arrayValue ?? []).compactMap(\.stringValue), defaultValue: c["default"]70 ))71 }72 self.init(name: object.id, title: object.name, columns: columns)73 }7475 public func column(_ name: String) -> ColumnSchema? { columns.first { $0.name == name } }7677 /// Converts user or file input into the stored representation, or explains why it cannot.78 public func coerce(_ value: JSONValue, for column: ColumnSchema) throws -> JSONValue {79 if value.isNull || value == .string("") {80 if column.required { throw DataError("\(column.label) is required.") }81 return .null82 }83 switch column.type {84 case .text: return .string(value.displayString)85 case .boolean:86 if let b = value.boolValue { return .int(b ? 1 : 0) }87 if let n = value.numericValue { return .int(n != 0 ? 1 : 0) }88 let s = value.displayString.lowercased()89 if ["true", "yes", "y"].contains(s) { return .int(1) }90 if ["false", "no", "n"].contains(s) { return .int(0) }91 throw DataError("\(column.label) must be true or false.")92 case .date:93 guard let iso = DateCoding.normalize(value.displayString) else {94 throw DataError("\(column.label) must be a date such as 2026-03-14.")95 }96 return .string(iso)97 case .number, .currency, .integer:98 guard let n = value.doubleValue ?? NumberText.parse(value.displayString) else {99 throw DataError("\(column.label) must be a number.")100 }101 if column.type == .integer {102 guard n.rounded() == n, abs(n) < 9e15 else { throw DataError("\(column.label) must be a whole number.") }103 return .int(Int(n))104 }105 return .double(n)106 }107 }108}109110public enum NumberText {111 /// Parses `1,234.50`, `$12`, `(45.10)`, `-3`, `12 %`. Returns nil for anything else.112 public static func parse(_ text: String) -> Double? {113 var t = text.trimmingCharacters(in: .whitespaces)114 var negative = false115 if t.hasPrefix("("), t.hasSuffix(")") { negative = true; t = String(t.dropFirst().dropLast()) }116 t = t.filter { !"$€£¥,% \u{a0}".contains($0) }117 guard !t.isEmpty, let v = Double(t), v.isFinite else { return nil }118 return negative ? -v : v119 }120}121