forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

page.rs285 lines, 10.0 KiBHistoryRawDownload
1//! One paged `SELECT` — the window and the `total` that goes with it, both
2//! done by the database.
3//!
4//! WHY: `?limit=10` used to run an unbounded `SELECT *`, hand the whole table
5//! to the web layer and slice ten rows off it. The scan (and the decode of
6//! every row) grew with the table no matter how small the page was. Here the
7//! window is `LIMIT/OFFSET` in SQL, and `total` is a `count(*)` over the
8//! *same* `WHERE` as a second statement, so a page can never disagree with
9//! the count that pages it.
10//!
11//! ```ignore
12//! PagedList::new("note WHERE user_id = $1", "ORDER BY id DESC")
13//! .bind(owner.0)
14//! .run::<Note>(limit, offset, db)
15//! .await
16//! ```
17//!
18//! Paging stays opt-in: `limit = None, offset = 0` is the unpaged read, and
19//! it runs exactly one statement (no count — the rows in hand *are* the
20//! total), so internal callers that just want the list pay nothing.
21//!
22//! Runtime-checked SQL by design: `from_where` is assembled per call site,
23//! which is this module's named exemption from the compile-time `query!`
24//! rule. Placeholders are positional (`$1, $2, …`) in [`.bind`] order, and
25//! the window's own placeholders continue the numbering. The count is a plain
26//! `count(*)`, which always answers one `NOT NULL` row — no planner-shape
27//! decoding to preserve.
28//!
29//! The dynamic parts of every statement here are table/column names (in-crate
30//! constants and literals, never client text) and the `$n` numbers this
31//! builder prints itself; every value binds — which is the audit the
32//! [`AssertSqlSafe`] wraps stand on.
33//!
34//! Only for lists the database can express whole. A handler that filters rows
35//! in Rust after the read (visibility, audience resolution, a schedule
36//! window) must keep slicing in the web layer: a DB `LIMIT` in front of a
37//! Rust filter silently returns a short page.
38
39use sqlx::postgres::{PgArguments, PgRow};
40use sqlx::{Arguments, AssertSqlSafe, FromRow};
41use uuid::Uuid;
42
43use crate::database::Database;
44use crate::error::AppError;
45
46/// One bound parameter of a runtime-checked builder's statement, in
47/// `$1, $2, …` order.
48///
49/// [`PagedList`] and [`crate::db::field_update::FieldUpdate`] are the named
50/// exemptions from the compile-time `query!` rule: their SQL is assembled at
51/// run time, so their parameters ride this closed enum — owned values, no
52/// borrow to tie a builder's lifetime to, [`Clone`] because one builder run
53/// can need the same `WHERE` bound twice (page, then count). A caller that
54/// needs a type the enum lacks adds a variant here; sqlx's borrow-tied
55/// dynamic binding does not survive being stored in a builder.
56#[derive(Clone, Debug)]
57pub(crate) enum Param {
58 I64(i64),
59 Text(String),
60 Uuid(Uuid),
61 /// A nullable column value: `None` binds SQL `NULL` with the uuid type
62 /// still named, so `IS NOT DISTINCT FROM $n` compares an absent link
63 /// truthfully.
64 OptUuid(Option<Uuid>),
65 /// Nullable TEXT column clear/set — same NULL-with-type rationale as
66 /// OptUuid.
67 OptText(Option<String>),
68 /// Nullable BIGINT column clear/set.
69 OptI64(Option<i64>),
70 /// A TEXT-array predicate value (`col = ANY($n)`): the closed role set a
71 /// visibility filter allows, the tag list a search narrows to.
72 Texts(Vec<String>),
73 /// BOOLEAN filter (e.g. folder read/unread).
74 Bool(bool),
75}
76
77impl Param {
78 /// Push onto runtime-checked arguments. sqlx defers encode failures to
79 /// execution, so there is nothing to check here.
80 pub(crate) fn add_to(self, args: &mut PgArguments) {
81 let _ = match self {
82 Param::I64(value) => args.add(value),
83 Param::Text(value) => args.add(value),
84 Param::Uuid(value) => args.add(value),
85 Param::OptUuid(value) => args.add(value),
86 Param::OptText(value) => args.add(value),
87 Param::OptI64(value) => args.add(value),
88 Param::Texts(value) => args.add(value),
89 Param::Bool(value) => args.add(value),
90 };
91 }
92}
93
94impl From<i64> for Param {
95 fn from(value: i64) -> Self {
96 Self::I64(value)
97 }
98}
99
100impl From<String> for Param {
101 fn from(value: String) -> Self {
102 Self::Text(value)
103 }
104}
105
106impl From<Uuid> for Param {
107 fn from(value: Uuid) -> Self {
108 Self::Uuid(value)
109 }
110}
111
112impl From<Option<Uuid>> for Param {
113 fn from(value: Option<Uuid>) -> Self {
114 Self::OptUuid(value)
115 }
116}
117
118impl From<Option<String>> for Param {
119 fn from(value: Option<String>) -> Self {
120 Self::OptText(value)
121 }
122}
123
124impl From<Option<i64>> for Param {
125 fn from(value: Option<i64>) -> Self {
126 Self::OptI64(value)
127 }
128}
129
130pub(crate) struct PagedList {
131 /// Everything after `FROM`, e.g. `note WHERE user_id = $1`. Placeholders
132 /// are positional in [`PagedList::bind`] order; shared verbatim by the
133 /// page and the count.
134 from_where: String,
135 /// The full `ORDER BY ...`, applied to the page only.
136 order: &'static str,
137 binds: Vec<Param>,
138}
139
140impl PagedList {
141 /// `from_where` is a whole-table read (`"term"`) or a filtered one
142 /// (`"note WHERE user_id = $1"`).
143 pub(crate) fn new(from_where: impl Into<String>, order: &'static str) -> Self {
144 Self {
145 from_where: from_where.into(),
146 order,
147 binds: Vec::new(),
148 }
149 }
150
151 /// Bind the next positional parameter: the first call fills `$1`, the
152 /// second `$2`, … — `from_where` must carry the placeholders in the same
153 /// order.
154 #[must_use]
155 pub(crate) fn bind<T: Into<Param>>(mut self, value: T) -> Self {
156 self.binds.push(value.into());
157 self
158 }
159
160 /// The page statement and, when the window can hide rows, the count
161 /// statement. Split out so a test can read the SQL: the whole point of
162 /// this type is that `LIMIT/OFFSET` reach the database instead of a
163 /// `Vec` slice.
164 fn statements(&self, limit: Option<i64>, offset: i64) -> (String, Option<String>) {
165 let mut next = self.binds.len();
166 let mut sql = format!("SELECT * FROM {} {}", self.from_where, self.order);
167 if limit.is_some() {
168 next += 1;
169 sql.push_str(&format!(" LIMIT ${next}"));
170 }
171 // A window that can hide rows needs the count; an unpaged read from
172 // row zero already holds every row, so it stays a single statement.
173 let counted = limit.is_some() || offset > 0;
174 if counted {
175 next += 1;
176 sql.push_str(&format!(" OFFSET ${next}"));
177 }
178 let count = counted.then(|| format!("SELECT count(*) FROM {}", self.from_where));
179 (sql, count)
180 }
181
182 /// The page plus the full row count. `limit = None` runs from `offset` to
183 /// the end, matching the unpaged envelope.
184 pub(crate) async fn run<T>(
185 self,
186 limit: Option<i64>,
187 offset: i64,
188 db: &Database,
189 ) -> Result<(Vec<T>, i64), AppError>
190 where
191 T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
192 {
193 let (page_sql, count_sql) = self.statements(limit, offset);
194 let mut args = PgArguments::default();
195 for bind in self.binds.iter().cloned() {
196 bind.add_to(&mut args);
197 }
198 if let Some(limit) = limit {
199 Param::from(limit).add_to(&mut args);
200 }
201 if count_sql.is_some() {
202 Param::from(offset).add_to(&mut args);
203 }
204 let rows: Vec<T> = sqlx::query_as_with(AssertSqlSafe(page_sql), args)
205 .fetch_all(db)
206 .await?;
207 let total = match count_sql {
208 Some(count_sql) => {
209 let mut args = PgArguments::default();
210 for bind in self.binds {
211 bind.add_to(&mut args);
212 }
213 let scalar: i64 = sqlx::query_scalar_with(AssertSqlSafe(count_sql), args)
214 .fetch_one(db)
215 .await?;
216 scalar
217 }
218 None => rows.len() as i64,
219 };
220 Ok((rows, total))
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227
228 fn list() -> PagedList {
229 PagedList::new("note WHERE user_id = $1", "ORDER BY id DESC").bind(Uuid::nil())
230 }
231
232 /// The window has to be SQL — a `Vec` slice would leave the scan
233 /// unbounded, which is the whole reason this type exists.
234 #[test]
235 fn a_paged_read_windows_and_counts_in_sql() {
236 let (sql, count) = list().statements(Some(10), 20);
237 assert!(sql.contains("ORDER BY id DESC LIMIT $2 OFFSET $3"));
238 assert_eq!(
239 count.as_deref(),
240 Some("SELECT count(*) FROM note WHERE user_id = $1")
241 );
242 }
243
244 /// A whole-table read counts the bare table.
245 #[test]
246 fn an_unfiltered_list_counts_the_bare_table() {
247 let (sql, count) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0);
248 assert!(sql.contains("LIMIT $1 OFFSET $2"));
249 assert_eq!(count.as_deref(), Some("SELECT count(*) FROM term"));
250 }
251
252 /// Unpaged from row zero: the rows in hand are the total, so no count
253 /// runs.
254 #[test]
255 fn an_unpaged_read_stays_one_statement() {
256 let (sql, count) = list().statements(None, 0);
257 assert_eq!(
258 sql,
259 "SELECT * FROM note WHERE user_id = $1 ORDER BY id DESC"
260 );
261 assert_eq!(count, None);
262 // An offset without a limit still hides rows, so it needs the count.
263 let (sql, count) = list().statements(None, 3);
264 assert!(sql.contains("OFFSET $2"));
265 assert!(!sql.contains("LIMIT"));
266 assert!(count.is_some());
267 }
268
269 /// The window's placeholders continue the caller's numbering, in emission
270 /// order.
271 #[test]
272 fn window_placeholders_continue_the_where_numbering() {
273 let (sql, count) = PagedList::new(
274 "note WHERE user_id = $1 AND archived_at IS NULL",
275 "ORDER BY id",
276 )
277 .bind(Uuid::nil())
278 .statements(Some(2), 4);
279 assert!(sql.contains("LIMIT $2 OFFSET $3"));
280 assert_eq!(
281 count.as_deref(),
282 Some("SELECT count(*) FROM note WHERE user_id = $1 AND archived_at IS NULL")
283 );
284 }
285}