Add SQLX_OFFLINE env variable to force metadata usage

This commit is contained in:
Jonas Platte 2020-07-16 16:59:11 +02:00 committed by Ryan Leckey
parent f75891725f
commit 4c394de70b
2 changed files with 20 additions and 5 deletions

View File

@ -52,6 +52,7 @@ Compares the migration history of the running database against the `migrations/`
any scripts that are still pending. 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`. Note: must be run as `cargo sqlx`.
```bash ```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 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. 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.

View File

@ -35,11 +35,14 @@ pub fn expand_input(input: QueryMacroInput) -> crate::Result<TokenStream> {
} }
// if `dotenv` wasn't initialized by the above we make sure to do it here // if `dotenv` wasn't initialized by the above we make sure to do it here
match dotenv::var("DATABASE_URL").ok() { match (
Some(db_url) => expand_from_db(input, &db_url), dotenv::var("SQLX_OFFLINE").is_ok(),
dotenv::var("DATABASE_URL"),
) {
(false, Ok(db_url)) => expand_from_db(input, &db_url),
#[cfg(feature = "offline")] #[cfg(feature = "offline")]
None => { _ => {
let data_file_path = std::path::Path::new(&manifest_dir).join("sqlx-data.json"); let data_file_path = std::path::Path::new(&manifest_dir).join("sqlx-data.json");
if data_file_path.exists() { if data_file_path.exists() {
@ -54,7 +57,12 @@ pub fn expand_input(input: QueryMacroInput) -> crate::Result<TokenStream> {
} }
#[cfg(not(feature = "offline"))] #[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()),
} }
} }