Skip to main content

doido_generators/commands/
db.rs

1//! `doido db` — database management.
2//!
3//! Exposes every SeaORM CLI subcommand and option verbatim (`doido db migrate
4//! …`, `doido db generate entity …`) plus Doido's own `doido db create`, which
5//! SeaORM does not provide. Doido changes two SeaORM defaults to match its app
6//! layout:
7//!   * migrations live in [`DEFAULT_MIGRATION_DIR`] (`db/migration`), and
8//!   * generated entities are written to [`DEFAULT_ENTITY_OUTPUT_DIR`]
9//!     (`app/models/_entities`).
10//!
11//! A user-supplied `-d/--migration-dir` or `-o/--output-dir` always wins.
12
13use clap::Subcommand;
14use sea_orm_cli::{
15    handle_error, run_generate_command, run_migrate_command, Commands, GenerateSubcommands,
16};
17
18/// Subcommands of `doido db`: Doido's `create` plus the flattened SeaORM CLI.
19#[derive(Subcommand)]
20// The flattened SeaORM `Commands` is large, but this is parsed once at startup
21// and can't be boxed through clap's `#[command(flatten)]`.
22#[allow(clippy::large_enum_variant)]
23pub enum DbCommand {
24    /// Create the database for the current environment
25    Create,
26    /// Drop every table and reload `db/schema.sql`
27    Reset,
28    /// Load `db/schema.sql` only if the database has no tables yet (idempotent)
29    Prepare,
30    /// Run `db/seeds.sql` against the database
31    Seed,
32    /// Schema dump/load (`db/schema.sql`)
33    Schema {
34        #[command(subcommand)]
35        action: SchemaCommand,
36    },
37    /// SeaORM CLI commands (migrate, generate entity)
38    #[command(flatten)]
39    SeaOrm(Commands),
40}
41
42/// Subcommands of `doido db schema`.
43#[derive(Subcommand)]
44pub enum SchemaCommand {
45    /// Dump the current schema to `db/schema.sql`
46    Dump,
47    /// Load `db/schema.sql` into the database
48    Load,
49}
50
51/// Where Doido keeps its SeaORM migration crate.
52const DEFAULT_MIGRATION_DIR: &str = "db/migration";
53/// Where Doido writes generated SeaORM entities.
54const DEFAULT_ENTITY_OUTPUT_DIR: &str = "app/models/_entities";
55/// Canonical schema file (Rails `db/schema.rb` analogue).
56const SCHEMA_FILE: &str = "db/schema.sql";
57/// Plain-SQL seed script (Rails `db/seeds.rb` analogue).
58const SEEDS_FILE: &str = "db/seeds.sql";
59
60/// Upstream SeaORM CLI defaults — used to detect "the user didn't override this".
61const SEA_ORM_CLI_DEFAULT_MIGRATION_DIR: &str = "./migration";
62const SEA_ORM_CLI_DEFAULT_OUTPUT_DIR: &str = "./";
63
64/// Populates `DATABASE_URL` from the app's `config/<env>.yml` (`database.url`)
65/// when it isn't already set in the environment.
66///
67/// SeaORM CLI reads the database URL from the `DATABASE_URL` env var (both
68/// `migrate` and `generate entity` bind to it). Seeding it from config means
69/// `doido db …` works without the user exporting `DATABASE_URL` by hand, while
70/// an explicit `-u/--database-url` or a pre-set env var still wins. Call this
71/// before clap parses so the required `generate entity` URL is satisfied.
72pub fn ensure_database_url_from_config() {
73    if std::env::var_os("DATABASE_URL").is_some() {
74        return;
75    }
76    // Only seed from a real config file; absent config leaves DATABASE_URL unset
77    // so the user gets the usual "missing database URL" error rather than a
78    // surprising default.
79    if let Ok(config) = doido_model::config::YamlConfig::load() {
80        std::env::set_var("DATABASE_URL", config.database.url);
81    }
82}
83
84/// Runs a `doido db <command>`.
85pub async fn run(command: DbCommand, verbose: bool) {
86    match command {
87        DbCommand::Create => create().await,
88        DbCommand::Reset => reset().await,
89        DbCommand::Prepare => prepare().await,
90        DbCommand::Seed => seed().await,
91        DbCommand::Schema { action } => schema(action).await,
92        DbCommand::SeaOrm(command) => run_sea_orm(command, verbose).await,
93    }
94}
95
96/// Opens a connection to the resolved [`database_url`], exiting on failure.
97async fn connect() -> doido_model::DatabaseConnection {
98    let url = database_url();
99    match doido_model::connect_with_url(&url).await {
100        Ok(conn) => conn,
101        Err(e) => {
102            doido_core::tracing::error!("failed to connect to {url}: {e}");
103            std::process::exit(1);
104        }
105    }
106}
107
108/// Reads a file, logging (and returning `None`) on failure.
109fn read_sql_file(path: &str) -> Option<String> {
110    match std::fs::read_to_string(path) {
111        Ok(contents) => Some(contents),
112        Err(e) => {
113            doido_core::tracing::error!("could not read {path}: {e}");
114            None
115        }
116    }
117}
118
119/// `doido db reset` — drop everything, then reload `db/schema.sql`.
120async fn reset() {
121    let Some(schema) = read_sql_file(SCHEMA_FILE) else {
122        return;
123    };
124    let conn = connect().await;
125    match doido_model::tasks::reset(&conn, &schema).await {
126        Ok(()) => doido_core::tracing::info!("reset database from {SCHEMA_FILE}"),
127        Err(e) => doido_core::tracing::error!("db reset failed: {e}"),
128    }
129}
130
131/// `doido db prepare` — load `db/schema.sql` only if the database is empty.
132async fn prepare() {
133    let Some(schema) = read_sql_file(SCHEMA_FILE) else {
134        return;
135    };
136    let conn = connect().await;
137    match doido_model::tasks::prepare(&conn, &schema).await {
138        Ok(()) => doido_core::tracing::info!("prepared database from {SCHEMA_FILE}"),
139        Err(e) => doido_core::tracing::error!("db prepare failed: {e}"),
140    }
141}
142
143/// `doido db seed` — execute `db/seeds.sql` (a plain SQL script). Rust-closure
144/// seeders threaded through `run()` are a future enhancement.
145async fn seed() {
146    let Some(sql) = read_sql_file(SEEDS_FILE) else {
147        return;
148    };
149    let conn = connect().await;
150    match doido_model::schema::load(&conn, &sql).await {
151        Ok(()) => doido_core::tracing::info!("seeded database from {SEEDS_FILE}"),
152        Err(e) => doido_core::tracing::error!("db seed failed: {e}"),
153    }
154}
155
156/// `doido db schema dump|load` over [`SCHEMA_FILE`].
157async fn schema(action: SchemaCommand) {
158    let conn = connect().await;
159    match action {
160        SchemaCommand::Dump => match doido_model::schema::dump(&conn).await {
161            Ok(sql) => {
162                if let Some(parent) = std::path::Path::new(SCHEMA_FILE).parent() {
163                    let _ = std::fs::create_dir_all(parent);
164                }
165                match std::fs::write(SCHEMA_FILE, sql) {
166                    Ok(()) => doido_core::tracing::info!("wrote schema to {SCHEMA_FILE}"),
167                    Err(e) => doido_core::tracing::error!("could not write {SCHEMA_FILE}: {e}"),
168                }
169            }
170            Err(e) => doido_core::tracing::error!("schema dump failed: {e}"),
171        },
172        SchemaCommand::Load => {
173            let Some(sql) = read_sql_file(SCHEMA_FILE) else {
174                return;
175            };
176            match doido_model::schema::load(&conn, &sql).await {
177                Ok(()) => doido_core::tracing::info!("loaded schema from {SCHEMA_FILE}"),
178                Err(e) => doido_core::tracing::error!("schema load failed: {e}"),
179            }
180        }
181    }
182}
183
184/// Creates the database named by the resolved [`database_url`].
185async fn create() {
186    let url = database_url();
187    match doido_model::create_database(&url).await {
188        Ok(()) => doido_core::tracing::info!("created database: {url}"),
189        Err(e) if e.to_string().contains("already exists") => {
190            doido_core::tracing::info!("database already exists: {url}");
191        }
192        Err(e) => handle_error(e),
193    }
194}
195
196/// Resolves the database URL from `DATABASE_URL` or `config/<env>.yml`, exiting
197/// with an error if neither is available.
198fn database_url() -> String {
199    if let Ok(url) = std::env::var("DATABASE_URL") {
200        return url;
201    }
202    if let Ok(config) = doido_model::config::YamlConfig::load() {
203        return config.database.url;
204    }
205    doido_core::tracing::error!("DATABASE_URL is not set and config/<env>.yml could not be read");
206    std::process::exit(1);
207}
208
209/// Dispatches a flattened SeaORM CLI command, applying Doido's directory defaults.
210async fn run_sea_orm(command: Commands, verbose: bool) {
211    match command {
212        Commands::Generate { mut command } => {
213            apply_entity_output_default(&mut command);
214            run_generate_command(command, verbose)
215                .await
216                .unwrap_or_else(handle_error);
217        }
218        Commands::Migrate {
219            migration_dir,
220            database_schema,
221            database_url,
222            command,
223        } => {
224            let migration_dir = override_migration_dir(migration_dir);
225            run_migrate_command(
226                command,
227                &migration_dir,
228                database_schema,
229                database_url,
230                verbose,
231            )
232            .unwrap_or_else(handle_error);
233        }
234    }
235}
236
237/// Substitutes Doido's migration directory when the user left the SeaORM default.
238fn override_migration_dir(migration_dir: String) -> String {
239    if migration_dir == SEA_ORM_CLI_DEFAULT_MIGRATION_DIR {
240        DEFAULT_MIGRATION_DIR.to_string()
241    } else {
242        migration_dir
243    }
244}
245
246/// Substitutes Doido's entity output directory when the user left the SeaORM default.
247fn apply_entity_output_default(command: &mut GenerateSubcommands) {
248    let GenerateSubcommands::Entity { output_dir, .. } = command;
249    if output_dir == SEA_ORM_CLI_DEFAULT_OUTPUT_DIR {
250        *output_dir = DEFAULT_ENTITY_OUTPUT_DIR.to_string();
251    }
252}