cja/db.rs
1//! Database utilities and migration management.
2//!
3//! CJA ships with migrations for its core tables (`jobs`, `dead_letter_jobs`,
4//! `crons`, `sessions`). Use [`run_migrations`] to apply them on startup.
5//!
6//! # Migration Locations
7//!
8//! Migrations exist in multiple locations in the repository:
9//!
10//! | Location | Purpose |
11//! |----------|---------|
12//! | `crates/cja/migrations/` | **Source of truth** — used by [`run_migrations`] |
13//! | `migrations/` (root) | Copy for `sqlx migrate run` CLI |
14//! | `crates/cja.app/migrations/` | Example app's copy |
15//!
16//! When adding a new framework migration, copy it to all three locations.
17//!
18//! # Advisory Locking
19//!
20//! `SQLx` handles advisory locking internally during migrations. Do **not** wrap
21//! [`run_migrations`] with custom `pg_advisory_lock`/`pg_advisory_unlock` calls —
22//! this is redundant and potentially harmful with connection poolers like `PgBouncer`.
23
24/// Run CJA's built-in database migrations.
25///
26/// This applies all framework migrations (jobs, crons, sessions, `dead_letter_jobs`)
27/// using `SQLx`'s built-in advisory locking for safe concurrent startup.
28pub async fn run_migrations(db_pool: &sqlx::PgPool) -> crate::Result<()> {
29 sqlx::migrate!("./migrations").run(db_pool).await?;
30 Ok(())
31}