Skip to content

Commit

Permalink
Add support for crate specific .env files
Browse files Browse the repository at this point in the history
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
  • Loading branch information
xyzd authored and mehcode committed Apr 24, 2020
1 parent 581bcf0 commit e7c1486
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions sqlx-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn std::error::Error>;
Expand Down Expand Up @@ -60,6 +62,16 @@ macro_rules! async_macro (
let res: Result<proc_macro2::TokenStream> = 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() {
Expand Down

0 comments on commit e7c1486

Please sign in to comment.