use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ColumnChangeType {
RenameColumn,
ModifyColumn,
NullabilityChanged,
DefaultChanged,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColumnChange {
pub change_type: ColumnChangeType,
pub table_name: String,
pub column_name: String,
pub new_column_name: Option<String>,
pub new_type: Option<String>,
pub nullable: Option<bool>,
pub default_value: Option<String>,
}
impl ColumnChange {
pub fn new(change_type: ColumnChangeType, table_name: String, column_name: String, value: String) -> Self {
let new_column_name = match change_type {
ColumnChangeType::RenameColumn => Some(value.clone()),
_ => None,
};
let new_type = match change_type {
ColumnChangeType::ModifyColumn => Some(value.clone()),
_ => None,
};
Self {
change_type,
table_name,
column_name,
new_column_name,
new_type,
nullable: None,
default_value: None,
}
}
pub fn with_nullable(mut self, nullable: bool) -> Self {
self.nullable = Some(nullable);
self
}
pub fn with_default(mut self, default: String) -> Self {
self.default_value = Some(default);
self
}
}
#[cfg(test)]
mod tests {
use super::{ColumnChange, ColumnChangeType};
#[test]
fn test_rename_column() {
let change = ColumnChange::new(
ColumnChangeType::RenameColumn,
"users".to_string(),
"old_name".to_string(),
"new_name".to_string(),
);
assert_eq!(change.table_name, "users");
assert_eq!(change.column_name, "old_name");
assert_eq!(change.new_column_name, Some("new_name".to_string()));
}
#[test]
fn test_modify_column() {
let change = ColumnChange::new(
ColumnChangeType::ModifyColumn,
"users".to_string(),
"age".to_string(),
"INT".to_string(),
);
assert_eq!(change.change_type, ColumnChangeType::ModifyColumn);
assert_eq!(change.table_name, "users");
assert_eq!(change.column_name, "age");
assert_eq!(change.new_type, Some("INT".to_string()));
}
#[test]
fn test_with_nullable() {
let change = ColumnChange::new(
ColumnChangeType::ModifyColumn,
"users".to_string(),
"email".to_string(),
"VARCHAR".to_string(),
)
.with_nullable(true);
assert_eq!(change.nullable, Some(true));
}
#[test]
fn test_with_default() {
let change = ColumnChange::new(
ColumnChangeType::ModifyColumn,
"users".to_string(),
"email".to_string(),
"DEFAULT".to_string(),
)
.with_default("test@default.com".to_string());
assert_eq!(change.default_value, Some("test@default.com".to_string()));
}
}