From 1dfbdeb8ed9fef41bc9eb37a6db14c312c5033b3 Mon Sep 17 00:00:00 2001 From: Denux Date: Sat, 7 Dec 2024 21:47:07 +0100 Subject: [PATCH] Added ability to seed via rust code --- src/db.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/db.rs b/src/db.rs index 1494d89d7..d2a9dff37 100644 --- a/src/db.rs +++ b/src/db.rs @@ -3,8 +3,6 @@ //! This module defines functions and operations related to the application's //! database interactions. -use std::{collections::HashMap, fs::File, io::Write, path::Path, sync::OnceLock, time::Duration}; - use chrono::{DateTime, Utc}; use duct::cmd; use fs_err::{self as fs, create_dir_all}; @@ -14,6 +12,8 @@ use sea_orm::{ DatabaseConnection, DbConn, EntityTrait, IntoActiveModel, Statement, }; use sea_orm_migration::MigratorTrait; +use std::future::Future; +use std::{collections::HashMap, fs::File, io::Write, path::Path, sync::OnceLock, time::Duration}; use tracing::info; use super::Result as AppResult; @@ -35,6 +35,16 @@ fn get_extract_db_name() -> &'static Regex { EXTRACT_DB_NAME.get_or_init(|| Regex::new(r"/([^/]+)$").unwrap()) } +/// A trait for seeding the database with initial data. +/// Seeders should be kept in `src/seeders`. +pub trait Seeder: Send + Sync { + /// The unique name of the seeder. + fn name(&self) -> String; + + /// Seeds the database with initial data. + fn seed(&self, db: &DatabaseConnection) -> impl Future>; +} + #[derive(Default, Clone, Debug)] pub struct MultiDb { pub db: HashMap, @@ -277,6 +287,15 @@ where Ok(()) } +/// Seed the database with the given Seeder. +/// +/// # Errors +/// +/// Returns an error if the seeder fails. +pub async fn seed_via_seeder(db: &DatabaseConnection, seeder: &impl Seeder) -> crate::Result<()> { + seeder.seed(db).await +} + /// Function to reset auto-increment /// # Errors /// Returns error if it fails