From d52576c7fc7a073ee2e32d4b1db3f4294e6808c6 Mon Sep 17 00:00:00 2001 From: Dan B Date: Sun, 19 Apr 2020 13:20:30 +0100 Subject: [PATCH] Add support for crate specific .env files This change will attempt to load an .env file from CARGO_MANIFEST_DIR, if it exists. For backwards compatibility, if the .env file does not exist, we will fall back to default dotenv behaviour. Resolves #267 --- sqlx-macros/src/lib.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/sqlx-macros/src/lib.rs b/sqlx-macros/src/lib.rs index f6d225dc97..e9a3a6d72b 100644 --- a/sqlx-macros/src/lib.rs +++ b/sqlx-macros/src/lib.rs @@ -60,6 +60,16 @@ macro_rules! async_macro ( let res: Result = block_on(async { use sqlx::connection::Connect; + // If a .env file exists at CARGO_MANIFEST_DIR, load environment variables from this, + // otherwise fallback to default dotenv behaviour. + if let Ok(dir) = std::env::var("CARGO_MANIFEST_DIR") { + let env_path = Path::from(&dir).join(".env"); + if env_path.exists() { + dotenv::from_path(env_path.as_path()) + .map_err(|e| format!("failed to load environment from {:?}, {}", env_path, e))? + } + } + let db_url = Url::parse(&dotenv::var("DATABASE_URL").map_err(|_| "DATABASE_URL not set")?)?; match db_url.scheme() {