feat: help for preparing sqlx query data

This commit is contained in:
Max Hohlfeld 2025-07-03 17:58:47 +02:00
parent 428f46b853
commit 45cf6dda10
73 changed files with 32 additions and 3 deletions

View File

@ -33,6 +33,8 @@ enum Command {
Migrate, Migrate,
#[command(about = "Create a new migration")] #[command(about = "Create a new migration")]
NewMigration { title: String }, NewMigration { title: String },
#[command(about = "Prepare sqlx query metadata for offline compile-time verification")]
Prepare,
} }
#[async_std::main] #[async_std::main]
@ -48,7 +50,6 @@ async fn main() {
create_db(&db_config) create_db(&db_config)
.await .await
.expect("Failed creating database."); .expect("Failed creating database.");
migrate_db(&db_config) migrate_db(&db_config)
.await .await
.expect("Failed migrating database."); .expect("Failed migrating database.");
@ -57,11 +58,9 @@ async fn main() {
drop_db(&db_config) drop_db(&db_config)
.await .await
.expect("Failed dropping database."); .expect("Failed dropping database.");
create_db(&db_config) create_db(&db_config)
.await .await
.expect("Failed creating database."); .expect("Failed creating database.");
migrate_db(&db_config) migrate_db(&db_config)
.await .await
.expect("Failed migrating database."); .expect("Failed migrating database.");
@ -76,6 +75,7 @@ async fn main() {
.await .await
.expect("Failed creating new migration."); .expect("Failed creating new migration.");
} }
Command::Prepare => prepare().await.expect("Failed preparing query metadata."),
} }
} }
@ -169,6 +169,35 @@ async fn create_new_migration(title: &str) -> anyhow::Result<()> {
Ok(()) Ok(())
} }
async fn prepare() -> anyhow::Result<()> {
let cargo = std::env::var("CARGO")
.map_err(|_| anyhow::anyhow!("Please invoke me using Cargo, e.g.: `cargo db <ARGS>`"))
.expect("Existence of CARGO env var is asserted by calling `ensure_sqlx_cli_installed`");
let mut sqlx_prepare_command = {
let mut cmd = std::process::Command::new(&cargo);
cmd.args(["sqlx", "prepare", "--", "--all-targets", "--all-features"]);
let cmd_cwd = db_package_root().context("Error finding the root of the db package!")?;
cmd.current_dir(cmd_cwd);
cmd
};
let o = sqlx_prepare_command
.output()
.context("Could not run {cargo} sqlx prepare!")?;
if !o.status.success() {
let error = anyhow::anyhow!(String::from_utf8_lossy(&o.stdout).to_string()).context("Error generating query metadata. Are you sure the database is running and all migrations are applied?");
return Err(error);
}
println!("Query data written to db/.sqlx directory; please check this into version control.");
Ok(())
}
fn db_package_root() -> Result<PathBuf, anyhow::Error> { fn db_package_root() -> Result<PathBuf, anyhow::Error> {
Ok(PathBuf::from( Ok(PathBuf::from(
std::env::var("CARGO_MANIFEST_DIR").expect("This command needs to be invoked using cargo"), std::env::var("CARGO_MANIFEST_DIR").expect("This command needs to be invoked using cargo"),