Skip to content

Commit

Permalink
Assume offline mode in sqlx (#4926)
Browse files Browse the repository at this point in the history
* Assume offline mode

* PR feedback
  • Loading branch information
dynco-nym authored Sep 25, 2024
1 parent 5d4a0fe commit 487bf67
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 16 deletions.
31 changes: 16 additions & 15 deletions nym-data-observatory/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,41 +7,42 @@ const POSTGRES_USER: &str = "nym";
const POSTGRES_PASSWORD: &str = "password123";
const POSTGRES_DB: &str = "data_obs_db";

/// If you need to re-run migrations or reset the db, just run
/// cargo clean -p nym-node-status-api
/// if schema changes, rerun `cargo sqlx prepare` with a running DB
/// https://github.com/launchbadge/sqlx/blob/main/sqlx-cli/README.md#enable-building-in-offline-mode-with-query
#[tokio::main]
async fn main() -> Result<()> {
if let Ok(value) = std::env::var("CI") {
if value == "true" {
println!("cargo::rustc-env=SQLX_OFFLINE=true");
}
} else {
let db_url = export_db_variables()?;
let db_url =
format!("postgresql://{POSTGRES_USER}:{POSTGRES_PASSWORD}@localhost:5432/{POSTGRES_DB}");

// if a live DB is reachable, use that
if PgConnection::connect(&db_url).await.is_ok() {
export_db_variables(&db_url)?;
println!("cargo::rustc-env=SQLX_OFFLINE=false");
run_migrations(&db_url).await?;
} else {
// by default, run in offline mode
println!("cargo::rustc-env=SQLX_OFFLINE=true");
}

rerun_if_changed();

Ok(())
}

fn export_db_variables() -> Result<String> {
fn export_db_variables(db_url: &str) -> Result<()> {
let mut map = HashMap::new();
map.insert("POSTGRES_USER", POSTGRES_USER);
map.insert("POSTGRES_PASSWORD", POSTGRES_PASSWORD);
map.insert("POSTGRES_DB", POSTGRES_DB);
let db_url = format!(
"postgresql://{}:{}@localhost:5432/{}",
POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB
);
map.insert("DATABASE_URL", db_url.as_str());
map.insert("DATABASE_URL", db_url);

let mut file = File::create(".env")?;
for (var, value) in map.iter() {
println!("cargo::rustc-env={}={}", var, value);
writeln!(file, "{}={}", var, value).expect("Failed to write to dotenv file");
}

Ok(db_url)
Ok(())
}

async fn run_migrations(db_url: &str) -> Result<()> {
Expand Down
5 changes: 4 additions & 1 deletion nym-data-observatory/pg_up.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
source .env

# Launching a container in such a way that it's destroyed after you detach from the terminal:
docker compose up --abort-on-container-exit --remove-orphans
docker compose up

# docker exec -it nym-data-observatory-pg /bin/bash
# psql -U youruser -d yourdb

echo "Tearing down containers to have a clean slate"
docker compose down -v

0 comments on commit 487bf67

Please sign in to comment.