Skip to content

Commit

Permalink
remove dependency on sqlx command for build script
Browse files Browse the repository at this point in the history
  • Loading branch information
jgraef committed Jul 11, 2024
1 parent ee8e2e7 commit 8476aa0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 28 deletions.
4 changes: 4 additions & 0 deletions skunk-flow-store/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ serde_json = "1.0.120"
sqlx = { version = "0.7.4", features = ["chrono", "json", "macros", "migrate", "runtime-tokio", "sqlite", "uuid"] }
thiserror = "1.0.61"
uuid = "1.9.1"

[build-dependencies]
sqlx = { version = "0.7.4", features = ["migrate", "runtime-tokio", "sqlite"] }
tokio = { version = "1.37.0", features = ["macros", "rt"] }
60 changes: 32 additions & 28 deletions skunk-flow-store/build.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,43 @@
use std::{
path::PathBuf,
process::Command,
};
use std::path::PathBuf;

fn main() {
let crate_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
use sqlx::sqlite::SqliteConnectOptions;

#[tokio::main(flavor = "current_thread")]
async fn main() {
let crate_dir =
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set"));
let out_dir = PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR not set"));

let migrations_dir = crate_dir.join("migrations");
let db_file = out_dir.join("schema.db");
let db_url = format!("sqlite://{}", db_file.display());

println!("cargo::rerun-if-changed={}", migrations_dir.display());

// delete existing file
if db_file.exists() {
std::fs::remove_file(&db_file).unwrap();
}

std::fs::write(&db_file, b"").unwrap();

let exit_status = Command::new("sqlx")
.arg("migrate")
.arg("run")
.arg("--source")
.arg(&migrations_dir)
.arg("--database-url")
.arg(&db_url)
.spawn()
.unwrap()
.wait()
.unwrap();

if !exit_status.success() {
panic!("sqlx failed: {exit_status}");
std::fs::remove_file(&db_file).unwrap_or_else(|_| {
panic!(
"Failed to delete existing database file: {}",
db_file.display()
)
});
}

println!("cargo::rustc-env=DATABASE_URL={}", db_url,);
// create new database
let options = SqliteConnectOptions::new()
.filename(&db_file)
.create_if_missing(true);
let pool = sqlx::SqlitePool::connect_with(options)
.await
.unwrap_or_else(|_| panic!("Could not open database: {}", db_file.display()));
sqlx::migrate!("./migrations")
.run(&pool)
.await
.unwrap_or_else(|e| panic!("Failed to run migrations: {e}"));
pool.close().await;

println!(
"cargo::rustc-env=DATABASE_URL=sqlite://{}",
db_file.display()
);
}

0 comments on commit 8476aa0

Please sign in to comment.