use crate::backends::schema::{BaseDatabaseSchemaEditor, SchemaEditorError, SchemaEditorResult};
fn quote_mysql_identifier(name: &str) -> String {
format!("`{}`", name.replace('`', "``"))
}
#[derive(Debug, Default, Clone)]
pub struct MySQLSchemaEditor;
impl MySQLSchemaEditor {
pub fn new() -> Self {
Self
}
pub fn alter_column_sql(&self, table_name: &str, column_name: &str, new_type: &str) -> String {
format!(
"ALTER TABLE {} MODIFY COLUMN {} {}",
quote_mysql_identifier(table_name),
quote_mysql_identifier(column_name),
new_type
)
}
pub fn rename_table_sql(&self, old_name: &str, new_name: &str) -> String {
format!(
"ALTER TABLE {} RENAME TO {}",
quote_mysql_identifier(old_name),
quote_mysql_identifier(new_name)
)
}
pub fn add_constraint_sql(&self, table_name: &str, constraint_sql: &str) -> String {
format!(
"ALTER TABLE {} ADD {}",
quote_mysql_identifier(table_name),
constraint_sql
)
}
pub fn drop_constraint_sql(&self, table_name: &str, constraint_name: &str) -> String {
format!(
"ALTER TABLE {} DROP CONSTRAINT {}",
quote_mysql_identifier(table_name),
quote_mysql_identifier(constraint_name)
)
}
}
#[async_trait::async_trait]
impl BaseDatabaseSchemaEditor for MySQLSchemaEditor {
fn database_type(&self) -> crate::backends::types::DatabaseType {
crate::backends::types::DatabaseType::Mysql
}
async fn execute(&mut self, _sql: &str) -> SchemaEditorResult<()> {
Err(SchemaEditorError::ExecutionError(
"Execution not supported in schema editor".to_string(),
))
}
fn alter_column_statement(&self, table: &str, column: &str, new_type: &str) -> String {
self.alter_column_sql(table, column, new_type)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_alter_column_sql() {
let editor = MySQLSchemaEditor::new();
let sql = editor.alter_column_sql("users", "email", "TEXT");
assert_eq!(sql, "ALTER TABLE `users` MODIFY COLUMN `email` TEXT");
}
#[test]
fn test_alter_column_statement() {
use crate::backends::schema::BaseDatabaseSchemaEditor;
let editor = MySQLSchemaEditor::new();
let sql = editor.alter_column_statement("users", "email", "TEXT");
assert_eq!(sql, "ALTER TABLE `users` MODIFY COLUMN `email` TEXT");
assert!(sql.contains("MODIFY COLUMN"));
assert!(!sql.contains("ALTER COLUMN"));
}
#[test]
fn test_rename_table_sql() {
let editor = MySQLSchemaEditor::new();
let sql = editor.rename_table_sql("users", "people");
assert_eq!(sql, "ALTER TABLE `users` RENAME TO `people`");
}
#[test]
fn test_add_constraint_sql() {
let editor = MySQLSchemaEditor::new();
let sql = editor.add_constraint_sql("users", "UNIQUE (email)");
assert_eq!(sql, "ALTER TABLE `users` ADD UNIQUE (email)");
}
#[test]
fn test_drop_constraint_sql() {
let editor = MySQLSchemaEditor::new();
let sql = editor.drop_constraint_sql("users", "unique_email");
assert_eq!(sql, "ALTER TABLE `users` DROP CONSTRAINT `unique_email`");
}
}