🧮 read a page total the planner answered from an index
Browse files at this commit4889fd9f0702ebbd97f55c16a6c9f037dacfb1a0Parent: 0684656- fix
- 🧮 read a page total the planner answered from an index
1 changed file +66 -19
- src/domain/page.rs +66 -19
src/domain/page.rsmodified+66 -19
| @@ -18,6 +18,9 @@ | |||
| 18 | //! emits exactly one statement (no count — the rows in hand *are* the total), | 18 | //! emits exactly one statement (no count — the rows in hand *are* the total), |
| 19 | //! so internal callers that just want the list pay nothing. | 19 | //! so internal callers that just want the list pay nothing. |
| 20 | //! | 20 | //! |
| 21 | +//! The count's result shape is the planner's to choose (see [`total_of`]) — | ||
| 22 | +//! both shapes decode to the same `total`. | ||
| 23 | +//! | ||
| 21 | //! Only for lists the database can express whole. A handler that filters rows | 24 | //! Only for lists the database can express whole. A handler that filters rows |
| 22 | //! in Rust after the read (visibility, audience resolution, a schedule window) | 25 | //! in Rust after the read (visibility, audience resolution, a schedule window) |
| 23 | //! must keep slicing in the web layer: a DB `LIMIT` in front of a Rust filter | 26 | //! must keep slicing in the web layer: a DB `LIMIT` in front of a Rust filter |
| @@ -41,17 +44,8 @@ impl PagedList { | |||
| 41 | /// `from_where` is a whole-table read (`"term"`) or a filtered one | 44 | /// `from_where` is a whole-table read (`"term"`) or a filtered one |
| 42 | /// (`"note WHERE user = $usr"`). | 45 | /// (`"note WHERE user = $usr"`). |
| 43 | pub fn new(from_where: impl Into<String>, order: &'static str) -> Self { | 46 | pub fn new(from_where: impl Into<String>, order: &'static str) -> Self { |
| 44 | - let from_where = from_where.into(); | ||
| 45 | Self { | 47 | Self { |
| 46 | - // A *bare* `SELECT VALUE count() FROM t GROUP ALL` comes back as an | 48 | + from_where: from_where.into(), |
| 47 | - // object rather than the projected int ("Expected int, got object") | ||
| 48 | - // — the whole-table read takes a path that drops the `VALUE`. Any | ||
| 49 | - // `WHERE`, even a trivial one, keeps it an int, so an unfiltered | ||
| 50 | - // list gets one. Cheaper than special-casing the take. | ||
| 51 | - from_where: match from_where.contains(" WHERE ") { | ||
| 52 | - true => from_where, | ||
| 53 | - false => format!("{from_where} WHERE true"), | ||
| 54 | - }, | ||
| 55 | order, | 49 | order, |
| 56 | bindings: Vec::new(), | 50 | bindings: Vec::new(), |
| 57 | } | 51 | } |
| @@ -104,16 +98,42 @@ impl PagedList { | |||
| 104 | } | 98 | } |
| 105 | let mut result = query.await?.check()?; | 99 | let mut result = query.await?.check()?; |
| 106 | let rows = result.take::<Vec<T>>(0)?; | 100 | let rows = result.take::<Vec<T>>(0)?; |
| 107 | - let total = if counted { | 101 | + let total = match counted { |
| 108 | - // `GROUP ALL` yields no row at all when nothing matched. | 102 | + true => total_of(result.take::<Value>(1)?)?, |
| 109 | - result.take::<Vec<i64>>(1)?.first().copied().unwrap_or(0) | 103 | + false => rows.len() as i64, |
| 110 | - } else { | ||
| 111 | - rows.len() as i64 | ||
| 112 | }; | 104 | }; |
| 113 | Ok((rows, total)) | 105 | Ok((rows, total)) |
| 114 | } | 106 | } |
| 115 | } | 107 | } |
| 116 | 108 | ||
| 109 | +/// The count statement's slot, in either shape the planner answers in. | ||
| 110 | +/// | ||
| 111 | +/// `SELECT VALUE count() ... GROUP ALL` normally yields the projected int, but | ||
| 112 | +/// whenever the planner can answer the count straight out of an index or the | ||
| 113 | +/// table count (`IndexCountScan` — an indexed field compared to a value known | ||
| 114 | +/// at plan time, `grade IS NONE` or a *literal*, and any bare table read) it | ||
| 115 | +/// returns `{ count: N }` and drops the `SELECT VALUE` projection. Decoding | ||
| 116 | +/// only the int is where "Expected int, got object" came from; the number is | ||
| 117 | +/// the same either way. The in-memory engine never rewrites the plan, so only | ||
| 118 | +/// a real server ever produces the object. | ||
| 119 | +fn total_of(count: Value) -> Result<i64, AppError> { | ||
| 120 | + // `GROUP ALL` yields no row at all when nothing matched. | ||
| 121 | + let row = match count { | ||
| 122 | + Value::Array(rows) => rows.into_iter().next().unwrap_or_default(), | ||
| 123 | + other => other, | ||
| 124 | + }; | ||
| 125 | + let row = match row { | ||
| 126 | + Value::Object(mut object) => object.remove("count").unwrap_or_default(), | ||
| 127 | + other => other, | ||
| 128 | + }; | ||
| 129 | + match row.is_nullish() { | ||
| 130 | + true => Ok(0), | ||
| 131 | + false => row | ||
| 132 | + .into_t::<i64>() | ||
| 133 | + .map_err(|e| AppError::Internal(format!("count decode: {e}"))), | ||
| 134 | + } | ||
| 135 | +} | ||
| 136 | + | ||
| 117 | #[cfg(test)] | 137 | #[cfg(test)] |
| 118 | mod tests { | 138 | mod tests { |
| 119 | use super::*; | 139 | use super::*; |
| @@ -136,12 +156,39 @@ mod tests { | |||
| 136 | assert!(counted); | 156 | assert!(counted); |
| 137 | } | 157 | } |
| 138 | 158 | ||
| 139 | - /// A whole-table read still gets a `WHERE`, or its count comes back as an | 159 | + /// A whole-table read counts the table as it stands — no `WHERE true` to |
| 140 | - /// object instead of an int. | 160 | + /// force a scan, because [`total_of`] now takes the count-from-index shape |
| 161 | + /// that hack existed to avoid. | ||
| 141 | #[test] | 162 | #[test] |
| 142 | - fn an_unfiltered_list_still_counts_as_an_int() { | 163 | + fn an_unfiltered_list_counts_the_bare_table() { |
| 143 | let (sql, _) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0); | 164 | let (sql, _) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0); |
| 144 | - assert!(sql.contains("SELECT VALUE count() FROM term WHERE true GROUP ALL;")); | 165 | + assert!(sql.contains("SELECT VALUE count() FROM term GROUP ALL;")); |
| 166 | + } | ||
| 167 | + | ||
| 168 | + /// Both shapes of the count slot mean the same number. The object is what | ||
| 169 | + /// a real server returns whenever it answers `count()` from an index or the | ||
| 170 | + /// table count; the in-memory engine only ever produces the int, so this is | ||
| 171 | + /// the only place the object arm can be pinned. Drop that arm and the | ||
| 172 | + /// second assert fails with "count decode: Expected int, got object" — | ||
| 173 | + /// which is the 500 `GET /classes?grade=&limit=1` served. | ||
| 174 | + #[test] | ||
| 175 | + fn a_count_decodes_from_either_shape() { | ||
| 176 | + let projected = Value::Array([Value::from_t(7i64)].into_iter().collect()); | ||
| 177 | + let from_index = Value::Array( | ||
| 178 | + [Value::Object( | ||
| 179 | + [("count".to_string(), Value::from_t(7i64))] | ||
| 180 | + .into_iter() | ||
| 181 | + .collect(), | ||
| 182 | + )] | ||
| 183 | + .into_iter() | ||
| 184 | + .collect(), | ||
| 185 | + ); | ||
| 186 | + assert_eq!(total_of(projected).unwrap(), 7); | ||
| 187 | + assert_eq!(total_of(from_index).unwrap(), 7); | ||
| 188 | + // `GROUP ALL` yields no row at all when nothing matched. | ||
| 189 | + assert_eq!(total_of(Value::Array(Default::default())).unwrap(), 0); | ||
| 190 | + // Any other shape is an error, never a silently wrong `total`. | ||
| 191 | + assert!(total_of(Value::Array([Value::from_t("7")].into_iter().collect())).is_err()); | ||
| 145 | } | 192 | } |
| 146 | 193 | ||
| 147 | /// Unpaged from row zero: the rows in hand are the total, so no count runs. | 194 | /// Unpaged from row zero: the rows in hand are the total, so no count runs. |