From 4c394de70b61abade373acc496ce528dcab622e2 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Thu, 16 Jul 2020 16:59:11 +0200 Subject: [PATCH] Add SQLX_OFFLINE env variable to force metadata usage --- sqlx-cli/README.md | 9 ++++++++- sqlx-macros/src/query/mod.rs | 16 ++++++++++++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/sqlx-cli/README.md b/sqlx-cli/README.md index 9318a3d0..e9916f42 100644 --- a/sqlx-cli/README.md +++ b/sqlx-cli/README.md @@ -51,7 +51,8 @@ $ sqlx migration run Compares the migration history of the running database against the `migrations/` folder and runs any scripts that are still pending. -#### Enable building in "offline" mode with `query!()` +#### Enable building in "offline" mode with `query!()` + Note: must be run as `cargo sqlx`. ```bash @@ -74,3 +75,9 @@ cargo sqlx prepare --check ``` Exits with a nonzero exit status if the data in `sqlx-data.json` is out of date with the current database schema and queries in the project. Intended for use in Continuous Integration. + +#### Force building in offline mode + +To make sure an accidentally-present `DATABASE_URL` environment variable or `.env` file does not +result in `cargo build` (trying to) access the database, you can set the `SQLX_OFFLINE` environment +variable. diff --git a/sqlx-macros/src/query/mod.rs b/sqlx-macros/src/query/mod.rs index e41ea998..04f2193b 100644 --- a/sqlx-macros/src/query/mod.rs +++ b/sqlx-macros/src/query/mod.rs @@ -35,11 +35,14 @@ pub fn expand_input(input: QueryMacroInput) -> crate::Result { } // if `dotenv` wasn't initialized by the above we make sure to do it here - match dotenv::var("DATABASE_URL").ok() { - Some(db_url) => expand_from_db(input, &db_url), + match ( + dotenv::var("SQLX_OFFLINE").is_ok(), + dotenv::var("DATABASE_URL"), + ) { + (false, Ok(db_url)) => expand_from_db(input, &db_url), #[cfg(feature = "offline")] - None => { + _ => { let data_file_path = std::path::Path::new(&manifest_dir).join("sqlx-data.json"); if data_file_path.exists() { @@ -54,7 +57,12 @@ pub fn expand_input(input: QueryMacroInput) -> crate::Result { } #[cfg(not(feature = "offline"))] - None => Err("`DATABASE_URL` must be set to use query macros".into()), + (true, _) => { + Err("The cargo feature `offline` has to be enabled to use `SQLX_OFFLINE`".into()) + } + + #[cfg(not(feature = "offline"))] + (false, Err(_)) => Err("`DATABASE_URL` must be set to use query macros".into()), } }