use crate::backends::schema::{BaseDatabaseSchemaEditor, SchemaEditorError, SchemaEditorResult};
fn quote_sqlite_identifier(name: &str) -> String {
format!("\"{}\"", name.replace('"', "\"\""))
}
#[derive(Debug, Default, Clone)]
pub struct SQLiteSchemaEditor;
impl SQLiteSchemaEditor {
pub fn new() -> Self {
Self
}
pub fn alter_column_note(&self, table_name: &str) -> String {
format!(
"-- SQLite does not support ALTER COLUMN, table recreation required for {}",
quote_sqlite_identifier(table_name)
)
}
pub fn rename_table_sql(&self, old_name: &str, new_name: &str) -> String {
format!(
"ALTER TABLE {} RENAME TO {}",
quote_sqlite_identifier(old_name),
quote_sqlite_identifier(new_name)
)
}
pub fn add_constraint_note(&self, table_name: &str) -> String {
format!(
"-- SQLite does not support ADD CONSTRAINT, table recreation required for {}",
quote_sqlite_identifier(table_name)
)
}
pub fn drop_constraint_note(&self, table_name: &str) -> String {
format!(
"-- SQLite does not support DROP CONSTRAINT, table recreation required for {}",
quote_sqlite_identifier(table_name)
)
}
}
#[async_trait::async_trait]
impl BaseDatabaseSchemaEditor for SQLiteSchemaEditor {
fn database_type(&self) -> crate::backends::types::DatabaseType {
crate::backends::types::DatabaseType::Sqlite
}
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_note(table)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_alter_column_note() {
let editor = SQLiteSchemaEditor::new();
let sql = editor.alter_column_note("users");
assert!(sql.contains("SQLite does not support ALTER COLUMN"));
assert!(sql.contains("\"users\""));
}
#[test]
fn test_alter_column_statement() {
use crate::backends::schema::BaseDatabaseSchemaEditor;
let editor = SQLiteSchemaEditor::new();
let sql = editor.alter_column_statement("users", "email", "TEXT");
assert!(sql.contains("SQLite does not support ALTER COLUMN"));
assert!(sql.contains("table recreation required"));
assert!(sql.contains("\"users\""));
}
#[test]
fn test_rename_table_sql() {
let editor = SQLiteSchemaEditor::new();
let sql = editor.rename_table_sql("users", "people");
assert_eq!(sql, "ALTER TABLE \"users\" RENAME TO \"people\"");
}
#[test]
fn test_add_constraint_note() {
let editor = SQLiteSchemaEditor::new();
let sql = editor.add_constraint_note("users");
assert!(sql.contains("SQLite does not support ADD CONSTRAINT"));
assert!(sql.contains("\"users\""));
}
#[test]
fn test_drop_constraint_note() {
let editor = SQLiteSchemaEditor::new();
let sql = editor.drop_constraint_note("users");
assert!(sql.contains("SQLite does not support DROP CONSTRAINT"));
assert!(sql.contains("\"users\""));
}
}