feat(diagram): enhance ER diagram editing and exports
This commit is contained in:
1 parent
9fda1d690a
commit
212cf1da7e
92 files changed
+12231
-943
No files matched your search
@@ -3408,6 +3408,7 @@ pub async fn get_columns(pool: &MySqlPool, database: &str, table: &str) -> Resul
|
||||
};
|
||||
Some(ColumnInfo {
|
||||
is_primary_key: column_key.eq_ignore_ascii_case("PRI"),
|
||||
is_unique: column_key.eq_ignore_ascii_case("UNI"),
|
||||
name,
|
||||
data_type: column_type,
|
||||
is_nullable: get_str_by_name(row, "IS_NULLABLE") == "YES",
|
||||
@@ -3468,6 +3469,7 @@ pub async fn get_columns_show(pool: &MySqlPool, database: &str, table: &str) ->
|
||||
is_nullable: get_str_by_name(row, "Null").eq_ignore_ascii_case("YES"),
|
||||
column_default: get_opt_str(row, "Default"),
|
||||
is_primary_key: key.eq_ignore_ascii_case("PRI"),
|
||||
is_unique: key.eq_ignore_ascii_case("UNI"),
|
||||
extra: get_opt_str(row, "Extra"),
|
||||
comment: get_opt_str(row, "Comment")
|
||||
.map(|s| fix_potential_double_encoding(&s))
|
||||
@@ -4439,6 +4441,438 @@ pub async fn show_create_table_ddl(pool: &MySqlPool, database: &str, table: &str
|
||||
.ok_or_else(|| "Failed to read DDL".to_string())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Doris / StarRocks multi-catalog support.
|
||||
//
|
||||
// These engines expose external catalogs (iceberg, hive, jdbc, ...) alongside
|
||||
// the native `internal` catalog via `SHOW CATALOGS`. The functions below address
|
||||
// objects in a specific catalog using 3-part qualified names
|
||||
// (`<catalog>.<database>.<table>`), which the engines accept directly without
|
||||
// needing to `SWITCH` the session catalog.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Build a 2-part qualified identifier `` `<catalog>`.`<database>` ``.
|
||||
fn doris_catalog_database_ref(catalog: &str, database: &str) -> String {
|
||||
format!("{}.{}", quote_identifier(catalog), quote_identifier(database))
|
||||
}
|
||||
|
||||
/// Build a 3-part qualified identifier `` `<catalog>`.`<database>`.`<table>` ``.
|
||||
fn doris_catalog_table_ref(catalog: &str, database: &str, table: &str) -> String {
|
||||
format!("{}.{}.{}", quote_identifier(catalog), quote_identifier(database), quote_identifier(table))
|
||||
}
|
||||
|
||||
/// `SHOW CATALOGS` → list of catalogs visible to the current user.
|
||||
///
|
||||
/// Column layouts differ between engines: Doris exposes `CatalogName` (with
|
||||
/// `CatalogId`/`IsCurrent`/`CreateTime`/`LastUpdateTime`), while StarRocks
|
||||
/// exposes `Catalog` (only `Type`/`Comment`, no `IsCurrent`). The name is read
|
||||
/// from either column; missing trailing columns degrade gracefully to
|
||||
/// empty/None. The built-in catalog is named `internal` in Doris and
|
||||
/// `default_catalog` in StarRocks (both with `Type=internal`); detection is
|
||||
/// type-based (see `CatalogInfo::is_internal`), not name-based.
|
||||
pub async fn list_doris_catalogs(pool: &MySqlPool) -> Result<Vec<crate::db::CatalogInfo>, String> {
|
||||
let mut conn = get_conn_with_timeout(pool, super::connection_timeout()).await?;
|
||||
let result = conn.query_iter("SHOW CATALOGS").await.map_err(|e| e.to_string())?;
|
||||
let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;
|
||||
let catalogs: Vec<crate::db::CatalogInfo> = rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
// Doris column is `CatalogName`; StarRocks column is `Catalog`.
|
||||
let name = first_nonempty_str_by_name(row, &["CatalogName", "Catalog"]).trim().to_string();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let catalog_type = get_str_by_name(row, "Type").trim().to_string();
|
||||
let is_current = {
|
||||
let value = get_str_by_name(row, "IsCurrent").trim().to_ascii_lowercase();
|
||||
!value.is_empty() && value != "no" && value != "false" && value != "0"
|
||||
};
|
||||
let comment = get_opt_str(row, "Comment").map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
|
||||
Some(crate::db::CatalogInfo { name, catalog_type, is_current, comment })
|
||||
})
|
||||
.collect();
|
||||
Ok(normalize_doris_catalogs(catalogs))
|
||||
}
|
||||
|
||||
/// Sort with the built-in catalog first, then the rest alphabetically by name.
|
||||
/// The built-in catalog is identified by `CatalogInfo::is_internal` (type-based)
|
||||
/// rather than by name, so StarRocks `default_catalog` sorts first just like
|
||||
/// Doris `internal`. No synthetic catalog is injected: `SHOW CATALOGS` always
|
||||
/// lists the built-in catalog on both engines, and a single-catalog result is
|
||||
/// handled by the flat-sidebar fallback in the caller.
|
||||
fn normalize_doris_catalogs(mut catalogs: Vec<crate::db::CatalogInfo>) -> Vec<crate::db::CatalogInfo> {
|
||||
catalogs.sort_by(|a, b| match (a.is_internal(), b.is_internal()) {
|
||||
(true, false) => std::cmp::Ordering::Less,
|
||||
(false, true) => std::cmp::Ordering::Greater,
|
||||
_ => a.name.cmp(&b.name),
|
||||
});
|
||||
catalogs
|
||||
}
|
||||
|
||||
/// `SHOW DATABASES FROM <catalog>` → databases in the given catalog.
|
||||
pub async fn list_databases_show_from(pool: &MySqlPool, catalog: &str) -> Result<Vec<DatabaseInfo>, String> {
|
||||
let mut conn = get_conn_with_timeout(pool, super::connection_timeout()).await?;
|
||||
let sql = format!("SHOW DATABASES FROM {}", quote_identifier(catalog));
|
||||
let result = conn.query_iter(&sql).await.map_err(|e| e.to_string())?;
|
||||
let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;
|
||||
Ok(database_infos_from_names(rows.iter().map(|row| get_str(row, 0)), false))
|
||||
}
|
||||
|
||||
/// `SHOW TABLES FROM <catalog>.<database>` → tables in an external catalog.
|
||||
///
|
||||
/// External catalogs do not support `SHOW TABLE STATUS`, so comments/status are
|
||||
/// not fetched (the caller only needs names + types for browsing).
|
||||
pub async fn list_tables_show_from(pool: &MySqlPool, catalog: &str, database: &str) -> Result<Vec<TableInfo>, String> {
|
||||
let sql = format!("SHOW TABLES FROM {}", doris_catalog_database_ref(catalog, database));
|
||||
let mut conn = get_conn_with_timeout(pool, super::connection_timeout()).await?;
|
||||
let result = conn.query_iter(&sql).await.map_err(|e| e.to_string())?;
|
||||
let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;
|
||||
let mut tables: Vec<TableInfo> = rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
let name = get_str(row, 0).trim().to_string();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// SHOW FULL TABLES exposes a type column; plain SHOW TABLES does not.
|
||||
let table_type = get_str(row, 1);
|
||||
Some(TableInfo {
|
||||
name,
|
||||
table_type: if table_type.trim().is_empty() { "TABLE".to_string() } else { table_type },
|
||||
comment: None,
|
||||
parent_schema: None,
|
||||
parent_name: None,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
tables.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
Ok(tables)
|
||||
}
|
||||
|
||||
/// `SHOW COLUMNS FROM <catalog>.<database>.<table>` → columns of an external
|
||||
/// catalog table. Falls back to `DESCRIBE` if `SHOW COLUMNS` is rejected.
|
||||
pub async fn get_columns_show_from(
|
||||
pool: &MySqlPool,
|
||||
catalog: &str,
|
||||
database: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<ColumnInfo>, String> {
|
||||
let qualified = doris_catalog_table_ref(catalog, database, table);
|
||||
let full_sql = format!("SHOW FULL COLUMNS FROM {qualified}");
|
||||
let plain_sql = format!("SHOW COLUMNS FROM {qualified}");
|
||||
let describe_sql = format!("DESCRIBE {qualified}");
|
||||
let mut conn = get_conn_with_health_check(pool).await?;
|
||||
let rows: Vec<mysql_async::Row> = match conn.query_iter(&full_sql).await {
|
||||
Ok(result) => result.collect_and_drop().await.map_err(|e| e.to_string())?,
|
||||
Err(_) => match conn.query_iter(&plain_sql).await {
|
||||
Ok(result) => result.collect_and_drop().await.map_err(|e| e.to_string())?,
|
||||
Err(_) => {
|
||||
let result = conn.query_iter(&describe_sql).await.map_err(|e| e.to_string())?;
|
||||
result.collect_and_drop().await.map_err(|e| e.to_string())?
|
||||
}
|
||||
},
|
||||
};
|
||||
Ok(rows
|
||||
.iter()
|
||||
.filter_map(|row| {
|
||||
let name = get_str_by_name(row, "Field").trim().to_string();
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let key = get_str_by_name(row, "Key");
|
||||
let collation = get_opt_str(row, "Collation").filter(|s| !s.is_empty());
|
||||
Some(ColumnInfo {
|
||||
name,
|
||||
data_type: get_str_by_name(row, "Type"),
|
||||
is_nullable: get_str_by_name(row, "Null").eq_ignore_ascii_case("YES"),
|
||||
column_default: get_opt_str(row, "Default"),
|
||||
is_primary_key: key.eq_ignore_ascii_case("PRI"),
|
||||
is_unique: key.eq_ignore_ascii_case("UNI"),
|
||||
extra: get_opt_str(row, "Extra"),
|
||||
comment: get_opt_str(row, "Comment")
|
||||
.map(|s| fix_potential_double_encoding(&s))
|
||||
.filter(|s| !s.is_empty()),
|
||||
numeric_precision: None,
|
||||
numeric_scale: None,
|
||||
character_maximum_length: None,
|
||||
enum_values: None,
|
||||
character_set: collation
|
||||
.as_deref()
|
||||
.and_then(|c| c.split_once('_').map(|(charset, _)| charset.to_string()))
|
||||
.filter(|s| !s.is_empty()),
|
||||
collation,
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// `SHOW CREATE TABLE <catalog>.<database>.<table>` → DDL for an external
|
||||
/// catalog table.
|
||||
pub async fn show_create_table_ddl_from(
|
||||
pool: &MySqlPool,
|
||||
catalog: &str,
|
||||
database: &str,
|
||||
table: &str,
|
||||
) -> Result<String, String> {
|
||||
let sql = format!("SHOW CREATE TABLE {}", doris_catalog_table_ref(catalog, database, table));
|
||||
let mut conn = get_conn_with_health_check(pool).await?;
|
||||
let result = conn.query_iter(&sql).await.map_err(|e| e.to_string())?;
|
||||
let rows: Vec<mysql_async::Row> = result.collect_and_drop().await.map_err(|e| e.to_string())?;
|
||||
let row = rows.first().ok_or("DDL not found")?;
|
||||
row.get_opt::<String, usize>(1)
|
||||
.and_then(|result| result.ok())
|
||||
.or_else(|| {
|
||||
row.get_opt::<Vec<u8>, usize>(1)
|
||||
.and_then(|result| result.ok())
|
||||
.map(|b| String::from_utf8_lossy(&b).to_string())
|
||||
})
|
||||
.ok_or_else(|| "Failed to read DDL".to_string())
|
||||
}
|
||||
|
||||
/// Best-effort index listing for an external catalog table. External catalogs
|
||||
/// generally do not expose MySQL-style index metadata via `information_schema`
|
||||
/// (that view is scoped to the internal catalog), so indexes are derived from
|
||||
/// `SHOW CREATE TABLE` parsing. Returns empty on failure (graceful degradation
|
||||
/// — indexes are informational for external tables).
|
||||
pub async fn list_doris_catalog_indexes(
|
||||
pool: &MySqlPool,
|
||||
catalog: &str,
|
||||
database: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<IndexInfo>, String> {
|
||||
let ddl = show_create_table_ddl_from(pool, catalog, database, table).await?;
|
||||
Ok(doris_indexes_from_create_table_ddl(&ddl))
|
||||
}
|
||||
|
||||
fn doris_indexes_from_create_table_ddl(ddl: &str) -> Vec<IndexInfo> {
|
||||
let mut indexes = Vec::new();
|
||||
for raw_line in ddl.lines() {
|
||||
let line = trim_ddl_definition_line(raw_line);
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let upper = line.to_ascii_uppercase();
|
||||
if upper.starts_with("PRIMARY KEY") {
|
||||
if let Some(index) = doris_table_key_index("PRIMARY", line, true, true, "PRIMARY KEY") {
|
||||
indexes.push(index);
|
||||
}
|
||||
} else if upper.starts_with("UNIQUE KEY") {
|
||||
if let Some(index) = doris_table_key_index("UNIQUE KEY", line, true, false, "UNIQUE KEY") {
|
||||
indexes.push(index);
|
||||
}
|
||||
} else if upper.starts_with("INDEX ") {
|
||||
if let Some(index) = doris_secondary_index(line) {
|
||||
indexes.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
indexes
|
||||
}
|
||||
|
||||
fn trim_ddl_definition_line(line: &str) -> &str {
|
||||
let mut trimmed = line.trim();
|
||||
if let Some(rest) = trimmed.strip_prefix(',') {
|
||||
trimmed = rest.trim_start();
|
||||
}
|
||||
while let Some(rest) = trimmed.strip_suffix(',') {
|
||||
trimmed = rest.trim_end();
|
||||
}
|
||||
trimmed
|
||||
}
|
||||
|
||||
fn doris_table_key_index(
|
||||
name: &str,
|
||||
line: &str,
|
||||
is_unique: bool,
|
||||
is_primary: bool,
|
||||
index_type: &str,
|
||||
) -> Option<IndexInfo> {
|
||||
let columns = parse_mysql_index_columns(first_parenthesized_content(line)?);
|
||||
if columns.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(IndexInfo {
|
||||
name: name.to_string(),
|
||||
columns,
|
||||
is_unique,
|
||||
is_primary,
|
||||
filter: None,
|
||||
index_type: Some(index_type.to_string()),
|
||||
included_columns: None,
|
||||
comment: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn doris_secondary_index(line: &str) -> Option<IndexInfo> {
|
||||
let (_, rest) = split_keyword_prefix(line, "INDEX")?;
|
||||
let (name, after_name) = read_mysql_identifier(rest.trim_start())?;
|
||||
let columns = parse_mysql_index_columns(first_parenthesized_content(after_name)?);
|
||||
if columns.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(IndexInfo {
|
||||
name,
|
||||
columns,
|
||||
is_unique: false,
|
||||
is_primary: false,
|
||||
filter: None,
|
||||
index_type: mysql_keyword_argument(after_name, "USING").or_else(|| Some("INDEX".to_string())),
|
||||
included_columns: None,
|
||||
comment: mysql_quoted_string_argument(after_name, "COMMENT"),
|
||||
})
|
||||
}
|
||||
|
||||
fn split_keyword_prefix<'a>(line: &'a str, keyword: &str) -> Option<(&'a str, &'a str)> {
|
||||
if line.len() < keyword.len() || !line[..keyword.len()].eq_ignore_ascii_case(keyword) {
|
||||
return None;
|
||||
}
|
||||
let rest = &line[keyword.len()..];
|
||||
if !rest.is_empty() && is_mysql_identifier_byte(rest.as_bytes()[0]) {
|
||||
return None;
|
||||
}
|
||||
Some((&line[..keyword.len()], rest))
|
||||
}
|
||||
|
||||
fn read_mysql_identifier(input: &str) -> Option<(String, &str)> {
|
||||
let input = input.trim_start();
|
||||
if input.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let bytes = input.as_bytes();
|
||||
if bytes[0] == b'`' {
|
||||
let mut i = 1;
|
||||
let mut value = String::new();
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'`' {
|
||||
if i + 1 < bytes.len() && bytes[i + 1] == b'`' {
|
||||
value.push('`');
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
return Some((value, &input[i + 1..]));
|
||||
}
|
||||
let ch = input[i..].chars().next()?;
|
||||
value.push(ch);
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let end = input.find(|ch: char| ch.is_whitespace() || matches!(ch, '(' | ')' | ',')).unwrap_or(input.len());
|
||||
if end == 0 {
|
||||
return None;
|
||||
}
|
||||
Some((input[..end].to_string(), &input[end..]))
|
||||
}
|
||||
|
||||
fn first_parenthesized_content(input: &str) -> Option<&str> {
|
||||
let bytes = input.as_bytes();
|
||||
let mut depth = 0usize;
|
||||
let mut start = None;
|
||||
let mut i = 0usize;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'\'' | b'"' | b'`' => {
|
||||
i = skip_mysql_quoted(input, i, bytes[i]);
|
||||
continue;
|
||||
}
|
||||
b'(' => {
|
||||
if depth == 0 {
|
||||
start = Some(i + 1);
|
||||
}
|
||||
depth += 1;
|
||||
}
|
||||
b')' if depth > 0 => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return start.map(|start| &input[start..i]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn split_top_level_csv(input: &str) -> Vec<&str> {
|
||||
let bytes = input.as_bytes();
|
||||
let mut parts = Vec::new();
|
||||
let mut depth = 0usize;
|
||||
let mut start = 0usize;
|
||||
let mut i = 0usize;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'\'' | b'"' | b'`' => {
|
||||
i = skip_mysql_quoted(input, i, bytes[i]);
|
||||
continue;
|
||||
}
|
||||
b'(' => depth += 1,
|
||||
b')' if depth > 0 => depth -= 1,
|
||||
b',' if depth == 0 => {
|
||||
parts.push(input[start..i].trim());
|
||||
start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
parts.push(input[start..].trim());
|
||||
parts
|
||||
}
|
||||
|
||||
fn parse_mysql_index_columns(input: &str) -> Vec<String> {
|
||||
split_top_level_csv(input)
|
||||
.into_iter()
|
||||
.filter_map(|part| read_mysql_identifier(part).map(|(column, _)| column))
|
||||
.filter(|column| !column.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn mysql_keyword_argument(input: &str, keyword: &str) -> Option<String> {
|
||||
let bytes = input.as_bytes();
|
||||
let mut i = 0usize;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'\'' | b'"' | b'`' => {
|
||||
i = skip_mysql_quoted(input, i, bytes[i]);
|
||||
continue;
|
||||
}
|
||||
_ if mysql_keyword_at(input, i, keyword) => {
|
||||
return read_mysql_identifier(&input[i + keyword.len()..]).map(|(value, _)| value);
|
||||
}
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn mysql_quoted_string_argument(input: &str, keyword: &str) -> Option<String> {
|
||||
let bytes = input.as_bytes();
|
||||
let mut i = 0usize;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'\'' | b'"' | b'`' => {
|
||||
i = skip_mysql_quoted(input, i, bytes[i]);
|
||||
continue;
|
||||
}
|
||||
_ if mysql_keyword_at(input, i, keyword) => {
|
||||
let rest = input[i + keyword.len()..].trim_start();
|
||||
if rest.as_bytes().first().copied() != Some(b'\'') {
|
||||
return None;
|
||||
}
|
||||
let end = skip_mysql_quoted(rest, 0, b'\'');
|
||||
if end <= 1 || end > rest.len() {
|
||||
return None;
|
||||
}
|
||||
return Some(rest[1..end - 1].replace("\\'", "'").replace("''", "'"));
|
||||
}
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub async fn list_foreign_keys(pool: &MySqlPool, database: &str, table: &str) -> Result<Vec<ForeignKeyInfo>, String> {
|
||||
let column_sql = format!(
|
||||
"SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_SCHEMA, \
|
||||
|
||||
@@ -191,6 +191,7 @@ pub async fn get_columns_show_from(
|
||||
is_nullable: get_str_by_name(row, "Null").eq_ignore_ascii_case("YES"),
|
||||
column_default: get_opt_str(row, "Default"),
|
||||
is_primary_key: key.eq_ignore_ascii_case("PRI"),
|
||||
is_unique: key.eq_ignore_ascii_case("UNI"),
|
||||
extra: get_opt_str(row, "Extra"),
|
||||
comment: get_opt_str(row, "Comment")
|
||||
.map(|s| fix_potential_double_encoding(&s))
|
||||
|
||||
@@ -5415,6 +5415,7 @@ fn deduplicate_column_infos(columns: Vec<db::ColumnInfo>) -> Vec<db::ColumnInfo>
|
||||
for column in columns {
|
||||
if let Some(existing) = result.iter_mut().find(|existing| existing.name == column.name) {
|
||||
existing.is_primary_key |= column.is_primary_key;
|
||||
existing.is_unique |= column.is_unique;
|
||||
existing.is_nullable &= column.is_nullable;
|
||||
merge_optional_string(&mut existing.column_default, column.column_default);
|
||||
merge_optional_string(&mut existing.extra, column.extra);
|
||||
@@ -5438,6 +5439,37 @@ fn deduplicate_column_infos(columns: Vec<db::ColumnInfo>) -> Vec<db::ColumnInfo>
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn get_all_columns_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
database: &str,
|
||||
schema: &str,
|
||||
) -> Result<Vec<db::TableColumnsResult>, String> {
|
||||
let tables = list_tables_core(state, connection_id, database, schema, None, None, None, None, None).await?;
|
||||
|
||||
let mut result: Vec<db::TableColumnsResult> = Vec::with_capacity(tables.len());
|
||||
for table in tables {
|
||||
match get_columns_core(state, connection_id, database, schema, &table.name).await {
|
||||
Ok(columns) => {
|
||||
result.push(db::TableColumnsResult { table_name: table.name, columns, error: None });
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"[schema][get_all_columns] connection_id={} database={} schema={} table={} error={}",
|
||||
connection_id,
|
||||
database,
|
||||
schema,
|
||||
table.name,
|
||||
e
|
||||
);
|
||||
result.push(db::TableColumnsResult { table_name: table.name, columns: Vec::new(), error: Some(e) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn merge_optional_string(target: &mut Option<String>, candidate: Option<String>) {
|
||||
let Some(candidate) = candidate else {
|
||||
return;
|
||||
|
||||
@@ -3899,6 +3899,7 @@ mod tests {
|
||||
is_nullable: false,
|
||||
column_default: None,
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: comment.map(str::to_string),
|
||||
numeric_precision: None,
|
||||
@@ -5091,6 +5092,7 @@ mod tests {
|
||||
is_nullable: true,
|
||||
column_default: None,
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
@@ -7385,6 +7387,7 @@ mod tests {
|
||||
column_default: Some("'default'".into()),
|
||||
comment: Some("new".into()),
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
numeric_precision: None,
|
||||
numeric_scale: None,
|
||||
@@ -7400,6 +7403,7 @@ mod tests {
|
||||
column_default: None,
|
||||
comment: Some("old".into()),
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
numeric_precision: None,
|
||||
numeric_scale: None,
|
||||
@@ -7642,6 +7646,7 @@ mod tests {
|
||||
data_type: "int(11)".into(),
|
||||
is_nullable: false,
|
||||
is_primary_key: true,
|
||||
is_unique: false,
|
||||
extra: Some("auto_increment".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
|
||||
@@ -1363,6 +1363,7 @@ mod tests {
|
||||
is_nullable: true,
|
||||
column_default: None,
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
@@ -2234,6 +2235,7 @@ mod tests {
|
||||
is_nullable: true,
|
||||
column_default: None,
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
@@ -2249,6 +2251,7 @@ mod tests {
|
||||
is_nullable: true,
|
||||
column_default: None,
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
|
||||
@@ -127,6 +127,8 @@ pub struct ColumnInfo {
|
||||
pub is_nullable: bool,
|
||||
pub column_default: Option<String>,
|
||||
pub is_primary_key: bool,
|
||||
#[serde(default)]
|
||||
pub is_unique: bool,
|
||||
pub extra: Option<String>,
|
||||
pub comment: Option<String>,
|
||||
pub numeric_precision: Option<i32>,
|
||||
@@ -140,6 +142,14 @@ pub struct ColumnInfo {
|
||||
pub collation: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TableColumnsResult {
|
||||
pub table_name: String,
|
||||
pub columns: Vec<ColumnInfo>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CompletionAssistantObjectKind {
|
||||
|
||||
@@ -231,6 +231,7 @@ fn column_info_serialization_roundtrip() {
|
||||
is_nullable: false,
|
||||
column_default: None,
|
||||
is_primary_key: true,
|
||||
is_unique: true,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: Some(10),
|
||||
@@ -241,9 +242,65 @@ fn column_info_serialization_roundtrip() {
|
||||
collation: None,
|
||||
};
|
||||
let json = serde_json::to_value(&col).unwrap();
|
||||
assert_eq!(json.get("is_unique"), Some(&serde_json::json!(true)));
|
||||
let deserialized: ColumnInfo = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(col.name, deserialized.name);
|
||||
assert_eq!(col.numeric_precision, deserialized.numeric_precision);
|
||||
assert!(deserialized.is_unique);
|
||||
|
||||
let legacy = serde_json::json!({
|
||||
"name": "email",
|
||||
"data_type": "varchar",
|
||||
"is_nullable": true,
|
||||
"column_default": null,
|
||||
"is_primary_key": false,
|
||||
"extra": null,
|
||||
"comment": null,
|
||||
"numeric_precision": null,
|
||||
"numeric_scale": null,
|
||||
"character_maximum_length": 255
|
||||
});
|
||||
let from_legacy: ColumnInfo = serde_json::from_value(legacy).unwrap();
|
||||
assert!(!from_legacy.is_unique);
|
||||
}
|
||||
|
||||
/// TableColumnsResult (get_all_columns) uses snake_case `table_name`, not camelCase.
|
||||
#[test]
|
||||
fn table_columns_result_serialization_contract() {
|
||||
use dbx_core::db::TableColumnsResult;
|
||||
|
||||
let result = TableColumnsResult {
|
||||
table_name: "users".to_string(),
|
||||
columns: vec![ColumnInfo {
|
||||
name: "id".to_string(),
|
||||
data_type: "int".to_string(),
|
||||
is_nullable: false,
|
||||
column_default: None,
|
||||
is_primary_key: true,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
numeric_scale: None,
|
||||
character_maximum_length: None,
|
||||
enum_values: None,
|
||||
character_set: None,
|
||||
collation: None,
|
||||
}],
|
||||
error: Some("partial".to_string()),
|
||||
};
|
||||
let json = serde_json::to_value(&result).unwrap();
|
||||
let obj = json.as_object().expect("object");
|
||||
assert!(obj.contains_key("table_name"));
|
||||
assert!(!obj.contains_key("tableName"));
|
||||
assert!(obj.contains_key("columns"));
|
||||
assert!(obj.contains_key("error"));
|
||||
assert_eq!(json["columns"][0]["is_unique"], false);
|
||||
|
||||
let roundtrip: TableColumnsResult = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(roundtrip.table_name, "users");
|
||||
assert_eq!(roundtrip.error.as_deref(), Some("partial"));
|
||||
assert_eq!(roundtrip.columns.len(), 1);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
|
||||
@@ -19,6 +19,7 @@ fn col(name: &str, data_type: &str) -> ColumnInfo {
|
||||
is_nullable: false,
|
||||
column_default: None,
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
|
||||
@@ -22,6 +22,7 @@ fn col(name: &str, data_type: &str) -> ColumnInfo {
|
||||
is_nullable: false,
|
||||
column_default: None,
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
|
||||
@@ -37,6 +37,7 @@ fn generate_details(tables: &[TableInfo], columns_per_table: usize) -> Vec<Table
|
||||
is_nullable: j % 2 == 0,
|
||||
column_default: if j == 0 { Some("0".to_string()) } else { None },
|
||||
is_primary_key: j == 0,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: if j % 3 == 0 { Some(10) } else { None },
|
||||
|
||||
@@ -28,6 +28,7 @@ fn col(name: &str, data_type: &str) -> ColumnInfo {
|
||||
is_nullable: false,
|
||||
column_default: None,
|
||||
is_primary_key: false,
|
||||
is_unique: false,
|
||||
extra: None,
|
||||
comment: None,
|
||||
numeric_precision: None,
|
||||
|
||||
Reference in new issue
Block a user