From f3265c6e91d374138623ac2ed460e96f5576b93b 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 | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/sqlx-macros/src/lib.rs b/sqlx-macros/src/lib.rs index f6d225dc97..b1a95422a9 100644 --- a/sqlx-macros/src/lib.rs +++ b/sqlx-macros/src/lib.rs @@ -11,6 +11,8 @@ use quote::quote; #[cfg(feature = "runtime-async-std")] use async_std::task::block_on; +use std::path::PathBuf; + use url::Url; type Error = Box; @@ -60,6 +62,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 = PathBuf::from(&dir).join(".env"); + if env_path.exists() { + dotenv::from_path(&env_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() {