//! The read half a tool handler works through — a thin typed query layer over //! the store's driver. //! //! The TypeScript reached the file through `pgrest`, a query builder that //! spoke PostgREST's dialect to a SQLite file because the server used to be an //! edge function in front of Postgres. That layer is DROPPED (design S2): //! handlers speak SQL through the driver. What they should NOT each rewrite is //! the part that is the same every time — the workspace scope, the parameter //! binding, and turning a row back into the JSON shapes the codecs say it is. //! //! DELIBERATELY SMALL. It is the floor the handler groups (2c, 2d) grow: a //! `select` with filters, an order and a limit, and `one` for a row by id. //! Anything a handler needs beyond it — a join, an FTS query, an aggregate — //! is written as SQL in that handler, because a query builder that grows to //! cover those is the layer this one replaced. use cotton_store::driver::Driver; use cotton_store::schema::codecs::decode_value; use cotton_store::schema::specs::spec_for; use cotton_store::soft_refs; use cotton_store::{Result, StoreError}; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; /// One condition on a column. #[derive(Debug, Clone, PartialEq)] pub enum Filter { Eq(String, SqlValue), Ne(String, SqlValue), Lt(String, SqlValue), Lte(String, SqlValue), Gt(String, SqlValue), Gte(String, SqlValue), /// `IN (…)`. An EMPTY list matches nothing, which is what an empty `IN` /// means — never "everything", which is the direction that leaks rows. In(String, Vec), /// `NOT IN (…)`. An EMPTY list excludes NOTHING, which is what an empty /// `NOT IN` means — the mirror of the rule above, and the reason both are /// spelled out rather than left to SQL's own handling of an empty list. NotIn(String, Vec), /// Membership in a workspace-scoped, single-column query. Null members /// are excluded so the inverse also returns rows with no related evidence. /// The member query is a set: pagination and ordering are refused. InQuery { column: String, query: Box, negate: bool }, Like(String, String), /// `LIKE` any ONE of these patterns — an `OR` over a single column. /// /// A variant rather than several [`Filter::Like`]s for the reason /// [`Filter::KeysetBefore`] is one: filters are `AND`ed, and "any of" /// cannot be said that way. An EMPTY list matches NOTHING, the same rule as /// an empty [`Filter::In`] and for the same reason — "everything" is the /// direction that leaks rows. /// /// The caller supplies whole patterns, `Like`'s own contract: `%` and `_` /// in a value are wildcards, so a caller passing something a person typed /// escapes it or validates it first. LikeAny(String, Vec), IsNull(String), NotNull(String), /// The column holds nothing: null, or the empty text. Blank(String), /// The column holds something: neither null nor the empty text. NotBlank(String), /// Any ONE of these columns holds this text, in any case — an `OR` over /// several columns, for a search that reads a picture's caption and its /// description alike. The text is bound, never a pattern: `%` and `_` are /// letters here. An EMPTY column list matches nothing, the rule every /// "any of" keeps. ContainsAny(Vec, String), /// A descending KEYSET cursor over two columns: strictly before `value` on /// the first, or equal on it and strictly before `tie` on the second. /// /// The reason it is a variant rather than two filters: two filters are /// `AND`ed, and this condition is an `OR` — which is the whole point. A /// cursor on an instant alone drops every row that shares the boundary /// instant with the row the page stopped on, for ever, and "rarely" is the /// wrong standard for a page whose promise is that a conversation reads to /// its beginning. `crates/cotton-ffi/src/phone/traffic.rs` is the same /// rule on the other side, and `crates/cotton-ffi/src/browse/cursor.rs` is /// its generic form. /// /// Both columns are checked against the table's spec, like every other /// column here. KeysetBefore { column: String, value: SqlValue, tie_column: String, tie: SqlValue, }, /// The ASCENDING mirror of [`Filter::KeysetBefore`]: strictly after `value` /// on the first column, or equal on it and strictly after `tie` on the /// second. /// /// A list read OLDEST first — `list_todos`, which reads what is owed next — /// pages forwards, and a descending cursor cannot say that. Same contract /// otherwise: one variant because the condition is an `OR`, and both /// columns are checked against the table's spec. KeysetAfter { column: String, value: SqlValue, tie_column: String, tie: SqlValue, }, /// A condition written in the CODE, verbatim — for the one rule a column /// filter cannot say, such as a message hidden by its thread's /// `cleared_before`. `&'static str` on purpose: a fragment is a constant in /// the source, never text an argument could have built. Static(&'static str), /// A condition the CODE composed from parts it checked: column names the /// table spec declares, days and offsets it computed, choice values a /// definition names (quoted, `'` doubled) — the day plan's sections /// (`tables::day_plan`). Never text an argument wrote. Composed(String), /// A trusted code expression with separately bound values. ComposedBound(String, Vec), /// A SOFT column (`cotton_store::soft_refs`) names a row of its parent /// that is present — rendered through `soft_refs::soft_names`, the one /// place the rule is written. Refused on a column that is not a soft /// reference: `IsNull`/`NotNull` are for those. SoftNames(String), /// The mirror: a soft column names no present row — null, or its row is /// trashed, archived, deleted or gone (`soft_refs::soft_absent`). SoftAbsent(String), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Order { Asc, Desc, /// Soonest first with the rows that hold NO value last — the order a list /// of work still to do reads in (what is owed, then what is coming, then /// the undated). SQLite's plain `ASC` puts NULL first. AscNullsLast, /// A definition's own ascending `sort`: names read A to Z whatever their /// capitals, and the rows that hold nothing — NULL or an empty text — last. AscBlanksLast, /// The "column" is an EXPRESSION the code composed (`Filter::Composed`'s /// contract), ordered ascending as it stands — a day plan's one sort key. Composed, /// A composed expression, descending: a definition's newest-first sort /// over a computed column. ComposedDesc, } /// THE INDEX A READ BY THREAD (OR BY PERSON) GOES THROUGH. Every read here also names the /// workspace, and these tables carry an index led by `workspace_id` alone; /// with two single-term equalities and no order to steer it, SQLite took that /// one and walked every email in the file once per thread (block_sender, 11 /// Oct 2026: 194,183,597 steps in one call). A read that names a thread reads /// that thread's rows by the thread's own index. const THREAD_INDEXES: &[(&str, &str, &str)] = &[ ("cotton_emails", "thread_id", "idx_cotton_emails_thread_sent"), ("cotton_email_participants", "thread_id", "idx_cotton_email_participants_thread"), // One person's money rows: Owed's window for a write (derive, 7 Nov // 2026), which walked all 20,000 rows of a synthetic book by workspace. ("cotton_money_transactions", "counterparty_person_id", "idx_cotton_money_transactions_person"), ]; pub(crate) const EXPECTED_TRANSACTIONS: &str = "status = 'expected'"; /// A code-owned literal predicate can prove a partial index applies before /// values are bound. Home's presence probes and compiled figure queries use /// the same choice, so a competing covering index cannot turn a probe into /// a search through actual history. pub(crate) fn indexed_by_predicate(table: &str, predicate: &str) -> &'static str { match (table, predicate) { ("cotton_money_transactions", EXPECTED_TRANSACTIONS | "status = 'expected' AND trashed_at IS NULL") => " INDEXED BY idx_cotton_money_transactions_expected", _ => "", } } /// A membership projection excludes absent links. Choose its sparse index /// from typed table/column metadata, before quoting its column for SQL. fn indexed_by_membership(table: &str, column: &str) -> &'static str { match (table, column) { ("cotton_money_transactions", "settles_transaction_id") => " INDEXED BY idx_cotton_money_transactions_settles", _ => "", } } /// The money columns a filter narrows too little to beat the date's order: /// a read held only by these (and the workspace) pages off the date index. const MONEY_BROAD_COLUMNS: [&str; 6] = ["status", "direction", "currency", "moves_money", "between_us", "amount_known"]; /// A money read newest first and narrowed by nothing a sparse index holds /// (an id, a person, an account) walks the date index in its own order, /// never sorting every row to cut one page: the planner otherwise takes the /// glance index for a page of Owed and sorts the whole book per page. fn money_by_date(table: &str, query: &Query) -> bool { table == "cotton_money_transactions" && matches!(query.order.first(), Some((column, Order::Desc)) if column == "occurred_on") && money_narrowed_broadly(query) } /// A money read narrowed by nothing a sparse index holds: every equality is /// on a broad column (`MONEY_BROAD_COLUMNS`). fn money_narrowed_broadly(query: &Query) -> bool { query.filters.iter().all(|filter| match filter { Filter::Eq(column, _) | Filter::In(column, _) => MONEY_BROAD_COLUMNS.contains(&column.as_str()), Filter::InQuery { negate, .. } => *negate, _ => true, }) } /// Whether every row `query` answers has its soft `column` naming a present /// row: the where holds it so (`Filter::SoftNames`, one of the conditions /// every row meets), so the projection need not ask the parent again. fn names_present(query: &Query, column: &str) -> bool { query.filters.iter().any(|filter| matches!(filter, Filter::SoftNames(named) if named == column)) } /// How many ids a read narrowed to them looks up by the primary key. const FEW_IDS: usize = 256; /// The index that covers Owed's cut and heads: every money row naming a /// person, by its workspace, status, trash, person and day, with the columns /// the cut and the heads read beside them. pub const MONEY_OWED_INDEX: &str = "idx_cotton_money_transactions_owed"; /// A money read of every row naming a present person (`Filter::SoftNames` /// on the counterparty), not a page of them: Owed's cut, its heads and its /// count. It reads the person index that covers it, never the table; a page /// (at most `MAX_LIST` rows) still walks the date index to its place. fn money_owed_whole(table: &str, query: &Query) -> bool { table == "cotton_money_transactions" && names_present(query, "counterparty_person_id") && money_narrowed_broadly(query) && query.limit.is_none_or(|limit| limit > crate::mcp::handlers::common::MAX_LIST) } fn indexed_by(table: &str, query: &Query) -> String { for filter in &query.filters { if let Filter::Static(predicate) = filter { let index = indexed_by_predicate(table, predicate); if !index.is_empty() { return index.into(); } } } if money_owed_whole(table, query) { return format!(" INDEXED BY {MONEY_OWED_INDEX}"); } if money_by_date(table, query) { return " INDEXED BY idx_cotton_money_transactions_workspace_date".into(); } THREAD_INDEXES .iter() .find(|(name, column, _)| { *name == table && query.filters.iter().any(|filter| match filter { Filter::Eq(on, _) | Filter::In(on, _) => on == column, _ => false, }) }) .map_or_else(String::new, |(_, _, index)| format!(" INDEXED BY {index}")) } /// What to read. Built with the `Query::on(table)` chain. #[derive(Debug, Clone, PartialEq)] pub struct Query { pub table: String, /// `None` reads every column the spec declares. pub columns: Option>, pub filters: Vec, pub order: Vec<(String, Order)>, pub limit: Option, pub offset: Option, } impl Query { pub fn on(table: &str) -> Query { Query { table: table.to_string(), columns: None, filters: Vec::new(), order: Vec::new(), limit: None, offset: None, } } #[must_use] pub fn columns(mut self, columns: &[&str]) -> Query { self.columns = Some(columns.iter().map(|c| (*c).to_string()).collect()); self } #[must_use] pub fn filter(mut self, filter: Filter) -> Query { self.filters.push(filter); self } #[must_use] pub fn eq(self, column: &str, value: impl Into) -> Query { self.filter(Filter::Eq(column.to_string(), value.into())) } #[must_use] pub fn order_by(mut self, column: &str, order: Order) -> Query { self.order.push((column.to_string(), order)); self } #[must_use] pub fn limit(mut self, limit: i64) -> Query { self.limit = Some(limit); self } #[must_use] pub fn offset(mut self, offset: i64) -> Query { self.offset = Some(offset); self } } /// Reads, scoped to one workspace's file. /// /// The scope is not a filter a caller may forget: `select` adds /// `workspace_id = ?` for every table that HAS the column, from `TABLE_SPECS`, /// so a handler cannot write a query that reads across workspaces. (There is /// one file per person, so the column is belt and braces — but the belt is /// what the 2026-08-29 review was about.) pub struct ReadDb<'a> { db: &'a Driver, workspace_id: String, } impl<'a> ReadDb<'a> { pub fn new(db: &'a Driver, workspace_id: &str) -> ReadDb<'a> { ReadDb { db, workspace_id: workspace_id.to_string(), } } pub fn driver(&self) -> &'a Driver { self.db } /// The index a read is held to (`indexed_by`), else, for a read /// narrowed to a few ids (`Filter::In` on `id`, at most /// [`FEW_IDS`]), the table's own primary key: without it the planner /// takes a covering index for its equalities and walks every row to /// find a few (Owed's `among`, 452k steps for 50 rows of 50k). fn indexed_by(&self, table: &str, query: &Query) -> String { let held = indexed_by(table, query); let few = query.filters.iter().any(|filter| matches!(filter, Filter::In(column, ids) if column == "id" && !ids.is_empty() && ids.len() <= FEW_IDS)); if !held.is_empty() && !few { return held; } if few { if let Some(index) = self.primary_key(table) { return format!(" INDEXED BY {index}"); } } held } /// The index SQLite keeps a table's primary key in, where it keeps one /// apart from the table (a rowid table keyed by a text id): read once /// per table, the schema's own. fn primary_key(&self, table: &str) -> Option { static KEYS: std::sync::OnceLock>>> = std::sync::OnceLock::new(); let keys = KEYS.get_or_init(Default::default); if let Some(key) = keys.lock().ok()?.get(table) { return key.clone(); } let key = self.db.get("SELECT name FROM pragma_index_list(?) WHERE origin = 'pk'", &[SqlValue::Text(table.to_string())]).ok()? .and_then(|row| row.text("name").map(str::to_string)); keys.lock().ok()?.insert(table.to_string(), key.clone()); key } pub fn workspace_id(&self) -> &str { &self.workspace_id } /// Rows as JSON, decoded through each column's declared codec — so a /// `Bool` column reads back `true` rather than `1` and a `Json` column /// reads back its tree rather than its text. pub fn select(&self, query: &Query) -> Result>> { let (spec, wanted, sql, params) = self.select_sql(query)?; let codecs: Vec<_> = wanted.iter().map(|name| cotton_store::schema::specs::codec_of(spec.name, name)).collect(); let rows = self.db.all(&sql, ¶ms)?; rows.iter() .map(|row| { let mut out = Map::new(); for ((name, value), codec) in row.columns().iter().zip(&codecs) { let decoded = match codec { Some(codec) => decode_value(*codec, value)?, None => Value::Null, }; out.insert(name.clone(), decoded); } Ok(out) }) .collect() } /// Rows as [`ReadDb::select`] reads them, each its values by position in /// the order `query.columns` names them: no map per row. A whole list's /// narrow cut, which answers `[[id, …]]` arrays. pub fn select_rows(&self, query: &Query) -> Result>> { let (spec, wanted, sql, params) = self.select_sql(query)?; let codecs: Vec<_> = wanted.iter().map(|name| cotton_store::schema::specs::codec_of(spec.name, name)).collect(); self.db .all_values(&sql, ¶ms)? .iter() .map(|row| { row.iter() .zip(&codecs) .map(|(value, codec)| match codec { Some(codec) => decode_value(*codec, value), None => Ok(Value::Null), }) .collect() }) .collect() } /// The statement [`ReadDb::select`] runs, the columns it selects in order /// and the values it binds. fn select_sql<'q>( &self, query: &'q Query, ) -> Result<(&'static cotton_store::schema::decl::TableSpec, Vec<&'q str>, String, Vec)> { let spec = spec_for(&query.table).ok_or_else(|| { StoreError::refused(format!("cotton-mcp: no table spec for {}", query.table)) })?; let wanted: Vec<&str> = match &query.columns { Some(columns) => columns.iter().map(String::as_str).collect(), None => spec.columns.iter().map(|(name, _)| *name).collect(), }; for column in &wanted { if !spec.columns.iter().any(|(name, _)| name == column) { return Err(StoreError::refused(format!( "cotton-mcp: {} has no column {column}", query.table ))); } } let (where_parts, params) = self.conditions(spec, query)?; // THE GENERIC ROW PROJECTION of a soft reference (design 3.9): a soft // column is read as empty while the row it names is not present, so a // handler never answers a name that points at nothing — and the name // is still on the row, so it reads again when the parent comes back. // Where the read already holds the column to a present row // (`Filter::SoftNames`), every row it answers names one: the parent is // looked up once per row, in the where, never again here. let columns = wanted .iter() .map(|name| match soft_refs::parent_of(spec.name, name) { Some(parent) if !names_present(query, name) => format!( "{} AS {}", soft_refs::soft_value(&format!("{}.{name}", spec.name), parent), quoted(name) ), _ => quoted(name), }) .collect::>() .join(", "); let mut sql = format!("SELECT {columns} FROM {}{}", spec.name, self.indexed_by(spec.name, query)); if !where_parts.is_empty() { sql.push_str(" WHERE "); sql.push_str(&where_parts.join(" AND ")); } if !query.order.is_empty() { let order = query .order .iter() .map(|(raw, direction)| { let column = quoted(raw); match direction { Order::Asc => format!("{column} ASC"), Order::Desc => format!("{column} DESC"), Order::AscNullsLast => format!("{column} IS NULL, {column} ASC"), Order::AscBlanksLast => { format!("({column} IS NULL OR {column} = ''), {column} COLLATE NOCASE ASC") } Order::Composed => format!("{raw} ASC"), Order::ComposedDesc => format!("{raw} DESC"), } }) .collect::>() .join(", "); sql.push_str(&format!(" ORDER BY {order}")); } if let Some(limit) = query.limit { sql.push_str(&format!(" LIMIT {limit}")); if let Some(offset) = query.offset { sql.push_str(&format!(" OFFSET {offset}")); } } Ok((spec, wanted, sql, params)) } /// How many rows a query's filters match — its order, limit and offset /// ignored, so a page can say how many there are in all. pub fn count(&self, query: &Query) -> Result { let spec = spec_for(&query.table).ok_or_else(|| { StoreError::refused(format!("cotton-mcp: no table spec for {}", query.table)) })?; let (where_parts, params) = self.conditions(spec, query)?; let mut sql = format!("SELECT COUNT(*) AS n FROM {}{}", spec.name, self.indexed_by(spec.name, query)); if !where_parts.is_empty() { sql.push_str(" WHERE "); sql.push_str(&where_parts.join(" AND ")); } let key = format!("query-count:{sql}:{params:?}"); Ok(self.db.cached_counts(&key, || { Ok(vec![self.db.get(&sql, ¶ms)?.and_then(|row| row.int("n")).unwrap_or(0)]) })?[0]) } /// The query as a sub-select of `columns` with its workspace scope and /// filters (no order, no page), and the values it binds: for a read that /// joins or sums over the rows a list's filters chose. pub fn sub_select(&self, query: &Query, columns: &str) -> Result<(String, Vec)> { let spec = spec_for(&query.table).ok_or_else(|| { StoreError::refused(format!("cotton-mcp: no table spec for {}", query.table)) })?; let (where_parts, params) = self.conditions(spec, query)?; let mut sql = format!("SELECT {columns} FROM {}{}", spec.name, self.indexed_by(spec.name, query)); if !where_parts.is_empty() { sql.push_str(" WHERE "); sql.push_str(&where_parts.join(" AND ")); } Ok((sql, params)) } /// The query's rows grouped by one of its columns, in one statement: /// each group's value read as [`ReadDb::select`] reads it (a soft /// reference empty while the row it names is not present, decoded by the /// column's codec), beside `aggregates` — expressions the code composed /// over the table's own columns (`Filter::Composed`'s contract). A list's /// group heads, summed by the file rather than over every row read. pub fn grouped(&self, query: &Query, column: &str, aggregates: &str) -> Result> { let spec = spec_for(&query.table).ok_or_else(|| { StoreError::refused(format!("cotton-mcp: no table spec for {}", query.table)) })?; let codec = cotton_store::schema::specs::codec_of(spec.name, column) .ok_or_else(|| StoreError::refused(format!("cotton-mcp: {} has no column {column}", query.table)))?; let group_expr = match soft_refs::parent_of(spec.name, column) { Some(parent) if !names_present(query, column) => soft_refs::soft_value(&format!("{}.{column}", spec.name), parent), _ => format!("{}.{}", spec.name, quoted(column)), }; let (where_parts, params) = self.conditions(spec, query)?; let mut sql = format!("SELECT {group_expr} AS \"@group\", {aggregates} FROM {}{}", spec.name, self.indexed_by(spec.name, query)); if !where_parts.is_empty() { sql.push_str(" WHERE "); sql.push_str(&where_parts.join(" AND ")); } sql.push_str(" GROUP BY 1 ORDER BY 1"); self.db .all(&sql, ¶ms)? .into_iter() .map(|row| { let value = match row.get("@group") { Some(value) => decode_value(codec, value)?, None => Value::Null, }; Ok((value, row)) }) .collect() } /// How many rows a query's filters match under each value of `key` — an /// expression the code composed (`Filter::Composed`'s contract) — in one /// pass: a day plan's sections counted over the whole table, never over a /// page. A row whose key is null is counted under `None`. pub fn count_by(&self, query: &Query, key: &str) -> Result, i64)>> { let spec = spec_for(&query.table).ok_or_else(|| { StoreError::refused(format!("cotton-mcp: no table spec for {}", query.table)) })?; let (where_parts, params) = self.conditions(spec, query)?; let mut sql = format!("SELECT ({key}) AS k, COUNT(*) AS n FROM {}", spec.name); if !where_parts.is_empty() { sql.push_str(" WHERE "); sql.push_str(&where_parts.join(" AND ")); } sql.push_str(" GROUP BY k"); Ok(self .db .all(&sql, ¶ms)? .iter() .map(|row| (row.text("k").map(str::to_string), row.int("n").unwrap_or(0))) .collect()) } /// Each row a query's filters match, its primary key beside the value of /// `key` — an expression the code composed (`Filter::Composed`'s /// contract) — in one pass: a day plan's section of every row, for a /// reader that keeps them ([`ReadDb::count_by`]'s walk, uncounted). pub fn keyed_by(&self, query: &Query, key: &str) -> Result)>> { let spec = spec_for(&query.table).ok_or_else(|| { StoreError::refused(format!("cotton-mcp: no table spec for {}", query.table)) })?; let (where_parts, params) = self.conditions(spec, query)?; let mut sql = format!("SELECT {} AS id, ({key}) AS k FROM {}", quoted(spec.pk), spec.name); if !where_parts.is_empty() { sql.push_str(" WHERE "); sql.push_str(&where_parts.join(" AND ")); } Ok(self .db .all(&sql, ¶ms)? .iter() .filter_map(|row| Some((row.text("id")?.to_string(), row.text("k").map(str::to_string)))) .collect()) } /// The workspace scope and every filter, as `WHERE` parts and the values /// they bind — one compilation for [`ReadDb::select`] and [`ReadDb::count`]. fn conditions( &self, spec: &cotton_store::schema::decl::TableSpec, query: &Query, ) -> Result<(Vec, Vec)> { let mut where_parts: Vec = Vec::new(); let mut params: Vec = Vec::new(); if spec.columns.iter().any(|(name, _)| *name == "workspace_id") { where_parts.push("workspace_id = ?".to_string()); params.push(SqlValue::Text(self.workspace_id.clone())); } for filter in &query.filters { self.render_filter(spec.name, filter, &mut where_parts, &mut params)?; } Ok((where_parts, params)) } /// One row by its primary key, or `None`. pub fn by_id(&self, table: &str, id: &str) -> Result>> { let spec = spec_for(table).ok_or_else(|| { StoreError::refused(format!("cotton-mcp: no table spec for {table}")) })?; let query = Query::on(table) .filter(Filter::Eq(spec.pk.to_string(), SqlValue::Text(id.to_string()))) .limit(1); Ok(self.select(&query)?.into_iter().next()) } /// The first row a query answers, or `None`. pub fn one(&self, query: &Query) -> Result>> { let mut query = query.clone(); query.limit = Some(1); Ok(self.select(&query)?.into_iter().next()) } fn render_filter( &self, table: &str, filter: &Filter, where_parts: &mut Vec, params: &mut Vec, ) -> Result<()> { if let Filter::Static(fragment) = filter { where_parts.push(format!("({fragment})")); return Ok(()); } if let Filter::Composed(fragment) = filter { where_parts.push(format!("({fragment})")); return Ok(()); } if let Filter::ComposedBound(fragment, values) = filter { where_parts.push(format!("({fragment})")); params.extend(values.iter().cloned()); return Ok(()); } if let Filter::SoftNames(column) | Filter::SoftAbsent(column) = filter { let Some(parent) = soft_refs::parent_of(table, column) else { return Err(StoreError::refused(format!( "cotton-mcp: {table}.{column} is not a soft reference" ))); }; let qualified = format!("{table}.{column}"); where_parts.push(match filter { Filter::SoftNames(_) => soft_refs::soft_names(&qualified, parent), _ => soft_refs::soft_absent(&qualified, parent), }); return Ok(()); } if let Filter::ContainsAny(columns, words) = filter { if columns.is_empty() { where_parts.push("0".to_string()); return Ok(()); } let mut any = Vec::with_capacity(columns.len()); for column in columns { if cotton_store::schema::specs::codec_of(table, column).is_none() { return Err(StoreError::refused(format!( "cotton-mcp: {table} has no column {column}" ))); } any.push(format!( "instr(lower(COALESCE({}, '')), lower(?)) > 0", quoted(column) )); params.push(SqlValue::Text(words.clone())); } where_parts.push(format!("({})", any.join(" OR "))); return Ok(()); } let column = match filter { Filter::Static(_) | Filter::Composed(_) | Filter::ComposedBound(..) | Filter::ContainsAny(..) | Filter::SoftNames(_) | Filter::SoftAbsent(_) => { unreachable!("answered above") } Filter::Eq(column, _) | Filter::Ne(column, _) | Filter::Lt(column, _) | Filter::Lte(column, _) | Filter::Gt(column, _) | Filter::Gte(column, _) | Filter::In(column, _) | Filter::InQuery { column, .. } | Filter::NotIn(column, _) | Filter::Like(column, _) | Filter::LikeAny(column, _) | Filter::IsNull(column) | Filter::NotNull(column) | Filter::Blank(column) | Filter::NotBlank(column) => column, Filter::KeysetBefore { column, tie_column, .. } | Filter::KeysetAfter { column, tie_column, .. } => { // The SECOND column is checked here, since the shared check // below sees only one. if cotton_store::schema::specs::codec_of(table, tie_column).is_none() { return Err(StoreError::refused(format!( "cotton-mcp: {table} has no column {tie_column}" ))); } column } }; // A column name is never a parameter, so it is checked against the // spec rather than escaped — the one place a handler could otherwise // build SQL out of an argument. if cotton_store::schema::specs::codec_of(table, column).is_none() { return Err(StoreError::refused(format!( "cotton-mcp: {table} has no column {column}" ))); } let column = quoted(column); match filter { Filter::Eq(_, value) => { where_parts.push(format!("{column} = ?")); params.push(value.clone()); } Filter::Ne(_, value) => { where_parts.push(format!("{column} <> ?")); params.push(value.clone()); } Filter::Lt(_, value) => { where_parts.push(format!("{column} < ?")); params.push(value.clone()); } Filter::KeysetBefore { value, tie_column, tie, .. } => { let tie_column = quoted(tie_column); where_parts.push(format!( "({column} < ? OR ({column} = ? AND {tie_column} < ?))" )); params.push(value.clone()); params.push(value.clone()); params.push(tie.clone()); } Filter::KeysetAfter { value, tie_column, tie, .. } => { let tie_column = quoted(tie_column); where_parts.push(format!( "({column} > ? OR ({column} = ? AND {tie_column} > ?))" )); params.push(value.clone()); params.push(value.clone()); params.push(tie.clone()); } Filter::Lte(_, value) => { where_parts.push(format!("{column} <= ?")); params.push(value.clone()); } Filter::Gt(_, value) => { where_parts.push(format!("{column} > ?")); params.push(value.clone()); } Filter::Gte(_, value) => { where_parts.push(format!("{column} >= ?")); params.push(value.clone()); } Filter::In(_, values) => { if values.is_empty() { // An empty `IN` matches nothing. Spelled out rather than // omitted, because omitting it would match EVERYTHING. where_parts.push("0 = 1".to_string()); } else { let holes = vec!["?"; values.len()].join(", "); where_parts.push(format!("{column} IN ({holes})")); params.extend(values.iter().cloned()); } } Filter::InQuery { query, negate, .. } => { let spec = spec_for(&query.table).ok_or_else(|| StoreError::refused( format!("cotton-mcp: no table spec for {}", query.table)))?; let selected = query.columns.as_ref().filter(|columns| columns.len() == 1) .ok_or_else(|| StoreError::refused("cotton-mcp: membership requires one column"))?; let member = &selected[0]; if cotton_store::schema::specs::codec_of(spec.name, member).is_none() { return Err(StoreError::refused(format!("cotton-mcp: {} has no column {member}", spec.name))); } if !query.order.is_empty() || query.limit.is_some() || query.offset.is_some() { return Err(StoreError::refused("cotton-mcp: membership cannot paginate or order its set")); } let (mut conditions, bound) = self.conditions(spec, query)?; let index = indexed_by_membership(spec.name, member); let present = match soft_refs::parent_of(spec.name, member) { Some(parent) => soft_refs::soft_names(&format!("{}.{member}", spec.name), parent), None => format!("{} IS NOT NULL", quoted(member)), }; let member = quoted(member); // Membership excludes null links, which also proves the sparse // link index applies; do not collect them by scanning history. conditions.push(present); let operator = if *negate { "NOT IN" } else { "IN" }; where_parts.push(format!("{column} {operator} (SELECT {member} FROM {}{index} WHERE {})", spec.name, conditions.join(" AND "))); params.extend(bound); } Filter::NotIn(_, values) => { if values.is_empty() { // An empty `NOT IN` excludes nothing. Spelled out rather // than omitted, so the pair reads as one decision. where_parts.push("1 = 1".to_string()); } else { let holes = vec!["?"; values.len()].join(", "); where_parts.push(format!("{column} NOT IN ({holes})")); params.extend(values.iter().cloned()); } } Filter::Like(_, pattern) => { where_parts.push(format!("{column} LIKE ?")); params.push(SqlValue::Text(pattern.clone())); } Filter::LikeAny(_, patterns) => { if patterns.is_empty() { // An empty "any of" matches nothing — never everything. where_parts.push("0".to_string()); } else { let clauses = patterns .iter() .map(|_| format!("{column} LIKE ?")) .collect::>() .join(" OR "); where_parts.push(format!("({clauses})")); params.extend(patterns.iter().map(|p| SqlValue::Text(p.clone()))); } } Filter::IsNull(_) => where_parts.push(format!("{column} IS NULL")), Filter::NotNull(_) => where_parts.push(format!("{column} IS NOT NULL")), Filter::Blank(_) => where_parts.push(format!("COALESCE({column}, '') = ''")), Filter::NotBlank(_) => where_parts.push(format!("COALESCE({column}, '') <> ''")), Filter::Static(_) | Filter::Composed(_) | Filter::ComposedBound(..) | Filter::ContainsAny(..) | Filter::SoftNames(_) | Filter::SoftAbsent(_) => { unreachable!("answered above") } } Ok(()) } } /// SQLite keywords that appear as Cotton column names and need quoting — the /// store's own list, which is one name long. fn quoted(column: &str) -> String { if column == "position" { format!("\"{column}\"") } else { column.to_string() } } #[cfg(test)] #[path = "read_db_tests.rs"] mod tests;