дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
feat(database): read and edit table and column comments in Modify Table (#6257)
Fixes #6129 The Modify Table dialog now reads and edits table and column comments on PostgreSQL, MySQL, Oracle and Snowflake. - `ide-db`: `TableDetails.comment` and `ColumnInfo.comment` (optional). Read from `obj_description` / `col_description` (PostgreSQL), `information_schema` (MySQL; a view's `VIEW` placeholder is not a comment), `all_tab_comments` / `all_col_comments` (Oracle), `DESCRIBE TABLE` and `SHOW TABLES` (Snowflake), and `system.tables` / `system.columns` (ClickHouse, read only: it has no Modify Table). - Modify Table / Create Table: a Comment field under the table name and a Column comment field per column. Statements go into the Preview: - PostgreSQL / Oracle / Snowflake: `comment on table|column … is '…'`; clearing is `is null` (PostgreSQL), `is ''` (Oracle), `unset comment` (Snowflake). - MySQL: `alter table … comment = '…'`; a column's comment is part of its definition, so `change column` now carries it. Before, changing a MySQL column's type, default or nullability silently dropped its comment. - Columns are commented by their new name; the table rename still comes last. - After OK the table's details (and, after a rename or a create, the schema's tables) are reloaded, so the tree and the next Modify Table show the table as it now is. Before, reopening Modify Table showed the columns as they were. Tests: `objects.test.ts` (statements per engine, MySQL comment kept on change, new table), `modifyTableGroups.test.tsx` (fields and preview, no fields on SQLite), `cargo test -p ide-db` incl. the PostgreSQL 17 and MySQL 8.4 integration tests with comments, full vitest, typecheck. Checked in the app against PostgreSQL: existing comments shown, set / changed / cleared through OK, values reloaded, light and dark.
Цей коміт міститься в:
1 джерело
cd7582c5e5
коміт
2d021a3414
14 files changed
+347
-22
No files matched your search
@@ -157,6 +157,10 @@ pub struct ColumnInfo {
|
||||
pub nullable: bool,
|
||||
pub default: Option<String>,
|
||||
pub primary_key: bool,
|
||||
/// `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -172,6 +176,10 @@ pub struct IndexInfo {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableDetails")]
|
||||
pub struct TableDetails {
|
||||
/// The table's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
pub columns: Vec<ColumnInfo>,
|
||||
pub indexes: Vec<IndexInfo>,
|
||||
pub foreign_keys: Vec<ForeignKey>,
|
||||
@@ -1119,11 +1127,18 @@ impl DbManager {
|
||||
let nullable = flag(&it.next().flatten());
|
||||
let default = it.next().flatten();
|
||||
let primary_key = flag(&it.next().flatten());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key })
|
||||
let comment = it.next().flatten().filter(|c| !c.is_empty());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key, comment })
|
||||
})
|
||||
.collect();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] });
|
||||
return Ok(TableDetails {
|
||||
comment: None,
|
||||
columns,
|
||||
indexes: vec![],
|
||||
foreign_keys: vec![],
|
||||
triggers: vec![],
|
||||
});
|
||||
}
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
@@ -1175,7 +1190,17 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
|
||||
let comment = match sql::table_comment(driver, schema, table) {
|
||||
Some(q) => pool.rows(&q, 1).await.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
|
||||
@@ -132,6 +132,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
nullable: yes(r.get("null?")),
|
||||
default: r.get("default").filter(|d| !d.is_empty()).map(str::to_owned),
|
||||
primary_key: yes(r.get("primary key")),
|
||||
comment: r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -140,7 +141,16 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
Ok(keys) => foreign_keys(&keys),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
Ok(TableDetails { columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
// `LIKE` matches without case and with wildcards: the exact name picks the row.
|
||||
let like = format!("SHOW TABLES LIKE {} IN SCHEMA {}", quote_literal(DRIVER, table), schema_path(pool, schema));
|
||||
let comment = match show(pool, &like).await {
|
||||
Ok(shown) => shown
|
||||
.records()
|
||||
.find(|r| r.get("name") == Some(table))
|
||||
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
|
||||
Err(_) => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
}
|
||||
|
||||
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
|
||||
|
||||
@@ -145,7 +145,8 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n
|
||||
WHEN data_type = 'TEXT' THEN 'VARCHAR(' || character_maximum_length || ')' \
|
||||
WHEN data_type LIKE 'TIME%' THEN data_type || '(' || datetime_precision || ')' ELSE data_type END";
|
||||
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`.
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`, and the column's
|
||||
/// comment on the engines that keep one (PostgreSQL, MySQL, Oracle, ClickHouse).
|
||||
pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
@@ -153,7 +154,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \
|
||||
OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key, comment \
|
||||
FROM system.columns WHERE database = {s} AND table = {t} ORDER BY position"
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
@@ -166,13 +167,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
|
||||
col_description(format('%I.%I', c.table_schema, c.table_name)::regclass, c.ordinal_position::int) \
|
||||
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
|
||||
ORDER BY c.ordinal_position"
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT column_name, column_type, is_nullable, column_default, \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END, column_comment \
|
||||
FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \
|
||||
ORDER BY ordinal_position"
|
||||
),
|
||||
@@ -192,8 +194,10 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), c.data_default, \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
|
||||
FROM all_tab_columns c \
|
||||
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
|
||||
AND cc.column_name = c.column_name \
|
||||
LEFT JOIN (SELECT kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
AND kc.constraint_name = con.constraint_name \
|
||||
@@ -204,6 +208,28 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// One row, one column: the table's comment (`NULL` or empty for none). `None` for the
|
||||
/// engines whose comments the IDE doesn't read here (Snowflake reads it with `SHOW`).
|
||||
pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT obj_description(c.oid, 'pg_class') FROM pg_class c \
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = {s} AND c.relname = {t}"
|
||||
)),
|
||||
// A view's `table_comment` is the word `VIEW`.
|
||||
DbDriver::Mysql => Some(format!(
|
||||
"SELECT CASE WHEN table_type = 'VIEW' THEN NULL ELSE table_comment END \
|
||||
FROM information_schema.tables WHERE table_schema = {s} AND table_name = {t}"
|
||||
)),
|
||||
DbDriver::Oracle => {
|
||||
Some(format!("SELECT comments FROM all_tab_comments WHERE owner = {s} AND table_name = {t}"))
|
||||
}
|
||||
DbDriver::Clickhouse => Some(format!("SELECT comment FROM system.tables WHERE database = {s} AND name = {t}")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
|
||||
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
|
||||
// most columns an index or key has): unlike a series per catalog row, it lets the planner find the
|
||||
@@ -956,6 +982,22 @@ mod tests {
|
||||
assert_eq!(quote_literal(DbDriver::Mysql, "it's \\"), "'it''s \\\\'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_read_where_the_engine_keeps_them() {
|
||||
assert!(columns(DbDriver::Postgres, "public", "t").contains("col_description("));
|
||||
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
|
||||
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
|
||||
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
|
||||
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
|
||||
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
|
||||
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
|
||||
assert!(table_comment(DbDriver::Oracle, "S", "T").unwrap().contains("all_tab_comments"));
|
||||
assert!(table_comment(DbDriver::Clickhouse, "db", "t").unwrap().contains("system.tables"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Snowflake] {
|
||||
assert_eq!(table_comment(driver, "s", "t"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clickhouse_escapes_backslashes_and_delimiters() {
|
||||
let driver = DbDriver::Clickhouse;
|
||||
|
||||
@@ -40,7 +40,8 @@ async fn create_schemas(db: &DbManager) {
|
||||
format!("DROP DATABASE IF EXISTS `{s}`"),
|
||||
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
|
||||
format!(
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin COMMENT '名字', \
|
||||
raw VARBINARY(4)) COMMENT = '用户表'"
|
||||
),
|
||||
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
|
||||
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
|
||||
@@ -59,6 +60,9 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
assert_eq!(d.comment.as_deref(), Some("用户表"));
|
||||
let comments: Vec<_> = d.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, Some("名字"), None]);
|
||||
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
|
||||
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
|
||||
}
|
||||
|
||||
@@ -338,6 +338,8 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
"CREATE TABLE oi_meta.lines (n INT PRIMARY KEY, o_region INT, o_id INT, \
|
||||
FOREIGN KEY (o_region, o_id) REFERENCES oi_meta.orders (region, id))",
|
||||
"CREATE INDEX lines_order ON oi_meta.lines (o_id, o_region)",
|
||||
"COMMENT ON TABLE oi_meta.orders IS 'Customer''s orders'",
|
||||
"COMMENT ON COLUMN oi_meta.orders.note IS 'Free text'",
|
||||
"CREATE FUNCTION oi_meta.twice(v INT) RETURNS INT AS 'SELECT v * 2' LANGUAGE sql",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
@@ -350,6 +352,10 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
assert_eq!(details.foreign_keys[0].columns, ["o_region", "o_id"]);
|
||||
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
|
||||
let orders = db.table_details("p", "oi_meta", "orders").await?;
|
||||
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, None, Some("Free text")]);
|
||||
assert_eq!(details.comment, None);
|
||||
let key = orders.indexes.iter().find(|i| i.unique).expect("primary key index");
|
||||
assert_eq!(key.columns, ["region", "id"]);
|
||||
|
||||
|
||||
@@ -5256,6 +5256,8 @@ export type DbColumnInfo = {
|
||||
nullable: boolean,
|
||||
default: string | null,
|
||||
primaryKey: boolean,
|
||||
/** `None` when it has none, or the engine keeps no comments. */
|
||||
comment?: string | null,
|
||||
};
|
||||
|
||||
/** The schema model SQL completion and resolution work from. */
|
||||
@@ -5678,6 +5680,8 @@ export type DbStatementOutcome = {
|
||||
};
|
||||
|
||||
export type DbTableDetails = {
|
||||
/** The table's comment; `None` when it has none, or the engine keeps no comments. */
|
||||
comment?: string | null,
|
||||
columns: DbColumnInfo[],
|
||||
indexes: DbIndexInfo[],
|
||||
foreignKeys: DbForeignKey[],
|
||||
|
||||
@@ -35,6 +35,8 @@ import {
|
||||
canAlterColumn,
|
||||
createDatabaseSql,
|
||||
createSchemaSql,
|
||||
commentsSupported,
|
||||
createTableCommentSql,
|
||||
createTableSql,
|
||||
draftOf,
|
||||
dropDatabaseSql,
|
||||
@@ -60,6 +62,7 @@ import {
|
||||
renameDatabase,
|
||||
loadDetails,
|
||||
loadGrants,
|
||||
loadTables,
|
||||
openSourceDialog,
|
||||
readableDdl,
|
||||
refresh,
|
||||
@@ -546,6 +549,7 @@ function blankColumn(driver: DbDriver, n: number): ColumnDraft {
|
||||
notNull: false,
|
||||
default: "",
|
||||
primaryKey: false,
|
||||
comment: "",
|
||||
dropped: false,
|
||||
};
|
||||
}
|
||||
@@ -655,11 +659,19 @@ function ModifyTableForm({
|
||||
return columns[Math.max(0, focus)]?.key ?? null;
|
||||
});
|
||||
const { busy, runAndClose } = useRunner();
|
||||
const comments = commentsSupported(driver);
|
||||
const [comment, setComment] = useState(details?.comment ?? "");
|
||||
|
||||
const statements = useMemo(() => {
|
||||
if (!table) return [createTableSql(driver, schema, name.trim() || "table_name", columns)];
|
||||
return alterTableSql(driver, schema, table, name, columns);
|
||||
}, [columns, driver, schema, table, name]);
|
||||
if (!table) {
|
||||
const created = name.trim() || "table_name";
|
||||
return [
|
||||
createTableSql(driver, schema, created, columns, comment),
|
||||
...createTableCommentSql(driver, schema, created, columns, comment),
|
||||
];
|
||||
}
|
||||
return alterTableSql(driver, schema, table, name, columns, { original: details?.comment ?? "", value: comment });
|
||||
}, [columns, driver, schema, table, name, comment, details?.comment]);
|
||||
|
||||
const current = columns.find((c) => c.key === selected) ?? null;
|
||||
const patch = (p: Partial<ColumnDraft>) =>
|
||||
@@ -718,7 +730,14 @@ function ModifyTableForm({
|
||||
label: "OK",
|
||||
role: "default",
|
||||
disabled: busy || !statements.length || !name.trim(),
|
||||
onClick: () => void runAndClose(id, statements),
|
||||
onClick: () =>
|
||||
void runAndClose(id, statements).then((ok) => {
|
||||
if (!ok) return;
|
||||
// The tree and the next Modify Table show the table as it now is.
|
||||
const final = name.trim();
|
||||
void loadDetails(id, schema, final);
|
||||
if (final !== table) void loadTables(id, schema);
|
||||
}),
|
||||
},
|
||||
]}
|
||||
>
|
||||
@@ -736,6 +755,19 @@ function ModifyTableForm({
|
||||
/>
|
||||
<span className={styles.formHint}>{schema}</span>
|
||||
</div>
|
||||
{comments && (
|
||||
<div className={styles.formRow}>
|
||||
<label className={styles.formLabel} htmlFor="db-table-comment">
|
||||
<T>Comment:</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-table-comment"
|
||||
className={styles.fill}
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{showGrants && (
|
||||
<Tabs
|
||||
variant="compact"
|
||||
@@ -867,6 +899,19 @@ function ModifyTableForm({
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(e) => patch({ default: e.target.value })}
|
||||
/>
|
||||
{comments && (
|
||||
<>
|
||||
<label className={styles.formLabel} htmlFor="db-col-comment">
|
||||
<T>Column comment</T>
|
||||
</label>
|
||||
<Input
|
||||
id="db-col-comment"
|
||||
value={current.comment}
|
||||
disabled={current.dropped || locked}
|
||||
onChange={(e) => patch({ comment: e.target.value })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{locked && (
|
||||
<>
|
||||
<span />
|
||||
|
||||
@@ -43,7 +43,7 @@ const rows = (group: string) =>
|
||||
.queryAllByRole("option")
|
||||
.map((o) => o.textContent);
|
||||
|
||||
afterEach(() => useDatabase.setState({ dialog: null, details: {} } as never));
|
||||
afterEach(() => useDatabase.setState({ dialog: null, details: {}, sources: [] } as never));
|
||||
|
||||
describe("Modify Table's list (DataGrip)", () => {
|
||||
it("groups the columns, keys, foreign keys and indexes, and filters them by name or type", () => {
|
||||
@@ -76,4 +76,37 @@ describe("Modify Table's list (DataGrip)", () => {
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Primary key" }));
|
||||
expect(rows("Keys")).toEqual(["PRIMARY KEY(id, column_2)"]);
|
||||
});
|
||||
|
||||
it("reads and edits the table's and the columns' comments where the engine keeps them", () => {
|
||||
useDatabase.setState({
|
||||
sources: [{ id: "pg", name: "pg", driver: "postgres" }],
|
||||
details: {
|
||||
[detailsKey("pg", "public", "orders")]: {
|
||||
status: "ok",
|
||||
value: {
|
||||
comment: "Customer orders",
|
||||
columns: [column("id", "integer", true), { ...column("note", "text"), comment: "Free text" }],
|
||||
indexes: [],
|
||||
foreignKeys: [],
|
||||
triggers: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
} as never);
|
||||
openDialog({ kind: "modifyTable", id: "pg", schema: "public", table: "orders", focusColumn: "note" });
|
||||
render(<ObjectDialogs />);
|
||||
expect(screen.getByLabelText("Comment:")).toHaveProperty("value", "Customer orders");
|
||||
expect(screen.getByLabelText("Column comment")).toHaveProperty("value", "Free text");
|
||||
fireEvent.change(screen.getByLabelText("Column comment"), { target: { value: "" } });
|
||||
fireEvent.change(screen.getByLabelText("Comment:"), { target: { value: "Orders" } });
|
||||
const preview = document.body.textContent ?? "";
|
||||
expect(preview).toContain("comment on table public.orders is 'Orders';");
|
||||
expect(preview).toContain("comment on column public.orders.note is null;");
|
||||
});
|
||||
|
||||
it("has no comment fields on an engine without comments", () => {
|
||||
open();
|
||||
expect(screen.queryByLabelText("Comment:")).toBeNull();
|
||||
expect(screen.queryByLabelText("Column comment")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
canModifyTable,
|
||||
createDatabaseSql,
|
||||
createSchemaSql,
|
||||
commentsSupported,
|
||||
createTableCommentSql,
|
||||
createTableSql,
|
||||
draftOf,
|
||||
dropDatabaseSql,
|
||||
@@ -188,6 +190,7 @@ describe("database object SQL", () => {
|
||||
notNull: false,
|
||||
default: "0",
|
||||
primaryKey: false,
|
||||
comment: "",
|
||||
dropped: false,
|
||||
});
|
||||
expect(alterTableSql("sqlite", "main", "users", "people", d)).toEqual([
|
||||
@@ -209,6 +212,71 @@ describe("database object SQL", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("table and column comments", () => {
|
||||
const commented = [col("id", "INTEGER", { primaryKey: true }), col("note", "TEXT", { comment: "Free text" })];
|
||||
|
||||
it("sets, changes and clears comments per engine", () => {
|
||||
const p = commented.map(draftOf);
|
||||
p[0] = { ...p[0]!, comment: "Order's id" };
|
||||
p[1] = { ...p[1]!, comment: "" };
|
||||
const table = { original: "", value: "Orders" };
|
||||
expect(alterTableSql("postgres", "public", "t", "t", p, table)).toEqual([
|
||||
"comment on table public.t is 'Orders';",
|
||||
"comment on column public.t.id is 'Order''s id';",
|
||||
"comment on column public.t.note is null;",
|
||||
]);
|
||||
expect(alterTableSql("oracle", "HR", "T", "T", p, { original: "Old", value: "" })).toEqual([
|
||||
"comment on table HR.T is '';",
|
||||
"comment on column HR.T.\"id\" is 'Order''s id';",
|
||||
"comment on column HR.T.\"note\" is '';",
|
||||
]);
|
||||
expect(alterTableSql("snowflake", "HR", "T", "T", p, { original: "Old", value: "" })).toEqual([
|
||||
"alter table HR.T unset comment;",
|
||||
"comment on column HR.T.\"id\" is 'Order''s id';",
|
||||
'alter table HR.T alter column "note" unset comment;',
|
||||
]);
|
||||
// MySQL keeps a column's comment in its definition.
|
||||
expect(alterTableSql("mysql", "app", "t", "t", p, { original: "", value: "a\\b" })).toEqual([
|
||||
"alter table app.t change column id id INTEGER comment 'Order''s id';",
|
||||
"alter table app.t change column note note TEXT;",
|
||||
"alter table app.t comment = 'a\\\\b';",
|
||||
]);
|
||||
expect(alterTableSql("sqlite", "main", "t", "t", p, table)).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps an unchanged comment, and comments a renamed column by its new name", () => {
|
||||
const p = commented.map(draftOf);
|
||||
expect(alterTableSql("postgres", "public", "t", "t", p, { original: "Orders", value: "Orders" })).toEqual([]);
|
||||
// A MySQL change of type keeps the column's comment.
|
||||
p[1] = { ...p[1]!, dataType: "varchar(40)" };
|
||||
expect(alterTableSql("mysql", "app", "t", "t", p)).toEqual([
|
||||
"alter table app.t change column note note varchar(40) comment 'Free text';",
|
||||
]);
|
||||
p[1] = { ...commented.map(draftOf)[1]!, name: "body", comment: "Body" };
|
||||
expect(alterTableSql("postgres", "public", "t", "renamed", p)).toEqual([
|
||||
"alter table public.t rename column note to body;",
|
||||
"comment on column public.t.body is 'Body';",
|
||||
"alter table public.t rename to renamed;",
|
||||
]);
|
||||
});
|
||||
|
||||
it("comments a new table", () => {
|
||||
const d = commented.map((c) => ({ ...draftOf(c, 0), original: null }));
|
||||
expect(createTableSql("mysql", "app", "t", d, "Orders")).toBe(
|
||||
"create table app.t\n(\n id INTEGER,\n note TEXT comment 'Free text',\n primary key (id)\n)\ncomment = 'Orders';\n",
|
||||
);
|
||||
expect(createTableCommentSql("mysql", "app", "t", d, "Orders")).toEqual([]);
|
||||
expect(createTableCommentSql("postgres", "public", "t", d, "Orders")).toEqual([
|
||||
"comment on table public.t is 'Orders';",
|
||||
"comment on column public.t.note is 'Free text';",
|
||||
]);
|
||||
expect(createTableCommentSql("postgres", "public", "t", d, "")).toEqual([
|
||||
"comment on column public.t.note is 'Free text';",
|
||||
]);
|
||||
expect(commentsSupported("sqlite")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("oracle object SQL", () => {
|
||||
const emp = [col("ID", "NUMBER", { primaryKey: true, nullable: false }), col("NAME", "VARCHAR2(40)")];
|
||||
const d = emp.map(draftOf);
|
||||
@@ -248,6 +316,7 @@ describe("oracle object SQL", () => {
|
||||
notNull: false,
|
||||
default: "SYSDATE",
|
||||
primaryKey: false,
|
||||
comment: "",
|
||||
dropped: false,
|
||||
} satisfies ColumnDraft);
|
||||
expect(alterTableSql("oracle", "HR", "EMPLOYEES", "EMPLOYEES", p)).toEqual([
|
||||
@@ -344,6 +413,7 @@ describe("snowflake object SQL", () => {
|
||||
notNull: false,
|
||||
default: "CURRENT_DATE",
|
||||
primaryKey: false,
|
||||
comment: "",
|
||||
dropped: false,
|
||||
} satisfies ColumnDraft);
|
||||
expect(alterTableSql("snowflake", "HR", "EMP", "STAFF", p)).toEqual([
|
||||
|
||||
@@ -305,6 +305,8 @@ export interface ColumnDraft {
|
||||
/** SQL expression; empty for none. */
|
||||
default: string;
|
||||
primaryKey: boolean;
|
||||
/** Empty for none. */
|
||||
comment: string;
|
||||
dropped: boolean;
|
||||
}
|
||||
|
||||
@@ -317,6 +319,7 @@ export function draftOf(c: DbColumnInfo, key: number): ColumnDraft {
|
||||
notNull: !c.nullable,
|
||||
default: c.default ?? "",
|
||||
primaryKey: c.primaryKey,
|
||||
comment: c.comment ?? "",
|
||||
dropped: false,
|
||||
};
|
||||
}
|
||||
@@ -335,21 +338,95 @@ function columnDefinition(driver: DbDriver, c: ColumnDraft): string {
|
||||
let s = `${ident(driver, c.name)} ${c.dataType.trim() || fallback}`;
|
||||
if (c.default.trim()) s += ` default ${c.default.trim()}`;
|
||||
if (c.notNull && driver !== "clickhouse") s += " not null";
|
||||
// MySQL keeps a column's comment in its definition: `change column` without it drops the comment.
|
||||
if (driver === "mysql" && c.comment) s += ` comment ${commentLiteral(driver, c.comment)}`;
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Engines whose table and column comments the Modify Table dialog reads and edits. */
|
||||
export function commentsSupported(driver: DbDriver): boolean {
|
||||
return driver === "postgres" || driver === "mysql" || driver === "oracle" || driver === "snowflake";
|
||||
}
|
||||
|
||||
/** A comment as a string literal (MySQL and Snowflake read backslash escapes). */
|
||||
function commentLiteral(driver: DbDriver, text: string): string {
|
||||
const escaped = driver === "mysql" || driver === "snowflake" ? text.replace(/\\/g, "\\\\") : text;
|
||||
return `'${escaped.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
/** A table comment as the dialog started (`original`) and as edited. */
|
||||
export interface CommentEdit {
|
||||
original: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The statements setting the table's comment and its columns' (`comment on …` where the
|
||||
* engine has it; MySQL's column comments are part of the definition, see `columnDefinition`).
|
||||
* Columns are named as they end up; the table as it is (a rename comes after).
|
||||
*/
|
||||
function commentSql(
|
||||
driver: DbDriver,
|
||||
schema: string,
|
||||
table: string,
|
||||
columns: readonly ColumnDraft[],
|
||||
comment: CommentEdit | undefined,
|
||||
): string[] {
|
||||
if (!commentsSupported(driver)) return [];
|
||||
const q = qualifiedName(driver, schema, table);
|
||||
const out: string[] = [];
|
||||
if (comment && comment.value !== comment.original) {
|
||||
const v = comment.value;
|
||||
if (driver === "mysql") out.push(`alter table ${q} comment = ${commentLiteral(driver, v)};`);
|
||||
else if (!v && driver === "snowflake") out.push(`alter table ${q} unset comment;`);
|
||||
else out.push(`comment on table ${q} is ${v || driver !== "postgres" ? commentLiteral(driver, v) : "null"};`);
|
||||
}
|
||||
if (driver === "mysql") return out;
|
||||
for (const c of columns) {
|
||||
const name = c.name.trim() || c.original?.name;
|
||||
if (c.dropped || !name || c.comment === (c.original?.comment ?? "")) continue;
|
||||
const col = ident(driver, name);
|
||||
if (!c.comment && driver === "snowflake") out.push(`alter table ${q} alter column ${col} unset comment;`);
|
||||
else
|
||||
out.push(
|
||||
`comment on column ${q}.${col} is ${c.comment || driver !== "postgres" ? commentLiteral(driver, c.comment) : "null"};`,
|
||||
);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `create table` for New › Table. */
|
||||
export function createTableSql(
|
||||
driver: DbDriver,
|
||||
schema: string,
|
||||
name: string,
|
||||
columns: readonly ColumnDraft[],
|
||||
comment = "",
|
||||
): string {
|
||||
const live = columns.filter((c) => !c.dropped && c.name.trim());
|
||||
const keys = live.filter((c) => c.primaryKey).map((c) => ident(driver, c.name));
|
||||
const items = live.map((c) => ` ${columnDefinition(driver, c)}`);
|
||||
if (keys.length && driver !== "clickhouse") items.push(` primary key (${keys.join(", ")})`);
|
||||
return `create table ${qualifiedName(driver, schema, name)}\n(\n${items.join(",\n")}\n)${driver === "clickhouse" ? "\nengine = MergeTree\norder by tuple()" : ""};\n`;
|
||||
const options =
|
||||
driver === "clickhouse"
|
||||
? "\nengine = MergeTree\norder by tuple()"
|
||||
: driver === "mysql" && comment
|
||||
? `\ncomment = ${commentLiteral(driver, comment)}`
|
||||
: "";
|
||||
return `create table ${qualifiedName(driver, schema, name)}\n(\n${items.join(",\n")}\n)${options};\n`;
|
||||
}
|
||||
|
||||
/** The `comment on` statements following New › Table's `create table` (MySQL takes them inline). */
|
||||
export function createTableCommentSql(
|
||||
driver: DbDriver,
|
||||
schema: string,
|
||||
name: string,
|
||||
columns: readonly ColumnDraft[],
|
||||
comment: string,
|
||||
): string[] {
|
||||
if (driver === "mysql") return [];
|
||||
const live = columns.filter((c) => !c.dropped && c.name.trim());
|
||||
return commentSql(driver, schema, name, live, { original: "", value: comment });
|
||||
}
|
||||
|
||||
/** Whether `alterTableSql` can express changing column `c` (SQLite only renames, adds and drops). */
|
||||
@@ -360,7 +437,7 @@ export function canAlterColumn(driver: DbDriver, c: ColumnDraft): boolean {
|
||||
/**
|
||||
* The statements turning the table `table` into `name` with `columns`
|
||||
* (Modify Table): renames, added / dropped columns, and — PostgreSQL / MySQL /
|
||||
* Oracle / Snowflake — type, nullability and default changes.
|
||||
* Oracle / Snowflake — type, nullability, default and comment changes, and the table's comment.
|
||||
*/
|
||||
export function alterTableSql(
|
||||
driver: DbDriver,
|
||||
@@ -368,6 +445,7 @@ export function alterTableSql(
|
||||
table: string,
|
||||
name: string,
|
||||
columns: readonly ColumnDraft[],
|
||||
comment?: CommentEdit,
|
||||
): string[] {
|
||||
if (!canModifyTable(driver)) return [];
|
||||
const out: string[] = [];
|
||||
@@ -391,7 +469,10 @@ export function alterTableSql(
|
||||
}
|
||||
const renamed = c.name.trim() && c.name !== o.name;
|
||||
const changed =
|
||||
c.dataType.trim() !== o.dataType || c.notNull !== !o.nullable || c.default.trim() !== (o.default ?? "").trim();
|
||||
c.dataType.trim() !== o.dataType ||
|
||||
c.notNull !== !o.nullable ||
|
||||
c.default.trim() !== (o.default ?? "").trim() ||
|
||||
(driver === "mysql" && c.comment !== (o.comment ?? ""));
|
||||
if (driver === "mysql" && (renamed || changed)) {
|
||||
out.push(`alter table ${q()} change column ${ident(driver, o.name)} ${columnDefinition(driver, c)};`);
|
||||
continue;
|
||||
@@ -439,6 +520,7 @@ export function alterTableSql(
|
||||
`alter table ${q()} alter column ${col} ${c.default.trim() ? `set default ${c.default.trim()}` : "drop default"};`,
|
||||
);
|
||||
}
|
||||
out.push(...commentSql(driver, schema, table, columns, comment));
|
||||
// Renamed last: the column statements above name the table as it was.
|
||||
if (name.trim() && name.trim() !== table)
|
||||
out.push(renameSql(driver, { kind: "table", schema, name: table }, name.trim()));
|
||||
|
||||
@@ -10181,5 +10181,6 @@
|
||||
"Where Clause": "Условие WHERE",
|
||||
"SQL INSERT": "SQL INSERT",
|
||||
"SQL UPDATE": "SQL UPDATE",
|
||||
"SQL DELETE": "SQL DELETE"
|
||||
"SQL DELETE": "SQL DELETE",
|
||||
"Column comment": "Комментарий к столбцу"
|
||||
}
|
||||
@@ -8842,5 +8842,6 @@
|
||||
"Where Clause": "WHERE Koşulu",
|
||||
"SQL INSERT": "SQL INSERT",
|
||||
"SQL UPDATE": "SQL UPDATE",
|
||||
"SQL DELETE": "SQL DELETE"
|
||||
"SQL DELETE": "SQL DELETE",
|
||||
"Column comment": "Sütun yorumu"
|
||||
}
|
||||
@@ -9380,5 +9380,6 @@
|
||||
"Where Clause": "Where 子句",
|
||||
"SQL INSERT": "SQL INSERT 陳述式",
|
||||
"SQL UPDATE": "SQL UPDATE 陳述式",
|
||||
"SQL DELETE": "SQL DELETE 陳述式"
|
||||
"SQL DELETE": "SQL DELETE 陳述式",
|
||||
"Column comment": "欄位註解"
|
||||
}
|
||||
@@ -10610,5 +10610,6 @@
|
||||
"Where Clause": "Where 子句",
|
||||
"SQL INSERT": "SQL INSERT 语句",
|
||||
"SQL UPDATE": "SQL UPDATE 语句",
|
||||
"SQL DELETE": "SQL DELETE 语句"
|
||||
"SQL DELETE": "SQL DELETE 语句",
|
||||
"Column comment": "列注释"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача