diff --git a/kitchen/build.rs b/kitchen/build.rs new file mode 100644 index 0000000..7609593 --- /dev/null +++ b/kitchen/build.rs @@ -0,0 +1,5 @@ +// generated by `sqlx migrate build-script` +fn main() { + // trigger recompilation when a new migration is added + println!("cargo:rerun-if-changed=migrations"); +} \ No newline at end of file diff --git a/kitchen/src/migrations.rs b/kitchen/src/migrations.rs new file mode 100644 index 0000000..df9120f --- /dev/null +++ b/kitchen/src/migrations.rs @@ -0,0 +1,22 @@ +// Copyright 2022 Jeremy Wall (Jeremy@marzhilsltudios.com) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +use sqlx::{migrate, SqlitePool}; +use std::sync::Arc; + +pub async fn run_migration(pool: Arc) { + sqlx::migrate!("./migrations") + .run(pool.as_ref()) + .await + .expect("Unable to run migratins"); +} diff --git a/kitchen/src/web/mod.rs b/kitchen/src/web/mod.rs index 67bebba..650f920 100644 --- a/kitchen/src/web/mod.rs +++ b/kitchen/src/web/mod.rs @@ -326,6 +326,10 @@ pub async fn ui_main(recipe_dir_path: PathBuf, store_path: PathBuf, listen_socke .await .expect("Unable to create app_store"), ); + app_store + .run_migrations() + .await + .expect("Failed to run database migrations"); let router = Router::new() .route("/", get(|| async { Redirect::temporary("/ui/plan") })) .route("/ui/*path", get(ui_static_assets)) diff --git a/kitchen/src/web/storage/mod.rs b/kitchen/src/web/storage/mod.rs index 70422ee..68a9717 100644 --- a/kitchen/src/web/storage/mod.rs +++ b/kitchen/src/web/storage/mod.rs @@ -204,6 +204,15 @@ impl SqliteStore { let pool = Arc::new(sqlx::SqlitePool::connect_with(options).await?); Ok(Self { pool, url }) } + + #[instrument(fields(conn_string=self.url), skip_all)] + pub async fn run_migrations(&self) -> sqlx::Result<()> { + info!("Running databse migrations"); + sqlx::migrate!("./migrations") + .run(self.pool.as_ref()) + .await?; + Ok(()) + } } #[async_trait]