Archived
1
0
Fork 0

refac: add trait for upgrade and downgrade

This commit is contained in:
Dmitriy Pleshevskiy 2021-02-14 00:03:37 +03:00
parent 429b33f8d7
commit 481760ee6e
3 changed files with 19 additions and 9 deletions

View file

@ -1,5 +1,6 @@
use crate::config::Config; use crate::config::Config;
use crate::database::DatabaseConnection; use crate::database::DatabaseConnection;
use crate::migration::Downgrade;
use crate::StdResult; use crate::StdResult;
use std::convert::TryFrom; use std::convert::TryFrom;

View file

@ -1,5 +1,5 @@
use crate::database::DatabaseConnection; use crate::database::DatabaseConnection;
use crate::migration::Migration; use crate::migration::{Migration, Upgrade};
use crate::Config; use crate::Config;
use crate::StdResult; use crate::StdResult;
use std::convert::TryFrom; use std::convert::TryFrom;

View file

@ -1,8 +1,17 @@
use crate::database::DatabaseConnection; use crate::database::DatabaseConnection;
use crate::path::PathBuilder; use crate::path::PathBuilder;
use crate::StdResult;
use std::fs; use std::fs;
use std::path::PathBuf; use std::path::PathBuf;
pub trait Upgrade {
fn upgrade(&self, connection: &mut DatabaseConnection) -> StdResult<()>;
}
pub trait Downgrade {
fn downgrade(&self, connection: &mut DatabaseConnection) -> StdResult<()>;
}
#[derive(Debug)] #[derive(Debug)]
pub struct Migration { pub struct Migration {
upgrade_sql: PathBuf, upgrade_sql: PathBuf,
@ -31,15 +40,16 @@ impl Migration {
None None
} }
}
impl Migration {
pub fn name(&self) -> &String { pub fn name(&self) -> &String {
&self.name &self.name
} }
}
pub fn upgrade( impl Upgrade for Migration {
&self, fn upgrade(&self, connection: &mut DatabaseConnection) -> StdResult<()> {
connection: &mut DatabaseConnection,
) -> Result<(), Box<dyn std::error::Error + 'static>> {
let content = fs::read_to_string(&self.upgrade_sql)?; let content = fs::read_to_string(&self.upgrade_sql)?;
connection.create_migrations_table()?; connection.create_migrations_table()?;
@ -48,11 +58,10 @@ impl Migration {
Ok(()) Ok(())
} }
}
pub fn downgrade( impl Downgrade for Migration {
&self, fn downgrade(&self, connection: &mut DatabaseConnection) -> StdResult<()> {
connection: &mut DatabaseConnection,
) -> Result<(), Box<dyn std::error::Error + 'static>> {
let content = fs::read_to_string(&self.downgrade_sql)?; let content = fs::read_to_string(&self.downgrade_sql)?;
connection.apply_sql(&content)?; connection.apply_sql(&content)?;