Run migrations automatically on startup

Closes #21
This commit is contained in:
Jeremy Wall 2022-11-20 09:12:31 -05:00
parent f4e7c0cf63
commit 20db551090
4 changed files with 40 additions and 0 deletions

5
kitchen/build.rs Normal file
View File

@ -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");
}

22
kitchen/src/migrations.rs Normal file
View File

@ -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<SqlitePool>) {
sqlx::migrate!("./migrations")
.run(pool.as_ref())
.await
.expect("Unable to run migratins");
}

View File

@ -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))

View File

@ -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]