дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 14:44:34 +02:00
Порівняти коміти
8
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
3f57f1795b | ||
|
|
2d021a3414 | ||
|
|
cd7582c5e5 | ||
|
|
d16b852054 | ||
|
|
06223d9bd7 | ||
|
|
dcd81d601b | ||
|
|
762ebecd86 | ||
|
|
fd4efff6e3 |
No files matched your search
@@ -443,7 +443,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
|
||||
/// Installs (or updates to) the registry's current version of `id`, streaming progress
|
||||
/// through `emit`, and points the agent file at it.
|
||||
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
/// Installs agent `id`; an npm package retries against the public npm registry when the
|
||||
/// configured one misses it only with `public_npm_fallback`.
|
||||
pub fn install(
|
||||
paths: &RegistryPaths,
|
||||
id: &str,
|
||||
public_npm_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
// The saved index is what the user picked from; fetch only when there is none.
|
||||
let text = match fs::read_to_string(&paths.cache_file) {
|
||||
@@ -455,9 +463,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
|
||||
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
|
||||
let npm_installer =
|
||||
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn install_entry(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
@@ -466,7 +479,10 @@ fn install_entry(
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, true, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
@@ -663,20 +679,23 @@ fn install_npm(
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
@@ -704,6 +723,7 @@ fn install_npm_with(
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
public_fallback,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
@@ -1004,7 +1024,7 @@ mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
@@ -1043,8 +1063,8 @@ esac
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
@@ -1052,6 +1072,15 @@ esac
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
// Only the configured registries: the miss is the error, and npmjs is never asked.
|
||||
let only = dir.path().join("acme-only/1.2.0");
|
||||
fs::create_dir_all(&only).unwrap();
|
||||
let err =
|
||||
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 3, "{calls:?}");
|
||||
assert!(!calls[2].contains("--registry="), "{calls:?}");
|
||||
assert!(err.message.contains("notarget"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -432,6 +432,12 @@ pub struct ToolDownloadSettings {
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
/// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
/// installs and update checks never retry against the public npm registry, and the IDE
|
||||
/// fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
|
||||
@@ -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"]);
|
||||
|
||||
|
||||
@@ -701,6 +701,12 @@ impl Host {
|
||||
self.requests.begin(id)
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: nothing
|
||||
/// is fetched from public package registries the user's tools weren't pointed at.
|
||||
pub fn configured_registries_only(&self) -> bool {
|
||||
self.global_settings.effective().tool_downloads.configured_registries_only
|
||||
}
|
||||
|
||||
pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken {
|
||||
let token = self.begin_project_read_request(window, id);
|
||||
if self.project(window).is_ok_and(|p| !p.is_trusted()) {
|
||||
|
||||
@@ -185,6 +185,7 @@ pub async fn agent_registry_install(
|
||||
) -> IdeResult<()> {
|
||||
// The agent then shows in `agent_providers`.
|
||||
let paths = registry_paths(host);
|
||||
let public_npm_fallback = !host.configured_registries_only();
|
||||
let installing = Installing::begin(&id)?;
|
||||
let cancel = host.begin_request(request);
|
||||
// Also a background task of every project window, so it stays visible and can be
|
||||
@@ -211,7 +212,7 @@ pub async fn agent_registry_install(
|
||||
move || cancel.cancel()
|
||||
});
|
||||
report(None, None, false);
|
||||
let result = ide_agent::registry::install(&paths, &id, &cancel, &|e| {
|
||||
let result = ide_agent::registry::install(&paths, &id, public_npm_fallback, &cancel, &|e| {
|
||||
match &e {
|
||||
InstallEvent::Line { text } => report(Some(text.clone()), None, false),
|
||||
InstallEvent::Progress { fraction, message } => {
|
||||
|
||||
@@ -767,6 +767,7 @@ pub async fn maven_dependency_completion(
|
||||
use ide_build::maven::completion::{PomCompletionKind, local_options};
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let central = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -785,7 +786,10 @@ pub async fn maven_dependency_completion(
|
||||
// The local repository answers at once: Central gets `CENTRAL_WAIT`, then the
|
||||
// lookup finishes in the background and fills the cache for the next request.
|
||||
// Offline, behind a proxy or rate-limited, a failed fetch never fails completion.
|
||||
let remote = {
|
||||
// Only the configured package registries: the local repository alone.
|
||||
let remote = if !central {
|
||||
Vec::new()
|
||||
} else {
|
||||
let (cache, target) = (cache.clone(), target.clone());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
|
||||
@@ -212,6 +212,8 @@ pub async fn dependency_versions(
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let config_dir = host.config_dir.clone();
|
||||
// npm and crates.io are asked directly; `go` goes through the configured GOPROXY.
|
||||
let public_registries = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -228,6 +230,9 @@ pub async fn dependency_versions(
|
||||
let versions = cache.versions(&source, &dependency.package, &cancel)?;
|
||||
return Ok(vec![DependencyVersions { dependency, versions, update: None }]);
|
||||
}
|
||||
if !public_registries {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if snap.path.file_name().is_some_and(|name| name == "package.json") {
|
||||
let Some(dependency) = offset.and_then(|offset| npm::dependency_at(&snap.text, offset)) else {
|
||||
return Ok(Vec::new());
|
||||
@@ -310,6 +315,9 @@ pub async fn pypi_package(
|
||||
request: RequestId,
|
||||
) -> IdeResult<Option<pypi::PypiPackage>> {
|
||||
let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?;
|
||||
if host.configured_registries_only() {
|
||||
return Ok(None);
|
||||
}
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -334,6 +342,9 @@ pub async fn pypi_package(
|
||||
/// PyPI's name list, which the first search downloads and a search a day later refreshes.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult<Vec<String>> {
|
||||
if host.configured_registries_only() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let names = host.pypi_names.clone();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
|
||||
@@ -142,7 +142,8 @@ pub(crate) async fn resolve_launch(
|
||||
};
|
||||
if let Some(outputs) = built {
|
||||
progress("Resolving the classpath");
|
||||
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
|
||||
let server = project.lsp.java_launch(&module, test, false, false, false, cancel);
|
||||
let mut info = server_launch_extras(server, SERVER_EXTRAS_WAIT).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
@@ -393,6 +394,33 @@ fn is_maven_aggregator(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
|
||||
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
|
||||
/// when Settings › Gradle › Build and run using asks for the IDE.
|
||||
/// How long a launch whose classpath the IDE's Java build resolved waits for what jdtls adds
|
||||
/// (the JDK it compiles against, the Java project root). jdtls can be busy for minutes importing
|
||||
/// a Maven project (resolving plugin dependencies), and the run doesn't need it:
|
||||
/// [`finish_launch`] picks the project's JDK or an installed one.
|
||||
const SERVER_EXTRAS_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// jdtls' launch info, or an empty one when it doesn't answer within `wait` or fails.
|
||||
async fn server_launch_extras(
|
||||
server: impl std::future::Future<Output = IdeResult<JavaLaunchInfo>>,
|
||||
wait: std::time::Duration,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let fallback =
|
||||
|| JavaLaunchInfo { path_list_separator: if cfg!(windows) { ";" } else { ":" }.into(), ..Default::default() };
|
||||
match tokio::time::timeout(wait, server).await {
|
||||
Ok(Ok(info)) => Ok(info),
|
||||
Ok(Err(e)) if e.kind == ErrorKind::Cancelled => Err(e),
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!("Java launch without the language server's JDK: {}", e.message);
|
||||
Ok(fallback())
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::info!(wait_ms = wait.as_millis(), "Java language server busy; launching without its JDK");
|
||||
Ok(fallback())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
|
||||
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
|
||||
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
|
||||
@@ -922,7 +950,7 @@ pub async fn java_build_workspace(
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
/// Maven Central), and,
|
||||
/// Maven Central unless only the configured package registries are allowed), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
@@ -935,6 +963,7 @@ pub async fn java_junit_runner(
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let registries_only = host.configured_registries_only();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let scope = workspace::scope_for(&project, &module)?;
|
||||
let model = load_launch_model(&scope);
|
||||
@@ -948,7 +977,9 @@ pub async fn java_junit_runner(
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => {
|
||||
Some(download_junit_launcher(&data_dir, &version, registries_only)?)
|
||||
}
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
|
||||
@@ -1017,7 +1048,9 @@ fn junit_launch(
|
||||
}
|
||||
}
|
||||
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
|
||||
/// The launcher jar downloaded once from Maven Central; with only the configured package
|
||||
/// registries allowed (Settings › Tools › Download Mirrors), only one downloaded before.
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str, registries_only: bool) -> IdeResult<PathBuf> {
|
||||
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
|
||||
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
|
||||
}
|
||||
@@ -1026,6 +1059,14 @@ fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf>
|
||||
if dest.is_file() {
|
||||
return Ok(dest);
|
||||
}
|
||||
if registries_only {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{name} is not on the test classpath, and Settings › Tools › Download Mirrors allows only the \
|
||||
configured package registries, so it is not downloaded from Maven Central. Add \
|
||||
org.junit.platform:junit-platform-launcher to the test dependencies, or set Settings › Build Tools › \
|
||||
Maven › Run tests using to Maven."
|
||||
)));
|
||||
}
|
||||
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
|
||||
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
|
||||
let partial = dest.with_extension("jar.part");
|
||||
@@ -1060,6 +1101,22 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_busy_or_failing_language_server_does_not_block_a_resolved_launch() {
|
||||
let wait = std::time::Duration::from_secs(5);
|
||||
// jdtls importing a Maven project: no answer for minutes (#6122).
|
||||
let busy = server_launch_extras(std::future::pending(), wait).await.unwrap();
|
||||
assert!(busy.java_home.is_none() && busy.class_paths.is_empty());
|
||||
assert!(!busy.path_list_separator.is_empty());
|
||||
let failed = server_launch_extras(async { Err(IdeError::unavailable("timed out")) }, wait).await.unwrap();
|
||||
assert!(failed.java_home.is_none());
|
||||
let home = JavaLaunchInfo { java_home: Some(PathBuf::from("/jdk").into()), ..Default::default() };
|
||||
let answered = server_launch_extras(async { Ok(home) }, wait).await.unwrap();
|
||||
assert!(answered.java_home.is_some());
|
||||
let cancelled = server_launch_extras(async { Err(IdeError::cancelled()) }, wait).await;
|
||||
assert_eq!(cancelled.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junit_launch_applies_the_surefire_configuration() {
|
||||
let surefire = ide_build::surefire::SurefireConfig {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -700,7 +700,10 @@ mod tests {
|
||||
// tampered package — and the official host must still be asked.
|
||||
let candidates = mirror::candidates(
|
||||
"https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let asked: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
|
||||
let picked = try_sources(&candidates, |index, candidate| {
|
||||
@@ -731,7 +734,10 @@ mod tests {
|
||||
let url = "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin";
|
||||
let through = mirror::candidates(
|
||||
url,
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(through.len(), 2);
|
||||
assert_eq!(through[0].url, format!("https://gh-proxy.com/{url}"));
|
||||
@@ -741,7 +747,10 @@ mod tests {
|
||||
// A local index's own package is not on GitHub: no prefix may carry it.
|
||||
let local = mirror::candidates(
|
||||
"/srv/market/a.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(local.len(), 1);
|
||||
assert_eq!(local[0].url, "/srv/market/a.oiplugin");
|
||||
|
||||
@@ -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<()> {
|
||||
|
||||
@@ -211,7 +211,7 @@ fn write_index(
|
||||
|
||||
/// The download sources setting with `mirror` as the GitHub proxy prefix (Tools › Download sources).
|
||||
fn download_sources(mirror: &str) -> ide_core::settings::ToolDownloadSettings {
|
||||
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into() }
|
||||
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Security audit lead 5: an index entry's id and version name the download file,
|
||||
|
||||
@@ -1078,6 +1078,7 @@ impl Tools {
|
||||
},
|
||||
&specs,
|
||||
pnpm,
|
||||
!self.downloads.configured_registries_only,
|
||||
cancel,
|
||||
emit,
|
||||
)
|
||||
@@ -1463,6 +1464,12 @@ impl Tools {
|
||||
sources::openvsx_pick(&json, assets, self.platform)
|
||||
}
|
||||
ReleaseSource::MavenCentral { group, artifact } => {
|
||||
if self.downloads.configured_registries_only {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{group}:{artifact} is downloaded from Maven Central, and Settings › Tools › Download Mirrors \
|
||||
allows only the configured package registries"
|
||||
)));
|
||||
}
|
||||
let xml = http.get_text(&sources::maven_metadata_url(group, artifact), cancel)?;
|
||||
sources::maven_pick(group, artifact, &xml)
|
||||
}
|
||||
@@ -1690,7 +1697,7 @@ impl Tools {
|
||||
// on a slow registry takes several seconds per package, more when run side by side.
|
||||
let out = match view(&[]) {
|
||||
Some((true, out)) => Some(out),
|
||||
Some((false, out)) if is_npm_registry_miss(&out) => {
|
||||
Some((false, out)) if !self.downloads.configured_registries_only && is_npm_registry_miss(&out) => {
|
||||
let extra = npm_public_registry_args([packages[0]], pnpm);
|
||||
view(&extra).and_then(|(ok, retry)| ok.then_some(retry))
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ mod tests {
|
||||
const ASSET: &str = "https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/x.zip";
|
||||
|
||||
fn settings(mirror: &str) -> ToolDownloadSettings {
|
||||
ToolDownloadSettings { github_mirror: mirror.into() }
|
||||
ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -110,13 +110,15 @@ pub fn run_streamed_picking(
|
||||
}
|
||||
|
||||
/// Runs an `npm` / `pnpm` command against the user's configured registry first (preserving
|
||||
/// corporate mirrors, proxies, and CAs), and retries once against [`PUBLIC_NPM_REGISTRY`] when
|
||||
/// the configured registry misses the package/version or rejects auth. Preserves the primary
|
||||
/// error if the public registry is unreachable.
|
||||
/// corporate mirrors, proxies, and CAs), and with `public_fallback` retries once against
|
||||
/// [`PUBLIC_NPM_REGISTRY`] when the configured registry misses the package/version or rejects
|
||||
/// auth. Preserves the primary error if the public registry is unreachable. Without
|
||||
/// `public_fallback` (Settings › Tools › Download Mirrors) the configured registry's error stands.
|
||||
pub fn run_npm_with_public_fallback(
|
||||
mut build: impl FnMut(&[String]) -> Command,
|
||||
specs: &[String],
|
||||
pnpm: bool,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<String> {
|
||||
@@ -127,7 +129,7 @@ pub fn run_npm_with_public_fallback(
|
||||
return Ok(output);
|
||||
}
|
||||
let err = failed_command(&label, &output, &status);
|
||||
if cancel.is_cancelled() || !is_npm_registry_miss(&output) {
|
||||
if !public_fallback || cancel.is_cancelled() || !is_npm_registry_miss(&output) {
|
||||
return Err(err);
|
||||
}
|
||||
emit(InstallEvent::Line {
|
||||
|
||||
@@ -603,6 +603,34 @@ esac"#,
|
||||
assert!(!err.message.contains("ECONNRESET"), "{}", err.message);
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: a registry
|
||||
/// that refuses a package (a firewall's 403) is the answer.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn configured_registries_only_never_reach_public_registries() {
|
||||
let env = Env::new();
|
||||
let log = env.root.parent().unwrap().join("npm-only.txt");
|
||||
env.script(&env.sys, "node", "exit 0");
|
||||
env.script(
|
||||
&env.sys,
|
||||
"npm",
|
||||
&format!(
|
||||
r#"echo "$@" >> '{log}'
|
||||
echo "npm error code E403" >&2
|
||||
echo "npm error 403 Forbidden - GET https://nexus.example/yaml-language-server - quarantined" >&2
|
||||
exit 1"#,
|
||||
log = log.display()
|
||||
),
|
||||
);
|
||||
let only = ToolDownloadSettings { configured_registries_only: true, ..Default::default() };
|
||||
let tools = env.tools().with_downloads(only);
|
||||
let err = tools.install("yaml-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert!(err.message.contains("quarantined"), "{}", err.message);
|
||||
let calls = fs::read_to_string(&log).unwrap();
|
||||
assert_eq!(calls.lines().count(), 1, "{calls}");
|
||||
assert!(!calls.contains("registry.npmjs.org"), "{calls}");
|
||||
}
|
||||
|
||||
/// Servers that load TypeScript as a library get one with its JS API: `@latest`
|
||||
/// is TypeScript 7 (native, no `ts.server`), which crashed vue-language-server (#25).
|
||||
/// Uninstalling one keeps the TypeScript another installed server still uses.
|
||||
@@ -1344,7 +1372,10 @@ esac"#,
|
||||
),
|
||||
);
|
||||
// The first mirror is down: the next one is tried before the official host.
|
||||
let downloads = ToolDownloadSettings { github_mirror: "https://down.mirror.test/, https://mirror.test/".into() };
|
||||
let downloads = ToolDownloadSettings {
|
||||
github_mirror: "https://down.mirror.test/, https://mirror.test/".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let emit = |_: InstallEvent| {};
|
||||
env.tools()
|
||||
.with_downloads(downloads)
|
||||
|
||||
@@ -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| {
|
||||
|
||||
+13
-1
@@ -861,7 +861,7 @@ export const commands = {
|
||||
* The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
* the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
* classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
* Maven Central), and,
|
||||
* Maven Central unless only the configured package registries are allowed), and,
|
||||
* for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
*/
|
||||
javaJunitRunner: (module: string, classPaths: string[]) => typedError<JunitLaunch, IdeError>(__TAURI_INVOKE("java_junit_runner", { module, classPaths })),
|
||||
@@ -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[],
|
||||
@@ -14164,6 +14168,14 @@ export type ToolDownloadSettings = {
|
||||
* download on its official host.
|
||||
*/
|
||||
githubMirror?: string,
|
||||
/**
|
||||
* Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
* installs and update checks never retry against the public npm registry, and the IDE
|
||||
* fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
* Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
* crates.io). Off by default.
|
||||
*/
|
||||
configuredRegistriesOnly?: boolean,
|
||||
};
|
||||
|
||||
/** UI-facing state of one tool. */
|
||||
|
||||
@@ -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: [
|
||||
|
||||
@@ -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" });
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -120,6 +120,20 @@ export function viewMenu(
|
||||
];
|
||||
}
|
||||
|
||||
/** Copy as › SQL INSERT / UPDATE / DELETE of the whole selected rows, in the selected order. */
|
||||
function sqlCopies(rows: readonly number[], extractor: ExtractorMenu): MenuItem[] {
|
||||
const copy = (format: ExportFormat) => () =>
|
||||
void Promise.resolve(extractor.table()).then((data) => {
|
||||
const picked = data && rows.flatMap((r) => (data.rows[r] ? [data.rows[r]] : []));
|
||||
if (picked?.length) void writeClipboardText(exportData(format, { ...data!, rows: picked }));
|
||||
});
|
||||
return [
|
||||
{ label: "SQL INSERT", run: copy("sql") },
|
||||
{ label: "SQL UPDATE", run: copy("sqlUpdates") },
|
||||
{ label: "SQL DELETE", run: copy("sqlDeletes") },
|
||||
];
|
||||
}
|
||||
|
||||
/** The Record / Value / Aggregates panel's toggle (IDEA's "Show Value Editor"). */
|
||||
export function PanelToggle({ panel, onChange }: { panel: DataPanel | null; onChange: (p: DataPanel | null) => void }) {
|
||||
return (
|
||||
@@ -300,6 +314,7 @@ export function DataView(props: DataViewProps) {
|
||||
driver={props.driver}
|
||||
sort={sort}
|
||||
onSort={onSort}
|
||||
copyAs={props.extractor && ((rows) => sqlCopies(rows.map(at), props.extractor!))}
|
||||
rowMenu={(rows) => {
|
||||
const own = props.rowMenu?.(rows.map(at)) ?? [];
|
||||
const view = viewMenu(panel, onPanelChange, props.extractor);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { notifications } from "@/workbench/contributions";
|
||||
import {
|
||||
DEFAULT_EXPORT_OPTIONS,
|
||||
EXPORT_FORMATS,
|
||||
SQL_FORMATS,
|
||||
exportData,
|
||||
type ExportData,
|
||||
type ExportFormat,
|
||||
@@ -169,7 +170,7 @@ export function ExportDialog({
|
||||
<CodePreview
|
||||
className={styles.exportPreviewText}
|
||||
aria-label="Export preview"
|
||||
sql={format === "sql"}
|
||||
sql={SQL_FORMATS.has(format)}
|
||||
text={preview + (data.rows.length > PREVIEW_ROWS ? `\n… ${data.rows.length - PREVIEW_ROWS} more rows` : "")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1084,4 +1084,35 @@ describe("the data view's context menu (DataGrip)", () => {
|
||||
"false",
|
||||
);
|
||||
});
|
||||
|
||||
it("copies the selected whole rows as SQL INSERT / UPDATE / DELETE (#6143)", async () => {
|
||||
const writeText = vi.fn((_text: string) => Promise.resolve());
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
const keyed = [{ ...columns[0]!, primaryKey: true }, columns[1]!];
|
||||
const table = () => ({ columns: keyed, rows: data, table: "cities", driver: "postgres" as const });
|
||||
render(
|
||||
<>
|
||||
<DataView
|
||||
columns={keyed}
|
||||
rowCount={2}
|
||||
value={value}
|
||||
panel={null}
|
||||
onPanelChange={() => {}}
|
||||
extractor={{ value: "csv", onChange: () => {}, table }}
|
||||
/>
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
// Only the second row's city cell: the statements still cover its whole row.
|
||||
fireEvent.mouseDown(screen.getAllByRole("gridcell")[3]!, { button: 0 });
|
||||
const copyAs = async (entry: string) => {
|
||||
fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 });
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: /^Copy as/ }));
|
||||
await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: new RegExp(`^${entry}`) })));
|
||||
return writeText.mock.lastCall?.[0];
|
||||
};
|
||||
expect(await copyAs("SQL INSERT")).toBe("INSERT INTO cities (id, city) VALUES (2, 'Beijing');");
|
||||
expect(await copyAs("SQL UPDATE")).toBe("UPDATE cities SET city = 'Beijing' WHERE id = 2;");
|
||||
expect(await copyAs("SQL DELETE")).toBe("DELETE FROM cities WHERE id = 2;");
|
||||
});
|
||||
});
|
||||
@@ -86,6 +86,8 @@ export interface GridProps {
|
||||
onSort?: (column: string, add: boolean) => void;
|
||||
/** Extra context menu items for the selected rows. */
|
||||
rowMenu?: (rows: number[]) => MenuItem[];
|
||||
/** More Copy as entries for the selected rows (SQL statements of the whole rows). */
|
||||
copyAs?: (rows: number[]) => MenuItem[];
|
||||
/** Row number shown for row 0 (paging). */
|
||||
firstRowNumber?: number;
|
||||
/** Row number shown for a row (local sort / filter reorder them); `firstRowNumber + row` otherwise. */
|
||||
@@ -629,6 +631,10 @@ export function Grid(props: GridProps) {
|
||||
{ kind: "action", action: "db.copyAsTsv", label: "TSV", arg: cellActions.current },
|
||||
{ kind: "action", action: "db.copyAsCsv", label: "CSV", arg: cellActions.current },
|
||||
{ kind: "action", action: "db.copyAsOneRow", label: "One-Row", arg: cellActions.current },
|
||||
...(() => {
|
||||
const more = props.copyAs?.(selectedRows()) ?? [];
|
||||
return more.length ? [{ kind: "separator" } as const, ...more] : [];
|
||||
})(),
|
||||
],
|
||||
},
|
||||
{ kind: "action", action: "db.copyWithHeader", arg: cellActions.current },
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -615,7 +619,8 @@ function objectGroups(
|
||||
rows: (details?.indexes ?? []).map((ix) => ({
|
||||
key: `ix-${ix.name}`,
|
||||
name: ix.name,
|
||||
detail: `${ix.unique ? "UNIQUE " : ""}${list(ix.columns)}`,
|
||||
// `UNIQUE` is SQL, not UI text.
|
||||
detail: ix.unique ? ["UNIQUE", list(ix.columns)].join(" ") : list(ix.columns),
|
||||
})),
|
||||
},
|
||||
{
|
||||
@@ -654,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>) =>
|
||||
@@ -717,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);
|
||||
}),
|
||||
},
|
||||
]}
|
||||
>
|
||||
@@ -735,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"
|
||||
@@ -866,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 />
|
||||
|
||||
@@ -469,7 +469,12 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return { columns, rows: rowsOf(r), driver, table: queryTable(text, { driver }) };
|
||||
return {
|
||||
columns: gridColumns.map((c) => ({ name: c.name, type: c.type, primaryKey: c.primaryKey })),
|
||||
rows: rowsOf(r),
|
||||
driver,
|
||||
table: queryTable(text, { driver }),
|
||||
};
|
||||
};
|
||||
const showExport = async (at: { x: number; y: number }) => {
|
||||
const data = await exportSource();
|
||||
|
||||
@@ -195,3 +195,60 @@ it.each<ExportFormat>(["csv", "tsv", "sql", "markdown", "onerow"])("%s retains e
|
||||
const value = "9223372036854775807";
|
||||
expect(exportData(format, data(value))).toContain(value);
|
||||
});
|
||||
|
||||
describe("SQL statements of rows (#6143)", () => {
|
||||
const rows: ExportData = {
|
||||
columns: [
|
||||
{ name: "id", type: "INTEGER", primaryKey: true },
|
||||
{ name: "name", type: "TEXT" },
|
||||
{ name: "note", type: "TEXT" },
|
||||
],
|
||||
rows: [
|
||||
["2", "O'Hara", null],
|
||||
["1", "Ann", "x"],
|
||||
],
|
||||
table: "people",
|
||||
driver: "postgres",
|
||||
};
|
||||
|
||||
it("writes one statement per row, in order, matching rows by the primary key", () => {
|
||||
expect(exportData("sql", rows)).toBe(
|
||||
[
|
||||
`INSERT INTO people (id, name, note) VALUES (2, 'O''Hara', NULL);`,
|
||||
`INSERT INTO people (id, name, note) VALUES (1, 'Ann', 'x');`,
|
||||
].join("\n"),
|
||||
);
|
||||
expect(exportData("sqlUpdates", rows)).toBe(
|
||||
[
|
||||
`UPDATE people SET name = 'O''Hara', note = NULL WHERE id = 2;`,
|
||||
`UPDATE people SET name = 'Ann', note = 'x' WHERE id = 1;`,
|
||||
].join("\n"),
|
||||
);
|
||||
expect(exportData("sqlDeletes", rows)).toBe(
|
||||
[`DELETE FROM people WHERE id = 2;`, `DELETE FROM people WHERE id = 1;`].join("\n"),
|
||||
);
|
||||
expect(exportData("where", rows)).toBe(`WHERE (id = 2) OR (id = 1)`);
|
||||
expect(exportData("where", { ...rows, rows: rows.rows.slice(1) })).toBe(`WHERE id = 1`);
|
||||
});
|
||||
|
||||
it("matches on every column, saying so, when no key is known, and writes IS NULL for a null", () => {
|
||||
const keyless = { ...rows, columns: rows.columns.map((c) => ({ ...c, primaryKey: false })), rows: [rows.rows[0]!] };
|
||||
expect(exportData("sqlDeletes", keyless)).toBe(
|
||||
`-- No primary key is known: rows are matched on every column.\n` +
|
||||
`DELETE FROM people WHERE id = 2 AND name = 'O''Hara' AND note IS NULL;`,
|
||||
);
|
||||
// A null key value too.
|
||||
const nullKey = { ...rows, rows: [[null, "x", "y"]] };
|
||||
expect(exportData("sqlDeletes", nullKey)).toBe(`DELETE FROM people WHERE id IS NULL;`);
|
||||
});
|
||||
|
||||
it("escapes backslashes for drivers that read them, as SQL Inserts did", () => {
|
||||
const d: ExportData = {
|
||||
columns: [{ name: "p", type: "String" }],
|
||||
rows: [["a\\b'"]],
|
||||
table: "t",
|
||||
driver: "clickhouse",
|
||||
};
|
||||
expect(exportData("sql", d)).toBe(`INSERT INTO t (p) VALUES ('a\\\\b''');`);
|
||||
});
|
||||
});
|
||||
@@ -7,24 +7,40 @@
|
||||
import type { DbDriver } from "@/platform/ipc";
|
||||
import { jsonNumber } from "@/platform/losslessJson";
|
||||
import { isNumericColumn } from "./Grid";
|
||||
import { toCsv, toOneRow, toTsv, type Cell } from "./model";
|
||||
import { sqlLiteral, toCsv, toOneRow, toTsv, type Cell } from "./model";
|
||||
import { quoteIdent } from "./sql/complete";
|
||||
|
||||
export type ExportFormat = "csv" | "tsv" | "json" | "sql" | "markdown" | "onerow";
|
||||
export type ExportFormat =
|
||||
| "csv"
|
||||
| "tsv"
|
||||
| "json"
|
||||
| "sql"
|
||||
| "sqlUpdates"
|
||||
| "sqlDeletes"
|
||||
| "where"
|
||||
| "markdown"
|
||||
| "onerow";
|
||||
|
||||
/** The formats written as SQL (highlighted as SQL in the Export Data preview). */
|
||||
export const SQL_FORMATS: ReadonlySet<ExportFormat> = new Set(["sql", "sqlUpdates", "sqlDeletes", "where"]);
|
||||
|
||||
export const EXPORT_FORMATS: ReadonlyArray<{ id: ExportFormat; label: string; extension: string }> = [
|
||||
{ id: "csv", label: "CSV", extension: "csv" },
|
||||
{ id: "tsv", label: "TSV", extension: "tsv" },
|
||||
{ id: "json", label: "JSON", extension: "json" },
|
||||
{ id: "sql", label: "SQL Inserts", extension: "sql" },
|
||||
{ id: "sqlUpdates", label: "SQL Updates", extension: "sql" },
|
||||
{ id: "sqlDeletes", label: "SQL Deletes", extension: "sql" },
|
||||
{ id: "where", label: "Where Clause", extension: "sql" },
|
||||
{ id: "markdown", label: "Markdown", extension: "md" },
|
||||
{ id: "onerow", label: "One-Row", extension: "txt" },
|
||||
];
|
||||
|
||||
export interface ExportData {
|
||||
columns: ReadonlyArray<{ name: string; type: string }>;
|
||||
/** `primaryKey` columns identify a row in SQL Updates, SQL Deletes and Where Clause. */
|
||||
columns: ReadonlyArray<{ name: string; type: string; primaryKey?: boolean }>;
|
||||
rows: ReadonlyArray<readonly Cell[]>;
|
||||
/** Target of SQL inserts (the query's table, when it reads one). */
|
||||
/** Target of SQL statements (the query's table, when it reads one). */
|
||||
table: string;
|
||||
driver: DbDriver;
|
||||
}
|
||||
@@ -89,16 +105,11 @@ export function exportData(
|
||||
});
|
||||
return rows.length ? `[\n${rows.join(",\n")}\n]` : "[]";
|
||||
}
|
||||
case "sql": {
|
||||
const literal = (v: Cell, i: number) =>
|
||||
v === null
|
||||
? "NULL"
|
||||
: numeric[i] && Number.isFinite(Number(v))
|
||||
? v
|
||||
: `'${(d.driver === "clickhouse" || d.driver === "snowflake" ? v.replace(/\\/g, "\\\\") : v).replace(/'/g, "''")}'`;
|
||||
const head = `INSERT INTO ${quoteIdent(d.table, d.driver)} (${names.map((n) => quoteIdent(n, d.driver)).join(", ")}) VALUES`;
|
||||
return d.rows.map((r) => `${head} (${r.map(literal).join(", ")});`).join("\n");
|
||||
}
|
||||
case "sql":
|
||||
case "sqlUpdates":
|
||||
case "sqlDeletes":
|
||||
case "where":
|
||||
return sqlStatements(format, d, numeric);
|
||||
case "markdown": {
|
||||
const cell = (v: Cell) => (v ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
|
||||
const t = laidOut(d, options);
|
||||
@@ -115,3 +126,41 @@ export function exportData(
|
||||
return toOneRow(d.rows, (c) => numeric[c]!);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL Inserts, Updates, Deletes and the Where Clause of the rows, one statement per row in
|
||||
* their order. A row is identified by its primary key columns; with none known, by every
|
||||
* column, which the text says first.
|
||||
*/
|
||||
function sqlStatements(format: ExportFormat, d: ExportData, numeric: readonly boolean[]): string {
|
||||
const ident = (name: string) => quoteIdent(name, d.driver);
|
||||
const names = d.columns.map((c) => ident(c.name));
|
||||
const literal = (v: Cell | undefined, i: number) => sqlLiteral(v ?? null, numeric[i]!, d.driver);
|
||||
const table = ident(d.table);
|
||||
if (format === "sql")
|
||||
return d.rows
|
||||
.map((r) => `INSERT INTO ${table} (${names.join(", ")}) VALUES (${r.map(literal).join(", ")});`)
|
||||
.join("\n");
|
||||
const keys = d.columns.flatMap((c, i) => (c.primaryKey ? [i] : []));
|
||||
const match = keys.length ? keys : names.map((_, i) => i);
|
||||
const where = (r: readonly Cell[]) =>
|
||||
match.map((i) => (r[i] == null ? `${names[i]} IS NULL` : `${names[i]} = ${literal(r[i], i)}`)).join(" AND ");
|
||||
const note = keys.length || !d.rows.length ? "" : "-- No primary key is known: rows are matched on every column.\n";
|
||||
if (format === "where") {
|
||||
if (!d.rows.length) return "";
|
||||
const body = d.rows.length === 1 ? where(d.rows[0]!) : d.rows.map((r) => `(${where(r)})`).join(" OR ");
|
||||
return `${note}WHERE ${body}`;
|
||||
}
|
||||
if (format === "sqlDeletes") return note + d.rows.map((r) => `DELETE FROM ${table} WHERE ${where(r)};`).join("\n");
|
||||
// Updates set the other columns (every column when no key is known).
|
||||
const set = keys.length ? names.flatMap((_, i) => (keys.includes(i) ? [] : [i])) : match;
|
||||
return (
|
||||
note +
|
||||
d.rows
|
||||
.map(
|
||||
(r) =>
|
||||
`UPDATE ${table} SET ${set.map((i) => `${names[i]} = ${literal(r[i], i)}`).join(", ")} WHERE ${where(r)};`,
|
||||
)
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
@@ -30,9 +30,18 @@ export function toTsv(header: readonly string[] | null, rows: ReadonlyArray<read
|
||||
* single-quoted with `'` doubled. `numeric(c)` decides quoting per column.
|
||||
*/
|
||||
export function toOneRow(rows: ReadonlyArray<readonly Cell[]>, numeric: (col: number) => boolean): string {
|
||||
const literal = (v: Cell, c: number) =>
|
||||
v === null ? "NULL" : numeric(c) && Number.isFinite(Number(v)) ? v : `'${v.replace(/'/g, "''")}'`;
|
||||
return rows.flatMap((r) => r.map(literal)).join(", ");
|
||||
return rows.flatMap((r) => r.map((v, c) => sqlLiteral(v, numeric(c)))).join(", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* A value as an SQL literal: NULL, a number unquoted in a numeric column, else single-quoted
|
||||
* with `'` doubled (and `\\` doubled for drivers that read backslash escapes in strings).
|
||||
*/
|
||||
export function sqlLiteral(v: Cell, numeric: boolean, driver?: DbDriver): string {
|
||||
if (v === null) return "NULL";
|
||||
if (numeric && Number.isFinite(Number(v))) return v;
|
||||
const escaped = driver === "clickhouse" || driver === "snowflake" ? v.replace(/\\/g, "\\\\") : v;
|
||||
return `'${escaped.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
/** RFC 4180 CSV; NULL is an empty field. */
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -118,7 +118,7 @@ export interface ValidSettings extends WorkflowSettings {
|
||||
proxy: ProxySettingsValid;
|
||||
remoteDevelopment: { idleTimeoutMinutes: number };
|
||||
/** Tools › Download sources: a mirror prefix for the installer's release downloads. */
|
||||
toolDownloads: { githubMirror: string };
|
||||
toolDownloads: { githubMirror: string; configuredRegistriesOnly: boolean };
|
||||
languages: LanguagesValid;
|
||||
cmake: ReturnType<typeof validateCMake>;
|
||||
projectStructure: ProjectStructureValid;
|
||||
@@ -227,7 +227,7 @@ export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
notifications: DEFAULT_NOTIFICATIONS,
|
||||
proxy: DEFAULT_PROXY,
|
||||
remoteDevelopment: { idleTimeoutMinutes: DEFAULT_REMOTE_IDLE_MINUTES },
|
||||
toolDownloads: { githubMirror: "" },
|
||||
toolDownloads: { githubMirror: "", configuredRegistriesOnly: false },
|
||||
languages: DEFAULT_LANGUAGES,
|
||||
cmake: {},
|
||||
projectStructure: DEFAULT_PROJECT_STRUCTURE,
|
||||
@@ -435,6 +435,7 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
|
||||
typeof obj(root.toolDownloads).githubMirror === "string"
|
||||
? String(obj(root.toolDownloads).githubMirror).trim()
|
||||
: "",
|
||||
configuredRegistriesOnly: obj(root.toolDownloads).configuredRegistriesOnly === true,
|
||||
},
|
||||
languages: validateLanguages(root.languages),
|
||||
cmake: validateCMake(root.cmake),
|
||||
|
||||
@@ -892,7 +892,20 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
title: "Download Mirrors",
|
||||
group: TOOLS_GROUP,
|
||||
order: 590,
|
||||
keywords: ["mirror", "download", "github", "proxy", "slow", "language server", "accelerate"],
|
||||
keywords: [
|
||||
"mirror",
|
||||
"download",
|
||||
"github",
|
||||
"proxy",
|
||||
"slow",
|
||||
"language server",
|
||||
"accelerate",
|
||||
"registry",
|
||||
"npm",
|
||||
"maven central",
|
||||
"nexus",
|
||||
"artifactory",
|
||||
],
|
||||
sections: [
|
||||
{
|
||||
title: "GitHub",
|
||||
@@ -905,6 +918,17 @@ export const TOOLS_PAGES: PageSpec[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Package Registries",
|
||||
options: [
|
||||
{
|
||||
kind: "toggle",
|
||||
key: "toolDownloads.configuredRegistriesOnly",
|
||||
label: "Use only the configured package registries",
|
||||
hint: "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -4157,5 +4157,14 @@
|
||||
"Keys": "Keys",
|
||||
"Triggers": "Triggers",
|
||||
"Filter by name or type": "Filter by name or type",
|
||||
"Filter columns": "Filter columns"
|
||||
"Filter columns": "Filter columns",
|
||||
"Package Registries": "Package Registries",
|
||||
"Use only the configured package registries": "Use only the configured package registries",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).",
|
||||
"SQL Updates": "SQL Updates",
|
||||
"SQL Deletes": "SQL Deletes",
|
||||
"Where Clause": "Where Clause",
|
||||
"SQL INSERT": "SQL INSERT",
|
||||
"SQL UPDATE": "SQL UPDATE",
|
||||
"SQL DELETE": "SQL DELETE"
|
||||
}
|
||||
@@ -10172,5 +10172,15 @@
|
||||
"Keys": "Ключи",
|
||||
"Triggers": "Триггеры",
|
||||
"Filter by name or type": "Фильтр по имени или типу",
|
||||
"Filter columns": "Фильтр столбцов"
|
||||
"Filter columns": "Фильтр столбцов",
|
||||
"Package Registries": "Реестры пакетов",
|
||||
"Use only the configured package registries": "Использовать только настроенные реестры пакетов",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "Для корпоративного реестра, например Nexus или Artifactory: при установке инструментов и агентов не выполняется повторная попытка через публичный реестр npm, если настроенный реестр отклонил пакет или не нашёл его, а сама IDE ничего не загружает из Maven Central, npm, PyPI или crates.io (JUnit Launcher, автодополнение версий зависимостей).",
|
||||
"SQL Updates": "SQL-обновления",
|
||||
"SQL Deletes": "SQL-удаления",
|
||||
"Where Clause": "Условие WHERE",
|
||||
"SQL INSERT": "SQL INSERT",
|
||||
"SQL UPDATE": "SQL UPDATE",
|
||||
"SQL DELETE": "SQL DELETE",
|
||||
"Column comment": "Комментарий к столбцу"
|
||||
}
|
||||
@@ -8833,5 +8833,15 @@
|
||||
"Keys": "Anahtarlar",
|
||||
"Triggers": "Tetikleyiciler",
|
||||
"Filter by name or type": "Ada veya türe göre filtrele",
|
||||
"Filter columns": "Sütunları filtrele"
|
||||
"Filter columns": "Sütunları filtrele",
|
||||
"Package Registries": "Paket Kayıt Defterleri",
|
||||
"Use only the configured package registries": "Yalnızca yapılandırılmış paket kayıt defterlerini kullan",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "Nexus veya Artifactory gibi bir şirket kayıt defteri için: araçlar ve ajanlar yüklenirken yapılandırılmış kayıt defteri bir paketi reddederse ya da bulamazsa genel npm kayıt defterinde yeniden denenmez ve IDE kendisi Maven Central, npm, PyPI veya crates.io'dan hiçbir şey indirmez (JUnit başlatıcısı, bağımlılık sürümü tamamlama).",
|
||||
"SQL Updates": "SQL Güncelleme İfadeleri",
|
||||
"SQL Deletes": "SQL Silme İfadeleri",
|
||||
"Where Clause": "WHERE Koşulu",
|
||||
"SQL INSERT": "SQL INSERT",
|
||||
"SQL UPDATE": "SQL UPDATE",
|
||||
"SQL DELETE": "SQL DELETE",
|
||||
"Column comment": "Sütun yorumu"
|
||||
}
|
||||
@@ -9371,5 +9371,15 @@
|
||||
"Keys": "鍵",
|
||||
"Triggers": "觸發器",
|
||||
"Filter by name or type": "依名稱或類型篩選",
|
||||
"Filter columns": "篩選欄"
|
||||
"Filter columns": "篩選欄",
|
||||
"Package Registries": "套件倉庫",
|
||||
"Use only the configured package registries": "僅使用已設定的套件倉庫",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "適用於 Nexus、Artifactory 等公司倉庫:安裝工具和 agent 時,若已設定的倉庫拒絕或找不到某個套件,不再改從公開 npm 倉庫重試;IDE 本身也不會從 Maven Central、npm、PyPI 或 crates.io 取得任何內容(JUnit 啟動器、相依版本補全)。",
|
||||
"SQL Updates": "SQL Update 陳述式",
|
||||
"SQL Deletes": "SQL Delete 陳述式",
|
||||
"Where Clause": "Where 子句",
|
||||
"SQL INSERT": "SQL INSERT 陳述式",
|
||||
"SQL UPDATE": "SQL UPDATE 陳述式",
|
||||
"SQL DELETE": "SQL DELETE 陳述式",
|
||||
"Column comment": "欄位註解"
|
||||
}
|
||||
@@ -10601,5 +10601,15 @@
|
||||
"Keys": "键",
|
||||
"Triggers": "触发器",
|
||||
"Filter by name or type": "按名称或类型过滤",
|
||||
"Filter columns": "过滤列"
|
||||
"Filter columns": "过滤列",
|
||||
"Package Registries": "包仓库",
|
||||
"Use only the configured package registries": "仅使用已配置的包仓库",
|
||||
"For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "适用于 Nexus、Artifactory 等公司仓库:安装工具和 agent 时,若已配置的仓库拒绝或找不到某个包,不再改从公共 npm 仓库重试;IDE 自身也不会从 Maven Central、npm、PyPI 或 crates.io 获取任何内容(JUnit 启动器、依赖版本补全)。",
|
||||
"SQL Updates": "SQL Update 语句",
|
||||
"SQL Deletes": "SQL Delete 语句",
|
||||
"Where Clause": "Where 子句",
|
||||
"SQL INSERT": "SQL INSERT 语句",
|
||||
"SQL UPDATE": "SQL UPDATE 语句",
|
||||
"SQL DELETE": "SQL DELETE 语句",
|
||||
"Column comment": "列注释"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача