Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 3f57f1795b feat(java): suggest variable names from the declared type 2026-11-27 04:54:02 +08:00
l0ng-ai 2d021a3414 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.
2026-11-27 04:46:32 +08:00
l0ng-ai cd7582c5e5 fix(plugins): keep plugin secrets in the OS credential store on Windows and Linux (#6240)
Part of #6142.

Plugin secrets (`secrets` grant) were stored in plain text in `plugin-secrets.json` everywhere except macOS, where the keychain was already used.

- New `CredentialSecretStore` in `ide-host`: stores each secret in the OS credential store (`ide_ssh::secrets::SecretFile`, the same store as SSH and database passwords) under `<plugin>/<name>`.
- Values still in the old file are read as a fallback and removed from it on the next write or delete.
- Without a usable credential store (e.g. headless Linux with no secret service) it keeps using the file and logs a warning.
- `src-tauri` switches to it on non-macOS platforms.

Tests: `cargo test -p ide-host --lib secret`, clippy on `ide-host` and `openidea`. Not run on a real Windows/Linux machine.

No Windows/Linux runner was available; the platform switch is one cfg line in src-tauri, the store itself is covered by tests on every platform.
2026-11-27 04:13:26 +08:00
20 змінених файлів з 748 додано та 23 видалено

No files matched your search

+28 -3
Переглянути файл
@@ -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
+11 -1
Переглянути файл
@@ -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> {
+47 -5
Переглянути файл
@@ -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;
+5 -1
Переглянути файл
@@ -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 `用户`"));
}
+6
Переглянути файл
@@ -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"]);
+116
Переглянути файл
@@ -217,6 +217,61 @@ impl SecretStore for FileSecretStore {
}
}
/// Plugin secrets in the OS credential store (Secret Service, Windows Credential
/// Manager), like saved SSH and agent values. Without a credential store a value
/// stays in the owner-only [`FileSecretStore`] file, which also still answers for
/// values saved there by an older version until they are set again.
pub struct CredentialSecretStore {
store: ide_ssh::secrets::SecretFile,
fallback: FileSecretStore,
}
impl CredentialSecretStore {
/// `dir`: the plugins' data directory (the index file and the fallback files live there).
pub fn new(dir: PathBuf) -> Self {
Self::with_store(ide_ssh::secrets::SecretFile::new(dir.join("plugin-secrets.json")), dir)
}
fn with_store(store: ide_ssh::secrets::SecretFile, dir: PathBuf) -> Self {
Self { store, fallback: FileSecretStore { dir } }
}
fn key(plugin: &str, name: &str) -> String {
format!("{plugin}/{name}")
}
/// Drops a value from the fallback file, writing it only when it held one.
fn forget_fallback(&self, plugin: &str, name: &str) -> Result<(), String> {
if self.fallback.get(plugin, name).is_none() {
return Ok(());
}
self.fallback.set(plugin, name, None)
}
}
impl SecretStore for CredentialSecretStore {
fn get(&self, plugin: &str, name: &str) -> Option<String> {
self.store.get(&Self::key(plugin, name)).or_else(|| self.fallback.get(plugin, name))
}
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
let key = Self::key(plugin, name);
match value {
Some(v) => match self.store.set(&key, v) {
Ok(()) => self.forget_fallback(plugin, name),
Err(e) => {
tracing::warn!("plugin secrets: {key} is kept in the plugin's data directory: {}", e.message);
self.fallback.set(plugin, name, Some(v))
}
},
None => {
self.store.delete(&key);
self.forget_fallback(plugin, name)
}
}
}
}
/// Largest response body a plugin receives.
const MAX_RESPONSE: usize = 16 << 20;
/// Largest stdout / stderr kept from a process by default.
@@ -4210,6 +4265,67 @@ mod tests {
assert_eq!(std::fs::read_to_string(&outside).unwrap(), "unchanged");
}
/// Plugin secrets go to the credential store; a value an older version left in
/// the owner-only file keeps working until it is set again, and then leaves the file.
#[test]
fn plugin_secrets_go_to_the_credential_store() {
ide_ssh::secrets::testing::use_memory_store();
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
FileSecretStore { dir: dir.clone() }.set("acme.lint", "old", Some("legacy-3f9a")).unwrap();
let secrets = CredentialSecretStore::new(dir.clone());
assert_eq!(secrets.get("acme.lint", "old").as_deref(), Some("legacy-3f9a"));
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
secrets.set("acme.lint", "old", Some("moved-5d2b")).unwrap();
let on_disk = ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e");
assert_eq!(on_disk, Vec::<PathBuf>::new());
assert_eq!(ide_ssh::secrets::testing::files_containing(tmp.path(), "legacy-3f9a"), Vec::<PathBuf>::new());
let again = CredentialSecretStore::new(dir);
assert_eq!(again.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
assert_eq!(again.get("acme.lint", "old").as_deref(), Some("moved-5d2b"));
assert_eq!(again.get("other.plugin", "token"), None);
again.set("acme.lint", "token", None).unwrap();
assert_eq!(again.get("acme.lint", "token"), None);
}
/// Without a credential store a value stays in the owner-only file.
#[test]
fn plugin_secrets_without_a_credential_store_stay_in_the_file() {
struct NoStore;
impl ide_ssh::secrets::Vault for NoStore {
fn available(&self) -> bool {
false
}
fn get(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<String> {
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
}
fn set(&self, _: &str, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
}
fn delete(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
}
}
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
let store = ide_ssh::secrets::SecretFile::with_vault(
dir.join("plugin-secrets.json"),
|v| serde_json::from_value(v).ok(),
Arc::new(NoStore),
);
let secrets = CredentialSecretStore::with_store(store, dir.clone());
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
assert_eq!(
ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e"),
[dir.join("acme.lint").join("secrets.json")]
);
assert_eq!(secrets.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
secrets.set("acme.lint", "token", None).unwrap();
assert_eq!(secrets.get("acme.lint", "token"), None);
}
#[cfg(unix)]
#[test]
fn storage_and_secrets_refuse_symlinked_private_directories() {
+7 -1
Переглянути файл
@@ -63,7 +63,7 @@ pub mod views;
pub mod web;
mod websocket;
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
pub use build_graph::{BuildGraph, GradleModule};
pub(crate) use hover::merge as merge_hover;
pub use icons::{
@@ -1949,6 +1949,12 @@ impl PluginHost {
*self.shared.secrets.write() = store;
}
/// Keeps plugin secrets in the OS credential store, with the owner-only
/// files under the plugins directory as the fallback.
pub fn use_credential_store(&self) {
self.set_secret_store(Arc::new(CredentialSecretStore::new(self.shared.data_dir.clone())));
}
/// Stores (or, with `None`, deletes) a secret the plugin declares under
/// `[[contributes.secrets]]`.
pub fn set_secret(&self, id: &str, name: &str, value: Option<&str>) -> IdeResult<()> {
+3
Переглянути файл
@@ -118,6 +118,9 @@ pub fn create_host(app: &AppHandle, data_dir: &Path, project_host: &Arc<ide_host
host.set_downloads(project_host.global_settings.effective().tool_downloads);
#[cfg(target_os = "macos")]
host.set_secret_store(Arc::new(KeychainSecrets));
// Secret Service / Windows Credential Manager elsewhere, like saved SSH and agent values.
#[cfg(not(target_os = "macos"))]
host.use_credential_store();
ide_host::plugins::set_editor_providers(Some(&host));
let weak = Arc::downgrade(project_host);
host.set_project_policy(Arc::new(move |root| {
+4
Переглянути файл
@@ -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[],
+5
Переглянути файл
@@ -63,6 +63,7 @@ import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature";
import { featureBackoff } from "./availability";
import { pathCompletionSource, pathContext, pathLike } from "./fileReferences";
import { cssVariablePrefix, cssVariableSource, STYLESHEETS, type VariableOption } from "./cssVariables";
import { javaDeclarationAt, variableNameSource } from "./variableNames";
import { editorPrefs } from "@/platform/editorSettings";
import { tx } from "@/platform/i18n";
import { showHint } from "./hint";
@@ -930,6 +931,9 @@ function gated(source: CompletionSource): CompletionSource {
if (ctx.state.field(smartLookup, false) && source !== claimingLspSource) return null;
const only = exclusiveSource(ctx);
if (only) return source === contributedSource ? only(ctx) : null;
// At a Java declaration's name only names fit: IDEA lists no live templates there, and
// jdtls' own name proposals repeat the type (`orderBookOrderBook`).
if (source !== variableNameSource && javaDeclarationAt(ctx)) return null;
if (!ctx.explicit && (!editorPrefs().completion.autoPopup || inplaceRenameActive(ctx.state))) return null;
if (!editorPrefs().completion.sortAlphabetically) return source(ctx);
return Promise.resolve(source(ctx)).then(
@@ -1208,6 +1212,7 @@ export function completionExtension() {
gated(contributedSource),
gated(pathFallbackSource),
gated(cssVariableSource),
gated(variableNameSource),
],
icons: false,
addToOptions: [
+59
Переглянути файл
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { declarationAt, namesForType, pluralize } from "./variableNames";
const names = (before: string) => {
const found = declarationAt(before);
return found ? namesForType(found.type) : null;
};
describe("variable names by type (IDEA)", () => {
it("suggests the type's name and its shorter endings", () => {
expect(names(" private IMesCheckStandardService c")).toEqual([
"iMesCheckStandardService",
"mesCheckStandardService",
"checkStandardService",
"standardService",
"service",
]);
expect(names(" MesProductPlan p")).toEqual(["mesProductPlan", "productPlan", "plan"]);
expect(names(" UserServiceImpl ")).toEqual(["userService", "service"]);
expect(names(" HttpURLConnection c")).toEqual(["httpURLConnection", "urlConnection", "connection"]);
});
it("names collections, arrays, optionals and generic types by their contents", () => {
expect(names("List<MesProductCheck> l")).toEqual([
"mesProductChecks",
"productChecks",
"checks",
"mesProductCheckList",
"productCheckList",
"checkList",
"list",
]);
expect(names("Order[] ")).toEqual(["orders"]);
expect(names("Optional<User> ")).toEqual(["user", "optionalUser", "userOptional", "optional"]);
expect(names("Map<String, Order> ")).toEqual(["stringOrderMap", "orderMap", "map"]);
expect(pluralize("Category")).toBe("Categories");
expect(pluralize("Box")).toBe("Boxes");
});
it("gives locals and parameters IDEA's short names", () => {
expect(names(" String ")).toEqual(["s", "string"]);
expect(names(" private String ")).toEqual(["string"]);
expect(names(" int ")).toEqual(["i"]);
expect(names(" } catch (IOException ")).toEqual(["e", "ioException", "exception"]);
expect(names("void run(Order o")).toEqual(["order"]);
});
it("is quiet where no name is declared", () => {
expect(declarationAt(" return Foo")).toBeNull();
expect(declarationAt(" return value ")).toBeNull();
expect(declarationAt("class Foo ")).toBeNull();
expect(declarationAt(" throw new Error ")).toBeNull();
expect(declarationAt("@Autowired ")).toBeNull();
expect(declarationAt(" private c")).toBeNull();
expect(declarationAt(" var x")).toBeNull();
expect(declarationAt(" foo.bar")).toBeNull();
expect(declarationAt(" Foo f")).toEqual({ type: expect.objectContaining({ name: "Foo" }), typed: "f" });
});
});
+211
Переглянути файл
@@ -0,0 +1,211 @@
/**
* Variable names by type, as IDEA's JavaCodeStyleManager suggests them: typing the name of a
* Java declaration (`private IUserService |`, `List<Order> |`, `catch (IOException |`) lists
* `userService`, `service`, `orders`, `e`… The language server offers nothing there.
*/
import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
import { syntaxTree } from "@codemirror/language";
import { lspDoc } from "./lsp";
/** The declared type at a name being typed: `Map<String, Order>[]` → `Map`, `[String, Order]`, array. */
export interface DeclaredType {
name: string;
args: string[];
array: boolean;
kind: "field" | "parameter" | "local";
}
const PRIMITIVES = new Set(["int", "long", "short", "byte", "char", "boolean", "float", "double"]);
/** Words before a type that make what follows something other than a declaration's name. */
const NOT_A_DECLARATION = new Set([
"new",
"class",
"interface",
"enum",
"record",
"extends",
"implements",
"permits",
"throws",
"import",
"package",
"return",
"throw",
"yield",
"assert",
"goto",
"var",
"this",
"super",
]);
const FIELD_MODIFIERS = /\b(?:private|protected|public|static|volatile|transient)\b/;
const DECLARATION =
/(^|[\s(,;{}])((?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]*)\s*(<[^;(){}=]*>)?((?:\s*\[\s*\])*)\s+([A-Za-z_$][\w$]*)?$/;
/**
* The type whose variable's name ends `before` (the line up to the caret), with the name typed so
* far; null when the caret isn't at a declared name.
*/
export function declarationAt(before: string): { type: DeclaredType; typed: string } | null {
const m = DECLARATION.exec(before);
if (!m) return null;
const qualified = m[2]!;
const name = qualified.slice(qualified.lastIndexOf(".") + 1);
if (!PRIMITIVES.has(name) && !/^[A-Z]/.test(name)) return null;
const head = before.slice(0, m.index + m[1]!.length);
const previous = /([A-Za-z_@][\w]*)\s*$/.exec(head)?.[1];
if (previous && (NOT_A_DECLARATION.has(previous) || previous.startsWith("@"))) return null;
if (/@\s*$/.test(head)) return null;
const params = /[(,]\s*$/.test(head) || /\(\s*(?:final\s+)?$/.test(head) || /\bcatch\s*\(\s*$/.test(head);
const kind = params ? "parameter" : FIELD_MODIFIERS.test(head) ? "field" : "local";
return {
type: { name, args: typeArguments(m[3] ?? ""), array: !!m[4]?.trim(), kind },
typed: m[5] ?? "",
};
}
/** The top-level type arguments' simple names (`<String, List<Order>>` → `String`, `List`); `?` and bounds skipped. */
function typeArguments(generic: string): string[] {
const inner = generic.slice(1, -1);
const out: string[] = [];
let depth = 0;
let current = "";
for (const ch of inner) {
if (ch === "<") depth++;
if (ch === ">") depth--;
if (ch === "," && depth === 0) {
out.push(current);
current = "";
} else if (depth === 0 && ch !== ">") current += ch;
}
out.push(current);
return out
.map((a) => a.trim())
.filter((a) => /^[A-Za-z_$][\w$.]*$/.test(a))
.map((a) => a.slice(a.lastIndexOf(".") + 1));
}
/** IDEA's NameUtilCore.nameToWordList: `IUserURLService` → `I`, `User`, `URL`, `Service`. */
function words(name: string): string[] {
return name.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z0-9]+|[A-Z]/g) ?? [];
}
/** StringUtil.pluralize for the usual cases. */
export function pluralize(word: string): string {
if (/(?:s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
return `${word}s`;
}
/** `UserService` → `userService`, `service` (longest first); an all-caps first word goes lower case. */
function suffixNames(name: string): string[] {
const ws = words(name);
const out: string[] = [];
for (let i = 0; i < ws.length; i++) {
const first = ws[i]!;
if (!/^[A-Za-z]/.test(first)) continue;
const head = first === first.toUpperCase() ? first.toLowerCase() : first[0]!.toLowerCase() + first.slice(1);
out.push(head + ws.slice(i + 1).join(""));
}
return out;
}
const SHORT_NAMES: Record<string, string> = {
int: "i",
boolean: "b",
byte: "b",
char: "c",
long: "l",
short: "i",
double: "v",
float: "v",
Integer: "i",
Short: "i",
Long: "l",
Boolean: "b",
Byte: "b",
Character: "c",
Double: "v",
Float: "v",
Object: "o",
String: "s",
};
const ITERABLES = new Set([
"Iterable",
"Collection",
"List",
"ArrayList",
"LinkedList",
"Set",
"HashSet",
"LinkedHashSet",
"TreeSet",
"SortedSet",
"NavigableSet",
"Queue",
"Deque",
"ArrayDeque",
"PriorityQueue",
"Stack",
"Vector",
"CopyOnWriteArrayList",
]);
/** `UserServiceImpl` names a `userService`, as in IDEA. */
const normalize = (name: string) => (name.length > 4 && name.endsWith("Impl") ? name.slice(0, -4) : name);
const JAVA_KEYWORDS = new Set(
(
"abstract assert boolean break byte case catch char class const continue default do double else enum extends " +
"final finally float for goto if implements import instanceof int interface long native new package private " +
"protected public return short static strictfp super switch synchronized this throw throws transient try void " +
"volatile while true false null var record yield"
).split(" "),
);
/** The names IDEA suggests for a variable of `type`, best first. */
export function namesForType(type: DeclaredType): string[] {
const base: string[] = [];
const short = type.kind === "field" ? undefined : SHORT_NAMES[type.name];
if (short) base.push(type.array ? pluralize(short) : short);
const name = normalize(type.name);
if (type.args.length === 1 && ITERABLES.has(type.name)) base.push(pluralize(normalize(type.args[0]!)));
if (type.args.length === 1 && type.name === "Optional") {
const content = normalize(type.args[0]!);
base.push(content, `optional${content}`);
}
if (type.args.length) base.push(type.args.map(normalize).join("") + name);
const own = type.array ? pluralize(name) : name;
if (type.kind === "parameter" && type.name.endsWith("Exception")) base.push("e");
base.push(own);
if (own.length > "Entity".length && own.endsWith("Entity")) base.push(own.slice(0, -"Entity".length));
const out: string[] = [];
for (const b of base) {
for (const n of PRIMITIVES.has(b) || b.length === 1 ? [b] : suffixNames(b)) {
if (!out.includes(n) && !JAVA_KEYWORDS.has(n) && /^[A-Za-z_$][\w$]*$/.test(n)) out.push(n);
}
}
return out;
}
/** The declaration under the caret in a Java file (not in a comment or string), or null. */
export function javaDeclarationAt(ctx: CompletionContext): { type: DeclaredType; typed: string } | null {
if (ctx.state.facet(lspDoc)?.language !== "java") return null;
const node = syntaxTree(ctx.state).resolveInner(ctx.pos, -1);
if (/Comment|String|TextBlock/.test(node.name)) return null;
const line = ctx.state.doc.lineAt(ctx.pos);
return declarationAt(line.text.slice(0, ctx.pos - line.from));
}
/** Completion source: the type's names at a Java declaration's name. */
export function variableNameSource(ctx: CompletionContext): CompletionResult | null {
const found = javaDeclarationAt(ctx);
if (!found) return null;
const names = namesForType(found.type);
const options: Completion[] = names.map((label, i) => ({ label, type: "variable", boost: 50 - i }));
return options.length ? { from: ctx.pos - found.typed.length, options, validFor: /^[\w$]*$/ } : null;
}
+49 -4
Переглянути файл
@@ -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 />
+34 -1
Переглянути файл
@@ -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();
});
});
+70
Переглянути файл
@@ -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([
+85 -3
Переглянути файл
@@ -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()));
+2 -1
Переглянути файл
@@ -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": "Комментарий к столбцу"
}
+2 -1
Переглянути файл
@@ -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"
}
+2 -1
Переглянути файл
@@ -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": "欄位註解"
}
+2 -1
Переглянути файл
@@ -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": "列注释"
}