midas-migrate-cli 0.8.2

Do painless migration 🦀
Documentation
//! Phase 5 database schema CLI tests. Require a reachable Postgres server.

mod common;

use std::fs;
use std::sync::atomic::{
  AtomicU64,
  Ordering,
};

use predicates::prelude::*;

static COUNTER: AtomicU64 = AtomicU64::new(0);

fn admin_url() -> String {
  std::env::var("MIDAS_TEST_POSTGRES_URL")
    .unwrap_or_else(|_| "postgres://postgres:postgres@localhost:55432/postgres".to_string())
}

fn database_url(base: &str, name: &str) -> String {
  match base.rfind('/') {
    Some(index) => format!("{}{name}", &base[..=index]),
    None => format!("{base}/{name}"),
  }
}

#[test]
#[ignore = "requires a reachable Postgres server"]
fn db_create_from_schema_pull_round_trips() {
  let temp = assert_fs::TempDir::new().expect("temp dir");
  let name = format!(
    "midas_cli_phase5_{}_{}",
    std::process::id(),
    COUNTER.fetch_add(1, Ordering::Relaxed)
  );
  let url = database_url(&admin_url(), &name);
  let schema = temp.path().join("schema.toml");
  fs::write(
    &schema,
    "version = 1\n[project]\ndefault_schema = \"app\"\n[[schema]]\nname = \"app\"\n[[table]]\nschema = \"app\"\nname = \"widget\"\nprimary_key = [\"id\"]\n[[table.column]]\nname = \"id\"\ntype = \"bigint\"\nnullable = false\n",
  )
  .expect("write schema");

  common::run_midas(
    &[
      "--database",
      &url,
      "db",
      "create",
      "--from-schema",
      &schema.to_string_lossy(),
    ],
    temp.path(),
  )
  .success();

  let output = temp.path().join("pulled.toml");
  common::run_midas(
    &[
      "--database",
      &url,
      "db",
      "pull",
      "--schema",
      "app",
      "--output",
      &output.to_string_lossy(),
      "--force",
    ],
    temp.path(),
  )
  .success()
  .stdout(predicate::str::contains("table(s)"));

  common::run_midas(&["schema", "validate", &output.to_string_lossy()], temp.path()).success();

  let pulled = fs::read_to_string(&output).expect("pulled");
  assert!(pulled.contains("name = \"widget\""), "{pulled}");

  common::run_midas(
    &[
      "--database",
      &url,
      "db",
      "pull",
      "--schema",
      "app",
      "--output",
      &output.to_string_lossy(),
    ],
    temp.path(),
  )
  .failure()
  .stderr(predicate::str::contains("already exists"));

  common::run_midas(&["--database", &url, "db", "drop"], temp.path()).success();
}

#[test]
#[ignore = "requires a reachable Postgres server"]
fn db_push_applies_desired_schema() {
  let temp = assert_fs::TempDir::new().expect("temp dir");
  let name = format!(
    "midas_cli_push_{}_{}",
    std::process::id(),
    COUNTER.fetch_add(1, Ordering::Relaxed)
  );
  let url = database_url(&admin_url(), &name);
  let schema = temp.path().join("schema.toml");
  fs::write(
    &schema,
    "version = 1\n[project]\ndefault_schema = \"app\"\n[[schema]]\nname = \"app\"\n[[table]]\nschema = \"app\"\nname = \"widget\"\n[[table.column]]\nname = \"id\"\ntype = \"bigint\"\n",
  )
  .expect("write schema");
  common::run_midas(&["--database", &url, "db", "create"], temp.path()).success();
  common::run_midas(
    &[
      "--database",
      &url,
      "db",
      "push",
      &schema.to_string_lossy(),
      "--accept-data-loss",
    ],
    temp.path(),
  )
  .success();
  fs::write(
    &schema,
    "version = 1\n[project]\ndefault_schema = \"app\"\n[[schema]]\nname = \"app\"\n[[table]]\nschema = \"app\"\nname = \"widget\"\n[[table.column]]\nname = \"id\"\ntype = \"bigint\"\n[[table]]\nschema = \"app\"\nname = \"extra\"\n[[table.column]]\nname = \"id\"\ntype = \"bigint\"\n",
  )
  .expect("write schema");
  common::run_midas(
    &["--database", &url, "db", "push", &schema.to_string_lossy()],
    temp.path(),
  )
  .success();
  let output = temp.path().join("pulled.toml");
  common::run_midas(
    &[
      "--database",
      &url,
      "db",
      "pull",
      "--schema",
      "app",
      "--output",
      &output.to_string_lossy(),
      "--force",
    ],
    temp.path(),
  )
  .success();
  assert!(fs::read_to_string(output)
    .expect("pull")
    .contains("name = \"extra\""));
  common::run_midas(&["--database", &url, "db", "drop"], temp.path()).success();
}

#[test]
#[ignore = "requires a reachable Postgres server"]
fn migrate_dev_uses_shadow_database_and_detects_drift() {
  let temp = assert_fs::TempDir::new().expect("temp dir");
  let name = format!(
    "midas_cli_shadow_{}_{}",
    std::process::id(),
    COUNTER.fetch_add(1, Ordering::Relaxed)
  );
  let url = database_url(&admin_url(), &name);
  let schema = temp.path().join("schema.toml");
  fs::write(
    &schema,
    "version = 1\n[project]\ndefault_schema = \"public\"\n[[table]]\nname = \"widget\"\nprimary_key = [\"id\"]\n[[table.column]]\nname = \"id\"\ntype = \"bigint\"\nnullable = false\n",
  )
  .expect("write schema");
  fs::create_dir_all(temp.path().join("migrations")).expect("migrations");

  common::run_midas(&["--database", &url, "db", "create"], temp.path()).success();

  common::run_midas(
    &[
      "--database",
      &url,
      "--source",
      "migrations",
      "migrate",
      "dev",
      "--name",
      "init",
    ],
    temp.path(),
  )
  .success()
  .stdout(predicate::str::contains("Created migration"));

  common::run_midas(
    &["--database", &url, "--source", "migrations", "migrate", "dev"],
    temp.path(),
  )
  .success()
  .stdout(predicate::str::contains("No schema changes"));

  let config = midas::config::Config {
    database_url: Some(url.clone()),
    ..midas::config::Config::default()
  };
  let mut backend = midas::sequel::connect(&config).expect("connect");
  backend
    .execute_batch("alter table \"widget\" add column \"out_of_band\" text;")
    .expect("drift");

  common::run_midas(
    &["--database", &url, "--source", "migrations", "migrate", "dev"],
    temp.path(),
  )
  .failure()
  .stderr(predicate::str::contains("drift detected"));

  common::run_midas(
    &[
      "--database",
      &url,
      "--source",
      "migrations",
      "migrate",
      "dev",
      "--force",
      "--accept-data-loss",
      "--create-only",
    ],
    temp.path(),
  )
  .success();

  common::run_midas(&["--database", &url, "db", "drop"], temp.path()).success();
}

#[test]
#[ignore = "requires Postgres and sqlx-cli"]
fn db_create_from_schema_supports_sqlx_prepare() {
  let temp = assert_fs::TempDir::new().expect("temp dir");
  let name = format!(
    "midas_cli_sqlx_{}_{}",
    std::process::id(),
    COUNTER.fetch_add(1, Ordering::Relaxed)
  );
  let url = database_url(&admin_url(), &name);
  let schema = temp.path().join("schema.toml");
  fs::write(
    &schema,
    "version = 1\n[project]\ndefault_schema = \"public\"\n[[table]]\nname = \"widget\"\nprimary_key = [\"id\"]\n[[table.column]]\nname = \"id\"\ntype = \"bigint\"\nnullable = false\n",
  )
  .expect("write schema");
  common::run_midas(
    &[
      "--database",
      &url,
      "db",
      "create",
      "--from-schema",
      &schema.to_string_lossy(),
    ],
    temp.path(),
  )
  .success();

  fs::create_dir_all(temp.path().join("src")).expect("src");
  fs::write(
    temp.path().join("Cargo.toml"),
    "[package]\nname = \"sqlx_fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\nsqlx = { version = \"0.9\", features = [\"runtime-tokio\", \"postgres\", \"macros\"] }\ntokio = { version = \"1\", features = [\"macros\", \"rt-multi-thread\"] }\n",
  )
  .expect("manifest");
  fs::write(
    temp.path().join("src/main.rs"),
    "#[allow(dead_code)]\nasync fn row(pool: &sqlx::PgPool) -> sqlx::Result<i64> {\n  let record = sqlx::query!(\"select id from widget\").fetch_one(pool).await?;\n  Ok(record.id)\n}\n\nfn main() {}",
  )
  .expect("main");

  let output = std::process::Command::new("cargo")
    .args(["sqlx", "prepare"])
    .current_dir(temp.path())
    .env("DATABASE_URL", &url)
    .output()
    .expect("cargo sqlx prepare");
  assert!(
    output.status.success(),
    "prepare failed: {}",
    String::from_utf8_lossy(&output.stderr)
  );

  let check = std::process::Command::new("cargo")
    .args(["sqlx", "prepare", "--check"])
    .current_dir(temp.path())
    .env("DATABASE_URL", &url)
    .output()
    .expect("cargo sqlx prepare --check");
  assert!(
    check.status.success(),
    "check failed: {}{}",
    String::from_utf8_lossy(&check.stdout),
    String::from_utf8_lossy(&check.stderr)
  );

  common::run_midas(&["--database", &url, "db", "drop"], temp.path()).success();
  let _ = schema;
}