From bf1aeb7191bfaa75f1acf47c675bc68b9fac1cd8 Mon Sep 17 00:00:00 2001 From: fx Date: Sat, 21 Oct 2023 21:11:28 +0200 Subject: add migrate macro --- migrations/20231009123228_devices.sql | 4 ++-- src/db.rs | 21 --------------------- src/main.rs | 4 ++-- 3 files changed, 4 insertions(+), 25 deletions(-) diff --git a/migrations/20231009123228_devices.sql b/migrations/20231009123228_devices.sql index 5856c3a..9d0c7ca 100644 --- a/migrations/20231009123228_devices.sql +++ b/migrations/20231009123228_devices.sql @@ -1,7 +1,7 @@ -- Add migration script here -CREATE TABLE "devices" +CREATE TABLE IF NOT EXISTS "devices" ( "id" TEXT PRIMARY KEY NOT NULL, "mac" TEXT NOT NULL, "broadcast_addr" TEXT NOT NULL -) \ No newline at end of file +) diff --git a/src/db.rs b/src/db.rs index e9d001f..295780e 100644 --- a/src/db.rs +++ b/src/db.rs @@ -4,8 +4,6 @@ use serde::Serialize; use sqlx::{PgPool, postgres::PgPoolOptions}; use tracing::{debug, info}; -use crate::error::WebolError; - #[derive(Serialize)] pub struct Device { pub id: String, @@ -13,25 +11,6 @@ pub struct Device { pub broadcast_addr: String } -impl Device { - async fn init(db: &PgPool) -> Result<(), WebolError> { - sqlx::query!(r#" - CREATE TABLE IF NOT EXISTS "devices" - ( - "id" TEXT PRIMARY KEY NOT NULL, - "mac" TEXT NOT NULL, - "broadcast_addr" TEXT NOT NULL - );"# - ).execute(db).await.map_err(|err| WebolError::Server(Box::new(err)))?; - - Ok(()) - } -} - -pub async fn setup_db(db: &PgPool) -> Result<(), WebolError> { - Device::init(db).await -} - pub async fn init_db_pool() -> PgPool { #[cfg(not(debug_assertions))] let db_url = SETTINGS.get_string("database.url").unwrap(); diff --git a/src/main.rs b/src/main.rs index 8b4e9eb..ce12cf6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,7 +7,7 @@ use time::util::local_offset; use tracing::{info, level_filters::LevelFilter}; use tracing_subscriber::{EnvFilter, fmt::{self, time::LocalTime}, prelude::*}; use crate::config::SETTINGS; -use crate::db::{init_db_pool, setup_db}; +use crate::db::init_db_pool; use crate::routes::device::{get_device, post_device, put_device}; use crate::routes::start::start; @@ -41,7 +41,7 @@ async fn main() { info!("start webol v{}", version); let db = init_db_pool().await; - setup_db(&db).await.unwrap(); + sqlx::migrate!().run(&db).await.unwrap(); let shared_state = Arc::new(AppState { db }); -- cgit v1.2.3