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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 069e587746 fix(debugger): enable Stop in the Debug tool window for the selected session only
Stop was enabled while any session was live, so a finished session's tab
showed an active Stop that did nothing. It now follows the selected tab like
the other toolbar buttons.
2026-11-20 18:33:20 +08:00
eclix-del 9c12cacbdb fix(database): 自定义 JDBC 源按 URL 方言加引号,修复 Oracle 混合大小写表名 (#4765)
fix(database): quote completions of custom JDBC sources by their URL's dialect

A custom JDBC source has driver "jdbc", so completion quoted only names that aren't plain words. On Oracle (and other case-folding servers) a mixed-case table such as BAS_MeterUnit was inserted bare and folded to BAS_METERUNIT (ORA-00942).

Completion now takes the dialect from the source's URL scheme (jdbc:oracle:thin:@…, jdbc:postgresql://…), using the vendor scheme table Data Source from URL already uses, and quotes table, column and JOIN candidates the way that dialect needs. Unknown schemes keep the previous behaviour.

Co-authored-by: eclix-del <[email protected]>
2026-11-20 18:27:18 +08:00
eclix-del d773621276 fix(database): 补全只遍历数据源选中的 schema,避免 Oracle 大实例下阻塞查询 (#4766)
JDBC completion read the columns of every schema on the server. The JDBC bridge runs one command at a time, so on a large Oracle instance (dozens of system schemas, minutes of metadata) the user's statements queued behind it.

Completion now reads only the schemas the data source's Schemas tab picks, matched the way the database tree matches them (exact names, `*` / `?` patterns); sources that show all schemas behave as before.

Co-authored-by: eclix-del <[email protected]>
2026-11-20 18:25:54 +08:00
9 змінених файлів з 192 додано та 16 видалено

No files matched your search

+7 -1
Переглянути файл
@@ -602,7 +602,13 @@ impl DbManager {
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
let mut tables = vec![];
let mut column_count = 0;
let schemas = self.schemas(id).await?;
// Read the schemas the source's Schemas tab picks, like the database tree does. It also
// keeps large instances usable: an Oracle server exposes dozens of system schemas, and
// dumping the columns of all of them takes minutes, during which the bridge (a single
// Java process that runs one command at a time) executes none of the user's statements.
let introspection = self.source(id)?.introspection;
let schemas: Vec<String> =
self.schemas(id).await?.into_iter().filter(|s| introspection.shows_schema(s)).collect();
for schema in &schemas {
// Columns of the whole namespace in one call; a driver that refuses it still completes tables.
let mut columns = if column_count < crate::MAX_META_ROWS {
+59
Переглянути файл
@@ -124,6 +124,45 @@ impl Default for DbIntrospection {
}
}
impl DbIntrospection {
/// Whether the tree shows this schema: every one with `all_schemas`, otherwise it has to
/// match one of the `schemas` patterns. The completion model uses the same test, so it
/// offers exactly the tables the tree lists (and does not read the ones it never shows).
pub fn shows_schema(&self, name: &str) -> bool {
self.all_schemas
|| self.schemas.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).any(|p| schema_matches(p, name))
}
}
/// `*` matches any run of characters, `?` a single one; a pattern without wildcards matches the
/// name as typed (the dialog fills names from the list the server returned, so case is settled).
fn schema_matches(pattern: &str, name: &str) -> bool {
if !pattern.contains('*') && !pattern.contains('?') {
return pattern == name;
}
let p: Vec<char> = pattern.chars().collect();
let n: Vec<char> = name.chars().collect();
let (mut pi, mut ni) = (0, 0);
// Position of the last `*` and how much of the name it has already swallowed.
let mut star: Option<(usize, usize)> = None;
while ni < n.len() {
if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
pi += 1;
ni += 1;
} else if pi < p.len() && p[pi] == '*' {
star = Some((pi, ni));
pi += 1;
} else if let Some((at, taken)) = star {
pi = at + 1;
ni = taken + 1;
star = Some((at, taken + 1));
} else {
return false;
}
}
p[pi..].iter().all(|&c| c == '*')
}
/// Advanced tab: a driver property. PostgreSQL: run-time parameters (and
/// `application_name`); MySQL: session variables (and `charset`, `collation`);
/// SQLite: pragmas. See [`crate::conn`].
@@ -765,4 +804,24 @@ mod tests {
assert_eq!(r.snowflake().auth, DbSnowflakeAuth::Browser);
assert_eq!(scheme_driver("snowflake"), Some(DbDriver::Snowflake));
}
#[test]
fn introspection_shows_only_the_picked_schemas() {
let mut i = DbIntrospection::default();
assert!(i.shows_schema("SYS"), "the default reads every schema");
i.all_schemas = false;
assert!(!i.shows_schema("SYS"), "nothing picked: the tree lists nothing either");
i.schemas = vec!["XMCB".into(), " APP_* ".into()];
assert!(i.shows_schema("XMCB"));
assert!(i.shows_schema("APP_INFO"));
assert!(!i.shows_schema("APP"), "`*` needs the text that follows it");
assert!(!i.shows_schema("SYS"));
assert!(!i.shows_schema("xmcb"), "patterns match the names the server returned");
i.schemas = vec!["?".into()];
assert!(i.shows_schema("A"));
assert!(!i.shows_schema("AB"));
}
}
+5
Переглянути файл
@@ -112,6 +112,7 @@ const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
import { formatElapsed } from "./resultView";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { jdbcDialect } from "./vendors";
export { SQL_LANGUAGE };
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
@@ -1069,6 +1070,9 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl
const current = id ? databaseRequest(id) : projectRequest();
const source = sourceById(id);
const driver: DbDriver = source?.driver ?? "sqlite";
// A custom JDBC source (`driver: "jdbc"`) says nothing about how its server folds
// identifiers; its URL does (`jdbc:oracle:thin:@…`). Quoting follows that dialect.
const dialect = driver === "jdbc" ? jdbcDialect(source?.url) : null;
const model = id ? (useDatabase.getState().completion[id] ?? null) : null;
if (id && !model) void loadCompletion(id);
// Unqualified names resolve in the console's active schema (IDEA's schema dropdown).
@@ -1091,6 +1095,7 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl
model: scoped,
analysis,
driver,
dialect,
sourceName: source?.name ?? undefined,
catalog: cataloged ? catalogOf(id) : undefined,
});
+28 -12
Переглянути файл
@@ -63,20 +63,26 @@ export function shouldAutoCompleteSql(analysis: Analysis): boolean {
const MAX_ALL_COLUMNS = 3000;
/** `name`, quoted when the dialect needs it (case, characters, reserved words). */
export function quoteIdent(name: string, driver: DbDriver): string {
/**
* `name`, quoted when the dialect needs it (case, characters, reserved words).
* A `jdbc` source quotes by the dialect its URL speaks (`dialect`); without one, only
* what is not a plain word is quoted, which is right for the dialects that fold case
* neither way.
*/
export function quoteIdent(name: string, driver: DbDriver, dialect?: DbDriver | null): string {
const d = driver === "jdbc" && dialect ? dialect : driver;
const plain =
driver === "postgres"
d === "postgres"
? /^[a-z_][a-z0-9_$]*$/
: // Oracle and Snowflake fold unquoted names to upper case; a lower-case name must stay quoted.
driver === "oracle" || driver === "snowflake"
d === "oracle" || d === "snowflake"
? /^[A-Z_][A-Z0-9_$]*$/
: driver === "clickhouse"
: d === "clickhouse"
? /^[A-Za-z_][A-Za-z0-9_]*$/
: /^[A-Za-z_][A-Za-z0-9_$]*$/;
if (plain.test(name) && !isReserved(name, driver)) return name;
if (driver === "clickhouse") return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
const q = driver === "mysql" ? "`" : '"';
if (plain.test(name) && !isReserved(name, d)) return name;
if (d === "clickhouse") return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
const q = d === "mysql" ? "`" : '"';
return q + name.split(q).join(q + q) + q;
}
@@ -121,11 +127,20 @@ export interface CompletionInput {
model: DbCompletion | null;
analysis: Analysis;
driver: DbDriver;
/** The dialect a `jdbc` source speaks, from its URL (`jdbcDialect`); quoting follows it. */
dialect?: DbDriver | null;
/** Data source name, shown next to tables like IDEA does. */
sourceName?: string;
}
export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog }: CompletionInput): SqlCandidate[] {
export function sqlCandidates({
model,
analysis: a,
driver,
dialect,
sourceName,
catalog,
}: CompletionInput): SqlCandidate[] {
const eq = nameMatcher(driver);
const ctx = a.context;
if (ctx.kind === "none") return [];
@@ -135,7 +150,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog
const kw = (k: string) => (lower ? k.toLowerCase() : k);
const tables = model?.tables ?? [];
const defaultSchema = model?.defaultSchema ?? "";
const exact = (n: string) => quoteIdent(n, driver);
const exact = (n: string) => quoteIdent(n, driver, dialect);
// Snowflake folds unquoted names to upper case, so a name typed in lower case may stay lower case.
const lowerQualifier = !!a.qualifier?.length && a.qualifier.every((p) => /[a-z]/.test(p) && p === p.toLowerCase());
// What is typed decides: the name's own prefix, else the qualifier before it, else the statement's keywords.
@@ -270,7 +285,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog
case "table": {
const taken = new Set(a.refs.flatMap((r) => [refName(r).toLowerCase(), r.name.toLowerCase()]));
if (ctx.join) out.push(...joinCandidates(a, model, driver, taken, kw));
if (ctx.join) out.push(...joinCandidates(a, model, driver, dialect, taken, kw));
for (const c of a.ctes) out.push({ label: c.name, kind: "table", tail: "(CTE)", boost: 40 });
const schemas = new Set<string>();
for (const t of tables) {
@@ -472,13 +487,14 @@ function joinCandidates(
a: Analysis,
model: DbCompletion | null,
driver: DbDriver,
dialect: DbDriver | null | undefined,
taken: Set<string>,
kw: Kw,
): SqlCandidate[] {
if (!model) return [];
const eq = nameMatcher(driver);
const out: SqlCandidate[] = [];
const q = (n: string) => quoteIdent(n, driver);
const q = (n: string) => quoteIdent(n, driver, dialect);
const seen = new Set<string>();
const local = (s: string) => eq(s, model.defaultSchema) || driver === "sqlite";
const tableText = (schema: string, name: string) => (local(schema) ? q(name) : `${q(schema)}.${q(name)}`);
+46
Переглянути файл
@@ -8,6 +8,7 @@ import { identName, inLiteral, lex } from "./lexer";
import { DATA_TYPES, statementStarters } from "./dialect";
import { bindParams, findParams } from "./params";
import { SqlResolver } from "./resolve";
import { jdbcDialect } from "../vendors";
const col = (name: string, dataType = "INTEGER", primaryKey = false, hasDefault = false) => ({
name,
@@ -280,6 +281,51 @@ describe("completion candidates", () => {
expect(quoteIdent('a"b', "oracle")).toBe('"a""b"');
});
it("quotes a custom JDBC source's names by the dialect its URL speaks", () => {
expect(jdbcDialect("jdbc:oracle:thin:@//db.local:1521/ORCL")).toBe("oracle");
expect(jdbcDialect("JDBC:Oracle:thin:@db:1521:ORCL")).toBe("oracle");
expect(jdbcDialect("jdbc:postgresql://db.local/shop")).toBe("postgres");
expect(jdbcDialect("jdbc:MariaDB://db/shop")).toBe("mysql");
expect(jdbcDialect("jdbc:sqlserver://db;databaseName=shop")).toBe("sqlServer");
expect(jdbcDialect("jdbc:unknown://db/shop")).toBeNull();
expect(jdbcDialect("")).toBeNull();
expect(jdbcDialect(null)).toBeNull();
// Oracle folds unquoted names to upper case, so only an upper-case name stays bare.
expect(quoteIdent("MyTable", "jdbc", "oracle")).toBe('"MyTable"');
expect(quoteIdent("MYTABLE", "jdbc", "oracle")).toBe("MYTABLE");
expect(quoteIdent("mytable", "jdbc", "oracle")).toBe('"mytable"');
// Without a dialect, a plain word still stays bare: the source never said which server it is.
expect(quoteIdent("MyTable", "jdbc")).toBe("MyTable");
expect(quoteIdent("MyTable", "jdbc", null)).toBe("MyTable");
const hr: DbCompletion = {
defaultSchema: "HR",
tables: [
{
schema: "HR",
name: "MyTable",
kind: "table",
columns: [col("ID", "NUMBER", true), col("fullName", "VARCHAR2")],
},
],
foreignKeys: [],
};
const tables = sqlCandidates({
model: hr,
analysis: at("SELECT * FROM |", "jdbc"),
driver: "jdbc",
dialect: jdbcDialect("jdbc:oracle:thin:@//db.local:1521/ORCL"),
});
expect(tables.find((c) => c.label === "MyTable")?.insert).toBe('"MyTable"');
const columns = sqlCandidates({
model: hr,
analysis: at("SELECT | FROM MyTable", "jdbc"),
driver: "jdbc",
dialect: "oracle",
});
expect(columns.find((c) => c.label === "ID")?.insert).toBe("ID");
expect(columns.find((c) => c.label === "fullName")?.insert).toBe('"fullName"');
});
it("offers Snowflake vocabulary and quotes names the server folds to upper case", () => {
expect(statementStarters("snowflake")).toEqual(
expect.arrayContaining([
+9
Переглянути файл
@@ -176,6 +176,15 @@ const SCHEMES: Record<string, string> = {
export const vendorOfScheme = (scheme: string): DbVendor | undefined => BY_ID.get(SCHEMES[scheme.toLowerCase()] ?? "");
/**
* The dialect a custom JDBC source's URL speaks (`jdbc:oracle:thin:@//db:1521/ORCL` → `oracle`):
* its `driver: "jdbc"` says nothing about how the server folds identifiers.
*/
export function jdbcDialect(url: string | null | undefined): DbDriver | null {
const scheme = /^(?:jdbc:)?([a-z][a-z0-9]*):/i.exec((url ?? "").trim())?.[1] ?? "";
return vendorOfScheme(scheme)?.driver ?? null;
}
const bracketed = (host: string) => (host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
/** The JDBC URL of a data source's fields (the General tab's URL preview). */
+26 -1
Переглянути файл
@@ -10,7 +10,15 @@ import {
updateBreakpoint,
useBreakpoints,
} from "../breakpoints/store";
import { adoptSession, useExecutionPoint, useDebug, handleDebugEvent, type DebugSession } from "../state";
import {
adoptSession,
selectSession,
stopTarget,
useExecutionPoint,
useDebug,
handleDebugEvent,
type DebugSession,
} from "../state";
import { getContext } from "@/platform/context";
import styles from "../editor/editor.module.css";
@@ -314,6 +322,23 @@ describe("session events", () => {
expect(getContext().debugSessionActive).toBe(false);
});
it("enables Stop for the selected session tab only (#4738)", () => {
adoptSession(80, { name: "server" });
adoptSession(81, { name: "client" });
selectSession(80);
expect(getContext().debugCanStop).toBe(true);
expect(stopTarget()?.id).toBe(80);
handleDebugEvent(81, { kind: "terminated" });
selectSession(81);
// The finished session's tab: Stop is off although the server still runs.
expect(getContext().debugSessionActive).toBe(true);
expect(getContext().debugCanStop).toBe(false);
expect(stopTarget()).toBeNull();
selectSession(80);
expect(getContext().debugCanStop).toBe(true);
handleDebugEvent(80, { kind: "terminated" });
});
it("ignores sessions this window did not start, but adopts children of its own", async () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
adoptSession(90, { name: "app", adapter: "js-debug" });
+3 -2
Переглянути файл
@@ -79,6 +79,7 @@ import {
startPreparedSession,
stopSession,
stopAssociatedProcess,
stopTarget,
useDebug,
type DebugSession,
} from "./state";
@@ -560,9 +561,9 @@ export function registerDebugActions(): () => void {
title: "Stop",
category: "Debug",
icon: "stop",
when: "debugSessionActive",
when: "debugCanStop",
run: () => {
const s = activeSession() ?? Object.values(useDebug.getState().sessions).find(isLive);
const s = stopTarget();
if (s) void stopSession(s.id);
},
},
+9
Переглянути файл
@@ -197,6 +197,13 @@ export function isLive(s: DebugSession | null | undefined): boolean {
return !!s && s.status !== "terminated";
}
/** The session the Debug tool window's Stop acts on: the selected one while it runs (any live one when none is selected). */
export function stopTarget(): DebugSession | null {
const s = activeSession();
if (s) return isLive(s) ? s : null;
return Object.values(useDebug.getState().sessions).find(isLive) ?? null;
}
/** Whether the session with this id is still there and running, as of now. */
export const isLiveSession = (id: DebugSessionId) => isLive(useDebug.getState().sessions[id]);
@@ -405,6 +412,8 @@ export function publishContext() {
});
const anyLive = Object.values(useDebug.getState().sessions).some(isLive);
setContext("debugSessionActive", anyLive);
// Stop acts on the selected session tab, so a finished one doesn't stop another session.
setContext("debugCanStop", !!stopTarget());
setContext("debugSessionRunning", s?.status === "running");
setContext("debugSessionPaused", s?.status === "paused");
// Dart and Flutter sessions: Hot Reload / Hot Restart.