use super::traits::*;
use super::{DatabaseConfig, DatabaseType};
use crate::migrate::Migration;
use crate::schema::{CompositeType, Grant, Index, Role, Table, View};
use anyhow::Result;
use sqlx::{mysql::MySqlConnectOptions, MySqlPool, Row};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
pub struct MySQL {
name: String,
type_mapping: MySQLTypeMapping,
sql_generator: MySQLSqlGenerator,
introspector: MySQLIntrospector,
connection_manager: MySQLConnectionManager,
migration_manager: MySQLMigrationManager,
}
impl MySQL {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
type_mapping: MySQLTypeMapping,
sql_generator: MySQLSqlGenerator,
introspector: MySQLIntrospector {
_pool: Arc::new(MySqlPool::connect_lazy("mysql://mock").unwrap()),
},
connection_manager: MySQLConnectionManager,
migration_manager: MySQLMigrationManager,
}
}
}
impl Database for MySQL {
fn database_type(&self) -> DatabaseType {
DatabaseType::MySQL
}
fn name(&self) -> &str {
&self.name
}
fn type_mapping(&self) -> &dyn TypeMapping {
&self.type_mapping
}
fn sql_generator(&self) -> &dyn SqlGenerator {
&self.sql_generator
}
fn introspector(&self) -> &dyn Introspector {
&self.introspector
}
fn connection_manager(&self) -> &dyn ConnectionManager {
&self.connection_manager
}
fn migration_manager(&self) -> &dyn MigrationManager {
&self.migration_manager
}
}
pub struct MySQLTypeMapping;
impl TypeMapping for MySQLTypeMapping {
fn rust_to_sql_type(&self, rust_type: &str) -> String {
match rust_type {
"String" => "TEXT".to_string(),
"i32" => "INT".to_string(),
"i64" => "BIGINT".to_string(),
"f32" => "FLOAT".to_string(),
"f64" => "DOUBLE".to_string(),
"bool" => "BOOLEAN".to_string(),
"chrono::DateTime<chrono::Utc>" => "DATETIME".to_string(),
"chrono::NaiveDateTime" => "DATETIME".to_string(),
"chrono::NaiveDate" => "DATE".to_string(),
"chrono::NaiveTime" => "TIME".to_string(),
"uuid::Uuid" => "CHAR(36)".to_string(),
"rust_decimal::Decimal" => "DECIMAL(65,30)".to_string(),
"serde_json::Value" => "JSON".to_string(),
"Vec<u8>" => "BLOB".to_string(),
_ => "TEXT".to_string(), }
}
fn sql_to_rust_type(&self, sql_type: &str) -> String {
match sql_type.to_uppercase().as_str() {
"TEXT" | "VARCHAR" | "CHAR" | "TINYTEXT" | "MEDIUMTEXT" | "LONGTEXT" => {
"String".to_string()
}
"INT" | "INTEGER" | "TINYINT" | "SMALLINT" | "MEDIUMINT" => "i32".to_string(),
"BIGINT" => "i64".to_string(),
"FLOAT" => "f32".to_string(),
"DOUBLE" => "f64".to_string(),
"BOOLEAN" | "BOOL" | "TINYINT(1)" => "bool".to_string(),
"DATETIME" | "TIMESTAMP" => "chrono::NaiveDateTime".to_string(),
"DATE" => "chrono::NaiveDate".to_string(),
"TIME" => "chrono::NaiveTime".to_string(),
"DECIMAL" | "NUMERIC" => "rust_decimal::Decimal".to_string(),
"JSON" => "serde_json::Value".to_string(),
"BLOB" | "TINYBLOB" | "MEDIUMBLOB" | "LONGBLOB" => "Vec<u8>".to_string(),
_ => "String".to_string(), }
}
fn default_value(&self, sql_type: &str) -> Option<String> {
match sql_type.to_uppercase().as_str() {
"BOOLEAN" | "BOOL" | "TINYINT(1)" => Some("false".to_string()),
"INT" | "INTEGER" | "TINYINT" | "SMALLINT" | "MEDIUMINT" | "BIGINT" => {
Some("0".to_string())
}
"FLOAT" | "DOUBLE" => Some("0.0".to_string()),
"DATETIME" | "TIMESTAMP" => Some("NOW()".to_string()),
"DATE" => Some("CURDATE()".to_string()),
"TIME" => Some("CURTIME()".to_string()),
_ => None,
}
}
fn supports_auto_increment(&self, sql_type: &str) -> bool {
matches!(
sql_type.to_uppercase().as_str(),
"INT" | "BIGINT" | "INTEGER"
)
}
fn max_string_length(&self, sql_type: &str) -> Option<usize> {
match sql_type.to_uppercase().as_str() {
"VARCHAR" => Some(65535), "CHAR" => Some(255), "TINYTEXT" => Some(255),
"TEXT" => Some(65535),
"MEDIUMTEXT" => Some(16777215),
"LONGTEXT" => Some(4294967295),
_ => None,
}
}
}
pub struct MySQLSqlGenerator;
impl SqlGenerator for MySQLSqlGenerator {
fn create_table_sql(&self, table: &Table) -> String {
let table_name = if let Some(schema) = &table.schema {
format!("`{}`.`{}`", schema, table.name)
} else {
format!("`{}`", table.name)
};
let mut sql = format!("CREATE TABLE {} (\n", table_name);
for (i, column) in table.columns.iter().enumerate() {
if i > 0 {
sql.push_str(",\n");
}
let sql_type = match column.column_type {
crate::schema::ColumnType::Timestamptz => "DATETIME".to_string(),
_ => column.column_type.to_sql(),
};
sql.push_str(&format!(" `{}` {}", column.name, sql_type));
if !column.nullable {
sql.push_str(" NOT NULL");
}
if column.unique {
sql.push_str(" UNIQUE");
}
if let Some(default) = &column.default {
sql.push_str(&format!(" DEFAULT {}", default));
}
}
if let Some(primary_key) = &table.primary_key {
sql.push_str(&format!(",\n PRIMARY KEY (`{}`)", primary_key));
}
sql.push_str("\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
sql
}
fn create_view_sql(&self, view: &View) -> String {
format!(
"CREATE VIEW `{}` AS {}",
view.name,
view.ddl.as_ref().unwrap_or(&"".to_string())
)
}
fn create_index_sql(&self, index: &Index) -> String {
let unique = if index.unique { "UNIQUE " } else { "" };
let columns = index.columns.join("`, `");
format!(
"CREATE {}INDEX `{}` ON `{}` (`{}`)",
unique, index.name, "table_name", columns
)
}
fn create_type_sql(&self, _composite_type: &CompositeType) -> String {
"".to_string()
}
fn create_schema_sql(&self, schema_name: &str) -> String {
format!("CREATE DATABASE IF NOT EXISTS `{}`;", schema_name)
}
fn alter_table_sql(&self, table: &Table, changes: &[String]) -> String {
let mut sql = format!("ALTER TABLE `{}`", table.name);
for (i, change) in changes.iter().enumerate() {
if i > 0 {
sql.push_str(",");
}
sql.push_str(&format!(" {}", change));
}
sql.push_str(";");
sql
}
fn drop_table_sql(&self, table_name: &str) -> String {
format!("DROP TABLE IF EXISTS `{}`;", table_name)
}
fn drop_view_sql(&self, view_name: &str) -> String {
format!("DROP VIEW IF EXISTS `{}`;", view_name)
}
fn drop_index_sql(&self, index_name: &str) -> String {
format!("DROP INDEX `{}`;", index_name)
}
fn insert_sql(&self, table_name: &str, columns: &[String], values: &[String]) -> String {
let columns_str = columns
.iter()
.map(|c| format!("`{}`", c))
.collect::<Vec<_>>()
.join(", ");
let values_str = values.join(", ");
format!(
"INSERT INTO `{}` ({}) VALUES ({});",
table_name, columns_str, values_str
)
}
fn update_sql(&self, table_name: &str, set_clause: &str, where_clause: &str) -> String {
format!(
"UPDATE `{}` SET {} WHERE {};",
table_name, set_clause, where_clause
)
}
fn delete_sql(&self, table_name: &str, where_clause: &str) -> String {
format!("DELETE FROM `{}` WHERE {};", table_name, where_clause)
}
fn select_sql(
&self,
table_name: &str,
columns: &[String],
where_clause: Option<&str>,
) -> String {
let columns_str = if columns.is_empty() {
"*".to_string()
} else {
columns
.iter()
.map(|c| format!("`{}`", c))
.collect::<Vec<_>>()
.join(", ")
};
let mut sql = format!("SELECT {} FROM `{}`", columns_str, table_name);
if let Some(where_clause) = where_clause {
sql.push_str(&format!(" WHERE {}", where_clause));
}
sql.push_str(";");
sql
}
fn quote_identifier(&self, identifier: &str) -> String {
format!("`{}`", identifier)
}
fn quote_string(&self, value: &str) -> String {
format!("'{}'", value.replace("'", "''"))
}
fn current_timestamp_function(&self) -> &str {
"NOW()"
}
fn auto_increment_keyword(&self) -> &str {
"AUTO_INCREMENT"
}
fn create_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- Setting '{}' = '{}' would need to be implemented using MySQL system variables or application-level configuration.",
guc.name, guc.value
)
}
fn reset_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- Resetting '{}' would need to be implemented using MySQL system variables or application-level configuration.",
guc.name
)
}
fn get_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- Getting '{}' would need to be implemented using MySQL system variables or application-level configuration.",
guc.name
)
}
fn list_guc_settings_sql(&self) -> String {
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- GUC settings would need to be tracked using MySQL system variables or application-level configuration.".to_string()
}
fn set_jwt_context_sql(
&self,
user_id: &str,
tenant_id: Option<&str>,
role: Option<&str>,
) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- JWT context (user_id: '{}', tenant_id: {:?}, role: {:?}) would need to be implemented using MySQL system variables or application-level configuration.",
user_id, tenant_id, role
)
}
fn clear_jwt_context_sql(&self) -> String {
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- Clearing JWT context would need to be implemented using MySQL system variables or application-level configuration.".to_string()
}
}
impl MySQLSqlGenerator {
pub fn create_policy_sql(&self, _policy: &crate::schema::Policy) -> String {
"-- MySQL doesn't support RLS natively. Use application-level security instead.".to_string()
}
pub fn enable_rls_sql(&self, table_name: &str, _schema: Option<&str>) -> String {
format!("-- MySQL doesn't support RLS natively. Table `{}` would need application-level security.", table_name)
}
pub fn disable_rls_sql(&self, table_name: &str, _schema: Option<&str>) -> String {
format!("-- MySQL doesn't support RLS natively. Table `{}` would need application-level security.", table_name)
}
pub fn drop_policy_sql(&self, _policy: &crate::schema::Policy) -> String {
"-- MySQL doesn't support RLS natively. Use application-level security instead.".to_string()
}
pub fn create_extension_sql(&self, extension: &crate::schema::Extension) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style extensions natively.\n-- Extension '{}' would need to be implemented using MySQL plugins or application-level setup.",
extension.name
)
}
pub fn drop_extension_sql(&self, extension: &crate::schema::Extension) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style extensions natively.\n-- Extension '{}' would need to be removed using MySQL plugin management or application-level cleanup.",
extension.name
)
}
pub fn extension_exists_sql(&self, extension_name: &str) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style extensions natively.\n-- Extension '{}' existence would need to be checked using MySQL plugin management or application-level tracking.",
extension_name
)
}
pub fn list_extensions_sql(&self) -> String {
"-- MySQL doesn't support PostgreSQL-style extensions natively.\n-- Extensions would need to be tracked using MySQL plugin management or application-level tracking.".to_string()
}
pub fn create_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- Setting '{}' = '{}' would need to be implemented using MySQL system variables or application-level configuration.",
guc.name, guc.value
)
}
pub fn reset_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- Resetting '{}' would need to be implemented using MySQL system variables or application-level configuration.",
guc.name
)
}
pub fn get_guc_sql(&self, guc: &crate::schema::GucSetting) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- Getting '{}' would need to be implemented using MySQL system variables or application-level configuration.",
guc.name
)
}
pub fn list_guc_settings_sql(&self) -> String {
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- GUC settings would need to be tracked using MySQL system variables or application-level configuration.".to_string()
}
pub fn set_jwt_context_sql(
&self,
user_id: &str,
tenant_id: Option<&str>,
role: Option<&str>,
) -> String {
format!(
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- JWT context (user_id: '{}', tenant_id: {:?}, role: {:?}) would need to be implemented using MySQL system variables or application-level configuration.",
user_id, tenant_id, role
)
}
pub fn clear_jwt_context_sql(&self) -> String {
"-- MySQL doesn't support PostgreSQL-style GUC settings natively.\n-- Clearing JWT context would need to be implemented using MySQL system variables or application-level configuration.".to_string()
}
}
pub struct MySQLIntrospector {
_pool: Arc<MySqlPool>,
}
impl MySQLIntrospector {
pub fn new(pool: Arc<MySqlPool>) -> Self {
Self { _pool: pool }
}
async fn _get_primary_keys(&self) -> Result<HashMap<String, String>> {
let query = r#"
SELECT
TABLE_NAME,
GROUP_CONCAT(COLUMN_NAME ORDER BY ORDINAL_POSITION) as primary_key_columns
FROM information_schema.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = DATABASE()
AND CONSTRAINT_NAME = 'PRIMARY'
GROUP BY TABLE_NAME
"#;
let rows = sqlx::query(query).fetch_all(&*self._pool).await?;
let mut primary_keys = HashMap::new();
for row in rows {
let table_name: String = row.get("TABLE_NAME");
let pk_columns: String = row.get("primary_key_columns");
primary_keys.insert(table_name, pk_columns);
}
Ok(primary_keys)
}
fn _map_mysql_type_to_ignis_type(
&self,
mysql_type: &str,
_is_nullable: bool,
max_length: Option<i32>,
precision: Option<i32>,
scale: Option<i32>,
) -> crate::schema::ColumnType {
match mysql_type.to_lowercase().as_str() {
"int" | "integer" => crate::schema::ColumnType::Int4,
"bigint" => crate::schema::ColumnType::Int8,
"smallint" => crate::schema::ColumnType::Int2,
"tinyint" => crate::schema::ColumnType::Int2,
"mediumint" => crate::schema::ColumnType::Int4,
"text" => crate::schema::ColumnType::Text,
"longtext" => crate::schema::ColumnType::Text,
"mediumtext" => crate::schema::ColumnType::Text,
"tinytext" => crate::schema::ColumnType::Text,
"varchar" => {
if let Some(length) = max_length {
crate::schema::ColumnType::Varchar(Some(length as usize))
} else {
crate::schema::ColumnType::Varchar(None)
}
}
"char" => crate::schema::ColumnType::Char,
"boolean" | "bool" | "tinyint(1)" => crate::schema::ColumnType::Bool,
"datetime" => crate::schema::ColumnType::Timestamptz,
"timestamp" => crate::schema::ColumnType::Timestamptz,
"date" => crate::schema::ColumnType::Date,
"time" => crate::schema::ColumnType::Time,
"year" => crate::schema::ColumnType::Int2,
"decimal" | "numeric" => match (precision, scale) {
(Some(p), Some(s)) => {
crate::schema::ColumnType::Numeric(Some(p as usize), Some(s as usize))
}
(Some(p), None) => crate::schema::ColumnType::Numeric(Some(p as usize), None),
(None, Some(s)) => crate::schema::ColumnType::Numeric(None, Some(s as usize)),
(None, None) => crate::schema::ColumnType::Numeric(None, None),
},
"float" => crate::schema::ColumnType::Numeric(None, None),
"double" => crate::schema::ColumnType::Numeric(None, None),
"json" => crate::schema::ColumnType::Json,
"blob" | "longblob" | "mediumblob" | "tinyblob" => crate::schema::ColumnType::Text, "binary" | "varbinary" => crate::schema::ColumnType::Text, "enum" => crate::schema::ColumnType::Custom("ENUM".to_string()),
"set" => crate::schema::ColumnType::Custom("SET".to_string()),
custom => crate::schema::ColumnType::Custom(custom.to_string()),
}
}
}
impl Introspector for MySQLIntrospector {
fn get_tables(&self) -> Result<Vec<Table>> {
println!("🔍 MySQL introspection: Getting all tables (mock data)");
let mut tables = Vec::new();
let mut table = Table::new("products");
table = table.add_column(
crate::schema::Column::new("id", crate::schema::ColumnType::Int4).not_null(),
);
table = table.add_column(
crate::schema::Column::new("name", crate::schema::ColumnType::Varchar(Some(255)))
.not_null(),
);
table = table.add_column(
crate::schema::Column::new(
"price",
crate::schema::ColumnType::Numeric(Some(10), Some(2)),
)
.not_null(),
);
tables.push(table);
Ok(tables)
}
fn get_table(&self, table_name: &str) -> Result<Option<Table>> {
println!(
"🔍 MySQL introspection: Getting table '{}' (mock data)",
table_name
);
let mut table = Table::new(table_name);
table = table.add_column(
crate::schema::Column::new("id", crate::schema::ColumnType::Int4).not_null(),
);
table = table.add_column(
crate::schema::Column::new("name", crate::schema::ColumnType::Varchar(Some(255)))
.not_null(),
);
table = table.add_column(
crate::schema::Column::new(
"price",
crate::schema::ColumnType::Numeric(Some(10), Some(2)),
)
.not_null(),
);
Ok(Some(table))
}
fn get_views(&self) -> Result<Vec<View>> {
Ok(Vec::new())
}
fn get_view(&self, view_name: &str) -> Result<Option<View>> {
let views = self.get_views()?;
Ok(views.into_iter().find(|v| v.name == view_name))
}
fn get_indexes(&self) -> Result<Vec<Index>> {
Ok(Vec::new())
}
fn get_table_indexes(&self, _table_name: &str) -> Result<Vec<Index>> {
Ok(Vec::new())
}
fn get_composite_types(&self) -> Result<Vec<CompositeType>> {
Ok(vec![])
}
fn get_composite_type(&self, _type_name: &str) -> Result<Option<CompositeType>> {
Ok(None)
}
fn get_roles(&self) -> Result<Vec<Role>> {
Ok(Vec::new())
}
fn get_grants(&self) -> Result<Vec<Grant>> {
Ok(Vec::new())
}
fn get_schema_version(&self) -> Result<Option<String>> {
Ok(None)
}
fn table_exists(&self, _table_name: &str) -> Result<bool> {
Ok(false)
}
fn view_exists(&self, _view_name: &str) -> Result<bool> {
Ok(false)
}
fn index_exists(&self, _index_name: &str) -> Result<bool> {
Ok(false)
}
}
pub struct MySQLConnectionManager;
impl ConnectionManager for MySQLConnectionManager {
fn create_pool(&self, config: &DatabaseConfig) -> Result<Box<dyn ConnectionPool>> {
println!("🔧 Creating MySQL connection pool for: {}", config.database);
Ok(Box::new(MySQLConnectionPool {
pool: Arc::new(MySqlPool::connect_lazy("mysql://mock").unwrap()),
}))
}
fn test_connection(&self, config: &DatabaseConfig) -> Result<()> {
let connection_string = self.connection_string(config);
println!("🔍 Testing MySQL connection: {}", connection_string);
Ok(())
}
fn connection_string(&self, config: &DatabaseConfig) -> String {
format!(
"mysql://{}:{}@{}:{}/{}",
config.username, config.password, config.host, config.port, config.database
)
}
fn connection_options(&self, config: &DatabaseConfig) -> Result<Box<dyn std::fmt::Debug>> {
let connection_string = self.connection_string(config);
let options = MySqlConnectOptions::from_str(&connection_string)
.map_err(|e| anyhow::anyhow!("Failed to parse connection string: {}", e))?;
Ok(Box::new(options))
}
}
pub struct MySQLConnectionPool {
pool: Arc<MySqlPool>,
}
impl ConnectionPool for MySQLConnectionPool {
fn execute_query(
&self,
sql: &str,
params: &[&dyn std::fmt::Display],
) -> Result<Vec<HashMap<String, String>>> {
println!("🔍 Executing MySQL query: {}", sql);
println!("📊 Parameters: {} items", params.len());
let mut results = Vec::new();
let mut map = HashMap::new();
map.insert("version".to_string(), "MySQL 8.0.43".to_string());
results.push(map);
Ok(results)
}
fn execute_command(&self, sql: &str, params: &[&dyn std::fmt::Display]) -> Result<u64> {
println!("🔧 Executing MySQL command: {}", sql);
println!("📊 Parameters: {} items", params.len());
Ok(1)
}
fn begin_transaction(&self) -> Result<Box<dyn Transaction>> {
let _rt = tokio::runtime::Runtime::new()
.map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;
Ok(Box::new(MySQLTransaction {}))
}
fn active_connections(&self) -> u32 {
self.pool.size() as u32
}
fn max_connections(&self) -> u32 {
self.pool.options().get_max_connections() as u32
}
}
pub struct MySQLTransaction {
}
impl Transaction for MySQLTransaction {
fn execute_query(
&self,
_sql: &str,
_params: &[&dyn std::fmt::Display],
) -> Result<Vec<HashMap<String, String>>> {
Err(anyhow::anyhow!(
"Transaction query execution not implemented yet"
))
}
fn execute_command(&self, _sql: &str, _params: &[&dyn std::fmt::Display]) -> Result<u64> {
Err(anyhow::anyhow!(
"Transaction command execution not implemented yet"
))
}
fn commit(self: Box<Self>) -> Result<()> {
Ok(())
}
fn rollback(self: Box<Self>) -> Result<()> {
Ok(())
}
}
pub struct MySQLMigrationManager;
impl MigrationManager for MySQLMigrationManager {
fn get_applied_migrations(&self) -> Result<Vec<Migration>> {
Ok(vec![])
}
fn apply_migration(&self, _migration: &Migration) -> Result<()> {
Err(anyhow::anyhow!("Not implemented yet"))
}
fn rollback_migration(&self, _migration: &Migration) -> Result<()> {
Err(anyhow::anyhow!("Not implemented yet"))
}
fn is_migration_applied(&self, _migration_id: &str) -> Result<bool> {
Ok(false)
}
fn create_migrations_table(&self) -> Result<()> {
Err(anyhow::anyhow!("Not implemented yet"))
}
fn get_current_version(&self) -> Result<Option<String>> {
Ok(None)
}
fn set_schema_version(&self, _version: &str) -> Result<()> {
Err(anyhow::anyhow!("Not implemented yet"))
}
}