// The generic verbs, as the Swift surfaces call them. One set for every table // by its id; the root's are the core's (`CoreRecords`, over cotton-ffi), and // `FixtureRecords` answers them from the bundled fixtures for tests and // previews only. import CottonKit import CottonValues import Foundation public struct RecordPage: Sendable { public var records: [TableRecord] /// The page to ask for next, or nil when this was the last. public var next: Int? /// How many records every page of this read holds together, as the store /// answers it; nil from a store that does not say. A count is read from /// here, never by paging through the whole table. public var total: Int? /// A list read as a day plan (the core's `day_plan`: a calendar, a todo /// list) says every section it holds and how many stand in each, counted /// over the whole table; nil from a store that plans nothing. public var sections: [PlanSection]? /// How many records the same read finds archived, on a table that /// archives (S7: what is archived can be found again) — what the list's /// "Archived · n" link counts; nil from a store that does not say. public var archived: Int? /// A grouped list whose group says figures (`group.summary`): each /// group's head lines, by the value its rows hold in the group's column, /// as the core says them over the WHOLE group; nil from a store that /// says none. public var groupHeads: [String: [String]]? public init( records: [TableRecord], next: Int?, total: Int? = nil, sections: [PlanSection]? = nil, archived: Int? = nil, groupHeads: [String: [String]]? = nil ) { self.records = records self.next = next self.total = total self.sections = sections self.archived = archived self.groupHeads = groupHeads } } /// One section of a planned read: its key (`coming`, `earlier`, `today`, /// `late`, `later`, `undated`, or `day` with the day), and its whole count. public struct PlanSection: Hashable, Sendable { public var key: String public var day: String? public var count: Int public init(key: String, day: String? = nil, count: Int) { self.key = key self.day = day self.count = count } /// The key as the plan names the section ("day:2026-10-06" for a day). public var fullKey: String { key == "day" ? "day:\(day ?? "")" : key } } /// How a list asks to be read as the reader's day plan: the one section it /// wants, in the reader's zone. The core's `day_plan` takes it. public struct PlanView: Hashable, Sendable { public var section: String public var timezone: String /// The day, for the section `day` (one of the days ahead), YYYY-MM-DD. public var day: String? /// The day the plan is read from, YYYY-MM-DD — "coming" is that day and /// after — where a route names one (a date slip opens its own day, walker /// 298); nil reads from this device's today. public var today: String? = nil public init(section: String, timezone: String = TimeZone.current.identifier, day: String? = nil) { self.section = section self.timezone = timezone self.day = day } /// The key the plan's `sections` name this view by ("day:2026-10-06"). public var key: String { day.map { "day:\($0)" } ?? section } /// The view that reads one of the plan's sections by its key. public static func reading(key: String) -> PlanView { if key.hasPrefix("day:") { return PlanView(section: "day", day: String(key.dropFirst(4))) } return PlanView(section: key) } /// The where key a narrowed list carries its plan section under: not a /// column, so the store never filters by it (`RecordListModel.where`). public static let whereKey = "_section" /// A calendar's first page: today and after, soonest first. public static let coming = PlanView(section: "coming") /// A calendar's past, newest first, behind one closed heading. public static let earlier = PlanView(section: "earlier") } public struct RecordLink: Hashable, Sendable { public let table: String public let id: String public init(table: String, id: String) { self.table = table; self.id = id } } extension TableDefinition { /// Every record `records` link to, once: a single link's one id and each /// id of a several-record link (a chat's people, a photo's albums) — the /// tags of one whose titles were never asked for draw as nothing. public func links(in records: [TableRecord]) -> [RecordLink] { // A column linking many (a photo's people, its albums) holds a list // of ids: every one is named, or its tags draw nothing. Array(Set(records.flatMap { record in columns.flatMap { column -> [RecordLink] in guard column.type == .link, let table = column.linkTo else { return [] } return RecordFilter.options(record[column.key]).filter { !$0.isEmpty }.map { RecordLink(table: table, id: $0) } } })) } } public protocol Records: AnyObject, Sendable { func tableDefinitions() async throws -> [TableDefinition] /// Total rows in the table, independent of search, project and pagination. func count(table: String) async throws -> Int /// Latest mutation timestamp, when the store supplies explicit metadata. func lastChanged(table: String) async throws -> String? func toolDefinitions() async throws -> [ToolDefinition] /// One page of `table`, narrowed to `project` and `query` when given, and /// to the records whose columns hold every value in `where` (column key → /// value; empty narrows nothing) — a conversation's messages by its id. func list(table: String, project: String?, query: String?, page: Int, where: [String: RecordValue]) async throws -> RecordPage /// The same read, asking for at most `limit` records on the page — a /// capped section's few, a count's one. A store with a page size of its /// own answers its own page (the default below); `total` still counts /// the whole. func list( table: String, project: String?, query: String?, page: Int, where: [String: RecordValue], limit: Int ) async throws -> RecordPage /// The same read kept to a Home `list` part's rows (`BoardRowKeep`): its /// `where`, and its `period` by the table's own date. A store that keeps /// no period refuses one by name (the default below), never answering /// the whole table as if it were the part. func list(table: String, project: String?, page: Int, keep: BoardRowKeep, limit: Int) async throws -> RecordPage /// The same read as one section of the reader's day plan (`PlanView`): /// the core cuts a calendar into what is coming and what is earlier. A /// store that plans nothing answers the plain page (the default below). func list( table: String, project: String?, query: String?, page: Int, where: [String: RecordValue], limit: Int?, plan: PlanView ) async throws -> RecordPage /// The same read as a tool's view reads it (`view`: `/`): the /// core lists the table in the view's own order with its own slip /// (`ToolView::over`), one section of the day plan when `plan` names one. /// A store that keeps no views answers the read without it (the default /// below). func list( table: String, project: String?, query: String?, page: Int, where: [String: RecordValue], limit: Int?, plan: PlanView?, view: String ) async throws -> RecordPage /// Only the records put away (S7), newest put away first, narrowed as /// any read. A store that keeps the archived in its ordinary pages (the /// fixtures) answers the plain page and the list keeps what is archived. func listArchived( table: String, project: String?, query: String?, page: Int, where: [String: RecordValue] ) async throws -> RecordPage /// How many records that archived read holds — the list's "Archived · /// n" link; nil from a store that does not say. func archivedCount(table: String, project: String?, query: String?, where: [String: RecordValue]) async throws -> Int? /// The figures `table`'s tile asks for (`TileLayout.summary`), computed /// by the core over every live record; empty when the tile asks for none. func summarize(table: String) async throws -> [SummaryFigure] /// The points of `table`'s sparkline face (`TileLayout.sparkline`), worked /// out by the core; nil when the tile draws none. func sparkline(table: String) async throws -> SparklineLine? /// The series of `table`'s chart face (`TileLayout.chart`), else of its /// chart view, worked out by the core over the window ending /// with `today`'s period; nil when the table draws no chart. func chart(table: String, today: String, at: String) async throws -> ChartSeries? /// Resolves all targets of one surface page in one batch. func linkTitles(for links: [RecordLink]) async throws -> LinkTitles func get(table: String, id: String) async throws -> TableRecord? func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord func delete(table: String, id: String) async throws -> ChangeRecord /// The same writes to a record that repeats, saying how far they reach /// (`WriteScope`). A store that cannot carry the reach refuses rather /// than write the whole series silently (the default below). func update(table: String, id: String, patch: [String: RecordValue], scope: WriteScope?) async throws -> ChangeRecord func delete(table: String, id: String, scope: WriteScope?) async throws -> ChangeRecord /// Writes `ids` as the table's order, first to last; records `ids` does /// not name keep their order after them. func reorder(table: String, ids: [String]) async throws -> ChangeRecord func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord func undo(change: String) async throws -> ChangeRecord } extension Records { /// A store with no core behind it has no figures to answer. public func summarize(table: String) async throws -> [SummaryFigure] { [] } public func sparkline(table: String) async throws -> SparklineLine? { nil } public func chart(table: String, today: String, at: String) async throws -> ChartSeries? { nil } public func toolDefinitions() async throws -> [ToolDefinition] { [] } /// Stores without a dedicated batch read scan each target table once, /// page by page; they never issue a get for each row. public func linkTitles(for links: [RecordLink]) async throws -> LinkTitles { guard !links.isEmpty else { return LinkTitles() } let definitions = try await tableDefinitions() var titles: [String: String] = [:] var pictures: [String: String] = [:] for table in Set(links.map(\.table)) { guard let definition = definitions.first(where: { $0.id == table }) else { continue } let ids = Set(links.filter { $0.table == table }.map(\.id)) var next: Int? = 0 while let page = next { let rows = try await list(table: table, project: nil, query: nil, page: page) for row in rows.records where ids.contains(row.id) { titles[row.id] = row.said?.slip.name ?? row[definition.title].text pictures[row.id] = LinkTitles.picture(of: row, in: definition) } next = ids.allSatisfy { titles[$0] != nil } ? nil : rows.next } } return LinkTitles(titles, pictures: pictures) } public func list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int ) async throws -> RecordPage { try await list(table: table, project: project, query: query, page: page, where: filter) } public func listArchived( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue] ) async throws -> RecordPage { try await list(table: table, project: project, query: query, page: page, where: filter) } public func archivedCount( table: String, project: String?, query: String?, where filter: [String: RecordValue] ) async throws -> Int? { nil } /// The same read as one section of the reader's day plan. A store that /// plans nothing (the fixtures) answers the plain page and no sections. public func list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int?, plan: PlanView ) async throws -> RecordPage { if let limit { return try await list(table: table, project: project, query: query, page: page, where: filter, limit: limit) } return try await list(table: table, project: project, query: query, page: page, where: filter) } /// A tool view's read, from a store that keeps no views: the read itself. public func list( table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue], limit: Int?, plan: PlanView?, view: String ) async throws -> RecordPage { if let plan { return try await list(table: table, project: project, query: query, page: page, where: filter, limit: limit, plan: plan) } if let limit { return try await list(table: table, project: project, query: query, page: page, where: filter, limit: limit) } return try await list(table: table, project: project, query: query, page: page, where: filter) } /// How many records a narrowed read holds, from the store's `total` on a /// page of one. Nil from a store that answers no total. public func total(table: String, query: String? = nil, where filter: [String: RecordValue]) async throws -> Int? { try await list(table: table, project: nil, query: query, page: 0, where: filter, limit: 1).total } /// One page of the whole table, narrowed only by project and search. public func list(table: String, project: String?, query: String?, page: Int) async throws -> RecordPage { try await list(table: table, project: project, query: query, page: page, where: [:]) } public func list(table: String, project: String?, page: Int, keep: BoardRowKeep, limit: Int) async throws -> RecordPage { guard keep.period == nil else { throw RecordsPeriodUnread(table: table) } return try await list(table: table, project: project, query: nil, page: page, where: keep.filter, limit: limit) } } extension Records { public func update(table: String, id: String, patch: [String: RecordValue], scope: WriteScope?) async throws -> ChangeRecord { guard scope == nil else { throw ScopeNotCarried() } return try await update(table: table, id: id, patch: patch) } public func delete(table: String, id: String, scope: WriteScope?) async throws -> ChangeRecord { guard scope == nil else { throw ScopeNotCarried() } return try await delete(table: table, id: id) } } /// A store that keeps no period was asked for a list kept to one. struct RecordsPeriodUnread: Error, Equatable { public let table: String } public enum RecordsError: Error, Equatable { case unknownTable(String) case unknownRecord(String) case unknownChange(String) case noOrderColumn(String) } extension Records { public func lastChanged(table: String) async throws -> String? { nil } } /// What `create` answers when the store needs one more value before it can /// make the record: its question, the column the answer goes in, and the /// answers it offers (each a value to write and its words). Nothing was made. /// The words are the store's, never composed here; `table` and `data` are the /// create it was asked about, so an answer re-sends that same create with /// `data[column]` set (`answered`). public struct CreateQuestion: Error, Hashable, Sendable, Decodable { public struct Option: Hashable, Sendable, Decodable, Identifiable { public var id: String public var label: String public init(id: String, label: String) { self.id = id self.label = label } } public var question: String public var column: String public var options: [Option] /// The table the create was for. public var table: String = "" /// The values the create was sent with. public var data: [String: RecordValue] = [:] /// The words the create was made from, when it came from the one input. public var words: String = "" /// A create command opens its resulting record after the question is answered. public var openCreated = false public init(question: String, column: String, options: [Option], table: String = "", data: [String: RecordValue] = [:]) { self.question = question self.column = column self.options = options self.table = table self.data = data } enum CodingKeys: String, CodingKey { case question, column, options, table, data } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) question = try c.decode(String.self, forKey: .question) column = try c.decode(String.self, forKey: .column) options = try c.decodeIfPresent([Option].self, forKey: .options) ?? [] table = try c.decodeIfPresent(String.self, forKey: .table) ?? "" data = try c.decodeIfPresent([String: RecordValue].self, forKey: .data) ?? [:] } /// The same create's values with `option` written into the asked column. public func answered(_ option: Option) -> [String: RecordValue] { var values = data values[column] = .text(option.id) return values } }