schedr_db/query.rs
1//! What the query modules share: one query text for both backends, and how times are stored.
2//!
3//! Queries are written once. `{uuid}`, `{ts}` and `{json}` after a parameter cast it for
4//! Postgres (whose columns are typed) and vanish for SQLite (text columns); `{text}` after a
5//! column reads it as text; `{ts<}expr{>ts}` reads a time as stored text (see [`db_time`]).
6//! `INTEGER` columns are read as `i32`: Postgres keeps them in four bytes and refuses a wider
7//! Rust type, SQLite reads either.
8
9use jiff::Timestamp;
10use sqlx::AssertSqlSafe;
11
12use crate::backend::Backend;
13use crate::database::DbError;
14
15/// Runs `$body` with `$pool` bound to a connection (`&mut` the backend's connection type) and
16/// `$backend` to its [`Backend`], once per backend (the queries are the same text, typed per
17/// driver), within the database's query limit: past it, the enclosing function returns
18/// [`DbError::QueryTimeout`] (the query is cut off here, whatever pooler is between; see
19/// archive/PROJECT.md, production path). Inside [`Database::atomically`] on this database the
20/// connection is that transaction's, so the work reads its own writes; otherwise one from the
21/// pool. For reads: writes go through [`in_tx`]. A body using `$pool` twice reborrows it
22/// (`&mut *pool`).
23///
24/// [`Database::atomically`]: crate::database::Database::atomically
25macro_rules! on_pool {
26 ($db:expr, |$pool:ident, $backend:ident| $body:expr) => {{
27 let db: &$crate::database::Database = $db;
28 let run = async {
29 if let Some(scope) = $crate::scope::current(db) {
30 // Marked broken until it succeeds: a failed or cut-off query voids the
31 // transaction (see `Database::atomically`).
32 let mut guard = scope.connection.lock().await;
33 let scoped = &mut *guard;
34 let was_broken = std::mem::replace(&mut scoped.broken, true);
35 let done = async {
36 Ok::<_, $crate::database::DbError>(match &mut scoped.connection {
37 $crate::scope::Connection::Sqlite(connection) => {
38 let $pool: &mut sqlx::SqliteConnection = &mut **connection;
39 let $backend = $crate::backend::Backend::Sqlite;
40 $body
41 }
42 $crate::scope::Connection::Postgres(connection) => {
43 let $pool: &mut sqlx::PgConnection = &mut **connection;
44 let $backend = $crate::backend::Backend::Postgres;
45 $body
46 }
47 })
48 }
49 .await;
50 if done.is_ok() {
51 scoped.broken = was_broken;
52 }
53 return done;
54 }
55 Ok::<_, $crate::database::DbError>({
56 match db.pool() {
57 $crate::database::Pool::Sqlite(pool) => {
58 let mut connection = pool.acquire().await?;
59 let $pool: &mut sqlx::SqliteConnection = &mut *connection;
60 let $backend = $crate::backend::Backend::Sqlite;
61 $body
62 }
63 $crate::database::Pool::Postgres(pool) => {
64 let mut connection = pool.acquire().await?;
65 let $pool: &mut sqlx::PgConnection = &mut *connection;
66 let $backend = $crate::backend::Backend::Postgres;
67 $body
68 }
69 }
70 })
71 };
72 db.limited(db.query_timeout(), run).await?
73 }};
74}
75pub(crate) use on_pool;
76
77/// How many query limits a write's transaction may take in all, by default: its statements
78/// are each limited by Postgres itself (and SQLite's busy timeout); this bounds the whole,
79/// waits for a connection and the network included.
80pub(crate) const WRITE_LIMITS: u32 = 2;
81
82/// As [`WRITE_LIMITS`], for a write of many statements (a parse's files, a code version's
83/// DAG changes).
84pub(crate) const BATCH_LIMITS: u32 = 6;
85
86/// Runs `$body` in a transaction, `$tx` bound to it and `$backend` to its [`Backend`]: the
87/// database's writes. A master's are fenced first (see [`Database::fenced`]); on Postgres
88/// each statement is limited by the query limit in Postgres too (`statement_timeout` for this
89/// transaction only, so it holds through any pooler, and a statement cut off stops there
90/// instead of running on); the whole by `$limits` query limits ([`WRITE_LIMITS`] if not
91/// given); on SQLite it takes the write lock at its start (`BEGIN IMMEDIATE`). The transaction
92/// commits when `$body` ends without an error.
93///
94/// On Postgres the transaction's start, its limit and the fence are one message to the
95/// server ([`Database::begin_postgres`]), so a write costs one round trip more than its own
96/// statements (the `COMMIT`). A connection whose start failed may be left in an aborted
97/// transaction, so it is closed rather than given back to the pool.
98///
99/// [`Database::fenced`]: crate::database::Database::fenced
100macro_rules! in_tx {
101 ($db:expr, |$tx:ident, $backend:ident| $body:expr) => {
102 $crate::query::in_tx!($db, $crate::query::WRITE_LIMITS, |$tx, $backend| $body)
103 };
104 ($db:expr, $limits:expr, |$tx:ident, $backend:ident| $body:expr) => {{
105 let db: &$crate::database::Database = $db;
106 let run = async {
107 // Inside `Database::atomically` on this database: its transaction (begun, limited
108 // and fenced already; committed at its end).
109 if let Some(scope) = $crate::scope::current(db) {
110 // Marked broken until it succeeds: a write failed or cut off voids the
111 // transaction, even if its error is handled (see `Database::atomically`).
112 let mut guard = scope.connection.lock().await;
113 let scoped = &mut *guard;
114 let was_broken = std::mem::replace(&mut scoped.broken, true);
115 // A write a test made fail leaves the transaction broken, as a real one would.
116 #[cfg(any(test, feature = "testing"))]
117 db.faults().before_write()?;
118 let done = async {
119 Ok::<_, $crate::database::DbError>(match &mut scoped.connection {
120 $crate::scope::Connection::Sqlite(connection) => {
121 let $backend = $crate::backend::Backend::Sqlite;
122 let $tx: &mut sqlx::SqliteConnection = &mut **connection;
123 $body
124 }
125 $crate::scope::Connection::Postgres(connection) => {
126 let $backend = $crate::backend::Backend::Postgres;
127 let $tx: &mut sqlx::PgConnection = &mut **connection;
128 $body
129 }
130 })
131 }
132 .await;
133 if done.is_ok() {
134 scoped.broken = was_broken;
135 }
136 return done;
137 }
138 #[cfg(any(test, feature = "testing"))]
139 db.faults().before_write()?;
140 Ok::<_, $crate::database::DbError>(match db.pool() {
141 $crate::database::Pool::Sqlite(pool) => {
142 let $backend = $crate::backend::Backend::Sqlite;
143 // The write lock at once, waiting for it under the busy timeout: a
144 // transaction begun deferred that reads first (the fence) fails at once if
145 // another connection writes before it does (B14).
146 let mut starting = $crate::query::Starting::new(pool.acquire().await?);
147 let mut $tx = starting.begin("BEGIN IMMEDIATE").await?;
148 db.check_fence_sqlite(&mut *$tx).await?;
149 let done = $body;
150 $tx.commit().await?;
151 done
152 }
153 $crate::database::Pool::Postgres(pool) => {
154 let $backend = $crate::backend::Backend::Postgres;
155 let mut starting = $crate::query::Starting::new(pool.acquire().await?);
156 let mut $tx = starting
157 .begin(db.begin_postgres())
158 .await
159 .map_err($crate::database::DbError::from_begin)?;
160 let done = $body;
161 $tx.commit().await?;
162 done
163 }
164 })
165 };
166 let ended = db.limited(db.query_timeout() * $limits, run).await;
167 // Inside `atomically`, its end counts the write instead.
168 if $crate::scope::current(db).is_none() {
169 db.wrote();
170 }
171 ended?
172 }};
173}
174pub(crate) use in_tx;
175
176/// A pooled connection whose transaction is starting: closed, not returned to the pool,
177/// unless the start completed. A start that failed may have left the connection in an
178/// unknown state, and one cut short (its write cancelled: a timeout) is finished by the
179/// database afterwards, the connection then inside a transaction sqlx doesn't know of, which
180/// no rollback ends (B84): on Postgres holding the lease's row and the transaction's settings.
181/// (On SQLite, whose `BEGIN IMMEDIATE` waits for the write lock, a test didn't show it; the
182/// same guard costs nothing there.)
183/// Every transaction this crate starts starts here, a migration's too.
184pub(crate) struct Starting<DB: sqlx::Database> {
185 conn: sqlx::pool::PoolConnection<DB>,
186 /// The start completed: from here on, the transaction rolls itself back if dropped.
187 begun: bool,
188}
189
190impl<DB: sqlx::Database> Starting<DB> {
191 pub(crate) const fn new(conn: sqlx::pool::PoolConnection<DB>) -> Self {
192 Self { conn, begun: false }
193 }
194
195 /// The connection, for work that begins transactions of its own (a migration's run);
196 /// [`Self::completed`] once it has completed.
197 pub(crate) fn conn(&mut self) -> &mut DB::Connection {
198 &mut self.conn
199 }
200
201 /// The work on [`Self::conn`] completed: the connection goes back to the pool.
202 pub(crate) const fn completed(&mut self) {
203 self.begun = true;
204 }
205
206 /// Begins the transaction with `statement`; the connection goes back to the pool once
207 /// it has.
208 pub(crate) fn begin(
209 &mut self,
210 statement: impl sqlx::SqlSafeStr,
211 ) -> impl Future<Output = Result<sqlx::Transaction<'_, DB>, sqlx::Error>> + Send + '_ {
212 let statement = statement.into_sql_str();
213 async move {
214 let tx = sqlx::Connection::begin_with(&mut *self.conn, statement).await?;
215 self.begun = true;
216 Ok(tx)
217 }
218 }
219}
220
221impl<DB: sqlx::Database> Drop for Starting<DB> {
222 fn drop(&mut self) {
223 if !self.begun {
224 self.conn.close_on_drop();
225 }
226 }
227}
228
229#[cfg(test)]
230mod tests;
231
232/// The format times are stored in: UTC, always six fraction digits, so SQLite compares the
233/// text in time order.
234const TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.6fZ";
235
236/// A query in this crate's dialect, for one backend.
237pub(crate) fn sql(backend: Backend, query: &'static str) -> AssertSqlSafe<String> {
238 sql_text(backend, query)
239}
240
241/// As [`sql`], for a query built at run time from this crate's fixed text (placeholders and
242/// casts only, never values: those are bound).
243pub(crate) fn sql_text(backend: Backend, query: &str) -> AssertSqlSafe<String> {
244 // `{json_each}($n{json})`: a bound JSON list's items, as rows of one column `value`.
245 let casts: [(&str, &str); 7] = match backend {
246 Backend::Sqlite => [
247 ("{json_each}", "json_each"),
248 ("{uuid}", ""),
249 ("{ts}", ""),
250 ("{json}", ""),
251 ("{text}", ""),
252 ("{ts<}", ""),
253 ("{>ts}", ""),
254 ],
255 Backend::Postgres => [
256 ("{json_each}", "jsonb_array_elements_text"),
257 ("{uuid}", "::uuid"),
258 ("{ts}", "::timestamptz"),
259 ("{json}", "::jsonb"),
260 ("{text}", "::text"),
261 ("{ts<}", "to_char(("),
262 (
263 "{>ts}",
264 r#") AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')"#,
265 ),
266 ],
267 };
268 let text = casts.iter().fold(query.to_owned(), |text, (marker, cast)| {
269 text.replace(marker, cast)
270 });
271 // Safe: built only from the static queries of this crate and fixed casts.
272 AssertSqlSafe(text)
273}
274
275/// A time as stored: `2026-10-21T08:00:00.000000Z` (microseconds, as Postgres keeps them).
276#[must_use]
277pub fn db_time(t: Timestamp) -> String {
278 t.strftime(TIME_FORMAT).to_string()
279}
280
281/// A stored time read back.
282pub(crate) fn parse_time(what: &'static str, text: &str) -> Result<Timestamp, DbError> {
283 text.parse().map_err(|e: jiff::Error| DbError::InvalidData {
284 what,
285 reason: e.to_string(),
286 })
287}
288
289/// Reads an optional stored time (see [`parse_time`]).
290pub(crate) fn optional_time(
291 what: &'static str,
292 text: Option<String>,
293) -> Result<Option<Timestamp>, DbError> {
294 text.map(|t| parse_time(what, &t)).transpose()
295}
296
297/// Stored JSON of model types.
298pub(crate) fn to_json(value: &impl serde::Serialize) -> String {
299 storable_json(serde_json::to_string(value).expect("model types always serialize"))
300}
301
302/// JSON text as stored: NUL, which Postgres refuses in `jsonb` and `text`, replaced with
303/// U+FFFD in every string and key (B105, decision 114). Text a worker sent (an error's
304/// message, an import error, a warning) may hold one; refusing it would refuse the attempt's
305/// end. Unchanged, and not parsed, when it holds none (JSON writes NUL only as `\u0000`).
306pub(crate) fn storable_json(text: String) -> String {
307 if !text.contains("\\u0000") {
308 return text;
309 }
310 let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else {
311 return text;
312 };
313 serde_json::to_string(&without_nul(value)).expect("JSON values always serialize")
314}
315
316fn without_nul(value: serde_json::Value) -> serde_json::Value {
317 use serde_json::Value;
318 let clean = |text: String| {
319 if text.contains('\0') {
320 text.replace('\0', "\u{fffd}")
321 } else {
322 text
323 }
324 };
325 match value {
326 Value::String(text) => Value::String(clean(text)),
327 Value::Array(items) => Value::Array(items.into_iter().map(without_nul).collect()),
328 Value::Object(fields) => Value::Object(
329 fields
330 .into_iter()
331 .map(|(key, item)| (clean(key), without_nul(item)))
332 .collect(),
333 ),
334 other => other,
335 }
336}
337
338/// Stored JSON read back.
339pub(crate) fn from_json<T: serde::de::DeserializeOwned>(
340 what: &'static str,
341 text: &str,
342) -> Result<T, DbError> {
343 serde_json::from_str(text).map_err(|e| DbError::InvalidData {
344 what,
345 reason: e.to_string(),
346 })
347}
348
349/// A stored enum name (a run kind, a state) read back.
350pub(crate) fn from_name<T: serde::de::DeserializeOwned>(
351 what: &'static str,
352 name: String,
353) -> Result<T, DbError> {
354 serde_json::from_value(serde_json::Value::String(name)).map_err(|e| DbError::InvalidData {
355 what,
356 reason: e.to_string(),
357 })
358}