fix(mysql): preserve generated columns in table editor
This commit is contained in:
7 files changed
+481
-7
No files matched your search
@@ -3562,6 +3562,94 @@ fn columns_sql(database: &str, table: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
fn generation_expressions_sql(database: &str, table: &str) -> String {
|
||||
format!(
|
||||
"SELECT COLUMN_NAME, GENERATION_EXPRESSION \
|
||||
FROM information_schema.COLUMNS \
|
||||
WHERE TABLE_SCHEMA = {} AND TABLE_NAME = {} \
|
||||
AND GENERATION_EXPRESSION IS NOT NULL AND GENERATION_EXPRESSION <> '' \
|
||||
ORDER BY ORDINAL_POSITION",
|
||||
quote_value(database),
|
||||
quote_value(table),
|
||||
)
|
||||
}
|
||||
|
||||
fn mysql_generated_column_storage(extra: &str) -> Option<&'static str> {
|
||||
let normalized = extra.split_whitespace().collect::<Vec<_>>().join(" ").to_ascii_lowercase();
|
||||
if normalized.contains("virtual generated") {
|
||||
Some("VIRTUAL")
|
||||
} else if normalized.contains("stored generated") {
|
||||
Some("STORED")
|
||||
} else if normalized.contains("persistent generated") {
|
||||
Some("PERSISTENT")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn mysql_generated_column_extra(extra: &str, expression: &str) -> Option<String> {
|
||||
let storage = mysql_generated_column_storage(extra)?;
|
||||
let expression = expression.trim();
|
||||
if expression.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(format!("GENERATED ALWAYS AS ({expression}) {storage}"))
|
||||
}
|
||||
|
||||
async fn enrich_mysql_generated_column_expressions(
|
||||
conn: &mut mysql_async::Conn,
|
||||
database: &str,
|
||||
table: &str,
|
||||
columns: &mut [ColumnInfo],
|
||||
) {
|
||||
if database.trim().is_empty()
|
||||
|| !columns
|
||||
.iter()
|
||||
.any(|column| column.extra.as_deref().is_some_and(|extra| mysql_generated_column_storage(extra).is_some()))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let sql = generation_expressions_sql(database, table);
|
||||
let rows = match conn.query_iter(&sql).await {
|
||||
Ok(result) => match result.collect_and_drop::<mysql_async::Row>().await {
|
||||
Ok(rows) => rows,
|
||||
Err(error) => {
|
||||
log::debug!("Failed to collect MySQL generated-column expressions with `{sql}`: {error}");
|
||||
return;
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
log::debug!("Failed to read MySQL generated-column expressions with `{sql}`: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let expressions = rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
let name = get_str_by_name(row, "COLUMN_NAME");
|
||||
let expression = get_str_by_name(row, "GENERATION_EXPRESSION");
|
||||
(!name.is_empty() && !expression.trim().is_empty()).then_some((name, expression))
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
apply_mysql_generated_column_expressions(columns, &expressions);
|
||||
}
|
||||
|
||||
fn apply_mysql_generated_column_expressions(columns: &mut [ColumnInfo], expressions: &HashMap<String, String>) {
|
||||
for column in columns {
|
||||
let Some(expression) = expressions.get(&column.name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(extra) = column.extra.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(generated_extra) = mysql_generated_column_extra(extra, expression) {
|
||||
column.extra = Some(generated_extra);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn table_collation_sql(database: &str, table: &str) -> String {
|
||||
format!(
|
||||
"SELECT TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_SCHEMA = {} AND TABLE_NAME = {} LIMIT 1",
|
||||
@@ -3778,6 +3866,7 @@ where
|
||||
return get_columns_show(pool, database, table).await;
|
||||
}
|
||||
|
||||
enrich_mysql_generated_column_expressions(&mut conn, database, table, &mut columns).await;
|
||||
normalize_mysql_column_charset_metadata(&mut columns, table_collation.as_deref());
|
||||
Ok(columns)
|
||||
}
|
||||
@@ -3834,6 +3923,7 @@ where
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
enrich_mysql_generated_column_expressions(&mut conn, database, table, &mut columns).await;
|
||||
normalize_mysql_column_charset_metadata(&mut columns, table_collation.as_deref());
|
||||
Ok(columns)
|
||||
}
|
||||
@@ -6603,6 +6693,57 @@ mod tests {
|
||||
assert!(!sql.contains("AS ENUM_VALUES"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_generation_expression_sql_is_separate_and_scoped() {
|
||||
let sql = generation_expressions_sql("app", "products");
|
||||
|
||||
assert!(sql.contains("COLUMN_NAME, GENERATION_EXPRESSION"));
|
||||
assert!(sql.contains("TABLE_SCHEMA = 'app'"));
|
||||
assert!(sql.contains("TABLE_NAME = 'products'"));
|
||||
assert!(sql.contains("GENERATION_EXPRESSION <> ''"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_generated_column_extra_rebuilds_virtual_and_stored_clauses() {
|
||||
assert_eq!(
|
||||
mysql_generated_column_extra("STORED GENERATED", "`price` * `quantity`"),
|
||||
Some("GENERATED ALWAYS AS (`price` * `quantity`) STORED".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
mysql_generated_column_extra("VIRTUAL GENERATED", "lower(`name`)"),
|
||||
Some("GENERATED ALWAYS AS (lower(`name`)) VIRTUAL".to_string())
|
||||
);
|
||||
assert_eq!(mysql_generated_column_extra("DEFAULT_GENERATED", "current_timestamp()"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_generated_column_expressions_enrich_only_generated_columns() {
|
||||
let mut columns = vec![
|
||||
ColumnInfo { name: "total".to_string(), extra: Some("STORED GENERATED".to_string()), ..Default::default() },
|
||||
ColumnInfo {
|
||||
name: "search_name".to_string(),
|
||||
extra: Some("VIRTUAL GENERATED".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
ColumnInfo {
|
||||
name: "created_at".to_string(),
|
||||
extra: Some("DEFAULT_GENERATED".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let expressions = HashMap::from([
|
||||
("total".to_string(), "`price` * `quantity`".to_string()),
|
||||
("search_name".to_string(), "lower(`name`)".to_string()),
|
||||
("created_at".to_string(), "current_timestamp()".to_string()),
|
||||
]);
|
||||
|
||||
apply_mysql_generated_column_expressions(&mut columns, &expressions);
|
||||
|
||||
assert_eq!(columns[0].extra.as_deref(), Some("GENERATED ALWAYS AS (`price` * `quantity`) STORED"));
|
||||
assert_eq!(columns[1].extra.as_deref(), Some("GENERATED ALWAYS AS (lower(`name`)) VIRTUAL"));
|
||||
assert_eq!(columns[2].extra.as_deref(), Some("DEFAULT_GENERATED"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_nullable_table_collation_uses_optional_string_conversion() {
|
||||
let collation = mysql_async::from_value_opt::<Option<String>>(mysql_async::Value::NULL)
|
||||
|
||||
Reference in new issue
Block a user