schedr_db/database.rs
1//! A connection pool to the schedr database, and schema migration and checks.
2
3use std::str::FromStr;
4use std::sync::Arc;
5use std::time::Duration;
6
7use sqlx::migrate::MigrateError;
8use sqlx::postgres::{PgConnectOptions, PgPool, PgPoolOptions};
9use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};
10
11use crate::backend::{Backend, UnsupportedUrl};
12use crate::query::Starting;
13use crate::status::SchemaStatus;
14
15/// A migration's end on its connection: given back to the pool once it ran; failed, its
16/// transaction's rollback, which sqlx only queues, run now, awaited (B150): the connection is
17/// then closed in the background, and SQLite's write lock held till that rollback would make
18/// the lease's release that follows wait, past its query limit on a loaded machine.
19async fn finish_migration<DB: sqlx::Database>(
20 whole: &mut Starting<DB>,
21 ran: Result<(), sqlx::migrate::MigrateError>,
22) -> Result<(), DbError>
23where
24 DB::Connection: sqlx::Connection<Database = DB>,
25{
26 match ran {
27 Ok(()) => {
28 whole.completed();
29 Ok(())
30 }
31 Err(error) => {
32 let _ = sqlx::Connection::ping(whole.conn()).await;
33 Err(error.into())
34 }
35 }
36}
37#[cfg(test)]
38mod tests;
39
40/// The longest a query may take by default (`query_timeout`).
41pub const DEFAULT_QUERY_TIMEOUT: Duration = Duration::from_secs(10);
42
43/// Why a database operation failed.
44#[derive(Debug, thiserror::Error)]
45pub enum DbError {
46 /// The URL doesn't name a supported database.
47 #[error(transparent)]
48 UnsupportedUrl(#[from] UnsupportedUrl),
49 /// A query or connection failed.
50 #[error("database error: {0}{hint}", hint = pooler_hint(.0))]
51 Sqlx(#[from] sqlx::Error),
52 /// Applying migrations failed.
53 #[error("migration failed: {0}")]
54 Migrate(#[from] MigrateError),
55 /// Stored data doesn't read back as the model (written by hand, or by an incompatible
56 /// version).
57 #[error("invalid stored data in {what}: {reason}")]
58 InvalidData {
59 /// The table and column.
60 what: &'static str,
61 /// Why it doesn't read.
62 reason: String,
63 },
64 /// A query took longer than the limit ([`Database::connect_with_timeout`]): cut off here.
65 #[error("a database query took longer than {} s (`query_timeout`)", .0.as_secs_f64())]
66 QueryTimeout(Duration),
67 /// The `COMMIT` of a [`Database::atomically`] transaction was cut off by the time limit or
68 /// lost with its connection: whether the transaction is stored isn't known (read it back).
69 #[error("the transaction's commit was cut off; whether it is stored is unknown")]
70 CommitUnknown,
71 /// A statement of a [`Database::atomically`] transaction failed or was cut off, though the
72 /// work went on: the transaction was rolled back, nothing of it stored.
73 #[error("a statement of this transaction failed; nothing of it is stored")]
74 TransactionFailed,
75 /// A master's write found the lease no longer its own (another master took it over): it
76 /// was refused, nothing of it stored ([`Database::fenced`]).
77 #[error("this master no longer holds the database's lease (another took it over)")]
78 NotLeading,
79}
80
81/// A connection pool to the schedr database, and the lease its writes are fenced by, if any.
82#[derive(Debug, Clone)]
83pub struct Database {
84 pool: Pool,
85 fence: Option<Arc<Fence>>,
86 /// DAG definitions by version, parsed once (shared by clones; see [`DagCache`]).
87 dags: Arc<DagCache>,
88 /// The same for every clone: which database a transaction of
89 /// [`Database::atomically`] belongs to.
90 identity: Arc<()>,
91 /// How the master learns of new commands (see [`Database::with_notifications`]).
92 notifications: Arc<Notifications>,
93 /// Write transactions ended (shared by clones): a round's probe taken before one is taken
94 /// again (decision 485, [`crate::probe`]).
95 writes: Arc<std::sync::atomic::AtomicU64>,
96 /// Told when a write transaction ended outside [`Database::quietly`] (shared by clones):
97 /// what the master's trigger loop waits on (decision 486).
98 changed: Arc<tokio::sync::Notify>,
99 /// Told when a named event posted here cleared waiting steps' looks (decision 487): the
100 /// master's round looks at once, not at its next tick.
101 waits: Arc<tokio::sync::Notify>,
102 /// Writes made to fail, for tests (shared by clones; decision 98).
103 #[cfg(any(test, feature = "testing"))]
104 faults: Arc<crate::faults::Faults>,
105}
106
107/// `[database] notifications` and `notifications_url`.
108#[derive(Clone)]
109pub(crate) struct Notifications {
110 /// On: a new command is announced, and the master listens.
111 pub(crate) on: bool,
112 /// The connection the master listens through, if not this database's own.
113 pub(crate) url: Option<String>,
114}
115
116impl std::fmt::Debug for Notifications {
117 /// The URL's password hidden (B206's review).
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 f.debug_struct("Notifications")
120 .field("on", &self.on)
121 .field(
122 "url",
123 &self.url.as_deref().map(crate::backend::redact_password),
124 )
125 .finish()
126 }
127}
128
129impl Default for Notifications {
130 fn default() -> Self {
131 Self {
132 on: true,
133 url: None,
134 }
135 }
136}
137
138/// DAG definitions by version ID, each parsed once: a version never changes once stored, so
139/// what is cached never goes stale. Rounds read many rows of the same few versions (a wide
140/// DAG's ready tasks, every active DAG); each brought and parsed its whole definition (B13).
141/// Cleared when it holds its most versions ([`DagCache::MAX`] by default,
142/// `SCHEDR_HIDDEN__DATABASE__DAG_VERSIONS_CACHED`): the current ones come back at once.
143#[derive(Debug)]
144pub(crate) struct DagCache(
145 std::sync::Mutex<std::collections::HashMap<String, Arc<schedr_model::Dag>>>,
146 usize,
147);
148
149impl Default for DagCache {
150 fn default() -> Self {
151 Self::keeping(Self::MAX)
152 }
153}
154
155impl DagCache {
156 /// The most versions kept before clearing, by default.
157 pub(crate) const MAX: usize = 4096;
158
159 /// An empty cache keeping at most `most` versions.
160 pub(crate) fn keeping(most: usize) -> Self {
161 Self(std::sync::Mutex::default(), most.max(1))
162 }
163
164 pub(crate) fn get(&self, version_id: &str) -> Option<Arc<schedr_model::Dag>> {
165 self.map().get(version_id).cloned()
166 }
167
168 pub(crate) fn insert(&self, version_id: &str, dag: Arc<schedr_model::Dag>) {
169 let mut map = self.map();
170 if map.len() >= self.1 {
171 map.clear();
172 }
173 map.insert(version_id.to_owned(), dag);
174 }
175
176 fn map(
177 &self,
178 ) -> std::sync::MutexGuard<'_, std::collections::HashMap<String, Arc<schedr_model::Dag>>> {
179 self.0
180 .lock()
181 .unwrap_or_else(std::sync::PoisonError::into_inner)
182 }
183}
184
185/// The connection pool of a [`Database`].
186#[derive(Debug, Clone)]
187pub enum Pool {
188 /// SQLite.
189 Sqlite(SqlitePool),
190 /// Postgres.
191 Postgres(PgPool),
192}
193
194/// The lease a master's writes need (see [`Database::fenced`]).
195#[derive(Debug)]
196pub(crate) struct Fence {
197 /// The master's name in the lease.
198 pub(crate) holder: String,
199 /// The takeover counter when it took the lease.
200 pub(crate) epoch: i32,
201}
202
203/// Whether a database error code is the database's own trouble rather than a statement's data:
204/// on Postgres (SQLSTATE) the classes of transaction rollback (40: deadlock, serialization),
205/// insufficient resources (53), object not ready (55: lock not available), operator
206/// intervention (57: a statement cancelled at its limit, a shutdown), connection (08) and
207/// system errors (58); on SQLite (a number) busy, locked, I/O, full and can't open.
208fn databases_trouble(postgres: bool, code: &str) -> bool {
209 if postgres {
210 // SQLSTATE: five characters, often all digits (57014), so told by the backend.
211 return ["40", "53", "55", "57", "08", "58"]
212 .iter()
213 .any(|class| code.starts_with(class));
214 }
215 code.parse::<i64>()
216 .is_ok_and(|sqlite| matches!(sqlite & 0xff, 5 | 6 | 10 | 13 | 14))
217}
218
219/// The likely cause of an error showing a notification where a query's answer was expected:
220/// a connection pooler in transaction mode lends a server connection that someone `LISTEN`s
221/// on to other clients (B16); empty for any other error.
222fn pooler_hint(error: &sqlx::Error) -> &'static str {
223 if error.to_string().contains("NotificationResponse") {
224 " (probably a connection pooler in transaction mode, PgBouncer or similar, in front of \
225 Postgres while a master listens for notifications: set `[database] notifications = \
226 false`, or `notifications_url` to a connection straight to Postgres)"
227 } else {
228 ""
229 }
230}
231
232impl DbError {
233 /// What a failed `COMMIT` means: refused by the database (a constraint checked at commit,
234 /// a serialization failure: rolled back, the error as it is), or cut off or its connection
235 /// lost ([`Self::CommitUnknown`]: it may be stored).
236 #[must_use]
237 pub fn from_commit(error: Self) -> Self {
238 match error {
239 Self::Sqlx(sqlx::Error::Database(_)) => error,
240 _ => Self::CommitUnknown,
241 }
242 }
243
244 /// Whether the database couldn't be reached for now, so a role starting should wait and
245 /// try again rather than exit (the user, 2026-11-15, after B247): a time limit (a query's,
246 /// or the pool's wait for a connection), a connection refused, reset or lost, a pool closed,
247 /// or Postgres saying it can't take connections yet (starting up, shutting down, too many
248 /// connections, a connection exception). Not a wrong URL, password or TLS setting, a schema
249 /// to migrate or anything about data: those fail the same way again.
250 #[must_use]
251 pub fn is_transient(&self) -> bool {
252 match self {
253 Self::QueryTimeout(_)
254 | Self::Sqlx(
255 sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::Io(_),
256 ) => true,
257 // The database's own trouble, as a statement's retry tells it (the review of
258 // M5.1q): a connection lost or refused (08: PgBouncer's own refusals too, a full
259 // pool among them), out of connections or resources, starting or shutting down,
260 // a statement timeout, a lock not given; SQLite busy, locked, full or unopenable.
261 // Not a wrong password, database or TLS setting.
262 Self::Sqlx(sqlx::Error::Database(error)) => {
263 let postgres = error
264 .try_downcast_ref::<sqlx::postgres::PgDatabaseError>()
265 .is_some();
266 error
267 .code()
268 .is_some_and(|code| databases_trouble(postgres, &code))
269 }
270 _ => false,
271 }
272 }
273
274 /// What a role waiting for its database says about this error: no text the database
275 /// server wrote (it may name the user: "too many connections for role ..."), only the
276 /// error's kind or code (the user, 2026-11-15: the warning names only the host).
277 #[must_use]
278 pub fn waiting_reason(&self) -> String {
279 match self {
280 Self::QueryTimeout(limit) => format!("no answer within {limit:?}"),
281 Self::Sqlx(sqlx::Error::PoolTimedOut) => "no connection in time".to_owned(),
282 Self::Sqlx(sqlx::Error::PoolClosed) => "its connection pool is closed".to_owned(),
283 // The operating system's words (refused, unreachable, a name not found).
284 Self::Sqlx(sqlx::Error::Io(error)) => error.to_string(),
285 Self::Sqlx(sqlx::Error::Database(error)) => {
286 let code = error.code().unwrap_or_default();
287 let named = match &*code {
288 "57P03" => "it is starting up",
289 "57P01" | "57P02" => "it is shutting down",
290 "53300" => "too many connections",
291 "57014" => "a statement timed out",
292 "5" | "517" => "it is busy",
293 "6" | "262" => "it is locked",
294 _ => "",
295 };
296 match (named, &*code) {
297 ("", "") => "an error with no code".to_owned(),
298 ("", code) => format!("error {code}"),
299 (named, code) => format!("{named}, error {code}"),
300 }
301 }
302 // Its kind's name only (`Sqlx(Tls`, `NotLeading`): the rest may carry server text.
303 other => {
304 let named = format!("{other:?}");
305 let kind = named.split([' ', '{', '"', ',']).next().unwrap_or_default();
306 kind.trim_end_matches('(').to_owned()
307 }
308 }
309 }
310
311 /// Whether this is about the data a statement touched (stored data that won't read, a
312 /// statement the database refuses for its data: a constraint, a trigger), not the
313 /// database's own trouble (unreachable, a time limit, its own statement limit, a deadlock
314 /// or serialization failure, a lock it couldn't get, an operator's shutdown, a busy SQLite,
315 /// a full disk) or the lease: retrying the same statement fails the same way, while other
316 /// statements may go through.
317 #[must_use]
318 pub fn is_data_fault(&self) -> bool {
319 match self {
320 Self::InvalidData { .. }
321 | Self::Sqlx(sqlx::Error::Decode(_) | sqlx::Error::ColumnDecode { .. }) => true,
322 Self::Sqlx(sqlx::Error::Database(error)) => {
323 let postgres = error
324 .try_downcast_ref::<sqlx::postgres::PgDatabaseError>()
325 .is_some();
326 !error
327 .code()
328 .is_some_and(|code| databases_trouble(postgres, &code))
329 }
330 _ => false,
331 }
332 }
333
334 /// A failed start of a write's transaction on Postgres: [`Self::NotLeading`] if it was the
335 /// fence that refused it ([`Database::begin_postgres`]).
336 pub(crate) fn from_begin(error: sqlx::Error) -> Self {
337 match &error {
338 sqlx::Error::Database(e) if e.code().as_deref() == Some(crate::lease::NOT_LEADING) => {
339 Self::NotLeading
340 }
341 _ => Self::Sqlx(error),
342 }
343 }
344}
345
346impl From<Pool> for Database {
347 fn from(pool: Pool) -> Self {
348 Self {
349 pool,
350 fence: None,
351 dags: Arc::default(),
352 identity: Arc::default(),
353 notifications: Arc::default(),
354 writes: Arc::default(),
355 changed: Arc::default(),
356 waits: Arc::default(),
357 #[cfg(any(test, feature = "testing"))]
358 faults: Arc::default(),
359 }
360 }
361}
362
363tokio::task_local! {
364 /// Set inside [`Database::quietly`]: its writes don't tell [`Database::changed`].
365 static QUIET: ();
366}
367
368impl Database {
369 /// The writes made to fail (tests only).
370 #[cfg(any(test, feature = "testing"))]
371 pub(crate) fn faults(&self) -> &crate::faults::Faults {
372 &self.faults
373 }
374
375 /// Connects to the database a URL names. SQLite files are created if missing, and
376 /// foreign keys are enforced. An in-memory SQLite database (`sqlite::memory:`) uses a
377 /// single connection, since each connection would otherwise see its own empty database.
378 ///
379 /// # Errors
380 ///
381 /// Returns [`DbError::UnsupportedUrl`] for an unknown scheme, or [`DbError::Sqlx`] if the
382 /// URL is malformed or the connection fails.
383 pub async fn connect(url: &str) -> Result<Self, DbError> {
384 Self::open(url, None).await
385 }
386
387 /// Connects to the database at `url`, no query (or wait for a connection) taking longer
388 /// than `query_timeout`, enforced here around each query ([`DbError::QueryTimeout`]; a
389 /// server-side `statement_timeout`, set by the DBA, stops the work in Postgres too), and
390 /// SQLite's busy timeout. The roles use it; migrations don't (a long migration must
391 /// finish). It works through any connection pooler: nothing is set on the session.
392 ///
393 /// # Errors
394 ///
395 /// As [`Self::connect`].
396 pub async fn connect_with_timeout(url: &str, query_timeout: Duration) -> Result<Self, DbError> {
397 Self::open(url, Some(query_timeout)).await
398 }
399
400 async fn open(url: &str, query_timeout: Option<Duration>) -> Result<Self, DbError> {
401 // Without a limit, sqlx's default wait for a connection.
402 let acquire = query_timeout.unwrap_or(Duration::from_secs(30));
403 match Backend::from_url(url)? {
404 Backend::Sqlite => {
405 let mut options = SqliteConnectOptions::from_str(url)?
406 .create_if_missing(true)
407 .foreign_keys(true);
408 if let Some(timeout) = query_timeout {
409 options = options.busy_timeout(timeout);
410 }
411 let max_connections = if url.contains(":memory:") { 1 } else { 8 };
412 let pool = SqlitePoolOptions::new()
413 .max_connections(max_connections)
414 .acquire_timeout(acquire)
415 .connect_with(options)
416 .await?;
417 Ok(Pool::Sqlite(pool).into())
418 }
419 Backend::Postgres => {
420 // No session state (see `crate::lease`): no `SET` on the connection, and no
421 // named prepared statements, which a pooler in transaction mode may not keep.
422 for name in crate::backend::unknown_postgres_parameters(url) {
423 tracing::warn!(
424 parameter = %name,
425 "the database URL's parameter `{name}` is ignored: the Postgres client \
426 doesn't know it (a typo?)"
427 );
428 }
429 let options = PgConnectOptions::from_str(url)?.statement_cache_capacity(0);
430 // No ping before each use (a round trip per query): a connection that died
431 // in the pool fails its query instead, and the caller's next try gets another.
432 let pool = PgPoolOptions::new()
433 .test_before_acquire(false)
434 .acquire_timeout(acquire)
435 .connect_with(options)
436 .await?;
437 Ok(Pool::Postgres(pool).into())
438 }
439 }
440 }
441
442 /// The connection pool.
443 #[must_use]
444 pub const fn pool(&self) -> &Pool {
445 &self.pool
446 }
447
448 /// The lease holder this database is [fenced](Self::fenced) for (a master's ID): `None`
449 /// if it isn't.
450 #[must_use]
451 pub fn fenced_as(&self) -> Option<&str> {
452 self.fence.as_ref().map(|fence| fence.holder.as_str())
453 }
454
455 /// This database for the master holding the lease as `holder` with takeover counter
456 /// `epoch`: each of its writes checks, in its own transaction, that the lease is still
457 /// that, and is refused ([`DbError::NotLeading`]) once another master took it over. On
458 /// Postgres the check holds the lease's row until the write commits, so a takeover waits
459 /// for it; SQLite runs one write at a time anyway. A write sent before a takeover but
460 /// reaching the database after it (held up by the network or a pooler's queue) is refused
461 /// too: what the master's own clock can't rule out (see archive/PROJECT.md, production path).
462 #[must_use]
463 pub fn fenced(&self, holder: &str, epoch: i64) -> Self {
464 Self {
465 pool: self.pool.clone(),
466 dags: self.dags.clone(),
467 identity: self.identity.clone(),
468 notifications: self.notifications.clone(),
469 writes: self.writes.clone(),
470 changed: self.changed.clone(),
471 waits: self.waits.clone(),
472 #[cfg(any(test, feature = "testing"))]
473 faults: self.faults.clone(),
474 fence: Some(Arc::new(Fence {
475 holder: holder.to_owned(),
476 epoch: i32::try_from(epoch).unwrap_or(i32::MAX),
477 })),
478 }
479 }
480
481 /// The DAG of version `version_id`, from the cache or read and parsed once (B13).
482 ///
483 /// # Errors
484 ///
485 /// [`DbError`] if the query fails or the stored DAG doesn't read; [`DbError::InvalidData`]
486 /// for an unknown version.
487 pub async fn dag_version(&self, version_id: &str) -> Result<Arc<schedr_model::Dag>, DbError> {
488 const JSON: &str = "SELECT dag_json{text} FROM dag_versions WHERE id = $1{uuid}";
489 if let Some(dag) = self.dags.get(version_id) {
490 return Ok(dag);
491 }
492 let json: Option<String> = crate::query::on_pool!(self, |pool, backend| {
493 sqlx::query_scalar(crate::query::sql(backend, JSON))
494 .bind(version_id)
495 .fetch_optional(pool)
496 .await?
497 });
498 let json = json.ok_or_else(|| DbError::InvalidData {
499 what: "dag_versions.id",
500 reason: format!("no DAG version `{version_id}`"),
501 })?;
502 let dag = Arc::new(crate::query::from_json::<schedr_model::Dag>(
503 "dag_versions.dag_json",
504 &json,
505 )?);
506 self.dags.insert(version_id, dag.clone());
507 Ok(dag)
508 }
509
510 /// This database with notifications of new commands `on` or off (`[database]
511 /// notifications`), the master listening through `url` if given (`notifications_url`) or
512 /// through this database's own connections. Off: commands aren't announced, and the master
513 /// polls (see [`Database::command_notifications`]).
514 #[must_use]
515 pub fn with_notifications(mut self, on: bool, url: Option<String>) -> Self {
516 self.notifications = Arc::new(Notifications { on, url });
517 self
518 }
519
520 /// This database keeping at most `most` DAG versions parsed (decision 493), a cache of its
521 /// own (made before its clones).
522 #[must_use]
523 pub fn with_dag_versions_cached(mut self, most: usize) -> Self {
524 self.dags = Arc::new(DagCache::keeping(most));
525 self
526 }
527
528 /// Whether notifications are on, and the connection the master listens through.
529 pub(crate) fn notifications(&self) -> &Notifications {
530 &self.notifications
531 }
532
533 /// A write transaction ended, stored or not (decision 485): a round's probe is taken again
534 /// before its next read, and, outside [`Database::quietly`], [`Database::changed`] is told
535 /// (decision 486).
536 pub(crate) fn wrote(&self) {
537 self.writes
538 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
539 if QUIET.try_with(|()| ()).is_err() {
540 self.changed.notify_one();
541 }
542 }
543
544 /// Waits until a write transaction ended outside [`Database::quietly`] since the last wait
545 /// returned (writes in between are one wake): the master's trigger loop (decision 486).
546 pub async fn changed(&self) {
547 self.changed.notified().await;
548 }
549
550 /// A named event posted cleared waiting steps' looks.
551 pub(crate) fn waits_woken(&self) {
552 self.waits.notify_one();
553 }
554
555 /// Waits until a named event posted in this process cleared waiting steps' looks since the
556 /// last wait returned (decision 487): the master's round looks at them at once.
557 pub async fn waits_due(&self) {
558 self.waits.notified().await;
559 }
560
561 /// Runs `work` with its writes left out of [`Database::changed`]: housekeeping that changes
562 /// nothing a trigger depends on (the lease, the master's row, a worker's last heartbeat),
563 /// and the trigger loop's own writes.
564 pub async fn quietly<F: std::future::Future>(&self, work: F) -> F::Output {
565 QUIET.scope((), work).await
566 }
567
568 /// Write transactions ended so far, in this process (shared by clones).
569 #[must_use]
570 pub fn writes_ended(&self) -> u64 {
571 self.write_ends()
572 }
573
574 /// Write transactions ended so far.
575 pub(crate) fn write_ends(&self) -> u64 {
576 self.writes.load(std::sync::atomic::Ordering::SeqCst)
577 }
578
579 /// The same for every clone of this database (see [`Database::atomically`]).
580 pub(crate) const fn identity(&self) -> &Arc<()> {
581 &self.identity
582 }
583
584 /// The lease this database's writes are fenced by, if any.
585 pub(crate) fn fence(&self) -> Option<&Fence> {
586 self.fence.as_deref()
587 }
588
589 /// The longest a query may take: the pool's wait for a connection, which
590 /// [`Self::connect_with_timeout`] sets to the query limit (sqlx's 30 s default otherwise).
591 #[must_use]
592 pub fn query_timeout(&self) -> Duration {
593 match &self.pool {
594 Pool::Sqlite(pool) => pool.options().get_acquire_timeout(),
595 Pool::Postgres(pool) => pool.options().get_acquire_timeout(),
596 }
597 }
598
599 /// `work` cut off after `limit` ([`DbError::QueryTimeout`]).
600 pub(crate) async fn limited<T>(
601 &self,
602 limit: Duration,
603 work: impl Future<Output = Result<T, DbError>>,
604 ) -> Result<T, DbError> {
605 tokio::time::timeout(limit, work)
606 .await
607 .unwrap_or(Err(DbError::QueryTimeout(limit)))
608 }
609
610 /// The backend of this database.
611 #[must_use]
612 pub const fn backend(&self) -> Backend {
613 match &self.pool {
614 Pool::Sqlite(_) => Backend::Sqlite,
615 Pool::Postgres(_) => Backend::Postgres,
616 }
617 }
618
619 /// Applies the migrations not applied yet (what `schedr db migrate` does).
620 ///
621 /// # Errors
622 ///
623 /// Returns [`DbError::Migrate`] if a migration fails or the applied migrations don't match
624 /// the built-in ones.
625 pub async fn migrate(&self) -> Result<(), DbError> {
626 let migrator = self.backend().migrator();
627 // As in `migrate`: on a guarded connection (B84). `run_direct` is what `run` does after
628 // acquiring, without its "`Acquire` is not general enough" error on a connection
629 // (sqlx's own words; doc-hidden, pinned with sqlx).
630 match &self.pool {
631 Pool::Sqlite(pool) => {
632 let mut whole = Starting::new(pool.acquire().await?);
633 let ran = migrator.run_direct(None, whole.conn(), false).await;
634 finish_migration(&mut whole, ran).await?;
635 }
636 Pool::Postgres(pool) => {
637 let mut whole = Starting::new(pool.acquire().await?);
638 let ran = migrator.run_direct(None, whole.conn(), false).await;
639 finish_migration(&mut whole, ran).await?;
640 }
641 }
642 Ok(())
643 }
644
645 /// As [`Self::migrate`], without the migrator's own lock (a session advisory lock on
646 /// Postgres, which connection poolers in transaction mode don't keep): for a master holding
647 /// the lease, which already rules out a second one migrating (see [`crate::lease`]).
648 ///
649 /// # Errors
650 ///
651 /// As [`Self::migrate`].
652 pub async fn migrate_as_lease_holder(&self) -> Result<(), DbError> {
653 // `Migrator` isn't `Clone`: a copy from its (public, semver-exempt) fields, checked by
654 // the tests at the pinned sqlx version.
655 let locked = self.backend().migrator();
656 let mut migrator = sqlx::migrate::Migrator {
657 migrations: locked.migrations.clone(),
658 ignore_missing: locked.ignore_missing,
659 locking: locked.locking,
660 no_tx: locked.no_tx,
661 table_name: locked.table_name.clone(),
662 create_schemas: locked.create_schemas.clone(),
663 };
664 migrator.set_locking(false);
665 // As in `migrate`: on a guarded connection (B84).
666 match &self.pool {
667 Pool::Sqlite(pool) => {
668 let mut whole = Starting::new(pool.acquire().await?);
669 let ran = migrator.run_direct(None, whole.conn(), false).await;
670 finish_migration(&mut whole, ran).await?;
671 }
672 Pool::Postgres(pool) => {
673 let mut whole = Starting::new(pool.acquire().await?);
674 let ran = migrator.run_direct(None, whole.conn(), false).await;
675 finish_migration(&mut whole, ran).await?;
676 }
677 }
678 Ok(())
679 }
680
681 /// The versions of the migrations applied successfully, in order; empty if none.
682 ///
683 /// # Errors
684 ///
685 /// Returns [`DbError::Sqlx`] if the query fails.
686 pub async fn applied_migrations(&self) -> Result<Vec<i64>, DbError> {
687 Ok(self
688 .applied_checksums()
689 .await?
690 .into_iter()
691 .map(|(version, _)| version)
692 .collect())
693 }
694
695 /// The applied migrations' versions and checksums, in order (none before the first migration).
696 async fn applied_checksums(&self) -> Result<Vec<(i64, Vec<u8>)>, DbError> {
697 const EXISTS_SQLITE: &str =
698 "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '_sqlx_migrations'";
699 const EXISTS_POSTGRES: &str =
700 "SELECT COUNT(*) FROM pg_tables WHERE tablename = '_sqlx_migrations'";
701 const APPLIED: &str =
702 "SELECT version, checksum FROM _sqlx_migrations WHERE success ORDER BY version";
703 let applied = match &self.pool {
704 Pool::Sqlite(pool) => {
705 let exists: i64 = sqlx::query_scalar(EXISTS_SQLITE).fetch_one(pool).await?;
706 if exists == 0 {
707 return Ok(Vec::new());
708 }
709 sqlx::query_as(APPLIED).fetch_all(pool).await?
710 }
711 Pool::Postgres(pool) => {
712 let exists: i64 = sqlx::query_scalar(EXISTS_POSTGRES).fetch_one(pool).await?;
713 if exists == 0 {
714 return Ok(Vec::new());
715 }
716 sqlx::query_as(APPLIED).fetch_all(pool).await?
717 }
718 };
719 Ok(applied)
720 }
721
722 /// How the database's schema compares with this binary's migrations.
723 ///
724 /// # Errors
725 ///
726 /// Returns [`DbError::Sqlx`] if reading the applied migrations fails.
727 pub async fn schema_status(&self) -> Result<SchemaStatus, DbError> {
728 // Within the query limit: a read hung on a quiet connection is tried again (the review
729 // of M5.1q), not waited for while the role stays starting.
730 let applied = self
731 .limited(self.query_timeout(), self.applied_checksums())
732 .await?;
733 let embedded: Vec<(i64, &[u8])> = self
734 .backend()
735 .migrator()
736 .iter()
737 .map(|m| (m.version, m.checksum.as_ref()))
738 .collect();
739 let applied: Vec<(i64, &[u8])> = applied.iter().map(|(v, c)| (*v, c.as_slice())).collect();
740 Ok(SchemaStatus::compare_checksums(&embedded, &applied))
741 }
742}