Merge branch 'main' of https://github.com/Abeautifulsnow/dbx into feat/ai-agent-loop-phase1
This commit is contained in:
commit
84a9fd6a0f
34 files changed
+953
-31
No files matched your search
@@ -324,7 +324,10 @@ impl AppState {
|
||||
|
||||
let conns = self.connections.read().await;
|
||||
if conns.contains_key(&pool_key) {
|
||||
return Ok(pool_key);
|
||||
drop(conns);
|
||||
if !self.remove_stale_connection_pool(&pool_key).await {
|
||||
return Ok(pool_key);
|
||||
}
|
||||
} else {
|
||||
drop(conns);
|
||||
}
|
||||
@@ -675,6 +678,49 @@ impl AppState {
|
||||
Ok(("127.0.0.1".to_string(), local_port))
|
||||
}
|
||||
|
||||
async fn remove_stale_connection_pool(&self, pool_key: &str) -> bool {
|
||||
let stale = {
|
||||
let connections = self.connections.read().await;
|
||||
let Some(pool) = connections.get(pool_key) else {
|
||||
return false;
|
||||
};
|
||||
match pool {
|
||||
PoolKind::SqlServer(client) => {
|
||||
let client = client.clone();
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
match db::sqlserver::test_connection(&mut client).await {
|
||||
Ok(()) => false,
|
||||
Err(err) => {
|
||||
log::warn!("SQL Server connection pool '{pool_key}' is stale: {err}");
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
PoolKind::Redis(redis) => match db::redis_driver::test_connection(redis).await {
|
||||
Ok(()) => false,
|
||||
Err(err) => {
|
||||
log::warn!("Redis connection pool '{pool_key}' is stale: {err}");
|
||||
true
|
||||
}
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
|
||||
if !stale {
|
||||
return false;
|
||||
}
|
||||
|
||||
let removed = self.connections.write().await.remove(pool_key);
|
||||
if let Some(pool) = removed {
|
||||
close_pool_kind(pool).await;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn reconnect_pool(&self, connection_id: &str, database: Option<&str>) -> Result<String, String> {
|
||||
self.reconnect_pool_for_session(connection_id, database, None).await
|
||||
}
|
||||
|
||||
@@ -1717,8 +1717,13 @@ pub async fn list_indexes(pool: &MySqlPool, database: &str, table: &str) -> Resu
|
||||
pub async fn list_foreign_keys(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<ForeignKeyInfo>, String> {
|
||||
let sql = format!(
|
||||
"SELECT kcu.CONSTRAINT_NAME, kcu.COLUMN_NAME, \
|
||||
kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME \
|
||||
kcu.REFERENCED_TABLE_SCHEMA, kcu.REFERENCED_TABLE_NAME, kcu.REFERENCED_COLUMN_NAME, \
|
||||
rc.UPDATE_RULE, rc.DELETE_RULE \
|
||||
FROM information_schema.KEY_COLUMN_USAGE kcu \
|
||||
LEFT JOIN information_schema.REFERENTIAL_CONSTRAINTS rc \
|
||||
ON rc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA \
|
||||
AND rc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME \
|
||||
AND rc.TABLE_NAME = kcu.TABLE_NAME \
|
||||
WHERE kcu.TABLE_SCHEMA = {} AND kcu.TABLE_NAME = {} \
|
||||
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL \
|
||||
ORDER BY kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION",
|
||||
@@ -1737,13 +1742,15 @@ pub async fn list_foreign_keys(pool: &MySqlPool, database: &str, table: &str) ->
|
||||
ref_schema: Some(get_str_by_name(row, "REFERENCED_TABLE_SCHEMA")),
|
||||
ref_table: get_str_by_name(row, "REFERENCED_TABLE_NAME"),
|
||||
ref_column: get_str_by_name(row, "REFERENCED_COLUMN_NAME"),
|
||||
on_update: Some(get_str_by_name(row, "UPDATE_RULE")).filter(|value| !value.is_empty()),
|
||||
on_delete: Some(get_str_by_name(row, "DELETE_RULE")).filter(|value| !value.is_empty()),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn list_triggers(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<TriggerInfo>, String> {
|
||||
let sql = format!(
|
||||
"SELECT TRIGGER_NAME, EVENT_MANIPULATION, ACTION_TIMING \
|
||||
"SELECT TRIGGER_NAME, EVENT_MANIPULATION, ACTION_TIMING, ACTION_STATEMENT \
|
||||
FROM information_schema.TRIGGERS \
|
||||
WHERE TRIGGER_SCHEMA = {} AND EVENT_OBJECT_TABLE = {} \
|
||||
ORDER BY TRIGGER_NAME",
|
||||
@@ -1760,6 +1767,7 @@ pub async fn list_triggers(pool: &MySqlPool, database: &str, table: &str) -> Res
|
||||
name: get_str_by_name(row, "TRIGGER_NAME"),
|
||||
event: get_str_by_name(row, "EVENT_MANIPULATION"),
|
||||
timing: get_str_by_name(row, "ACTION_TIMING"),
|
||||
statement: Some(get_str_by_name(row, "ACTION_STATEMENT")).filter(|value| !value.is_empty()),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -237,6 +237,8 @@ pub async fn list_foreign_keys(
|
||||
ref_schema: Some(get_str(row, 2)),
|
||||
ref_table: get_str(row, 3),
|
||||
ref_column: get_str(row, 4),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -265,7 +267,7 @@ pub async fn list_triggers(pool: &mysql_async::Pool, schema: &str, table: &str)
|
||||
} else {
|
||||
"INSTEAD OF"
|
||||
};
|
||||
TriggerInfo { name: get_str(row, 0), event: get_str(row, 1), timing: timing.to_string() }
|
||||
TriggerInfo { name: get_str(row, 0), event: get_str(row, 1), timing: timing.to_string(), statement: None }
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -1803,6 +1803,8 @@ pub async fn list_foreign_keys(pool: &Pool, schema: &str, table: &str) -> Result
|
||||
ref_schema: Some(row.get::<_, String>(2)),
|
||||
ref_table: row.get::<_, String>(3),
|
||||
ref_column: row.get::<_, String>(4),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -1826,6 +1828,7 @@ pub async fn list_triggers(pool: &Pool, schema: &str, table: &str) -> Result<Vec
|
||||
name: row.get::<_, String>(0),
|
||||
event: row.get::<_, String>(1),
|
||||
timing: row.get::<_, String>(2),
|
||||
statement: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -237,6 +237,30 @@ pub async fn connect_cluster(config: &ConnectionConfig) -> Result<RedisClusterPo
|
||||
Err(last_error.unwrap_or_else(|| "Redis cluster connection failed".to_string()))
|
||||
}
|
||||
|
||||
pub async fn test_connection(connection: &RedisConnection) -> Result<(), String> {
|
||||
match connection {
|
||||
RedisConnection::Direct(con) => {
|
||||
let mut con = con.lock().await;
|
||||
redis_ping(&mut *con, "Redis").await
|
||||
}
|
||||
RedisConnection::Cluster(cluster) => {
|
||||
let mut con = cluster.connection.lock().await;
|
||||
redis_ping(&mut *con, "Redis cluster").await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn redis_ping<C>(con: &mut C, label: &str) -> Result<(), String>
|
||||
where
|
||||
C: ConnectionLike + Send + Sync + Unpin,
|
||||
{
|
||||
tokio::time::timeout(super::connection_timeout(), redis::cmd("PING").query_async::<String>(con))
|
||||
.await
|
||||
.map_err(|_| format!("{label} ping timed out ({}s)", super::CONNECTION_TIMEOUT_SECS))?
|
||||
.map(|_| ())
|
||||
.map_err(|e| format!("{label} ping failed: {e}"))
|
||||
}
|
||||
|
||||
fn redis_sentinel_nodes(config: &ConnectionConfig) -> Result<Vec<ConnectionInfo>, String> {
|
||||
let raw_nodes = config.redis_sentinel_nodes.trim();
|
||||
let endpoints: Vec<String> = if raw_nodes.is_empty() {
|
||||
|
||||
@@ -198,6 +198,8 @@ pub async fn list_foreign_keys(
|
||||
ref_schema: None,
|
||||
ref_table: value_by_column(&result.columns, &row, "table").unwrap_or_default(),
|
||||
ref_column: value_by_column(&result.columns, &row, "to").unwrap_or_default(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -234,6 +236,7 @@ pub async fn list_triggers(client: &RqliteClient, _schema: &str, table: &str) ->
|
||||
name: value_as_string(row.first()).unwrap_or_default(),
|
||||
event: event.to_string(),
|
||||
timing: timing.to_string(),
|
||||
statement: value_as_string(row.get(1)),
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
|
||||
@@ -455,6 +455,8 @@ pub async fn list_foreign_keys(pool: &SqliteHandle, _schema: &str, table: &str)
|
||||
ref_schema: None,
|
||||
ref_table: row.get("table")?,
|
||||
ref_column: row.get("to")?,
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
})
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
@@ -476,7 +478,7 @@ pub async fn list_triggers(pool: &SqliteHandle, _schema: &str, table: &str) -> R
|
||||
let rows = stmt
|
||||
.query_map([table], |row| {
|
||||
let sql_text: Option<String> = row.get("sql")?;
|
||||
let upper = sql_text.unwrap_or_default().to_uppercase();
|
||||
let upper = sql_text.clone().unwrap_or_default().to_uppercase();
|
||||
let timing = if upper.contains("BEFORE") {
|
||||
"BEFORE"
|
||||
} else if upper.contains("AFTER") {
|
||||
@@ -491,7 +493,12 @@ pub async fn list_triggers(pool: &SqliteHandle, _schema: &str, table: &str) -> R
|
||||
} else {
|
||||
"DELETE"
|
||||
};
|
||||
Ok(TriggerInfo { name: row.get("name")?, event: event.to_string(), timing: timing.to_string() })
|
||||
Ok(TriggerInfo {
|
||||
name: row.get("name")?,
|
||||
event: event.to_string(),
|
||||
timing: timing.to_string(),
|
||||
statement: sql_text,
|
||||
})
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
|
||||
|
||||
@@ -601,6 +601,12 @@ pub async fn list_databases(client: &mut SqlServerClient) -> Result<Vec<Database
|
||||
Ok(rows.iter().map(|row| DatabaseInfo { name: row.get::<&str, _>(0).unwrap_or("").to_string() }).collect())
|
||||
}
|
||||
|
||||
pub async fn test_connection(client: &mut SqlServerClient) -> Result<(), String> {
|
||||
let stream = client.simple_query("SELECT 1").await.map_err(|e| e.to_string())?;
|
||||
let _ = stream.into_first_result().await.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn list_schemas(client: &mut SqlServerClient) -> Result<Vec<String>, String> {
|
||||
let stream = client
|
||||
.query(
|
||||
@@ -891,6 +897,8 @@ pub async fn list_foreign_keys(
|
||||
ref_schema: Some(row.get::<&str, _>(2).unwrap_or("").to_string()),
|
||||
ref_table: row.get::<&str, _>(3).unwrap_or("").to_string(),
|
||||
ref_column: row.get::<&str, _>(4).unwrap_or("").to_string(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -940,6 +948,7 @@ pub async fn list_triggers(
|
||||
name: row.get::<&str, _>(0).unwrap_or("").to_string(),
|
||||
event: row.get::<&str, _>(1).unwrap_or("").to_string(),
|
||||
timing: row.get::<&str, _>(2).unwrap_or("AFTER").to_string(),
|
||||
statement: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -237,6 +237,8 @@ pub async fn list_foreign_keys(
|
||||
ref_schema: None,
|
||||
ref_table: value_by_column(&result.columns, &row, "table").unwrap_or_default(),
|
||||
ref_column: value_by_column(&result.columns, &row, "to").unwrap_or_default(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -273,6 +275,7 @@ pub async fn list_triggers(client: &TursoClient, _schema: &str, table: &str) ->
|
||||
name: value_as_string(row.first()).unwrap_or_default(),
|
||||
event: event.to_string(),
|
||||
timing: timing.to_string(),
|
||||
statement: value_as_string(row.get(1)),
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
|
||||
@@ -3,10 +3,15 @@ use crate::db::redis_driver::{
|
||||
self, RedisCommandResult, RedisConnection, RedisDatabaseInfo, RedisScanResult, RedisValue,
|
||||
};
|
||||
|
||||
async fn ensure_redis_pool(state: &AppState, connection_id: &str) -> Result<(), String> {
|
||||
state.get_or_create_pool(connection_id, None).await.map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn redis_list_databases_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
) -> Result<Vec<RedisDatabaseInfo>, String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
@@ -29,6 +34,7 @@ pub async fn redis_scan_keys_core(
|
||||
pattern: &str,
|
||||
count: usize,
|
||||
) -> Result<RedisScanResult, String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
@@ -57,6 +63,7 @@ pub async fn redis_scan_values_core(
|
||||
include_key_matches: bool,
|
||||
count: usize,
|
||||
) -> Result<RedisScanResult, String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
@@ -86,6 +93,7 @@ pub async fn redis_get_value_in_db_core(
|
||||
db: u32,
|
||||
key_raw: &str,
|
||||
) -> Result<RedisValue, String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
@@ -126,6 +134,7 @@ pub async fn redis_set_string_in_db_core(
|
||||
value: &str,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
@@ -158,6 +167,7 @@ pub async fn redis_delete_key_in_db_core(
|
||||
db: u32,
|
||||
key_raw: &str,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
let pool = connections.get(connection_id).ok_or("Connection not found")?;
|
||||
match pool {
|
||||
@@ -200,6 +210,7 @@ pub async fn redis_hash_set_in_db_core(
|
||||
value: &str,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -232,6 +243,7 @@ pub async fn redis_hash_del_in_db_core(
|
||||
key_raw: &str,
|
||||
field: &str,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -271,6 +283,7 @@ pub async fn redis_list_push_in_db_core(
|
||||
value: &str,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -300,6 +313,7 @@ pub async fn redis_list_set_in_db_core(
|
||||
index: i64,
|
||||
value: &str,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -337,6 +351,7 @@ pub async fn redis_list_remove_in_db_core(
|
||||
key_raw: &str,
|
||||
index: i64,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -376,6 +391,7 @@ pub async fn redis_set_add_in_db_core(
|
||||
member: &str,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -413,6 +429,7 @@ pub async fn redis_set_remove_in_db_core(
|
||||
key_raw: &str,
|
||||
member: &str,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -443,6 +460,7 @@ pub async fn redis_zadd_in_db_core(
|
||||
score: f64,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -471,6 +489,7 @@ pub async fn redis_zrem_in_db_core(
|
||||
key_raw: &str,
|
||||
member: &str,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -501,6 +520,7 @@ pub async fn redis_stream_add_in_db_core(
|
||||
fields: Vec<(String, String)>,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -530,6 +550,7 @@ pub async fn redis_json_set_in_db_core(
|
||||
value: &str,
|
||||
ttl: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -556,6 +577,7 @@ pub async fn redis_check_json_module_in_db_core(
|
||||
connection_id: &str,
|
||||
db: u32,
|
||||
) -> Result<bool, String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => match redis {
|
||||
@@ -581,6 +603,7 @@ pub async fn redis_set_ttl_in_db_core(
|
||||
key_raw: &str,
|
||||
ttl: i64,
|
||||
) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -608,6 +631,7 @@ pub async fn redis_delete_keys_in_db_core(
|
||||
db: u32,
|
||||
key_raws: &[String],
|
||||
) -> Result<u64, String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
@@ -636,6 +660,7 @@ pub async fn redis_delete_keys_in_db_core(
|
||||
}
|
||||
|
||||
pub async fn redis_flush_db_core(state: &AppState, connection_id: &str, db: u32) -> Result<(), String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => match redis {
|
||||
@@ -660,6 +685,7 @@ pub async fn redis_execute_command_core(
|
||||
command: &str,
|
||||
skip_safety_check: bool,
|
||||
) -> Result<RedisCommandResult, String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => match redis {
|
||||
@@ -692,6 +718,7 @@ pub async fn redis_load_more_in_db_core(
|
||||
cursor: u64,
|
||||
count: usize,
|
||||
) -> Result<redis_driver::RedisValue, String> {
|
||||
ensure_redis_pool(state, connection_id).await?;
|
||||
let connections = state.connections.read().await;
|
||||
match connections.get(connection_id).ok_or("Not found")? {
|
||||
PoolKind::Redis(redis) => {
|
||||
|
||||
@@ -884,6 +884,8 @@ mod tests {
|
||||
ref_schema: overrides.ref_schema,
|
||||
ref_table: if overrides.ref_table.is_empty() { "users".to_string() } else { overrides.ref_table },
|
||||
ref_column: if overrides.ref_column.is_empty() { "id".to_string() } else { overrides.ref_column },
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -942,6 +944,8 @@ mod tests {
|
||||
ref_schema: None,
|
||||
ref_table: String::new(),
|
||||
ref_column: String::new(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
}),
|
||||
foreign_key(ForeignKeyInfo {
|
||||
name: "orders_account_id_fk".to_string(),
|
||||
@@ -949,6 +953,8 @@ mod tests {
|
||||
ref_schema: None,
|
||||
ref_table: "accounts".to_string(),
|
||||
ref_column: String::new(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
}),
|
||||
],
|
||||
&[
|
||||
@@ -958,6 +964,8 @@ mod tests {
|
||||
ref_schema: None,
|
||||
ref_table: "members".to_string(),
|
||||
ref_column: String::new(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
}),
|
||||
foreign_key(ForeignKeyInfo {
|
||||
name: "orders_region_id_fk".to_string(),
|
||||
@@ -965,6 +973,8 @@ mod tests {
|
||||
ref_schema: None,
|
||||
ref_table: "regions".to_string(),
|
||||
ref_column: String::new(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
}),
|
||||
],
|
||||
);
|
||||
@@ -1012,6 +1022,8 @@ mod tests {
|
||||
ref_schema: None,
|
||||
ref_table: "users".to_string(),
|
||||
ref_column: String::new(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
})),
|
||||
target: None,
|
||||
changes: Vec::new(),
|
||||
|
||||
@@ -4,7 +4,9 @@ mod columns;
|
||||
mod comments;
|
||||
mod create_table;
|
||||
mod dialect;
|
||||
mod foreign_keys;
|
||||
mod indexes;
|
||||
mod triggers;
|
||||
mod types;
|
||||
mod util;
|
||||
mod validation;
|
||||
@@ -18,13 +20,17 @@ pub use types::*;
|
||||
|
||||
use columns::build_column_sql;
|
||||
use comments::build_table_comment_sql;
|
||||
use foreign_keys::build_foreign_key_sql;
|
||||
use indexes::build_index_sql;
|
||||
use triggers::build_trigger_sql;
|
||||
use validation::validate_draft;
|
||||
|
||||
pub fn build_table_structure_change_sql(options: TableStructureSqlOptions) -> TableStructureSqlResult {
|
||||
let mut warnings = validate_draft(&options);
|
||||
let mut statements = build_column_sql(&options, &mut warnings);
|
||||
statements.extend(build_index_sql(&options, &mut warnings));
|
||||
statements.extend(build_foreign_key_sql(&options, &mut warnings));
|
||||
statements.extend(build_trigger_sql(&options, &mut warnings));
|
||||
statements.extend(build_table_comment_sql(&options, &mut warnings));
|
||||
TableStructureSqlResult { statements, warnings }
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
use super::column_format::{column_data_type, column_extra_clause};
|
||||
use super::comments::{build_sqlserver_column_comment_sql, build_sqlserver_table_comment_sql};
|
||||
use super::dialect::{capabilities_for, database_label, StructureDialect};
|
||||
use super::foreign_keys::build_foreign_key_sql;
|
||||
use super::indexes::build_create_index_statements;
|
||||
use super::triggers::build_trigger_sql;
|
||||
use super::types::{TableStructureSqlOptions, TableStructureSqlResult};
|
||||
use super::util::{clean, format_default_for_sql, normalize_default, qualified_table, quote_ident, quote_string};
|
||||
use super::validation::validate_columns;
|
||||
@@ -136,5 +138,8 @@ pub fn build_create_table_sql(options: TableStructureSqlOptions) -> TableStructu
|
||||
));
|
||||
}
|
||||
|
||||
statements.extend(build_foreign_key_sql(&options, &mut warnings));
|
||||
statements.extend(build_trigger_sql(&options, &mut warnings));
|
||||
|
||||
TableStructureSqlResult { statements, warnings }
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
use super::dialect::{database_label, StructureDialect};
|
||||
use super::types::{EditableStructureForeignKey, ForeignKeyInfo, TableStructureSqlOptions};
|
||||
use super::util::{clean, qualified_table, quote_ident};
|
||||
|
||||
pub(super) fn build_foreign_key_sql(options: &TableStructureSqlOptions, warnings: &mut Vec<String>) -> Vec<String> {
|
||||
if options.foreign_keys.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let database_label = database_label(options.database_type);
|
||||
if super::dialect::capabilities_for(options.database_type).dialect != StructureDialect::Mysql {
|
||||
warnings.push(format!("Editing foreign keys is not supported for {database_label} from this editor."));
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let table = qualified_table(StructureDialect::Mysql, options.schema.as_deref(), &options.table_name);
|
||||
let mut statements = Vec::new();
|
||||
|
||||
for foreign_key in &options.foreign_keys {
|
||||
if foreign_key.marked_for_drop {
|
||||
if let Some(original) = &foreign_key.original {
|
||||
statements.push(drop_foreign_key_sql(&table, &original.name));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(original) = &foreign_key.original {
|
||||
if !has_foreign_key_change(foreign_key, original) {
|
||||
continue;
|
||||
}
|
||||
statements.push(drop_foreign_key_sql(&table, &original.name));
|
||||
}
|
||||
|
||||
if let Some(sql) = create_foreign_key_sql(&table, foreign_key, warnings) {
|
||||
statements.push(sql);
|
||||
}
|
||||
}
|
||||
|
||||
statements
|
||||
}
|
||||
|
||||
fn has_foreign_key_change(foreign_key: &EditableStructureForeignKey, original: &ForeignKeyInfo) -> bool {
|
||||
clean(&foreign_key.name) != clean(&original.name)
|
||||
|| clean(&foreign_key.column) != clean(&original.column)
|
||||
|| clean(&foreign_key.ref_schema) != clean(original.ref_schema.as_deref().unwrap_or(""))
|
||||
|| clean(&foreign_key.ref_table) != clean(&original.ref_table)
|
||||
|| clean(&foreign_key.ref_column) != clean(&original.ref_column)
|
||||
|| normalize_action(&foreign_key.on_update) != normalize_action(original.on_update.as_deref().unwrap_or(""))
|
||||
|| normalize_action(&foreign_key.on_delete) != normalize_action(original.on_delete.as_deref().unwrap_or(""))
|
||||
}
|
||||
|
||||
fn drop_foreign_key_sql(table: &str, name: &str) -> String {
|
||||
format!("ALTER TABLE {table} DROP FOREIGN KEY {};", quote_ident(StructureDialect::Mysql, name))
|
||||
}
|
||||
|
||||
fn create_foreign_key_sql(
|
||||
table: &str,
|
||||
foreign_key: &EditableStructureForeignKey,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> Option<String> {
|
||||
let name = clean(&foreign_key.name);
|
||||
let columns = identifier_list(&foreign_key.column);
|
||||
let ref_table = clean(&foreign_key.ref_table);
|
||||
let ref_columns = identifier_list(&foreign_key.ref_column);
|
||||
if name.is_empty() || columns.is_empty() || ref_table.is_empty() || ref_columns.is_empty() {
|
||||
warnings.push("Foreign key name, column, referenced table, and referenced column are required.".to_string());
|
||||
return None;
|
||||
}
|
||||
if columns.len() != ref_columns.len() {
|
||||
warnings.push(format!("Foreign key \"{name}\" must have the same number of local and referenced columns."));
|
||||
return None;
|
||||
}
|
||||
|
||||
let ref_target = if clean(&foreign_key.ref_schema).is_empty() {
|
||||
quote_ident(StructureDialect::Mysql, &ref_table)
|
||||
} else {
|
||||
format!(
|
||||
"{}.{}",
|
||||
quote_ident(StructureDialect::Mysql, &foreign_key.ref_schema),
|
||||
quote_ident(StructureDialect::Mysql, &ref_table)
|
||||
)
|
||||
};
|
||||
|
||||
let mut sql = format!(
|
||||
"ALTER TABLE {table} ADD CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {ref_target} ({}",
|
||||
quote_ident(StructureDialect::Mysql, &name),
|
||||
columns.iter().map(|column| quote_ident(StructureDialect::Mysql, column)).collect::<Vec<_>>().join(", "),
|
||||
ref_columns.iter().map(|column| quote_ident(StructureDialect::Mysql, column)).collect::<Vec<_>>().join(", ")
|
||||
);
|
||||
sql.push(')');
|
||||
|
||||
if let Some(action) = action_clause("ON DELETE", &foreign_key.on_delete, warnings) {
|
||||
sql.push(' ');
|
||||
sql.push_str(&action);
|
||||
}
|
||||
if let Some(action) = action_clause("ON UPDATE", &foreign_key.on_update, warnings) {
|
||||
sql.push(' ');
|
||||
sql.push_str(&action);
|
||||
}
|
||||
sql.push(';');
|
||||
Some(sql)
|
||||
}
|
||||
|
||||
fn action_clause(prefix: &str, value: &str, warnings: &mut Vec<String>) -> Option<String> {
|
||||
let action = normalize_action(value);
|
||||
if action.is_empty() {
|
||||
return None;
|
||||
}
|
||||
match action.as_str() {
|
||||
"CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" => Some(format!("{prefix} {action}")),
|
||||
_ => {
|
||||
warnings.push(format!("Unsupported foreign key action \"{}\".", clean(value)));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_action(value: &str) -> String {
|
||||
clean(value).split_whitespace().collect::<Vec<_>>().join(" ").to_ascii_uppercase()
|
||||
}
|
||||
|
||||
fn identifier_list(value: &str) -> Vec<String> {
|
||||
value.split(',').map(clean).filter(|value| !value.is_empty()).collect()
|
||||
}
|
||||
@@ -33,6 +33,33 @@ fn index(name: &str, columns: &[&str]) -> EditableStructureIndex {
|
||||
}
|
||||
}
|
||||
|
||||
fn foreign_key(name: &str, column: &str, ref_table: &str, ref_column: &str) -> EditableStructureForeignKey {
|
||||
EditableStructureForeignKey {
|
||||
id: name.to_string(),
|
||||
name: name.to_string(),
|
||||
column: column.to_string(),
|
||||
ref_schema: String::new(),
|
||||
ref_table: ref_table.to_string(),
|
||||
ref_column: ref_column.to_string(),
|
||||
on_update: String::new(),
|
||||
on_delete: String::new(),
|
||||
original: None,
|
||||
marked_for_drop: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn trigger(name: &str, timing: &str, event: &str, statement: &str) -> EditableStructureTrigger {
|
||||
EditableStructureTrigger {
|
||||
id: name.to_string(),
|
||||
name: name.to_string(),
|
||||
timing: timing.to_string(),
|
||||
event: event.to_string(),
|
||||
statement: statement.to_string(),
|
||||
original: None,
|
||||
marked_for_drop: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_mysql_column_and_index_changes() {
|
||||
let mut renamed = column("display_name");
|
||||
@@ -72,6 +99,8 @@ fn builds_mysql_column_and_index_changes() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![renamed, email],
|
||||
indexes: vec![old_index, email_index],
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -100,6 +129,8 @@ fn mysql_add_timestamp_column_drops_invalid_precision() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![created_at],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -123,6 +154,8 @@ fn mysql_add_timestamp_column_preserves_valid_precision() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![created_at],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -153,6 +186,8 @@ fn builds_postgres_create_table_with_comments_and_index() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![id, name],
|
||||
indexes: vec![idx],
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -189,6 +224,8 @@ fn warns_for_sqlite_unsafe_column_changes() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -214,6 +251,8 @@ fn builds_rqlite_changes_with_sqlite_dialect() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![email],
|
||||
indexes: vec![email_index],
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -277,6 +316,8 @@ fn builds_mysql_column_reorder_statements() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![id, email, name],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -303,6 +344,8 @@ fn builds_sql_server_quoted_column_and_index_statements() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![email],
|
||||
indexes: vec![index("idx_users_email", &["email"])],
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -333,6 +376,8 @@ fn builds_duckdb_create_table_statements() {
|
||||
table_name: "events".to_string(),
|
||||
columns: vec![name, created_at],
|
||||
indexes: vec![index("idx_events_name", &["name"])],
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -373,6 +418,8 @@ fn builds_clickhouse_nullable_comment_and_reorder_statements() {
|
||||
table_name: "events".to_string(),
|
||||
columns: vec![source, status],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -414,6 +461,8 @@ fn builds_h2_schema_qualified_existing_column_statements() {
|
||||
table_name: "USERS".to_string(),
|
||||
columns: vec![name],
|
||||
indexes: vec![index("IDX_USERS_DISPLAY_NAME", &["DISPLAY_NAME"])],
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -454,6 +503,8 @@ fn builds_postgres_alter_table_add_primary_key() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![id],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -484,6 +535,8 @@ fn builds_postgres_alter_table_drop_primary_key() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![id],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -530,6 +583,8 @@ fn builds_mysql_alter_table_change_primary_key() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![old_pk, new_pk],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -563,6 +618,8 @@ fn builds_no_statements_when_primary_key_unchanged() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![id],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -593,6 +650,8 @@ fn warns_sqlite_cannot_alter_primary_key() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![id],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -616,6 +675,8 @@ fn mysql_create_table_with_auto_increment() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -639,6 +700,8 @@ fn mysql_create_table_with_on_update_current_timestamp() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -664,6 +727,8 @@ fn postgres_create_table_with_identity() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -689,6 +754,8 @@ fn sqlserver_create_table_with_identity() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -709,6 +776,8 @@ fn mysql_quotes_datetime_literal_default() {
|
||||
table_name: "events".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -729,6 +798,8 @@ fn mysql_does_not_quote_current_timestamp() {
|
||||
table_name: "events".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -750,6 +821,8 @@ fn mysql_does_not_quote_temporal_function_with_parens() {
|
||||
table_name: "events".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -770,6 +843,8 @@ fn mysql_date_literal_default_is_quoted() {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -790,6 +865,8 @@ fn mysql_time_literal_default_is_quoted() {
|
||||
table_name: "shifts".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -810,6 +887,8 @@ fn non_temporal_types_are_not_quoted() {
|
||||
table_name: "games".to_string(),
|
||||
columns: vec![col],
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
@@ -868,3 +947,109 @@ fn mysql_single_column_alter_quotes_datetime_literal() {
|
||||
|
||||
assert!(result.statements.iter().any(|s| s.contains("DEFAULT '2024-01-01 00:00:00'")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_mysql_foreign_key_changes() {
|
||||
let mut existing = foreign_key("fk_orders_users", "user_id", "users", "id");
|
||||
existing.on_delete = "CASCADE".to_string();
|
||||
existing.original = Some(ForeignKeyInfo {
|
||||
name: "fk_orders_users_old".to_string(),
|
||||
column: "customer_id".to_string(),
|
||||
ref_schema: None,
|
||||
ref_table: "customers".to_string(),
|
||||
ref_column: "id".to_string(),
|
||||
on_update: None,
|
||||
on_delete: Some("RESTRICT".to_string()),
|
||||
});
|
||||
|
||||
let mut dropped = foreign_key("fk_orders_accounts", "account_id", "accounts", "id");
|
||||
dropped.marked_for_drop = true;
|
||||
dropped.original = Some(ForeignKeyInfo {
|
||||
name: "fk_orders_accounts".to_string(),
|
||||
column: "account_id".to_string(),
|
||||
ref_schema: None,
|
||||
ref_table: "accounts".to_string(),
|
||||
ref_column: "id".to_string(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
});
|
||||
|
||||
let result = build_table_structure_change_sql(TableStructureSqlOptions {
|
||||
database_type: Some(DatabaseType::Mysql),
|
||||
schema: None,
|
||||
table_name: "orders".to_string(),
|
||||
columns: Vec::new(),
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: vec![existing, dropped],
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
|
||||
assert_eq!(result.warnings, Vec::<String>::new());
|
||||
assert_eq!(
|
||||
result.statements,
|
||||
vec![
|
||||
"ALTER TABLE `orders` DROP FOREIGN KEY `fk_orders_users_old`;",
|
||||
"ALTER TABLE `orders` ADD CONSTRAINT `fk_orders_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;",
|
||||
"ALTER TABLE `orders` DROP FOREIGN KEY `fk_orders_accounts`;",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_mysql_composite_foreign_key() {
|
||||
let composite = foreign_key("fk_order_items_product", "tenant_id, product_id", "products", "tenant_id, id");
|
||||
|
||||
let result = build_table_structure_change_sql(TableStructureSqlOptions {
|
||||
database_type: Some(DatabaseType::Mysql),
|
||||
schema: None,
|
||||
table_name: "order_items".to_string(),
|
||||
columns: Vec::new(),
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: vec![composite],
|
||||
triggers: Vec::new(),
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
|
||||
assert_eq!(result.warnings, Vec::<String>::new());
|
||||
assert_eq!(
|
||||
result.statements,
|
||||
vec![
|
||||
"ALTER TABLE `order_items` ADD CONSTRAINT `fk_order_items_product` FOREIGN KEY (`tenant_id`, `product_id`) REFERENCES `products` (`tenant_id`, `id`);",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_mysql_trigger_changes() {
|
||||
let mut existing = trigger("orders_bu", "BEFORE", "UPDATE", "BEGIN\n SET NEW.updated_at = NOW();\nEND");
|
||||
existing.original = Some(TriggerInfo {
|
||||
name: "orders_bu".to_string(),
|
||||
event: "UPDATE".to_string(),
|
||||
timing: "BEFORE".to_string(),
|
||||
statement: Some("SET NEW.updated_at = CURRENT_TIMESTAMP".to_string()),
|
||||
});
|
||||
|
||||
let result = build_table_structure_change_sql(TableStructureSqlOptions {
|
||||
database_type: Some(DatabaseType::Mysql),
|
||||
schema: None,
|
||||
table_name: "orders".to_string(),
|
||||
columns: Vec::new(),
|
||||
indexes: Vec::new(),
|
||||
foreign_keys: Vec::new(),
|
||||
triggers: vec![existing],
|
||||
table_comment: None,
|
||||
original_table_comment: None,
|
||||
});
|
||||
|
||||
assert_eq!(result.warnings, Vec::<String>::new());
|
||||
assert_eq!(
|
||||
result.statements,
|
||||
vec![
|
||||
"DROP TRIGGER `orders_bu`;",
|
||||
"CREATE TRIGGER `orders_bu` BEFORE UPDATE ON `orders` FOR EACH ROW\nBEGIN\n SET NEW.updated_at = NOW();\nEND;",
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use super::dialect::{database_label, StructureDialect};
|
||||
use super::types::{EditableStructureTrigger, TableStructureSqlOptions, TriggerInfo};
|
||||
use super::util::{clean, qualified_table, quote_ident};
|
||||
|
||||
pub(super) fn build_trigger_sql(options: &TableStructureSqlOptions, warnings: &mut Vec<String>) -> Vec<String> {
|
||||
if options.triggers.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let database_label = database_label(options.database_type);
|
||||
if super::dialect::capabilities_for(options.database_type).dialect != StructureDialect::Mysql {
|
||||
warnings.push(format!("Editing triggers is not supported for {database_label} from this editor."));
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let table = qualified_table(StructureDialect::Mysql, options.schema.as_deref(), &options.table_name);
|
||||
let mut statements = Vec::new();
|
||||
|
||||
for trigger in &options.triggers {
|
||||
if trigger.marked_for_drop {
|
||||
if let Some(original) = &trigger.original {
|
||||
statements.push(drop_trigger_sql(options.schema.as_deref(), &original.name));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(original) = &trigger.original {
|
||||
if !has_trigger_change(trigger, original) {
|
||||
continue;
|
||||
}
|
||||
statements.push(drop_trigger_sql(options.schema.as_deref(), &original.name));
|
||||
}
|
||||
|
||||
if let Some(sql) = create_trigger_sql(&table, trigger, warnings) {
|
||||
statements.push(sql);
|
||||
}
|
||||
}
|
||||
|
||||
statements
|
||||
}
|
||||
|
||||
fn has_trigger_change(trigger: &EditableStructureTrigger, original: &TriggerInfo) -> bool {
|
||||
clean(&trigger.name) != clean(&original.name)
|
||||
|| normalize_keyword(&trigger.timing) != normalize_keyword(&original.timing)
|
||||
|| normalize_keyword(&trigger.event) != normalize_keyword(&original.event)
|
||||
|| normalize_statement(&trigger.statement) != normalize_statement(original.statement.as_deref().unwrap_or(""))
|
||||
}
|
||||
|
||||
fn drop_trigger_sql(schema: Option<&str>, name: &str) -> String {
|
||||
let qualified_name = if schema.is_some_and(|schema| !schema.trim().is_empty()) {
|
||||
format!(
|
||||
"{}.{}",
|
||||
quote_ident(StructureDialect::Mysql, schema.unwrap()),
|
||||
quote_ident(StructureDialect::Mysql, name)
|
||||
)
|
||||
} else {
|
||||
quote_ident(StructureDialect::Mysql, name)
|
||||
};
|
||||
format!("DROP TRIGGER {qualified_name};")
|
||||
}
|
||||
|
||||
fn create_trigger_sql(table: &str, trigger: &EditableStructureTrigger, warnings: &mut Vec<String>) -> Option<String> {
|
||||
let name = clean(&trigger.name);
|
||||
let timing = normalize_keyword(&trigger.timing);
|
||||
let event = normalize_keyword(&trigger.event);
|
||||
let statement = clean(&trigger.statement);
|
||||
|
||||
if name.is_empty() || timing.is_empty() || event.is_empty() || statement.is_empty() {
|
||||
warnings.push("Trigger name, timing, event, and statement are required.".to_string());
|
||||
return None;
|
||||
}
|
||||
if !matches!(timing.as_str(), "BEFORE" | "AFTER") {
|
||||
warnings.push(format!("Unsupported trigger timing \"{}\".", clean(&trigger.timing)));
|
||||
return None;
|
||||
}
|
||||
if !matches!(event.as_str(), "INSERT" | "UPDATE" | "DELETE") {
|
||||
warnings.push(format!("Unsupported trigger event \"{}\".", clean(&trigger.event)));
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(format!(
|
||||
"CREATE TRIGGER {} {timing} {event} ON {table} FOR EACH ROW\n{};",
|
||||
quote_ident(StructureDialect::Mysql, &name),
|
||||
statement.trim_end_matches(';').trim_end()
|
||||
))
|
||||
}
|
||||
|
||||
fn normalize_keyword(value: &str) -> String {
|
||||
clean(value).to_ascii_uppercase()
|
||||
}
|
||||
|
||||
fn normalize_statement(value: &str) -> String {
|
||||
clean(value).trim_end_matches(';').trim().to_string()
|
||||
}
|
||||
@@ -105,6 +105,69 @@ pub struct IndexInfo {
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EditableStructureForeignKey {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub column: String,
|
||||
#[serde(default)]
|
||||
pub ref_schema: String,
|
||||
#[serde(default)]
|
||||
pub ref_table: String,
|
||||
#[serde(default)]
|
||||
pub ref_column: String,
|
||||
#[serde(default)]
|
||||
pub on_update: String,
|
||||
#[serde(default)]
|
||||
pub on_delete: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub original: Option<ForeignKeyInfo>,
|
||||
#[serde(default)]
|
||||
pub marked_for_drop: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ForeignKeyInfo {
|
||||
pub name: String,
|
||||
pub column: String,
|
||||
#[serde(default)]
|
||||
pub ref_schema: Option<String>,
|
||||
pub ref_table: String,
|
||||
pub ref_column: String,
|
||||
#[serde(default)]
|
||||
pub on_update: Option<String>,
|
||||
#[serde(default)]
|
||||
pub on_delete: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EditableStructureTrigger {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub timing: String,
|
||||
#[serde(default)]
|
||||
pub event: String,
|
||||
#[serde(default)]
|
||||
pub statement: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub original: Option<TriggerInfo>,
|
||||
#[serde(default)]
|
||||
pub marked_for_drop: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TriggerInfo {
|
||||
pub name: String,
|
||||
pub event: String,
|
||||
pub timing: String,
|
||||
#[serde(default)]
|
||||
pub statement: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TableStructureSqlOptions {
|
||||
@@ -117,6 +180,10 @@ pub struct TableStructureSqlOptions {
|
||||
pub columns: Vec<EditableStructureColumn>,
|
||||
#[serde(default)]
|
||||
pub indexes: Vec<EditableStructureIndex>,
|
||||
#[serde(default)]
|
||||
pub foreign_keys: Vec<EditableStructureForeignKey>,
|
||||
#[serde(default)]
|
||||
pub triggers: Vec<EditableStructureTrigger>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub table_comment: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
|
||||
@@ -3545,6 +3545,8 @@ mod tests {
|
||||
ref_schema: None,
|
||||
ref_table: "users".to_string(),
|
||||
ref_column: "id".to_string(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
},
|
||||
db::ForeignKeyInfo {
|
||||
name: "orders_user_id_fkey".to_string(),
|
||||
@@ -3552,6 +3554,8 @@ mod tests {
|
||||
ref_schema: None,
|
||||
ref_table: "users".to_string(),
|
||||
ref_column: "tenant_id".to_string(),
|
||||
on_update: None,
|
||||
on_delete: None,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -102,6 +102,10 @@ pub struct ForeignKeyInfo {
|
||||
pub ref_schema: Option<String>,
|
||||
pub ref_table: String,
|
||||
pub ref_column: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub on_update: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub on_delete: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -109,4 +113,6 @@ pub struct TriggerInfo {
|
||||
pub name: String,
|
||||
pub event: String,
|
||||
pub timing: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub statement: Option<String>,
|
||||
}
|
||||
Reference in new issue
Block a user