Migrate automatically on service start (#7103)

This avoids a forgettable manual step in deploying collab

Release Notes:

- N/A
This commit is contained in:
Conrad Irwin 2024-01-30 13:19:35 -07:00 committed by GitHub
parent 2e7f9c48bb
commit 911b4b5ae8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 24 additions and 65 deletions

View file

@ -28,49 +28,11 @@ async fn main() -> Result<()> {
Some("version") => {
println!("collab v{VERSION}");
}
Some("migrate") => {
let config = envy::from_env::<MigrateConfig>().expect("error loading config");
let mut db_options = db::ConnectOptions::new(config.database_url.clone());
db_options.max_connections(5);
let db = Database::new(db_options, Executor::Production).await?;
let migrations_path = config
.migrations_path
.as_deref()
.unwrap_or_else(|| Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")));
let migrations = db.migrate(&migrations_path, false).await?;
for (migration, duration) in migrations {
println!(
"Ran {} {} {:?}",
migration.version, migration.description, duration
);
}
return Ok(());
}
Some("serve") => {
let config = envy::from_env::<Config>().expect("error loading config");
init_tracing(&config);
if config.is_development() {
// sanity check database url so even if we deploy a busted ZED_ENVIRONMENT to production
// we do not run
if config.database_url != "postgres://postgres@localhost/zed" {
panic!("about to run development migrations on a non-development database?")
}
let migrations_path = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations"));
let db_options = db::ConnectOptions::new(config.database_url.clone());
let db = Database::new(db_options, Executor::Production).await?;
let migrations = db.migrate(&migrations_path, false).await?;
for (migration, duration) in migrations {
println!(
"Ran {} {} {:?}",
migration.version, migration.description, duration
);
}
}
run_migrations().await?;
let state = AppState::new(config).await?;
@ -116,6 +78,29 @@ async fn main() -> Result<()> {
Ok(())
}
async fn run_migrations() -> Result<()> {
let config = envy::from_env::<MigrateConfig>().expect("error loading config");
let db_options = db::ConnectOptions::new(config.database_url.clone());
let db = Database::new(db_options, Executor::Production).await?;
let migrations_path = config
.migrations_path
.as_deref()
.unwrap_or_else(|| Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/migrations")));
let migrations = db.migrate(&migrations_path, false).await?;
for (migration, duration) in migrations {
log::info!(
"Migrated {} {} {:?}",
migration.version,
migration.description,
duration
);
}
return Ok(());
}
async fn handle_root() -> String {
format!("collab v{VERSION}")
}