//! A list read as a day plan, on the READER's day: the one place a list of //! work still to do (`upcoming`: Todos) and a list split into days //! (`day_grouping`: the Calendar) are cut into the sections the screen draws, //! counted over the WHOLE table and paged one section at a time. //! //! Todos: today; late (owed from a day gone, newest first); each of the next //! seven days; later; undated; then the group's closed sections (done, //! dropped). The Calendar: what is coming (today and after, soonest first) and //! what is earlier (newest first). A repeating event is one row stored at its //! first start; the Calendar files it at its NEXT occurrence from today (and //! the read answers that occurrence's times), and every LATER occurrence of //! the year ahead stands as a row of its own (`@`, opening the //! series at that time), so a weekly swim stands under each day it happens, //! never once and never under the day it began. //! //! A record's day is the one the app draws (`UpcomingKeys.swift` //! `upcomingAt`): the LATEST of the `upcoming` dates, a later date (a snooze) //! counting only while it ends today or after. Every instant is read as the //! reader's wall clock (`timezone`, else the workspace's zone, else UTC) and //! judged against the reader's day (`today`, else the day in that zone) — never //! the workspace's, so a phone in Auckland and one in Los Angeles each see //! their own late. A day with no hour is stored as the workspace's midnight //! and read back as the bare day (`builtin::todo_extras`); here it is that day //! on the reader's calendar too. //! //! Every fragment is composed from column names the table stores (checked as //! plain identifiers), days and offsets this file computed, and choice values //! a definition names (quoted, `'` doubled) — `Filter::Composed`'s contract. use std::collections::HashMap; use chrono::{Duration, NaiveDate}; use cotton_core::definitions::TableDefinition; use cotton_core::transforms::zoned_clock::zone_offset_ms; use serde_json::{json, Map, Value}; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{ is_known_zone, optional_string, start_of_day_in, today_in, workspace_timezone_or_null, Valid, }; use crate::mcp::handlers::records_1::events::occurrences_from; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::{Filter, Order, Query}; /// How many days after today stand under their own heading. pub const DAYS_AHEAD: usize = 7; /// What a read asks of the plan: the reader's day and zone, and one section. #[derive(Debug, Clone, Default)] pub struct View { pub today: Option, pub from: Option, pub to: Option, pub timezone: Option, pub section: Option, pub day: Option, /// A light read's columns (`columns`): only these and the id are read, /// for a reader that cuts a whole list by them. pub columns: Option>, /// A narrow cut read (`cut`): beside `columns`, the rows are answered as /// `[id, …columns]` arrays, the store's values alone and no count. pub cut: bool, /// The list's own read narrowed to these ids (`among`): its filters and /// its order kept, so a reader that kept a whole list's cut reads only /// the rows a write named, and asks where they fall among the rest. pub among: Option>, /// Each row's section alone (`sectioned`): `[id, key]` for every row of /// the whole narrowed table, in one walk, and the plan's keys in the /// order drawn — what a reader keeps a plan's sections by, and patches /// for the rows a write names (a plan of work still to do alone). pub sectioned: bool, } impl View { pub fn of(args: &Map) -> View { View { today: optional_string(args, "today"), from: optional_string(args,"from"), to: optional_string(args,"to"), timezone: optional_string(args, "timezone"), section: optional_string(args, "section"), day: optional_string(args, "day"), columns: args.get("columns").and_then(Value::as_array).map(|columns| columns.iter().filter_map(|column| column.as_str().map(str::to_string)).collect()), cut: args.get("cut") == Some(&Value::Bool(true)), among: args.get("among").and_then(Value::as_array).map(|ids| ids.iter().filter_map(|id| id.as_str().map(str::to_string)).collect()), sectioned: args.get("sectioned") == Some(&Value::Bool(true)), } } } /// Which way a list is planned. #[derive(Debug, Clone)] enum Kind { /// Work still to do: today, late, the days ahead, later, undated, and the /// group's closed sections as `(key, values)`. Upcoming { status: Option, closed: Vec<(String, Vec)> }, /// A list split into days: coming (today and after), earlier. FromToday, } /// One table's plan on one reader's day. #[derive(Debug, Clone)] pub struct Plan { kind: Kind, /// Today, then each day after it, `DAYS_AHEAD + 1` of them: YYYY-MM-DD. days: Vec, /// The record's day as the reader's wall clock, `YYYY-MM-DDTHH:MM:SS.SSS`, /// or NULL for a record with none. effective: String, /// The section key of a row (`today`, `late`, `day:YYYY-MM-DD`, …). section_sql: String, created: bool, updated: bool, completed: bool, /// The section asked for, checked. section: Option, /// A view spanning existing sections, applied before the read counts. selection: Option, /// A repeating event's next occurrence from today, by the master's id: /// `(starts_at, ends_at)`, the times the read answers for it. occurrences: HashMap)>, /// Every later occurrence of a repeating event in the year ahead, soonest /// first: `(master id, starts_at, ends_at)` — rows the read adds to what /// is coming. later: Vec<(String, String, Option)>, /// The reader's offset from UTC, minutes. reader_minutes: i64, /// The workspace's offset from UTC, minutes, where it has a zone: an /// instant at its midnight is a bare day (`local`). workspace_minutes: Option, /// The one date a list split into days is filed by (`day_grouping`). column: String, /// The start of the reader's day as a stored instant, UTC /// (`YYYY-MM-DDTHH:MM:SS.SSSZ`): today's midnight on the reader's clock. day_starts: String, /// The section a whole read leads with, in its own order, ahead of the /// rest in theirs (`ListUpcoming::lead`). lead: Option, } fn identifier(column: &str) -> bool { !column.is_empty() && column.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') } fn literal(value: &str) -> String { format!("'{}'", value.replace('\'', "''")) } /// One stored date column as the reader's wall clock: a bare day is that /// day's midnight; the workspace's midnight (a due with no hour) is its day's /// midnight; any other instant is shifted by the reader's offset. fn local(column: &str, reader_minutes: i64, workspace_minutes: Option) -> String { let at_midnight = workspace_minutes.map_or_else(String::new, |w| { format!( "WHEN strftime('%H:%M:%f', {column}, '{w:+} minutes') = '00:00:00.000' \ THEN strftime('%Y-%m-%d', {column}, '{w:+} minutes') || 'T00:00:00.000' " ) }); format!( "(CASE WHEN {column} IS NULL OR {column} = '' THEN NULL \ WHEN length({column}) = 10 THEN {column} || 'T00:00:00.000' \ {at_midnight}ELSE strftime('%Y-%m-%dT%H:%M:%f', {column}, '{reader_minutes:+} minutes') END)" ) } impl Plan { /// The plan for a list of `definition` whose table stores `columns`, or /// `None` for a list that is not planned (no `upcoming`, no day split, or /// a date the table does not store) — and then a `section` is refused. pub fn of( ctx: &Ctx<'_>, definition: &TableDefinition, columns: &[&str], view: &View, ) -> Valid> { let stored = |key: &str| identifier(key) && columns.contains(&key); let (kind, dates) = if let Some(upcoming) = &definition.upcoming { let mut dates: Vec = upcoming.dates.clone().unwrap_or_default(); if dates.is_empty() { dates.extend(definition.date.clone()); } let status = definition.group.as_ref().map(|group| group.column.clone()).filter(|c| stored(c)); let closed = match (&status, definition.group.as_ref().and_then(|g| g.sections.as_ref())) { (Some(_), Some(sections)) => sections .iter() .skip(1) .filter_map(|section| Some((section.values.first()?.to_lowercase(), section.values.clone()))) .collect(), _ => Vec::new(), }; (Kind::Upcoming { status, closed }, dates) } else if let (Some(day), Some(_)) = (&definition.day_grouping, &definition.date) { (Kind::FromToday, vec![day.clone()]) } else { (Kind::Upcoming { status: None, closed: Vec::new() }, Vec::new()) }; if dates.is_empty() || !dates.iter().all(|date| stored(date)) { if view.section.is_some() { return Err(ToolFailure::new(format!( "{} is not read in sections; ask without section", definition.plural ))); } return Ok(None); } // The reader's zone and day. let workspace = workspace_timezone_or_null(ctx)?; let zone = match &view.timezone { Some(zone) if is_known_zone(zone) => zone.clone(), Some(zone) => return Err(ToolFailure::new(format!("timezone {zone:?} is not a known IANA zone"))), None => workspace.clone().unwrap_or_else(|| "UTC".to_string()), }; let now = ctx.now.timestamp_millis(); let today = match &view.today { Some(day) => day.clone(), None => today_in(&zone, now)?, }; let first = NaiveDate::parse_from_str(&today, "%Y-%m-%d") .map_err(|_| ToolFailure::new(format!("today is a day, YYYY-MM-DD; got {today:?}")))?; let days: Vec = (0..=DAYS_AHEAD as i64) .map(|n| (first + Duration::days(n)).format("%Y-%m-%d").to_string()) .collect(); let minutes = |zone: &str| zone_offset_ms(now, zone).map(|ms| ms / 60_000).ok(); let reader_minutes = minutes(&zone).unwrap_or(0); let workspace_minutes = workspace.as_deref().and_then(minutes); // The record's day: the first date, carried later by any other that // ends today or after. let t0 = literal(&days[0]); let mut effective = local(&dates[0], reader_minutes, workspace_minutes); for date in &dates[1..] { let later = local(date, reader_minutes, workspace_minutes); effective = format!( "(CASE WHEN {later} >= {t0} AND ({effective} IS NULL OR {later} > {effective}) \ THEN {later} ELSE {effective} END)" ); } // A repeating event: its next occurrence from the start of the // reader's day, read through the same wall clock as any start. let mut occurrences = HashMap::new(); let mut later = Vec::new(); if matches!(kind, Kind::FromToday) && definition.id == "event" && definition.has_engine() { for (id, starts, ends) in occurrences_from(ctx, start_of_day_in(&today, &zone)?)? { if occurrences.contains_key(&id) { later.push((id, starts, ends)); } else { occurrences.insert(id, (starts, ends)); } } } if !occurrences.is_empty() && identifier(&dates[0]) { let mut ids: Vec<&String> = occurrences.keys().collect(); ids.sort(); let whens: String = ids .into_iter() .map(|id| { let at = local(&literal(&occurrences[id].0), reader_minutes, workspace_minutes); format!("WHEN {} THEN {at} ", literal(id)) }) .collect(); effective = format!("(CASE id {whens}ELSE {effective} END)"); } let e = &effective; let section_sql = match &kind { Kind::Upcoming { status, closed } => { let mut whens = String::new(); if let Some(status) = status { for (key, values) in closed { let values = values.iter().map(|v| literal(v)).collect::>().join(", "); whens.push_str(&format!("WHEN {status} IN ({values}) THEN {} ", literal(key))); } } let t1 = literal(&days[1]); let after = literal(&(first + Duration::days(DAYS_AHEAD as i64 + 1)).format("%Y-%m-%d").to_string()); format!( "CASE {whens}WHEN {e} IS NULL THEN 'undated' WHEN {e} < {t0} THEN 'late' \ WHEN {e} < {t1} THEN 'today' WHEN {e} < {after} THEN 'day:' || substr({e}, 1, 10) \ ELSE 'later' END" ) } Kind::FromToday => { format!("CASE WHEN {e} IS NULL THEN 'undated' WHEN {e} < {t0} THEN 'earlier' ELSE 'coming' END") } }; let mut plan = Plan { kind, days, effective, section_sql, created: columns.contains(&"created_at"), updated: columns.contains(&"updated_at"), completed: columns.contains(&"completed_at"), section: None, selection: None, occurrences, later, reader_minutes, workspace_minutes, column: dates[0].clone(), day_starts: (first.and_hms_opt(0, 0, 0).expect("midnight") - Duration::minutes(reader_minutes)) .format("%Y-%m-%dT%H:%M:%S%.3fZ") .to_string(), lead: definition.upcoming.as_ref().and_then(|upcoming| upcoming.lead.clone()), }; let special = match (&plan.kind, view.section.as_deref()) { (Kind::Upcoming { .. }, Some("upcoming")) => Some(format!("(({}) LIKE 'day:%' OR ({}) = 'later')", plan.section_sql, plan.section_sql)), (Kind::FromToday, Some("today")) if definition.rows_table() != "call" => Some(format!("{} >= {} AND {} < {}", plan.effective, literal(&plan.days[0]), plan.effective, literal(&plan.days[1]))), (Kind::FromToday, Some("upcoming")) if definition.rows_table() != "call" => Some(format!("{} >= {}", plan.effective, literal(&plan.days[1]))), _ => None, }; if let Some(selection) = special { if view.day.is_some() { return Err(ToolFailure::new("day goes only with section day")); } plan.selection = Some(selection); let first = plan.days[0].clone(); let next = plan.days[1].clone(); // Later occurrences use the same wall clock, including all-day values, as the list. plan.later = plan.later.iter().filter(|(_, starts, _)| { plan.wall_clock(starts).is_some_and(|at| { let day = &at[..10]; if view.section.as_deref() == Some("today") { day == first } else { day >= next.as_str() } }) }).cloned().collect(); return Ok(Some(plan)); } plan.section = match &view.section { None => None, Some(section) => Some(plan.section_key(definition, section, view.day.as_deref())?), }; Ok(Some(plan)) } /// Every key a section of this plan may have, in the order drawn — the /// days ahead by date. pub fn keys(&self) -> Vec { match &self.kind { Kind::Upcoming { closed, .. } => { let mut keys = vec!["today".to_string(), "late".to_string()]; keys.extend(self.days[1..].iter().map(|day| format!("day:{day}"))); keys.extend(["later".to_string(), "undated".to_string()]); keys.extend(closed.iter().map(|(key, _)| key.clone())); keys } Kind::FromToday => vec!["coming".into(), "earlier".into(), "undated".into()], } } fn section_key(&self, definition: &TableDefinition, section: &str, day: Option<&str>) -> Valid { let key = match (section, day) { ("day", Some(day)) => format!("day:{day}"), ("day", None) => return Err(ToolFailure::new("section \"day\" needs day, YYYY-MM-DD")), (_, Some(_)) => return Err(ToolFailure::new("day goes only with section \"day\"")), (other, None) => other.to_string(), }; if self.keys().contains(&key) { return Ok(key); } let named: Vec = self .keys() .into_iter() .map(|key| if key.starts_with("day:") { "day".to_string() } else { key }) .fold(Vec::new(), |mut out, key| { if !out.contains(&key) { out.push(key); } out }); Err(ToolFailure::new(if section == "day" { format!("day is one of the next {DAYS_AHEAD} days after today ({} to {})", self.days[1], self.days[DAYS_AHEAD]) } else { format!("{} are read in the sections {}; got {section:?}", definition.plural, named.join(", ")) })) } /// A repeating event's next occurrence, `(starts_at, ends_at)`, when the /// row `id` is one — the times the list answers so its slip stands on /// the day it next happens. pub fn occurrence(&self, id: &str) -> Option<&(String, Option)> { self.occurrences.get(id) } /// The later occurrences this read adds — every one when it reads what is /// coming (the default read, or the `coming` section), none otherwise. pub fn later(&self) -> &[(String, String, Option)] { match self.section.as_deref() { None | Some("coming") => &self.later, Some(_) => &[], } } /// Keeps only the later occurrences of masters `keep` says this read lists. pub fn keep_later(&mut self, keep: impl Fn(&str) -> bool) { self.later.retain(|(id, _, _)| keep(id)); } /// Where a row read in this plan's order stands among the later /// occurrences: `Some(wall clock)` for a row of what is coming (its start /// as the reader's wall clock, the order `coming` reads in), `None` for a /// row past them all (earlier, undated). pub fn coming_at(&self, starts_at: Option<&str>) -> Option { let at = self.wall_clock(starts_at?)?; (at.as_str() >= self.days[0].as_str()).then_some(at) } /// An instant as the reader's wall clock, `YYYY-MM-DDTHH:MM:SS.SSS` — /// EXACTLY the SQL `local`, or a stored row and an occurrence disagree on /// their day: a bare day is its midnight, and so is the workspace's /// midnight (an all-day event stored at it; walk 1225 lost every one-off /// event to a reader in another zone when this rule was missing here). pub fn wall_clock(&self, value: &str) -> Option { if value.is_empty() { return None; } if value.len() == 10 { return Some(format!("{value}T00:00:00.000")); } let at = chrono::DateTime::parse_from_rfc3339(value).ok()?.with_timezone(&chrono::Utc); if let Some(w) = self.workspace_minutes { let there = at + Duration::minutes(w); if there.format("%H:%M:%S%.3f").to_string() == "00:00:00.000" { return Some(there.format("%Y-%m-%dT00:00:00.000").to_string()); } } Some((at + Duration::minutes(self.reader_minutes)).format("%Y-%m-%dT%H:%M:%S%.3f").to_string()) } /// The same day split for an engine view whose rows were already combined. pub fn materialized_date_section(&self, value: Option<&str>) -> Option<&'static str> { if !matches!(self.kind, Kind::FromToday) { return None; } Some(match value.and_then(|value| self.wall_clock(value)) { None => "undated", Some(value) if value.as_str() < self.days[0].as_str() => "earlier", Some(_) => "coming", }) } /// Whether every row's section is its own: a plan of work still to do, /// whose section a row's own columns, the reader's day and zone say. A /// list split into days files a repeating event by its occurrences, and /// a view spanning sections narrows by more than one key: neither. pub fn rows_own_sections(&self) -> bool { matches!(self.kind, Kind::Upcoming { .. }) && self.selection.is_none() && self.occurrences.is_empty() && self.later.is_empty() } /// Each row of `query` (narrowed, unordered) with its section's key, in /// one walk: `[[id, key], …]`, a row in no section (never written by /// Cotton) left out. pub fn sectioned(&self, ctx: &Ctx<'_>, query: &Query) -> Valid> { let mut whole = query.clone(); whole.order.clear(); whole.limit = None; whole.offset = None; let keyed = ctx.read.keyed_by(&whole, &self.section_sql).map_err(|error| ToolFailure::new(error.to_string()))?; Ok(keyed.into_iter().filter_map(|(id, key)| Some(json!([id, key?]))).collect()) } pub fn requested_section(&self) -> Option<&str> { self.section.as_deref() } /// Apply a view's date range before counting, paging or adding occurrences. pub fn select(&self, query: Query) -> Query { match &self.selection { Some(selection) => query.filter(Filter::Composed(selection.clone())), None => query, } } /// The query narrowed to the section asked for, if any. pub fn narrow(&self, query: Query) -> Query { match &self.section { Some(section) => query.filter(Filter::Composed(format!("({}) = {}", self.section_sql, literal(section)))), None => query, } } /// The query in the plan's order: one section's own, or — the default /// read — the whole list so its first page holds what the screen opens on. /// /// Todos, by default: today soonest first; then every day ahead soonest /// first (the next seven, then later); then the undated, newest made /// first; then the late, newest first; then done, newest completed first; /// then dropped, newest changed first. A list that leads with a section /// (`lead`: the All deck's late) reads that section first, in its own /// order, then the rest as above. The Calendar: today and after soonest /// first, then the past newest first. pub fn order(&self, query: Query) -> Query { let e = &self.effective; let jd = |expr: &str| format!("julianday({expr})"); // Newest first as an ascending number: julianday stays under 5e6. let newest = |expr: &str| format!("(5000000 - julianday({expr}))"); let created = if self.created { newest("created_at") } else { "0".into() }; let updated = if self.updated { newest("updated_at") } else { "0".into() }; let completed = match (self.completed, self.updated) { (true, true) => newest("COALESCE(completed_at, updated_at)"), (true, false) => newest("completed_at"), _ => updated.clone(), }; let by_section = |key: &str| -> String { match key { "late" | "earlier" => newest(e), "undated" => created.clone(), "today" | "later" | "coming" => jd(e), key if key.starts_with("day:") => jd(e), key => match &self.kind { Kind::Upcoming { closed, .. } if closed.first().is_some_and(|(first, _)| first == key) => { completed.clone() } _ => updated.clone(), }, } }; if let Some(key) = &self.section { return query.order_by(&by_section(key), Order::Composed); } let section_of = &self.section_sql; let expr = match &self.kind { Kind::Upcoming { closed, .. } => { // Rank × 1e7 plus the section's own number. let mut whens = format!( "WHEN 'today' THEN {} WHEN 'later' THEN 10000000 + {} WHEN 'undated' THEN 20000000 + {created} \ WHEN 'late' THEN 30000000 + {} ", jd(e), jd(e), newest(e) ); for (n, (key, _)) in closed.iter().enumerate() { whens.push_str(&format!("WHEN {} THEN {} + {} ", literal(key), 40000000 + n * 10000000, by_section(key))); } // Every `day:` key: the days ahead, beside later. let rest = format!("CASE ({section_of}) {whens}ELSE 10000000 + {} END", jd(e)); // The lead under every rank (each stays under 1e8). match &self.lead { Some(lead) => format!( "CASE WHEN ({section_of}) = {} THEN {} ELSE 100000000 + {rest} END", literal(lead), by_section(lead) ), None => rest, } } Kind::FromToday => format!( "CASE ({section_of}) WHEN 'coming' THEN {} WHEN 'earlier' THEN 10000000 + {} ELSE 20000000 + {created} END", jd(e), newest(e) ), }; query.order_by(&expr, Order::Composed) } /// How many rows of the whole narrowed table stand in each section, by /// its key — ONE walk of the table, which the read's `sections` and its /// `total` both answer from ([`Plan::sections_of`], [`Plan::total_of`]). pub fn counted(&self, ctx: &Ctx<'_>, query: &Query) -> Valid { let mut whole = query.clone(); whole.order.clear(); whole.limit = None; whole.offset = None; let counted = ctx .read .count_by(&whole, &self.section_sql) .map_err(|error| ToolFailure::new(error.to_string()))?; Ok(Counted(counted.into_iter().filter_map(|(key, n)| Some((key?, n))).collect())) } /// The `sections` a read answers: `[{key, count}]` (a day ahead also /// `day`), every count over the whole narrowed table, in the order drawn; /// a section with nothing in it is left out. pub fn sections_of(&self, counted: &Counted) -> Vec { self.keys() .into_iter() .filter_map(|key| { let mut count = counted.of(&key); if key == "coming" { count += self.later.len() as i64; } if count == 0 { return None; } Some(match key.strip_prefix("day:") { Some(day) => json!({ "key": "day", "day": day, "count": count }), None => json!({ "key": key, "count": count }), }) }) .collect() } /// How many stored rows the read answers: the section asked for, or every /// section — what a count of the narrowed query says, without a second /// walk of the table: every row stands in exactly one section. pub fn total_of(&self, counted: &Counted) -> i64 { match &self.section { Some(key) => counted.of(key), None => counted.0.iter().map(|(_, n)| n).sum(), } } /// A list split into days whose page is read off its date's index: one /// stored date (no repeating event's occurrence filed elsewhere), read /// whole or by `coming` or `earlier`. Its rows are read a section at a /// time in the date's own order — what is coming soonest first, what is /// earlier newest first, the undated newest made first — each narrowed to /// a RANGE of the date the index answers, so the first page reads the /// rows on it and never sorts the whole table by a worked-out key (295 F /// row 81, walker294: Meetings drew blank for ~20 s on a copy of 1.8 M /// records — every read walked every meeting three times, reading each /// row whole, and sorted them all over a key per row). pub fn indexed(&self) -> bool { matches!(self.kind, Kind::FromToday) && self.selection.is_none() && self.occurrences.is_empty() && self.later.is_empty() && identifier(&self.column) && matches!(self.section.as_deref(), None | Some("coming") | Some("earlier")) } /// The rows `[offset, offset + limit)` of an [`Plan::indexed`] read of /// `query` (narrowed, unordered) whose sections were `counted`: each /// section read in turn, the ones the offset passes whole skipped — in /// EXACTLY the order [`Plan::order`] reads the whole table in, because /// each section's rows are sorted by that same order, over a window of /// the stored date the index reads. /// /// Two ranges of the stored date bound a section's read, both wide /// enough never to leave out a row the order would put on the page: /// /// - Where the section lies. A row's day is its stored date as the /// reader's wall clock (`local`), which a bare day, the workspace's /// midnight, an offset written into the text or the reader's own /// offset each move by less than a day from what the text says — so a /// coming row's stored text is no earlier than two days before the /// reader's day starts, an earlier row's no later than two days after. /// - How far the page reaches. The stored text sorts by its date /// (`YYYY-MM-DD` leads it), and a row's wall clock is within three days /// of that date. So with `r` the date of the `offset + limit`-th row by /// the stored text, every row stored a week past `r` is later by the /// wall clock than all of the rows up to `r`, of which there are /// already enough to fill the page: it cannot be on the page, and the /// window stops there (a week before `r`, for what is earlier). /// /// Within the window the rows are ordered as the whole read orders them /// — the wall clock, then the id — so a bare day, a zone written into the /// text or a tie stands where it always stood. A stored date the store /// cannot read as one (never written by Cotton) leaves the window open: /// the section is read whole, as before. pub fn indexed_page( &self, ctx: &Ctx<'_>, query: &Query, counted: &Counted, offset: i64, limit: i64, ) -> Valid>> { let column = self.column.as_str(); let failed = |error: cotton_store::StoreError| ToolFailure::new(error.to_string()); let starts = chrono::DateTime::parse_from_rfc3339(&self.day_starts) .map_err(|error| ToolFailure::new(error.to_string()))?; let at = |days: i64| literal(&(starts + Duration::days(days)).format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()); let sections: Vec<&str> = match self.section.as_deref() { Some(key) => vec![key], None => vec!["coming", "earlier", "undated"], }; let mut skip = offset.max(0); let mut wanted = limit.max(0); let mut found = Vec::new(); for section in sections { let held = counted.of(section); if wanted == 0 || held == 0 { continue; } if skip >= held { skip -= held; continue; } let read = query.clone().filter(Filter::Composed(format!("({}) = {}", self.section_sql, literal(section)))); let read = match section { "coming" | "earlier" => { let soonest = section == "coming"; let read = read.filter(Filter::Composed(if soonest { format!("{column} >= {}", at(-2)) } else { format!("{column} < {}", at(2)) })); // The stored text of the row the page reaches, by the index. let reach = read .clone() .columns(&[column]) .order_by(column, if soonest { Order::Asc } else { Order::Desc }) .limit(1) .offset(skip + wanted - 1); let reached = ctx.read.select(&reach).map_err(failed)?.into_iter().next().and_then(|row| { let text = row.get(column)?.as_str()?.get(..10)?.to_string(); NaiveDate::parse_from_str(&text, "%Y-%m-%d").ok() }); match reached { Some(day) if soonest => read.filter(Filter::Composed(format!( "{column} < {}", literal(&(day + Duration::days(7)).format("%Y-%m-%d").to_string()) ))), Some(day) => read.filter(Filter::Composed(format!( "{column} >= {}", literal(&(day - Duration::days(7)).format("%Y-%m-%d").to_string()) ))), // Fewer rows than the page reaches: every one is read. None => read, } } _ => read, }; let rows = ctx .read .select(&self.order(read).order_by("id", Order::Asc).limit(wanted).offset(skip)) .map_err(failed)?; wanted -= rows.len() as i64; skip = 0; found.extend(rows); } Ok(found) } } /// How many rows stand in each section of a plan, by key. #[derive(Debug, Clone, Default)] pub struct Counted(Vec<(String, i64)>); impl Counted { fn of(&self, key: &str) -> i64 { self.0.iter().find(|(k, _)| k == key).map_or(0, |(_, n)| *n) } }