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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 871187e569 feat(terminal): add an optional Paste on right click
Settings › Tools › Terminal gains Paste on right click (terminal.rightClickPaste, off by default). When on, a plain right-click in a terminal pane pastes the clipboard through the same path as Paste and middle-click paste, so bracketed paste and multiline handling are unchanged; Ctrl or Shift + right-click still opens the context menu, and focus stays in the pane.

Fixes #6634
2026-11-29 16:55:05 +08:00
l0ng-ai 4812d28614 fix(dotnet): show only top-level solutions above the Project view folder (#6820)
Since #6224 the Project view listed every discovered .NET solution and standalone project above the project folder, so a polyglot repository with many solutions in subfolders got dozens of root nodes ahead of its own folder. Only solution and project files directly in a content root (the project root, or each workspace member folder) now get a node there; nested ones stay in their folders, where they already showed.

Fixes #6803
2026-11-29 16:47:13 +08:00
Muuтаmuutot 7c9f343ca4 feat(vcs): open changed files at their repository revision (#6816)
Adds Open Repository Version to the Git Log changed-files menu: each selected file opens read-only at its revision after the change through the existing revision editor. Deleted files and directory symlinks are skipped in both enablement and execution, read-only working-tree files still qualify, and grouped directory selections contribute their files. Includes zh and zh-TW translations.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:40:43 +08:00
Muuтаmuutot d815a8ef44 feat(editor): add Cut Line Backward action (#6815)
Adds Cut Line Backward, mapped from EditorCutLineBackward: it cuts from the start of the previous line to the primary caret (from the document start on the first line) and collects repeated cuts into one clipboard entry like the other kill-ring cuts, a backward cut going before the collected text. Includes zh and zh-TW translations.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:36:01 +08:00
l0ng-ai d22c42e471 test(vim): count Disable Sticky Lines for Language as a known action (#6817)
EditorStickyLinesDisableForLang (#6814) maps to editor.disableStickyLinesForLanguage, which no keymap preset binds, so the :action id check in rc.test.ts failed on main. The action is now in its known list.
2026-11-29 16:32:41 +08:00
Muuтаmuutot a111b32e11 feat(editor): disable sticky lines for the current language (#6814)
Adds a View action, Disable Sticky Lines for Language, that appends the active document's language to the existing per-language disabled list without touching the global Sticky Lines setting. It is available when sticky lines are on and the active editor has a known language (never for a notebook cell), keeps other entries, skips redundant writes, and is mapped from the EditorStickyLinesDisableForLang action id. Includes zh and zh-TW translations.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:22:20 +08:00
Muuтаmuutot f7141f6515 feat(search): inspect previewable results on single click (#6813)
With the preview shown, a single click on a previewable Search Everywhere result opened it and closed the popup, so results could not be browsed in the preview by mouse. A single click now only selects and previews such a row; a double click, Enter or Shift+Enter opens it. Action rows, rows without a preview and clicks with the preview hidden still open on a single click.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:21:58 +08:00
Muuтаmuutot 2d14368d2c feat(structure): jump to filtered symbols with F4 (#6811)
F4 in the File Structure popup navigated only when the tree had focus. The filter input now handles F4 like Enter, opening the selected symbol with the same node resolution, so the empty-query preselection, both narrowing modes, explicit tree selection and unmatched filters behave the same for both keys.

Co-authored-by: muutot <[email protected]>
2026-11-29 16:21:40 +08:00
Vladislav Kuzmin 5cbc4134a1 feat(database): join tables across saved data sources in a query workspace (#6265)
Query Workspace, opened from the Database tree, runs a single SELECT joining two to eight tables from saved PostgreSQL, ClickHouse, SQLite and file-backed DuckDB sources. Typing # picks a saved source without connecting; table and key completion fetch that source's metadata, and optional aliases disambiguate duplicate names. The project host reads the projected columns and join keys on independent read-only connections, complete or failing, within per-input and total row/byte limits, and joins them in the installed DuckDB JDBC driver. Run executes the statement at the caret or the selected statements in order and Execute Script runs the editor; each statement keeps its timing, result tab and page, and Stop or the first error ends the batch.

Closes #6177

Co-authored-by: principalwater <[email protected]>
2026-11-29 16:14:39 +08:00
Vladislav Kuzmin 5a92145ad9 feat(database): open and create DuckLake catalogs (#6206)
A DuckDB data source can be a DuckLake catalog: an existing catalog file or named DuckDB secret is attached read-only, without migrating its metadata version, optionally with a relocated local data directory. Create New DuckLake is a separate, confirmed action that requires a new directory, so testing or reconnecting never initializes a catalog. The Rust side limits DuckLake sources to read-only jdbc:duckdb with no credentials, properties, tunnels or session overrides, and saving catalog settings goes through a dedicated approval command so an older remote host cannot drop them silently. The JDBC bridge JAR is rebuilt from the updated sources.

Part of #334

Co-authored-by: principalwater <[email protected]>
2026-11-29 16:13:52 +08:00
Bert Verhelstтаbertyhell 4354839584 feat(database): edit a PostgreSQL table's owner, tablespace, storage options and persistence (#6693)
Modify Table on a PostgreSQL table gets a Properties tab for owner, tablespace, storage options (including toast.*) and logged/unlogged persistence, with access method and partition key shown read-only. Each change adds one alter table statement to the preview; the owner change runs last, after a rename. The properties are read with one pg_class query, with a fallback for catalogs before PostgreSQL 12; engines that report none show no tab.

Part of #6306

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:56:23 +08:00
Bert Verhelstтаbertyhell e1a1becadd feat(python): offer imports of names from installed packages in Alt+Enter (#6676)
basedpyright offers import fixes only for project and standard-library symbols. A library symbol index now reads each public module of the interpreter's site-packages once (its __all__, otherwise public top-level definitions, preferring stubs), rebuilt when a folder changes, and Alt+Enter on an unresolved name lists Import rows from it when the server has no import fix for that name.

Closes #6521

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:55:16 +08:00
Bert Verhelstтаbertyhell ad685ea19e feat(debugger): Disassembly view and instruction stepping for native debugging (#6694)
Native debug sessions whose adapter supports disassemble get a Disassembly tab showing the selected frame's instructions with the program counter highlighted, following stepping and frame selection, including frames without source. Show Disassembly is on the Frames list; Step Over Instruction and Step Into Instruction send steps with instruction granularity and are disabled with a reason when the adapter lacks it. Frames keep instructionPointerReference; when the PC is not where the requested window expects it, the view reads again from the PC.

lldb-dap sends instruction bytes already spaced and pads mnemonics unevenly; the view strips the spacing before grouping the bytes and pads mnemonics to one width.

Part of #5922

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:54:29 +08:00
Bert Verhelstтаbertyhell 5fb8f21c60 feat(debugger): native Memory View for C/C++ debugging (#6674)
Native debug sessions whose adapter supports readMemory get a read-only Memory View tab: an address or expression field, address/hex/ASCII rows aligned to 16 bytes with the target byte marked, paging and a re-read after each stop. View Memory is offered on variables and watches that carry a memoryReference. The client now declares supportsMemoryReferences in initialize and keeps memoryReference on variables and evaluation results; adapter errors are shown without ending the session.

Closes #5921

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:52:32 +08:00
Bert Verhelstтаbertyhell 68abe345cc feat(run): read-only caret with keyboard navigation in the Run console (#6670)
The Run console's output gets a read-only caret: Home/End go to the line ends, PageUp/PageDown move a page, Ctrl/Cmd+Home/End go to the start or end of the output, the arrows move the caret and Shift extends the selection. The caret is the browser selection's focus, so mouse and keyboard share it; moves are computed over the virtualized rows, keyboard selections keep only their end rows mounted and copy from the console model. Leaving the end of the output stops following and Ctrl/Cmd+End resumes it; typing returns the caret to the input. Covers Run, Services, stack-trace and thread-dump consoles.

Closes #6295

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:52:02 +08:00
audichuang 32381cc740 test(agents): wait for the fake agent's connections to close after shutdown (#6809)
Tests that shut the manager down while the fake agent waits on a permission request could hang: returning before the fake's side read the end of the connection dropped the runtime, which then waited forever on the blocked thread. A shut_down helper now waits for each fake connection to close.

Co-authored-by: audichuang <[email protected]>
2026-11-29 15:51:42 +08:00
Bert Verhelstтаbertyhell d897236bd7 feat(vcs): add a global Enable Git integration switch (#6704)
Settings > Version Control > Git gets an Enable Git integration master toggle (global, on by default). While it is off the IDE discovers no repositories and runs no git: status, log, blame, fetch, clone, GitHub, the MCP git tools, plugin repository access and agent worktrees refuse to run, and the Git menu, Get from Version Control, the Git, Commit and GitHub Actions tool windows, Git actions and the branch widget are hidden. Turning it back on restores them without reopening the project. Settings pages gain a reusable master toggle that disables the page's sections, and MenuConfig gains a hidden list applied to the native and in-app menus.

Co-authored-by: bertyhell <[email protected]>
2026-11-29 15:45:38 +08:00
l0ng-ai 68e3adde99 chore(bindings): regenerate after project_roots moved off the IPC thread (#6812)
#6799 made project_roots a spawned desktop command and added a doc line without regenerating src/bindings.ts and the command snapshot, which CI's generated-files check compares.
2026-11-29 15:36:33 +08:00
LU XIANGRUIтаwildcatDownstairs b5aa21e791 perf: cut per-file round trips on network drives (#6799)
On network shares every stat is a round trip, and several paths did one per file or per ancestor. Directory listings take kind, size and mtime from the listing itself; Project view expansion lists through the project watcher and reuses its ignore rules and repository root; root detection probes Unity and virtual-env markers only when their names appear; the Gradle build walk is reused for 30 seconds on hot paths; project_roots runs off the IPC thread; index warm start checks files against one listing per folder, in parallel, and stops when the project closes; git status on network paths compares only mtime and size.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-29 15:19:27 +08:00
169 змінених файлів з 14235 додано та 991 видалено

No files matched your search

+30 -4
Переглянути файл
@@ -112,6 +112,8 @@ pub type WorkspaceRootsHook = Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>;
/// Returns the project's git executable (`None`: the default), which the tasks' git runs.
pub type GitExecutableHook = Arc<dyn Fn() -> Option<PathBuf> + Send + Sync>;
/// Whether the project's Git integration is on (Settings › Version Control › Git).
pub type GitEnabledHook = Arc<dyn Fn() -> bool + Send + Sync>;
/// Returns the user's transient network retry window and cold-reopen recovery policy.
pub type RecoverySettingsHook = Arc<
@@ -260,6 +262,7 @@ struct Shared {
reconciled: AtomicBool,
workspace_roots: RwLock<Option<WorkspaceRootsHook>>,
git_executable: RwLock<Option<GitExecutableHook>>,
git_enabled: RwLock<Option<GitEnabledHook>>,
change_reads: Arc<tokio::sync::Semaphore>,
known: Arc<Mutex<HashMap<String, Known>>>,
providers: RwLock<Vec<provider::ProviderSpec>>,
@@ -1011,6 +1014,7 @@ impl AgentManager {
reconciled: AtomicBool::new(false),
workspace_roots: RwLock::new(None),
git_executable: RwLock::new(None),
git_enabled: RwLock::new(None),
change_reads: Arc::new(tokio::sync::Semaphore::new(MAX_CHANGE_READS)),
known,
providers,
@@ -1118,6 +1122,11 @@ impl AgentManager {
*self.shared.git_executable.write() = Some(hook);
}
/// Sets the callback that tells whether Git integration is on; off, tasks run no git.
pub fn set_git_enabled_hook(&self, hook: GitEnabledHook) {
*self.shared.git_enabled.write() = Some(hook);
}
/// Directory holding linked Git worktrees created for agent tasks of this project.
pub fn worktrees_dir(&self) -> &Path {
&self.shared.paths.worktrees_dir
@@ -1585,6 +1594,11 @@ impl AgentManager {
let project_root = Some(IpcPath(root.clone()));
let (cwd, branch, base, base_commit, before) = match req.isolation {
Isolation::Worktree => {
if !git_enabled(&self.shared) {
return Err(IdeError::invalid(
"worktrees need Git, which is disabled: run the task in the local checkout",
));
}
// The UI offers worktrees for git projects only; state it when it isn't one.
if Repo::discover(&root)?.is_none() {
return Err(IdeError::invalid(
@@ -1598,10 +1612,14 @@ impl AgentManager {
}
Isolation::Local => {
let r = root.clone();
let (head, before) = vcs(&self.shared, move || {
Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default()))
})
.await?;
let (head, before) = if git_enabled(&self.shared) {
vcs(&self.shared, move || {
Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default()))
})
.await?
} else {
(None, BTreeMap::new())
};
let (base, commit) = head.unzip();
(root, None, base, commit, before)
}
@@ -6291,8 +6309,16 @@ async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + '
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
}
fn git_enabled(shared: &Shared) -> bool {
shared.git_enabled.read().as_ref().is_none_or(|hook| hook())
}
/// [`blocking`] for work that runs git: the repositories it opens run the project's git.
/// Fails without running it while Git integration is off.
async fn vcs<T: Send + 'static>(shared: &Shared, f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
if !git_enabled(shared) {
return Err(IdeError::unavailable("Git integration is disabled"));
}
let git = shared.git_executable.read().as_ref().and_then(|hook| hook());
blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await
}
+22 -7
Переглянути файл
@@ -653,7 +653,7 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
shut_down(&mgr, &agent).await;
let restored_agent = Arc::new(FakeAgent::default());
let restored = manager(tmp.path(), restored_agent.clone());
// Listing the tasks leaves the conversation on disk until something asks for it.
@@ -672,7 +672,8 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
#[tokio::test(flavor = "multi_thread")]
async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
@@ -693,7 +694,7 @@ async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
mgr.archive(&task.id).unwrap();
assert!(snapshot(&mgr).commands.is_empty());
assert!(names(mgr.commands("claude", Some(&task.id)).await.unwrap()).contains(&"review".to_owned()));
mgr.shutdown();
shut_down(&mgr, &agent).await;
// A list saved with an archived task (by an earlier version) isn't read back.
let other = tempfile::tempdir().unwrap();
@@ -787,7 +788,7 @@ async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
shut_down(&mgr, &agent).await;
// In a store of its own: a late save of the first manager can't touch it.
let name = format!("{}.json", task.id);
let mut file: Value =
@@ -826,7 +827,7 @@ async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
mgr.shutdown();
shut_down(&mgr, &agent).await;
// The caller never deleted it (its window closed): only a saved task comes back.
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
@@ -1388,6 +1389,19 @@ async fn wait_for(mgr: &AgentManager, id: &str, status: AgentStatus) {
panic!("task never reached {status:?} (is {s:?})");
}
/// Shuts `mgr` down and waits until `agent` has seen each of its connections end. A fake still
/// waiting for an answer holds a blocking thread until its side reads that end; a test that
/// returned first would drop the runtime, and the drop waits for that thread forever.
async fn shut_down(mgr: &AgentManager, agent: &FakeAgent) {
mgr.shutdown();
let servers = agent.servers.lock().clone();
for server in servers {
tokio::time::timeout(Duration::from_secs(5), server.closed())
.await
.expect("the agent's side of the connection closes");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
let tmp = tempfile::tempdir().unwrap();
@@ -1968,7 +1982,8 @@ async fn shutdown_during_session_open_kills_connecting_peer_without_failing() {
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_during_permission_request_settles_without_failing() {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("decide"),
@@ -1980,7 +1995,7 @@ async fn shutdown_during_permission_request_settles_without_failing() {
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.shutdown();
shut_down(&mgr, &agent).await;
tokio::time::sleep(TURN_GRACE * 3).await;
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
+72 -4
Переглянути файл
@@ -5,8 +5,10 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
@@ -227,9 +229,41 @@ pub fn build_dir(root: &Path) -> Option<PathBuf> {
build_dirs(root).into_iter().next()
}
/// How long [`cached_build_dirs`] reuses a walk. Project roots, content roots and the index
/// ask for the builds many times while a project opens; on a network share each walk is
/// thousands of round trips. A build file changing in a project calls [`forget_build_dirs`].
const BUILD_DIRS_TTL: Duration = Duration::from_secs(30);
type BuildDirsCache = HashMap<PathBuf, (Instant, Vec<PathBuf>)>;
static BUILD_DIRS: Mutex<Option<BuildDirsCache>> = Mutex::new(None);
/// Walks for builds now; the result also refreshes [`cached_build_dirs`].
fn build_dirs(root: &Path) -> Vec<PathBuf> {
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
ide_core::project_roots::discover(root, &markers)
let dirs = ide_core::project_roots::discover(root, &markers);
let now = Instant::now();
let mut guard = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner());
let map = guard.get_or_insert_with(HashMap::new);
map.retain(|_, (at, _)| now.duration_since(*at) < BUILD_DIRS_TTL);
map.insert(root.to_path_buf(), (now, dirs.clone()));
dirs
}
fn cached_build_dirs(root: &Path) -> Vec<PathBuf> {
let cached = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(root)).cloned();
match cached {
Some((at, dirs)) if at.elapsed() < BUILD_DIRS_TTL => dirs,
_ => build_dirs(root),
}
}
/// Forgets the discovered Gradle builds of `root`, and of folders above or below it
/// (after a build or settings script appeared, changed or was removed there).
pub fn forget_build_dirs(root: &Path) {
if let Some(map) = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
map.retain(|dir, _| !dir.starts_with(root) && !root.starts_with(dir));
}
}
fn wrapper(dir: &Path) -> String {
@@ -506,10 +540,23 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
}
}
/// Linked build identities without reading their scripts (also used by index hot paths).
/// Linked build identities without reading their scripts, as of now (a sync, a build).
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
linked_dirs_from(root, settings, build_dirs)
}
/// [`linked_dirs`] for hot paths (project and index roots): discovered builds are reused for a while.
pub(crate) fn linked_dirs_cached(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
linked_dirs_from(root, settings, cached_build_dirs)
}
fn linked_dirs_from(
root: &Path,
settings: &ide_core::settings::GradleSettings,
discover: fn(&Path) -> Vec<PathBuf>,
) -> Vec<String> {
match &settings.linked_projects {
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
None => discover(root).iter().map(|dir| rel(root, dir)).collect(),
Some(dirs) => {
let mut out = Vec::new();
for dir in dirs {
@@ -1047,6 +1094,27 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
#[cfg(test)]
mod tests {
#[test]
fn discovered_builds_are_reused_until_forgotten() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
std::fs::create_dir_all(root.join("a")).unwrap();
std::fs::write(root.join("a/settings.gradle"), "").unwrap();
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
std::fs::create_dir_all(root.join("b")).unwrap();
std::fs::write(root.join("b/build.gradle"), "").unwrap();
// A walk per call is thousands of round trips on a network share.
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
super::forget_build_dirs(&root.join("b"));
assert_eq!(super::cached_build_dirs(root), vec![root.join("a"), root.join("b")]);
// A sync sees a new build at once, and so does every later lookup.
std::fs::create_dir_all(root.join("c")).unwrap();
std::fs::write(root.join("c/build.gradle"), "").unwrap();
let all = vec![root.join("a"), root.join("b"), root.join("c")];
assert_eq!(super::build_dirs(root), all);
assert_eq!(super::cached_build_dirs(root), all);
}
#[test]
fn default_linkage_discovers_all_shallow_builds() {
let temp = tempfile::tempdir().unwrap();
+2 -2
Переглянути файл
@@ -129,7 +129,7 @@ pub fn gradle_external_roots(
cache_dir: &Path,
settings: &ide_core::settings::GradleSettings,
) -> Vec<PathBuf> {
let builds = gradle::linked_dirs(root, settings);
let builds = gradle::linked_dirs_cached(root, settings);
let dirs: Vec<String> = builds
.iter()
.flat_map(|dir| {
@@ -171,7 +171,7 @@ pub fn gradle_source_roots(
cache_dir: &Path,
settings: &ide_core::settings::GradleSettings,
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
let reported = gradle::linked_dirs(root, settings)
let reported = gradle::linked_dirs_cached(root, settings)
.iter()
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
.collect::<Vec<_>>();
+1 -1
Переглянути файл
@@ -27,4 +27,4 @@ libc = "0.2"
[target.'cfg(windows)'.dependencies]
dirs.workspace = true
tracing.workspace = true
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
+1
Переглянути файл
@@ -19,6 +19,7 @@ pub mod ipc_path;
pub mod java_runtime;
pub mod jsonc;
pub mod memory;
pub mod network_path;
pub mod output_encoding;
pub mod output_rate;
pub mod platform;
+53
Переглянути файл
@@ -0,0 +1,53 @@
//! Whether a path is on a network file system, where every stat is a round trip to a server.
use std::path::{Component, Path, Prefix};
/// A UNC path (`\\server\share`, `\\wsl.localhost\…`) or a drive letter mapped to a network
/// share (`Z:\`). Always `false` off Windows: there a mount point is not visible in the path.
pub fn is_network_path(path: &Path) -> bool {
match path.components().next() {
Some(Component::Prefix(prefix)) => match prefix.kind() {
Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true,
Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => is_remote_drive(letter),
_ => false,
},
_ => false,
}
}
#[cfg(windows)]
fn is_remote_drive(letter: u8) -> bool {
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
/// `DRIVE_REMOTE` (WindowsProgramming).
const DRIVE_REMOTE: u32 = 4;
let root = [u16::from(letter), u16::from(b':'), u16::from(b'\\'), 0];
// SAFETY: `root` is a NUL-terminated wide string that outlives the call.
unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE }
}
#[cfg(not(windows))]
fn is_remote_drive(_letter: u8) -> bool {
false
}
#[cfg(test)]
mod tests {
use super::is_network_path;
use std::path::Path;
#[test]
fn unc_paths_are_on_the_network() {
if cfg!(windows) {
assert!(is_network_path(Path::new(r"\\server\share\repo")));
assert!(is_network_path(Path::new(r"\\?\UNC\server\share\repo")));
assert!(is_network_path(Path::new(r"\\wsl.localhost\Ubuntu\home")));
}
assert!(!is_network_path(Path::new("relative/path")));
}
#[test]
fn a_local_directory_is_not() {
let dir = std::env::temp_dir();
assert!(!is_network_path(&dir), "{}", dir.display());
}
}
+15
Переглянути файл
@@ -143,6 +143,9 @@ impl Default for GitAnnotateSettings {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GitSettings {
/// Git integration on: off, the IDE finds no repositories and runs no git at all
/// (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI.
pub enabled: bool,
pub annotate: GitAnnotateSettings,
/// Show blame after the current editor line.
pub inline_blame: bool,
@@ -201,6 +204,7 @@ pub struct GitSettings {
impl Default for GitSettings {
fn default() -> Self {
Self {
enabled: true,
annotate: GitAnnotateSettings::default(),
inline_blame: false,
inline_blame_clickable: true,
@@ -613,6 +617,8 @@ pub struct TerminalSettings {
pub mouse_reporting: bool,
pub copy_on_selection: bool,
pub paste_on_middle_click: bool,
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
pub right_click_paste: bool,
pub override_ide_shortcuts: bool,
pub shell_integration: bool,
pub highlight_hyperlinks: bool,
@@ -651,6 +657,7 @@ impl Default for TerminalSettings {
mouse_reporting: true,
copy_on_selection: false,
paste_on_middle_click: true,
right_click_paste: false,
override_ide_shortcuts: true,
shell_integration: true,
highlight_hyperlinks: true,
@@ -755,6 +762,14 @@ mod tests {
assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true);
}
#[test]
fn git_defaults_enabled_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
let off: GitSettings = serde_json::from_str(r#"{"enabled":false}"#).unwrap();
assert!(missing.enabled);
assert!(!off.enabled);
}
#[test]
fn clone_submodules_defaults_on_and_can_be_disabled() {
let missing: GitSettings = serde_json::from_str("{}").unwrap();
+115
Переглянути файл
@@ -0,0 +1,115 @@
//! Machine code of a native program (DAP `disassemble`), for the Disassembly view.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
/// The most instructions one request asks for.
pub const MAX_INSTRUCTIONS: u32 = 1000;
/// One disassembled instruction.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct Instruction {
/// Address as the adapter writes it (`0x5555…`); also a memory reference for the next request.
pub address: String,
/// The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`).
pub instruction: String,
/// Its machine code as hex (`488b45d8`), when the adapter sends it.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub bytes: Option<String>,
/// The function it belongs to, when the adapter names it (often on the first instruction only).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub symbol: Option<String>,
}
/// `disassemble`'s instructions in order; `None` for the padding adapters put where there is no
/// code (`presentationHint: "invalid"`, or no address).
pub(crate) fn instructions(body: &Value) -> Vec<Option<Instruction>> {
let text = |i: &Value, k: &str| i.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned);
let Some(list) = body.get("instructions").and_then(Value::as_array) else { return Vec::new() };
list.iter()
.map(|i| {
if i.get("presentationHint").and_then(Value::as_str) == Some("invalid") {
return None;
}
Some(Instruction {
address: text(i, "address")?,
instruction: text(i, "instruction").unwrap_or_default(),
bytes: text(i, "instructionBytes"),
symbol: text(i, "symbol"),
})
})
.collect()
}
/// A memory reference or address as a number (`0x7ffd…` or decimal).
pub(crate) fn address(reference: &str) -> Option<u128> {
let r = reference.trim();
match r.strip_prefix("0x").or_else(|| r.strip_prefix("0X")) {
Some(hex) => u128::from_str_radix(hex, 16).ok(),
None => r.parse().ok(),
}
}
/// Whether the instruction at `index` is the one at `reference`. References that are not
/// addresses cannot be checked and pass.
pub(crate) fn at_index(instructions: &[Option<Instruction>], reference: &str, index: usize) -> bool {
let Some(want) = address(reference) else { return instructions.len() > index };
instructions.get(index).and_then(Option::as_ref).and_then(|i| address(&i.address)) == Some(want)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn reads_gdbs_instructions() {
// GDB 17.1 at the reporter-style C fixture's loop line.
let body = json!({"instructions": [
{"address": "0x5555555551f5", "instruction": "mov -0x2c(%rbp),%eax", "instructionBytes": "8b45d4", "line": 14},
{"address": "0x5555555551f8", "instruction": "cltq", "instructionBytes": "4898", "symbol": "sum"},
]});
let got = instructions(&body);
assert_eq!(
got[0],
Some(Instruction {
address: "0x5555555551f5".into(),
instruction: "mov -0x2c(%rbp),%eax".into(),
bytes: Some("8b45d4".into()),
symbol: None,
})
);
assert_eq!(got[1].as_ref().unwrap().symbol.as_deref(), Some("sum"));
}
#[test]
fn padding_is_not_an_instruction() {
let body = json!({"instructions": [
{"address": "0xfff0", "instruction": "", "presentationHint": "invalid"},
{"instruction": "??"},
{"address": "0x10000", "instruction": "nop"},
]});
let got = instructions(&body);
assert_eq!((got[0].is_none(), got[1].is_none(), got[2].is_some()), (true, true, true));
assert!(instructions(&json!({})).is_empty());
}
#[test]
fn finds_the_reference_by_its_address() {
let list = instructions(&json!({"instructions": [
{"address": "0x00001000", "instruction": "push %rbp"},
{"address": "0x1001", "instruction": "mov %rsp,%rbp"},
]}));
assert!(at_index(&list, "0x1001", 1));
assert!(at_index(&list, "4097", 1));
assert!(at_index(&list, "0X1000", 0));
assert!(!at_index(&list, "0x1001", 0));
assert!(!at_index(&list, "0x1001", 2));
assert!(at_index(&list, "frame-3", 1), "opaque references cannot be checked");
assert_eq!(address("0xffffffffffffffff1"), Some(0xffffffffffffffff1));
}
}
+121 -2
Переглянути файл
@@ -13,6 +13,7 @@ pub mod attach;
mod cargo;
pub mod connection;
mod debugpy;
mod disassembly;
mod exception_classes;
pub mod jdwp;
mod js_cdp;
@@ -20,12 +21,14 @@ mod js_debug;
mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
mod memory;
mod session;
mod stream_trace;
pub mod unity;
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
use connection::{Connection, DapError};
pub use disassembly::{Instruction, MAX_INSTRUCTIONS};
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
use futures::future::join_all;
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
@@ -33,6 +36,7 @@ use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
pub use jvm_memory::*;
pub use memory::{MAX_READ, MemoryBlock};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -159,6 +163,12 @@ pub struct DebugCapabilities {
/// A stream chain can be traced while the program runs it ([`DebugManager::stream_trace`]).
/// Can change during the session, like `jvm_instances`.
pub stream_trace: bool,
/// The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View.
pub read_memory: bool,
/// The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view.
pub disassemble: bool,
/// Steps can move by one instruction ([`DebugManager::step_instruction`]).
pub instruction_stepping: bool,
}
/// Result of [`DebugManager::redefine_classes`].
@@ -225,6 +235,10 @@ pub struct StackFrame {
pub column: u32,
/// `subtle` frames (library/generated) are collapsed in the UI.
pub presentation_hint: Option<String>,
/// The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub instruction_pointer_reference: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -249,6 +263,10 @@ pub struct Variable {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
#[specta(optional)]
pub lazy: bool,
/// Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub memory_reference: Option<String>,
}
/// A completion the adapter offers for an expression (DAP `completions`).
@@ -611,6 +629,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
presentation_hint: hint,
instruction_pointer_reference: f
.get("instructionPointerReference")
.and_then(Value::as_str)
.filter(|r| !r.is_empty())
.map(str::to_owned),
}
}
@@ -687,6 +710,9 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities {
js_page: false,
live_evaluate: false,
stream_trace: false,
read_memory: has("supportsReadMemoryRequest"),
disassemble: has("supportsDisassembleRequest"),
instruction_stepping: has("supportsSteppingGranularity"),
}
}
@@ -775,9 +801,15 @@ pub(crate) fn variable_from(v: &Value) -> Variable {
variables_reference: v.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: s("evaluateName"),
lazy: v.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
memory_reference: memory_reference(v),
}
}
/// A variable's or evaluation result's `memoryReference`.
fn memory_reference(v: &Value) -> Option<String> {
v.get("memoryReference").and_then(Value::as_str).filter(|r| !r.is_empty()).map(str::to_owned)
}
async fn session_variables(session: &Session, reference: i64) -> IdeResult<Vec<Variable>> {
let body =
session.conn.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT).await?;
@@ -801,6 +833,7 @@ async fn resolve_in(session: &Session, variable: Variable) -> IdeResult<Variable
value: value.value,
variables_reference: value.variables_reference,
lazy: value.lazy,
memory_reference: value.memory_reference.or(variable.memory_reference),
},
_ => variable,
})
@@ -1333,7 +1366,7 @@ impl DebugManager {
"supportsProgressReporting": true,
// kotlin-lsp sends `invalidated` either way.
"supportsInvalidatedEvent": is_kotlin_lsp,
"supportsMemoryReferences": false,
"supportsMemoryReferences": true,
"supportsArgsCanBeInterpretedByShell": false,
}),
INIT_TIMEOUT,
@@ -1791,6 +1824,7 @@ impl DebugManager {
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: evaluate_name.or(Some(name)),
lazy: false,
memory_reference: memory_reference(&body),
})
}
@@ -1928,6 +1962,7 @@ impl DebugManager {
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: Some(expression),
lazy: body.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
memory_reference: memory_reference(&body),
};
if !session.spec.resolve_lazy_variables {
return Ok(result);
@@ -2019,6 +2054,22 @@ impl DebugManager {
}
pub async fn step(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id })).await
}
/// Step Over / Into Instruction: a step by one machine instruction (DAP `granularity`).
pub async fn step_instruction(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
let session = self.session(s)?;
if !session.supports("supportsSteppingGranularity") {
return Err(IdeError::unavailable(format!(
"debug adapter `{}` cannot step by instruction",
session.adapter
)));
}
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id, "granularity": "instruction" })).await
}
async fn step_with(&self, s: DebugSessionId, thread_id: i64, kind: StepKind, args: Value) -> IdeResult<()> {
let command = match kind {
StepKind::Over => "next",
StepKind::Into => "stepIn",
@@ -2030,7 +2081,7 @@ impl DebugManager {
quirks.step_sent();
}
let ticket = session.suspended.ticket();
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
let sent = session.conn.request_timeout(command, args, REQUEST_TIMEOUT).await;
step_settled(&session, sent)?;
// A step runs its thread; other threads stopped by their own events stay stopped.
session.finish_resume(ticket, thread_id, false);
@@ -2184,6 +2235,74 @@ impl DebugManager {
Ok(())
}
/// `count` bytes (at most [`MAX_READ`]) from `offset` bytes after `memory_reference`, which
/// comes from a variable, an evaluation result or an earlier read's address.
pub async fn read_memory(
&self,
s: DebugSessionId,
memory_reference: String,
offset: i64,
count: u32,
) -> IdeResult<MemoryBlock> {
let session = self.session(s)?;
if !session.supports("supportsReadMemoryRequest") {
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot read memory", session.adapter)));
}
let count = count.min(MAX_READ);
let body = session
.conn
.request_timeout(
"readMemory",
json!({ "memoryReference": memory_reference, "offset": offset, "count": count }),
REQUEST_TIMEOUT,
)
.await?;
memory::memory_block(&body, count)
}
/// `count` instructions (at most [`MAX_INSTRUCTIONS`]) from `before` instructions ahead of
/// `memory_reference` (a frame's instruction pointer or an instruction's address). Adapters that
/// cannot disassemble backwards start at the reference instead.
pub async fn disassemble(
&self,
s: DebugSessionId,
memory_reference: String,
before: u32,
count: u32,
) -> IdeResult<Vec<Instruction>> {
let session = self.session(s)?;
if !session.supports("supportsDisassembleRequest") {
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot disassemble", session.adapter)));
}
let count = count.clamp(1, MAX_INSTRUCTIONS);
let before = before.min(count - 1);
let request = |offset: i64, count: u32| {
session.conn.request_timeout(
"disassemble",
json!({
"memoryReference": memory_reference,
"offset": 0,
"instructionOffset": offset,
"instructionCount": count,
"resolveSymbols": true,
}),
REQUEST_TIMEOUT,
)
};
if before > 0 {
// GDB (up to 17 at least) answers a negative instruction offset with the instructions after
// the reference, or fails: only an answer with the reference in its place is used.
if let Ok(body) = request(-i64::from(before), count).await {
let instructions = disassembly::instructions(&body);
if disassembly::at_index(&instructions, &memory_reference, before as usize) {
return Ok(instructions.into_iter().flatten().collect());
}
}
}
let body = request(0, count - before).await?;
Ok(disassembly::instructions(&body).into_iter().flatten().collect())
}
pub fn capabilities(&self, s: DebugSessionId) -> IdeResult<DebugCapabilities> {
Ok(session_capabilities(&*self.session(s)?))
}
+88
Переглянути файл
@@ -0,0 +1,88 @@
//! Raw memory of a native program (DAP `readMemory`), for the Memory View.
use base64::Engine;
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
/// The most bytes one read asks for: a few pages of the view, never a whole mapping.
pub const MAX_READ: u32 = 64 * 1024;
/// Answer of `readMemory`: `data` starts at `address`; the `unreadable_bytes` after it could not be read.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MemoryBlock {
/// Address of the first byte, as the adapter writes it (`0x7ffd…`; may be wider than 53 bits).
pub address: String,
pub data: Vec<u8>,
pub unreadable_bytes: u32,
}
/// `readMemory`'s body for a read of `count` bytes. Adapters leave `data` out (or empty) when
/// nothing could be read; the bytes asked for then count as unreadable.
pub(crate) fn memory_block(body: &Value, count: u32) -> IdeResult<MemoryBlock> {
let address = match body.get("address") {
Some(Value::String(a)) if !a.is_empty() => a.clone(),
Some(Value::Number(n)) => n.to_string(),
_ => return Err(IdeError::internal("the debug adapter answered readMemory without an address")),
};
let mut data = match body.get("data").and_then(Value::as_str) {
Some(b64) if !b64.is_empty() => base64::engine::general_purpose::STANDARD
.decode(b64)
.map_err(|e| IdeError::internal(format!("the debug adapter sent memory that is not base64: {e}")))?,
_ => Vec::new(),
};
data.truncate(count as usize);
// At most the rest of what was asked for (the data is never more than that).
let rest = count - data.len() as u32;
let unreadable_bytes = match body.get("unreadableBytes").and_then(Value::as_u64) {
Some(n) => n.min(u64::from(rest)) as u32,
None if data.is_empty() => count,
None => 0,
};
Ok(MemoryBlock { address, data, unreadable_bytes })
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn decodes_the_bytes_and_keeps_the_address_as_written() {
// The reporter's `&msg[0]` (#5921): "Hello, World!\n" and its terminator.
let body = json!({"address": "0x000000016FDFE9A0", "data": "SGVsbG8sIFdvcmxkIQoA"});
let block = memory_block(&body, 15).unwrap();
assert_eq!(block.address, "0x000000016FDFE9A0");
assert_eq!(block.data, b"Hello, World!\n\0");
assert_eq!(block.unreadable_bytes, 0);
}
#[test]
fn missing_data_is_unreadable_not_empty() {
let block = memory_block(&json!({"address": "0x0"}), 256).unwrap();
assert!(block.data.is_empty());
assert_eq!(block.unreadable_bytes, 256);
let block = memory_block(&json!({"address": "0x0", "data": "", "unreadableBytes": 16}), 256).unwrap();
assert_eq!(block.unreadable_bytes, 16);
}
#[test]
fn a_partial_read_reports_the_rest_as_unreadable() {
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 13}), 16).unwrap();
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1, 2][..], 13));
// Counts that disagree with the request are clamped to it.
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 99}), 16).unwrap();
assert_eq!(block.unreadable_bytes, 13);
let block = memory_block(&json!({"address": "0x1000", "data": "AAECAw=="}), 2).unwrap();
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1][..], 0));
}
#[test]
fn rejects_answers_without_an_address_or_with_bad_data() {
assert!(memory_block(&json!({"data": "AA=="}), 1).is_err());
assert!(memory_block(&json!({"address": "0x10", "data": "not base64!"}), 1).is_err());
assert_eq!(memory_block(&json!({"address": 4096, "data": "AA=="}), 1).unwrap().address, "4096");
}
}
+212
Переглянути файл
@@ -6,6 +6,7 @@ mod stream_trace;
use super::*;
use crate::adapter::{AdapterIo, LaunchFuture};
use base64::Engine;
use ide_core::IdeEvent;
use ide_core::event::DebugEvent;
use ide_jsonrpc::framing;
@@ -195,6 +196,21 @@ struct Script {
accept: &'static [&'static str],
/// Requests of the adapter's own answered with a body and followed by events.
custom: Option<fn(&Value) -> Option<CustomReply>>,
/// Advertise `supportsReadMemoryRequest`: memory below 0x1010 reads as its low address byte,
/// memory from there on is unmapped.
read_memory: bool,
/// Advertise `supportsDisassembleRequest` and `supportsSteppingGranularity`, disassembling like
/// this adapter: 4-byte instructions from 0x1000 to 0x1100, nothing mapped around them.
disassemble: Option<FakeDisassembler>,
}
#[derive(Clone, Copy, PartialEq)]
enum FakeDisassembler {
/// Negative instruction offsets work; unmapped places are `invalid` padding.
Lldb,
/// GDB 17: disassembles `instructionOffset + instructionCount` instructions from the reference and
/// drops the first `instructionOffset` of them, the way a Python slice does.
Gdb,
}
/// The answer to a request of the adapter's own: the response body, then events (name, body).
@@ -242,6 +258,8 @@ impl Default for Script {
empty_thread_responses: 0,
accept: &[],
custom: None,
read_memory: false,
disassemble: None,
}
}
}
@@ -328,6 +346,9 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
"supportsDataBreakpoints": true,
"supportsStepInTargetsRequest": true,
"supportsRestartFrame": true,
"supportsReadMemoryRequest": script.read_memory,
"supportsDisassembleRequest": script.disassemble.is_some(),
"supportsSteppingGranularity": script.disassemble.is_some(),
"exceptionBreakpointFilters": [
{"filter": "raised", "label": "Raised"},
{"filter": "uncaught", "label": "Uncaught", "default": true, "description": "Uncaught exceptions"},
@@ -570,7 +591,58 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
]})
),
},
"evaluate" if msg["arguments"]["expression"] == "&msg[0]" => ok!(
msg,
json!({"result": "0x1000 \"Hello\"", "type": "char *", "variablesReference": 1, "memoryReference": "0x1000"})
),
"evaluate" => ok!(msg, json!({"result": "42", "type": "int", "variablesReference": 0})),
"readMemory" => {
let args = &msg["arguments"];
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
let start = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
let count = args["count"].as_i64().unwrap();
const END: i64 = 0x1010;
if start >= END {
send!(
json!({"type": "response", "request_seq": msg["seq"], "command": "readMemory", "success": false, "message": format!("Cannot access memory at address {start:#x}")})
);
} else {
let bytes: Vec<u8> = (start..(start + count).min(END)).map(|a| a as u8).collect();
ok!(
msg,
json!({"address": format!("{start:#x}"), "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "unreadableBytes": count - bytes.len() as i64})
);
}
}
"disassemble" => {
let args = &msg["arguments"];
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
let pc = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
let (offset, count) =
(args["instructionOffset"].as_i64().unwrap(), args["instructionCount"].as_i64().unwrap());
let insn = |a: i64| {
if (0x1000..0x1100).contains(&a) {
json!({"address": format!("{a:#x}"), "instruction": format!("insn {}", (a - 0x1000) / 4), "instructionBytes": "90909090"})
} else {
json!({"address": format!("{a:#x}"), "instruction": "", "presentationHint": "invalid"})
}
};
let addresses: Option<Vec<i64>> = match script.disassemble.unwrap() {
FakeDisassembler::Lldb => Some((0..count).map(|i| pc + 4 * (offset + i)).collect()),
FakeDisassembler::Gdb if offset + count < 0 => None,
FakeDisassembler::Gdb => {
let all: Vec<i64> = (0..offset + count).map(|i| pc + 4 * i).collect();
let from = if offset >= 0 { offset } else { (all.len() as i64 + offset).max(0) };
Some(all[from as usize..].to_vec())
}
};
match addresses {
Some(a) => ok!(msg, json!({"instructions": a.into_iter().map(insn).collect::<Vec<_>>()})),
None => send!(
json!({"type": "response", "request_seq": msg["seq"], "command": "disassemble", "success": false, "message": "Argument 'count' should be an non-negative integer."})
),
}
}
"completions" => ok!(
msg,
json!({"targets": [
@@ -1952,6 +2024,146 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn memory_view_reads_memory_from_a_reference() {
let h = harness(Script { read_memory: true, ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert_eq!(
h.request("initialize")["arguments"]["supportsMemoryReferences"],
true,
"adapters only send references when asked"
);
assert!(h.manager.capabilities(id).unwrap().read_memory);
let pointer = h.manager.evaluate_in(id, Some(10), "&msg[0]".into(), Some("watch".into())).await.unwrap();
assert_eq!(pointer.memory_reference.as_deref(), Some("0x1000"));
let plain = h.manager.evaluate(id, Some(10), "n".into()).await.unwrap();
assert_eq!(plain.memory_reference, None);
let block = h.manager.read_memory(id, "0x1000".into(), 0, 8).await.unwrap();
assert_eq!(block, MemoryBlock { address: "0x1000".into(), data: (0..8).collect(), unreadable_bytes: 0 });
assert_eq!(h.request("readMemory")["arguments"], json!({"memoryReference": "0x1000", "offset": 0, "count": 8}));
// Paging back and forth goes through `offset` on the same reference; the end of the mapping
// comes back as unreadable bytes.
let block = h.manager.read_memory(id, "0x1000".into(), 8, 16).await.unwrap();
assert_eq!((block.address.as_str(), block.data.len(), block.unreadable_bytes), ("0x1008", 8, 8));
assert_eq!(block.data[0], 0x08);
// Unmapped memory is the adapter's error, and the session goes on.
let err = h.manager.read_memory(id, "0x1000".into(), 0x20, 16).await.unwrap_err();
assert!(err.to_string().contains("Cannot access memory at address 0x1020"), "{err}");
assert!(!h.manager.threads(id).await.unwrap().is_empty());
let _ = h.manager.read_memory(id, "0x1000".into(), 0, u32::MAX).await;
let last = h.log.lock().iter().rev().find(|m| m["command"] == "readMemory").cloned().unwrap();
assert_eq!(last["arguments"]["count"], MAX_READ, "one read never asks for more than a few pages");
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn memory_view_says_when_the_adapter_cannot_read_memory() {
let h = harness(Script::default());
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert!(!h.manager.capabilities(id).unwrap().read_memory);
let err = h.manager.read_memory(id, "0x1000".into(), 0, 16).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.to_string().contains("debug adapter `debugpy` cannot read memory"), "{err}");
assert!(!h.commands().iter().any(|c| c == "readMemory"), "nothing is sent to an adapter without support");
h.manager.stop(id).await.unwrap();
}
#[test]
fn variables_keep_their_memory_reference() {
let v = variable_from(
&json!({"name": "words", "value": "0x4010", "variablesReference": 3, "memoryReference": "0x4010"}),
);
assert_eq!(v.memory_reference.as_deref(), Some("0x4010"));
assert_eq!(variable_from(&json!({"name": "n", "value": "1", "memoryReference": ""})).memory_reference, None);
let json = serde_json::to_value(variable_from(&json!({"name": "n", "value": "1"}))).unwrap();
assert!(json.get("memoryReference").is_none(), "absent, not null, for the UI's optional field");
}
#[tokio::test]
async fn disassembly_reads_instructions_around_the_instruction_pointer() {
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let caps = h.manager.capabilities(id).unwrap();
assert!(caps.disassemble && caps.instruction_stepping);
let list = h.manager.disassemble(id, "0x1010".into(), 2, 5).await.unwrap();
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
assert_eq!(addresses, ["0x1008", "0x100c", "0x1010", "0x1014", "0x1018"]);
assert_eq!((list[2].instruction.as_str(), list[2].bytes.as_deref()), ("insn 4", Some("90909090")));
assert_eq!(
requests(&h, "disassemble")[0],
json!({"memoryReference": "0x1010", "offset": 0, "instructionOffset": -2, "instructionCount": 5, "resolveSymbols": true})
);
// Before the first mapped instruction the adapter pads; the padding is not shown.
let list = h.manager.disassemble(id, "0x1004".into(), 4, 6).await.unwrap();
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
assert_eq!(addresses, ["0x1000", "0x1004", "0x1008"]);
let _ = h.manager.disassemble(id, "0x1000".into(), 0, u32::MAX).await;
assert_eq!(requests(&h, "disassemble").last().unwrap()["instructionCount"], MAX_INSTRUCTIONS);
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn disassembly_starts_at_the_instruction_pointer_when_the_adapter_cannot_go_back() {
let h = harness(Script { disassemble: Some(FakeDisassembler::Gdb), ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
// GDB's answer to "4 before" leaves out the instruction pointer; the view asks again from it.
let list = h.manager.disassemble(id, "0x1010".into(), 4, 10).await.unwrap();
assert_eq!(list.first().map(|i| i.address.as_str()), Some("0x1010"));
assert_eq!(list.len(), 6);
let offsets: Vec<Value> = requests(&h, "disassemble").iter().map(|r| r["instructionOffset"].clone()).collect();
assert_eq!(offsets, [json!(-4), json!(0)]);
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn instruction_steps_send_the_granularity_and_line_steps_do_not() {
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
h.manager.step_instruction(id, 1, StepKind::Into).await.unwrap();
assert_eq!(requests(&h, "stepIn").last().unwrap(), &json!({"threadId": 1, "granularity": "instruction"}));
h.manager.step(id, 1, StepKind::Over).await.unwrap();
assert_eq!(requests(&h, "next").last().unwrap(), &json!({"threadId": 1}));
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn disassembly_and_instruction_steps_say_when_the_adapter_cannot() {
let h = harness(Script::default());
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
let caps = h.manager.capabilities(id).unwrap();
assert!(!caps.disassemble && !caps.instruction_stepping);
let err = h.manager.disassemble(id, "0x1000".into(), 0, 16).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
assert!(err.to_string().contains("debug adapter `debugpy` cannot disassemble"), "{err}");
let err = h.manager.step_instruction(id, 1, StepKind::Over).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
let sent = h.commands();
assert!(!sent.iter().any(|c| c == "disassemble" || c == "next"), "nothing is sent to an adapter without support");
h.manager.stop(id).await.unwrap();
}
#[test]
fn frames_keep_their_instruction_pointer() {
let f = frame_from(&json!({"id": 1, "name": "atoi", "line": 0, "instructionPointerReference": "0x7ffff7c4a2e0"}));
assert_eq!(f.instruction_pointer_reference.as_deref(), Some("0x7ffff7c4a2e0"));
let json = serde_json::to_value(frame_from(&json!({"id": 1, "name": "main"}))).unwrap();
assert!(json.get("instructionPointerReference").is_none());
}
#[tokio::test]
async fn smart_step_into_and_reset_frame() {
let h = harness(Script::default());
+75 -2
Переглянути файл
@@ -1,11 +1,12 @@
//! Drives real debug adapters against tiny programs (one per language), checking the
//! launch templates and the IDEA-parity features: line / method breakpoints, Smart Step
//! Into, Reset Frame, Force Step Over, Force Run to Cursor and Set Value.
//! Into, Reset Frame, Force Step Over, Force Run to Cursor, Set Value, the Memory View and the Disassembly view.
//!
//! Ignored by default (needs the adapters installed). Run with
//! `OPENIDEA_DAP_FIXTURES=<dir> cargo test -p ide-dap --test real_adapters -- --ignored --nocapture`
//! where `<dir>` holds `py/app.py`, `node/app.js`, `go/demo` (built with `-N -l`),
//! `rust/target/debug/demo` and `c/main`. Adapters not found on `PATH` are skipped.
//! `rust/target/debug/demo` and `c/main` (whose loop function also has a `char msg[]` local, for
//! the Memory View). Adapters not found on `PATH` are skipped.
use ide_core::event::DebugEvent;
use ide_core::{DebugSessionId, IdeEvent, SharedSink};
@@ -280,6 +281,78 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
let caps = m.capabilities(s).map_err(|e| e.message)?;
report.push(format!("capabilities: {caps:?}"));
// Memory View: the bytes at an address expression (the C fixture's `msg`), and an unmapped address.
if caps.read_memory {
match m.evaluate_in(s, Some(top.id), "&msg[0]".into(), Some("watch".into())).await {
Ok(v) => match v.memory_reference {
Some(r) => match m.read_memory(s, r.clone(), 0, 16).await {
Ok(b) => report.push(format!(
"memory view `&msg[0]` ({r}): {} = {:02x?} {:?}, {} unreadable",
b.address,
b.data,
String::from_utf8_lossy(&b.data),
b.unreadable_bytes
)),
Err(e) => report.push(format!("memory view `&msg[0]`: FAILED {}", e.message)),
},
None => report.push(format!("memory view `&msg[0]` = {}: no memory reference", v.value)),
},
Err(e) => report.push(format!("memory view `&msg[0]`: not evaluated ({})", e.message)),
}
match m.read_memory(s, "0x0".into(), 0, 16).await {
Ok(b) => report.push(format!("memory view 0x0: {} bytes, {} unreadable", b.data.len(), b.unreadable_bytes)),
Err(e) => report.push(format!("memory view 0x0: error `{}`", e.message)),
}
} else {
report.push("memory view: readMemory not supported".into());
}
// Disassembly: the instructions around the stop's instruction pointer, then two instruction steps,
// which stay on the loop line and inside the instructions shown.
let address = |a: &str| u128::from_str_radix(a.trim_start_matches("0x"), 16).ok();
match (caps.disassemble, top.instruction_pointer_reference.clone()) {
(true, Some(pc)) => match m.disassemble(s, pc.clone(), 8, 24).await {
Ok(list) => {
let shown = |a: &str| list.iter().position(|i| address(&i.address) == address(a));
match shown(&pc) {
Some(at) => report.push(format!(
"disassembly at {pc}: {} instructions, the instruction pointer is #{at}: `{}` ({:?})",
list.len(),
list[at].instruction,
list[at].bytes
)),
None => report.push(format!("disassembly at {pc}: FAILED, not among {list:?}")),
}
if caps.instruction_stepping {
let mut steps = vec![pc];
for _ in 0..2 {
let seen = run.seen();
m.step_instruction(s, thread, StepKind::Over).await.map_err(|e| e.message)?;
run.stopped_after(seen).await.ok_or("no stop after step over instruction")?;
let f = run.top(s, thread).await;
if f.line != case.loop_line {
report.push(format!(
"step over instruction: left the loop line for {}:{}",
f.name,
f.line + 1
));
}
steps.push(f.instruction_pointer_reference.unwrap_or_default());
}
let all = steps.iter().all(|a| shown(a).is_some());
report.push(format!("step over instruction: {} (all shown: {all})", steps.join(" -> ")));
} else {
report.push("instruction stepping: not supported".into());
}
}
Err(e) => report.push(format!("disassembly at {pc}: FAILED {}", e.message)),
},
(true, None) => report.push("disassembly: the top frame has no instruction pointer".into()),
(false, _) => report.push("disassembly: not supported".into()),
}
// Instruction steps resumed the thread: frame ids from before them may be gone.
let top = run.top(s, thread).await;
// Set Value on the first local that is an integer.
let scopes = m.scopes(s, top.id).await.map_err(|e| e.message)?;
for scope in scopes.iter().filter(|sc| !sc.expensive) {
+136 -12
Переглянути файл
@@ -287,19 +287,56 @@ impl ClickhousePool {
}
/// `max_rows`: the rows the server may send (the skipped ones included).
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
fn request(
&self,
client: &Client,
query_id: &str,
max_rows: usize,
session: &Session,
workspace_bytes: Option<usize>,
) -> RequestBuilder {
let mut request = client
.post(self.0.endpoint.clone())
.basic_auth(&self.0.user, Some(&self.0.password))
.header(reqwest::header::CONTENT_TYPE, "text/plain; charset=utf-8")
.query(&self.0.settings)
.query(&[("query_id", query_id), ("default_format", FORMAT)]);
if workspace_bytes.is_some() && !session.strict_read_only {
let settings: Vec<_> = self
.0
.settings
.iter()
.filter(|(name, _)| !matches!(name.as_str(), "read_overflow_mode" | "timeout_overflow_mode"))
.collect();
request = request.query(&settings);
} else {
request = request.query(&self.0.settings);
}
if !session.strict_read_only {
request = request.query(&[
("output_format_json_quote_denormals", "1".into()),
("max_result_rows", max_rows.saturating_add(1).to_string()),
("result_overflow_mode", "break".into()),
]);
if let Some(bytes) = workspace_bytes {
request = request.query(&[
("max_result_rows", max_rows.to_string()),
("result_overflow_mode", "throw".into()),
("read_overflow_mode", "throw".into()),
("timeout_overflow_mode", "throw".into()),
]);
for (name, value) in [
("max_result_bytes", bytes),
("max_execution_time", 20),
("cancel_http_readonly_queries_on_client_close", 1),
("max_rows_to_read", 1_000_000),
("max_bytes_to_read", 268_435_456),
] {
if !self.0.settings.iter().any(|(setting, _)| setting == name) {
request = request.query(&[(name, value)]);
}
}
} else {
request = request.query(&[
("output_format_json_quote_denormals", "1".into()),
("max_result_rows", max_rows.saturating_add(1).to_string()),
("result_overflow_mode", "break".into()),
]);
}
}
if let Some(session_id) = &session.id {
request = request.query(&[("session_id", session_id.as_str()), ("session_timeout", "3600")]);
@@ -376,7 +413,8 @@ impl ClickhousePool {
));
}
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), session).body(sql.to_owned());
let request =
self.request(&client, &query_id, skip.saturating_add(max_rows), session, None).body(sql.to_owned());
let started = Instant::now();
let request_error = |error: reqwest::Error| {
if error.is_timeout() && !error.is_connect() {
@@ -402,7 +440,7 @@ impl ClickhousePool {
.and_then(|n| n.as_str().and_then(|n| n.parse::<u64>().ok()).or_else(|| n.as_u64()))
});
if !status.is_success() || exception_code.as_deref().is_some_and(|code| code != "0") {
let body = response.bytes().await.map_err(request_error)?;
let body = response_prefix(response).await.map_err(request_error)?;
return Err(self.server_error(status, exception_code.as_deref(), &body));
}
let (columns, rows, has_more) = if format.as_deref().is_some_and(|f| f != FORMAT) {
@@ -458,6 +496,66 @@ impl ClickhousePool {
}
}
/// Dedicated workspace sessions consume the response before any grid truncation or formatting.
pub(crate) async fn workspace_rows(
&self,
sql: &str,
max_rows: usize,
max_bytes: usize,
cancel: &CancellationToken,
mut consume: impl FnMut(&[u8]) -> IdeResult<()>,
) -> IdeResult<()> {
let mut slot = self.session(&self.0.session, cancel).await?;
let state = slot.as_mut().expect("session was initialized");
let mut stateless;
let session = if self.0.use_http_session {
state
} else {
stateless = state.clone();
drop(slot);
&mut stateless
};
let client = self.client()?;
let query_id = uuid::Uuid::new_v4().to_string();
let request = self.request(&client, &query_id, max_rows, session, Some(max_bytes)).body(sql.to_owned());
let fetch = async {
let mut response = request.send().await.map_err(http_error)?;
let status = response.status();
let metadata = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok());
let code = metadata("X-ClickHouse-Exception-Code").map(str::to_owned);
if !status.is_success() || code.as_deref().is_some_and(|code| code != "0") {
let body = response_prefix(response).await.map_err(http_error)?;
return Err(self.server_error(status, code.as_deref(), &body));
}
if metadata("X-ClickHouse-Format").is_some_and(|format| format != FORMAT) {
return Err(IdeError::invalid("ClickHouse did not return the workspace response format"));
}
let mut received = 0;
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
received += chunk.len();
if received > max_bytes {
return Err(IdeError::invalid("Workspace input exceeds the source byte limit"));
}
consume(&chunk)?;
}
Ok(())
};
let result = tokio::select! {
biased;
() = cancel.cancelled() => Err(IdeError::cancelled()),
() = self.0.closed.cancelled() => Err(IdeError::cancelled()),
() = tokio::time::sleep(Duration::from_secs(25)) =>
Err(IdeError::new(ErrorKind::TimedOut, "Workspace ClickHouse source read timed out")),
result = fetch => result,
};
if result.is_ok() {
session.initialized = true;
} else {
let _ = self.kill(&client, &query_id, session).await;
}
result.map_err(|e| self.redact_error(e))
}
async fn kill(&self, client: &Client, query_id: &str, session: &Session) -> IdeResult<()> {
let mut request = client
.post(self.0.endpoint.clone())
@@ -474,7 +572,7 @@ impl ClickhousePool {
.get("X-ClickHouse-Exception-Code")
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let body = response.bytes().await.map_err(http_error)?;
let body = response_prefix(response).await.map_err(http_error)?;
if status.is_success() && !code.as_deref().is_some_and(|code| code != "0") && !body.starts_with(b"Code:") {
Ok(())
} else {
@@ -503,6 +601,17 @@ impl ClickhousePool {
}
}
async fn response_prefix(mut response: reqwest::Response) -> Result<Vec<u8>, reqwest::Error> {
const LIMIT: usize = 16_384;
let mut body = Vec::new();
while body.len() < LIMIT {
let Some(chunk) = response.chunk().await? else { break };
let remaining = LIMIT - body.len();
body.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
}
Ok(body)
}
type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
@@ -1448,6 +1557,15 @@ mod tests {
#[tokio::test]
async fn stateless_queries_do_not_wait_for_a_shared_session() {
assert_stateless_requests_overlap(false).await;
}
#[tokio::test]
async fn stateless_workspace_reads_do_not_block_queries() {
assert_stateless_requests_overlap(true).await;
}
async fn assert_stateless_requests_overlap(workspace: bool) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let (started, received) = tokio::sync::oneshot::channel();
@@ -1465,9 +1583,15 @@ mod tests {
(first_request, second_request)
});
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
let pool = Pool::connect(&source, None, None).await.unwrap();
let Pool::Clickhouse(pool) = Pool::connect(&source, None, None).await.unwrap() else { unreachable!() };
let cancel = CancellationToken::new();
let first = pool.execute("SELECT 1", 1, &cancel);
let first = async {
if workspace {
pool.workspace_rows("SELECT 1", 1, 1024, &cancel, |_| Ok(())).await
} else {
pool.execute("SELECT 1", 1, &cancel).await.map(drop)
}
};
let second = async {
received.await.unwrap();
pool.execute("SELECT 2", 1, &cancel).await
+65
Переглянути файл
@@ -1330,6 +1330,71 @@ impl Pool {
Ok(conn.finish_read_only(owned, result).await?.1)
}
pub(crate) async fn read_workspace_postgres(
&self,
request: &crate::workspace_input::WorkspaceInputRequest,
selection: Option<&[&str]>,
cancel: &CancellationToken,
) -> IdeResult<crate::workspace_input::WorkspaceInput> {
let Pool::Postgres(pool) = self else {
return Err(IdeError::internal("Expected a PostgreSQL workspace connection"));
};
let mut conn = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
result = pool.get() => result?,
};
let mut backend = None;
let read = async {
if conn.options.read_only == PgReadOnly::Transaction {
conn.start_read_only().await?;
} else {
sqlx::raw_sql("BEGIN READ ONLY").execute(&mut **conn).await.map_err(db_err)?;
}
let row = sqlx::raw_sql(
"SELECT pg_catalog.pg_backend_pid(), pg_catalog.current_setting('transaction_read_only') = 'on'",
)
.fetch_one(&mut **conn)
.await
.map_err(db_err)?;
backend = Some(row.try_get::<i32, _>(0).map_err(db_err)?);
if !row.try_get::<bool, _>(1).map_err(db_err)? {
return Err(IdeError::new(
ErrorKind::PermissionDenied,
"Workspace PostgreSQL transaction is not read-only",
));
}
crate::workspace_input::read_postgres(&mut conn, request, selection).await
};
let result = tokio::select! {
biased;
() = cancel.cancelled() => Err(IdeError::cancelled()),
() = tokio::time::sleep(Duration::from_secs(30)) =>
Err(IdeError::new(ErrorKind::TimedOut, "Workspace PostgreSQL source read timed out")),
result = read => result,
};
if result.is_ok() {
// Do not send a PID-based cancel once a pooler may have released this backend.
let rollback =
tokio::time::timeout(Duration::from_secs(3), sqlx::raw_sql("ROLLBACK").execute(&mut **conn)).await;
if matches!(rollback, Ok(Ok(_))) {
conn.in_transaction = false;
} else {
conn.conn.take();
}
} else {
if let Some(pid) = backend {
let _ = tokio::time::timeout(
Duration::from_secs(3),
self.cancel_query(format!("SELECT pg_catalog.pg_cancel_backend({pid})")),
)
.await;
}
conn.conn.take();
}
result
}
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
/// the statement on the server (PostgreSQL, MySQL) and drops the connection.
pub async fn execute(&self, sql: &str, max_rows: usize, cancel: &CancellationToken) -> IdeResult<QueryResult> {
+103
Переглянути файл
@@ -0,0 +1,103 @@
use super::{DbJdbcDriver, JdbcPool};
use crate::source::{DUCKDB_URL, duck_lake_path};
use crate::{DataSource, DbDuckLake, DbDuckLakeKind, DbManager, Pool};
use ide_core::{IdeError, IdeResult};
const DUCKDB_CLASS: &str = "org.duckdb.DuckDBDriver";
impl DbManager {
pub fn approve_ducklake_source(&self, source: &DataSource) -> IdeResult<()> {
if source.duck_lake.is_none() {
return Err(IdeError::invalid("Expected a DuckLake data source"));
}
source.validate_duck_lake()?;
self.duck_lake_driver(&source.jdbc_driver)?.validate()?;
if source.global {
return Ok(());
}
self.record_jdbc_approval(source)
}
fn duck_lake_driver(&self, id: &str) -> IdeResult<DbJdbcDriver> {
let driver = self.jdbc_driver_by_id(id)?;
driver.require_vendor("duckdb")?;
if driver.class_name != DUCKDB_CLASS {
return Err(IdeError::invalid("Select a DuckDB driver profile with the official DuckDB JDBC driver class"));
}
Ok(driver)
}
/// Creates a lake in a new directory through a separate, disposable JDBC session.
pub async fn create_ducklake(&self, jdbc_driver: &str, directory: &str) -> IdeResult<()> {
duck_lake_path(directory, false)?;
let driver = self.duck_lake_driver(jdbc_driver)?;
let fields = duck_lake_fields("create", directory.to_owned(), "");
let pool = JdbcPool::open(driver, self.jdbc_registry()?.with_file_name("jdbc"), fields).await?;
pool.close().await;
Ok(())
}
pub(super) async fn open_ducklake(&self, source: &DataSource, lake: &DbDuckLake, testing: bool) -> IdeResult<Pool> {
source.validate_duck_lake()?;
self.check_jdbc_project_approval(source, testing)?;
let driver = self.duck_lake_driver(&source.jdbc_driver)?;
let cache = self.jdbc_registry()?.with_file_name("jdbc");
let (mode, value) = match lake.kind {
DbDuckLakeKind::Secret => ("secret", lake.value.clone()),
DbDuckLakeKind::File => {
let path = self.root.join(&lake.value);
let value = path.to_str().ok_or_else(|| IdeError::invalid("Invalid DuckLake catalog file path"))?;
duck_lake_path(value, false)?;
("file", value.to_owned())
}
};
let fields = duck_lake_fields(mode, value, lake.data_path.as_deref().unwrap_or_default());
JdbcPool::open(driver, cache, fields).await.map(Box::new).map(Pool::Jdbc)
}
}
fn duck_lake_fields(mode: &str, value: String, data_path: &str) -> Vec<String> {
vec![
"openDuckLake".into(),
DUCKDB_CLASS.into(),
DUCKDB_URL.into(),
String::new(),
String::new(),
(mode != "create").to_string(),
mode.into(),
value,
data_path.to_owned(),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn ordinary_jdbc_rejects_a_ducklake_even_with_a_file_url() {
let source = DataSource {
driver: crate::DbDriver::Jdbc,
url: "jdbc:duckdb:existing.duckdb".into(),
duck_lake: Some(DbDuckLake {
kind: DbDuckLakeKind::File,
value: "catalog.ducklake".into(),
data_path: None,
}),
..Default::default()
};
let driver = DbJdbcDriver {
id: "duckdb".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![],
class_name: DUCKDB_CLASS.into(),
url_template: DUCKDB_URL.into(),
};
let error = JdbcPool::connect(&source, None, driver, Default::default())
.await
.err()
.expect("ordinary JDBC must reject DuckLake fields before opening a connection");
assert_eq!(error.message, "DuckLake catalogs require a DuckLake connection");
}
}
+141 -26
Переглянути файл
@@ -15,6 +15,7 @@ use tokio::sync::Mutex;
use tokio::time::timeout;
mod bridge;
mod ducklake;
use bridge::Bridge;
@@ -79,6 +80,13 @@ pub fn jdbc_driver_classes(jars: &[String]) -> IdeResult<Vec<String>> {
}
impl DbJdbcDriver {
fn require_vendor(&self, vendor: &str) -> IdeResult<()> {
if self.vendor.as_deref() != Some(vendor) {
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
}
Ok(())
}
fn validate(&self) -> IdeResult<()> {
if self.id.is_empty()
|| self.name.trim().is_empty()
@@ -138,6 +146,30 @@ impl DbManager {
self.update_jdbc_driver(id, None)
}
fn record_jdbc_approval(&self, source: &DataSource) -> IdeResult<()> {
let (path, fingerprint) = self.jdbc_approval(source)?;
persist_local(&path, fingerprint.as_bytes())
}
fn jdbc_driver_by_id(&self, id: &str) -> IdeResult<DbJdbcDriver> {
self.jdbc_drivers()?
.into_iter()
.find(|d| d.id == id)
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))
}
fn check_jdbc_project_approval(&self, source: &DataSource, testing: bool) -> IdeResult<()> {
if !testing && !source.global {
let (path, expected) = self.jdbc_approval(source)?;
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
return Err(IdeError::invalid(
"Review this project's JDBC URL and properties, then save the data source before connecting",
));
}
}
Ok(())
}
fn jdbc_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
let registry = self.jdbc_registry()?;
let key = serde_json::to_vec(&(&self.root, &source.id)).map_err(|e| IdeError::internal(e.to_string()))?;
@@ -150,7 +182,10 @@ impl DbManager {
&source.options,
))
.map_err(|e| IdeError::internal(e.to_string()))?;
if self.jdbc_password_isolated(source) {
if let Some(lake) = &source.duck_lake {
settings.extend_from_slice(b"\0ducklake\0");
serde_json::to_writer(&mut settings, lake).map_err(|e| IdeError::internal(e.to_string()))?;
} else if self.jdbc_password_isolated(source) {
settings.extend_from_slice(b"\0jdbc-password");
}
Ok((
@@ -164,8 +199,70 @@ impl DbManager {
if source.driver != crate::DbDriver::Jdbc || source.plugin_owner.is_some() {
return Err(IdeError::invalid("Expected a user-managed JDBC data source"));
}
let (path, fingerprint) = self.jdbc_approval(source)?;
persist_local(&path, fingerprint.as_bytes())
if source.duck_lake.is_some() {
return self.approve_ducklake_source(source);
}
self.record_jdbc_approval(source)
}
/// A workspace uses only the selected host driver and a fresh in-memory database.
pub(crate) async fn workspace_engine(&self, profile: &str) -> IdeResult<JdbcPool> {
let driver = self
.jdbc_drivers()?
.into_iter()
.find(|driver| {
driver.id == profile
&& driver.vendor.as_deref() == Some("duckdb")
&& driver.class_name == "org.duckdb.DuckDBDriver"
})
.ok_or_else(|| IdeError::invalid("Choose an installed DuckDB JDBC driver for the workspace"))?;
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
JdbcPool::connect(&source, None, driver, self.jdbc_registry()?.with_file_name("jdbc")).await
}
pub(crate) async fn prepare_workspace_duckdb_source(
&self,
source: &DataSource,
) -> IdeResult<WorkspaceDuckDbSource> {
let driver = self.approved_jdbc_driver(source, false)?;
if driver.vendor.as_deref() != Some("duckdb") || driver.class_name != "org.duckdb.DuckDBDriver" {
return Err(IdeError::invalid("Choose a saved DuckDB source with an installed DuckDB driver"));
}
let target = source.url.strip_prefix("jdbc:duckdb:").unwrap_or_default();
let mut parts = target.split(';');
let filename = parts.next().unwrap_or_default();
let cache = self.jdbc_registry()?.with_file_name("jdbc");
let path = cache.join("files").join(filename);
if filename.is_empty()
|| filename.starts_with([':', ' '])
|| filename.starts_with("memory:")
|| filename.starts_with("md:")
|| filename.contains("://")
|| !tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file())
{
return Err(IdeError::invalid("Choose an existing local DuckDB database file as the workspace source"));
}
let limits = [
("enable_external_access", "false"),
("allow_unsigned_extensions", "false"),
("autoinstall_known_extensions", "false"),
("autoload_known_extensions", "false"),
("memory_limit", "96MiB"),
("threads", "1"),
("temp_directory", ""),
("max_temp_directory_size", "0B"),
];
let protected = |name: &str| limits.iter().any(|(key, _)| name.trim().eq_ignore_ascii_case(key));
if parts.any(|option| protected(option.split('=').next().unwrap_or_default())) {
return Err(IdeError::invalid("DuckDB Workspace source URL changes a workspace read limit"));
}
let mut target = source.clone();
target.read_only = true;
target.properties.retain(|property| !protected(&property.name));
target
.properties
.extend(limits.map(|(name, value)| crate::DbProperty { name: name.into(), value: value.into() }));
Ok(WorkspaceDuckDbSource { target, driver, cache })
}
pub(crate) async fn open_pool(
@@ -174,33 +271,42 @@ impl DbManager {
password: Option<&str>,
testing: bool,
) -> IdeResult<crate::Pool> {
if let Some(lake) = &source.duck_lake {
return self.open_ducklake(source, lake, testing).await;
}
if source.driver != crate::DbDriver::Jdbc {
return crate::Pool::connect(source, password, Some(&self.root)).await;
}
if source.plugin_owner.is_some() {
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
}
if !testing && !source.global {
let (path, expected) = self.jdbc_approval(source)?;
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
return Err(IdeError::invalid(
"Review this project's JDBC URL and properties, then save the data source before connecting",
));
}
}
let driver = self
.jdbc_drivers()?
.into_iter()
.find(|d| d.id == source.jdbc_driver)
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))?;
if !source.vendor.is_empty() && driver.vendor.as_deref() != Some(source.vendor.as_str()) {
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
}
let driver = self.approved_jdbc_driver(source, testing)?;
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
.await
.map(Box::new)
.map(crate::Pool::Jdbc)
}
fn approved_jdbc_driver(&self, source: &DataSource, testing: bool) -> IdeResult<DbJdbcDriver> {
if source.plugin_owner.is_some() {
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
}
self.check_jdbc_project_approval(source, testing)?;
let driver = self.jdbc_driver_by_id(&source.jdbc_driver)?;
if !source.vendor.is_empty() {
driver.require_vendor(&source.vendor)?;
}
Ok(driver)
}
}
pub(crate) struct WorkspaceDuckDbSource {
target: DataSource,
driver: DbJdbcDriver,
cache: PathBuf,
}
impl WorkspaceDuckDbSource {
pub(crate) async fn connect(self, password: Option<&str>) -> IdeResult<JdbcPool> {
JdbcPool::connect(&self.target, password, self.driver, self.cache).await
}
}
struct Session {
@@ -277,10 +383,12 @@ impl JdbcPool {
driver: DbJdbcDriver,
cache: PathBuf,
) -> IdeResult<Self> {
driver.validate()?;
if source.duck_lake.is_some() {
return Err(IdeError::invalid("DuckLake catalogs require a DuckLake connection"));
}
let mut fields = vec![
"open".to_string(),
driver.class_name,
driver.class_name.clone(),
source.url.clone(),
source.user.clone(),
password.unwrap_or_default().to_owned(),
@@ -292,6 +400,11 @@ impl JdbcPool {
}
fields.extend([p.name.clone(), p.value.clone()]);
}
Self::open(driver, cache, fields).await
}
async fn open(driver: DbJdbcDriver, cache: PathBuf, fields: Vec<String>) -> IdeResult<Self> {
driver.validate()?;
let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
@@ -306,7 +419,7 @@ impl JdbcPool {
bridge: Arc::new(bridge),
service: Session::new(0),
consoles: Default::default(),
shared_connection: private_database_url(&source.url),
shared_connection: private_database_url(&fields[2]),
version: metadata.next().flatten().unwrap_or_else(|| "Connected".into()),
identifier_quote: metadata.next().flatten().unwrap_or_default().trim().into(),
})
@@ -748,7 +861,9 @@ mod tests {
assert!(catalogs.contains(&vec![Some("memory".into()), Some("1".into())]));
assert!(catalogs.contains(&vec![Some("first".into()), Some("0".into())]));
assert!(catalogs.contains(&vec![Some(archive.into()), Some("0".into())]));
let schemas = pool.metadata(&["schemas", archive]).await?;
let mut schemas = pool.metadata(&["schemas", archive]).await?;
// DuckDB JDBC 1.1.3 also lists these system schemas for attached catalogs.
schemas.retain(|row| !matches!(row[0].as_deref(), Some("information_schema" | "pg_catalog")));
assert_eq!(schemas, ["main", "qaSimilar", "qa_%"].map(|schema| vec![Some(schema.into())]));
let tables = pool.metadata(&["tables", "qa_%", archive]).await?;
assert_eq!(tables.len(), 1);
+114 -14
Переглянути файл
@@ -25,14 +25,17 @@ pub mod sql;
pub mod tools;
mod watch;
pub use watch::SourcesWatch;
pub mod workspace;
pub mod workspace_input;
pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog};
pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
DataSource, DbColor, DbDriver, DbDuckLake, DbDuckLakeKind, DbExternalTunnel, DbIntrospection, DbOptions,
DbProperty, DbSchemaSelection, DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode,
DbVisibilityChange,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
@@ -201,7 +204,7 @@ impl DbKeyKind {
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTableDetails")]
pub struct TableDetails {
@@ -213,6 +216,53 @@ pub struct TableDetails {
pub indexes: Vec<IndexInfo>,
pub foreign_keys: Vec<ForeignKey>,
pub triggers: Vec<TriggerInfo>,
/// The role owning the table (PostgreSQL); `None` where the schema owns its tables.
#[serde(default)]
#[specta(optional)]
pub owner: Option<String>,
/// The table's tablespace, the database's default one when it names none (PostgreSQL).
#[serde(default)]
#[specta(optional)]
pub tablespace: Option<String>,
/// The table access method (PostgreSQL's `heap`, …); `None` for a partitioned table, and on
/// the engines without one.
#[serde(default)]
#[specta(optional)]
pub access_method: Option<String>,
/// The storage parameters set on the table, as `(name, value)`: PostgreSQL's reloptions,
/// its TOAST table's prefixed `toast.`. `None` on the engines without any.
#[serde(default)]
#[specta(optional)]
pub storage_options: Option<Vec<(String, String)>>,
/// The partition key (`RANGE (created)`); `None` when the table isn't partitioned.
#[serde(default)]
#[specta(optional)]
pub partitioning: Option<String>,
/// Whether the table is logged, unlogged or temporary (PostgreSQL).
#[serde(default)]
#[specta(optional)]
pub persistence: Option<DbPersistence>,
}
/// Whether a table's changes are written to the write-ahead log, and whether it outlives the session.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbPersistence {
Permanent,
Unlogged,
Temporary,
}
impl DbPersistence {
/// PostgreSQL's `pg_class.relpersistence`.
fn from_catalog(v: &str) -> Option<Self> {
match v {
"p" => Some(Self::Permanent),
"u" => Some(Self::Unlogged),
"t" => Some(Self::Temporary),
_ => None,
}
}
}
/// One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted
@@ -330,6 +380,7 @@ pub struct DbManager {
sessions: Mutex<HashMap<String, Session>>,
/// Result pages read on from where the previous page stopped, not by running the statement again.
cursors: conn::Cursors,
workspace_run: tokio::sync::Mutex<()>,
/// The data sources as last read from disk, for [`DbManager::reconcile_sources`]
/// (`None` until [`DbManager::watch_sources`]).
on_disk: Mutex<Option<Vec<DataSource>>>,
@@ -379,6 +430,25 @@ async fn catalog_rows(pool: &Pool, q: &str) -> IdeResult<Vec<Vec<Option<String>>
}
}
/// One [`sql::table_properties`] row into `details`.
fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
let mut it = row.into_iter().map(|v| v.filter(|v| !v.is_empty()));
let mut next = || it.next().flatten();
details.owner = next();
details.tablespace = next();
details.access_method = next();
details.storage_options = Some(
next()
.unwrap_or_default()
.lines()
.filter_map(|o| o.split_once('='))
.map(|(name, value)| (name.to_owned(), value.to_owned()))
.collect(),
);
details.partitioning = next();
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
}
fn flag(v: &Option<String>) -> bool {
matches!(v.as_deref(), Some("1" | "t" | "true" | "YES"))
}
@@ -478,6 +548,13 @@ pub fn split_target(target: &str) -> (&str, Option<&str>) {
}
}
fn reject_duck_lake_password(password: Option<&str>) -> IdeResult<()> {
if password.is_some_and(|p| !p.is_empty()) {
return Err(IdeError::invalid("DuckLake uses a catalog file or named secret without a JDBC or SSH password"));
}
Ok(())
}
/// Says which leg failed when the database is unreachable from the SSH host.
fn through_tunnel(e: IdeError, source: &DataSource, via: Option<&str>) -> IdeError {
let Some(via) = via.filter(|_| e.kind == ErrorKind::Io) else { return e };
@@ -548,6 +625,7 @@ impl DbManager {
on_disk: Mutex::default(),
sessions: Mutex::default(),
cursors: conn::Cursors::default(),
workspace_run: tokio::sync::Mutex::new(()),
}
}
@@ -631,13 +709,16 @@ impl DbManager {
/// Saves the data source list, preserving connections when only visibility rules change.
/// Global ones (`global`) go to the app-wide list, the others to the project's.
pub async fn save_sources(&self, mut sources: Vec<DataSource>) -> IdeResult<()> {
for source in &sources {
source.validate_duck_lake()?;
}
if sources.iter().any(|s| s.global && s.plugin_owner.is_some()) {
return Err(IdeError::invalid("plugin-owned data sources must stay project-scoped"));
}
let old = {
let _guard = plugin::EDIT.lock();
let old = self.sources().unwrap_or_default();
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc) {
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc && s.duck_lake.is_none()) {
// Retain the credential scope even when URL-only settings supplied the old authenticator.
if let Some(settings) = old.iter().find(|s| s.id == source.id).and_then(Self::non_password_snowflake) {
source.snowflake = Some(settings);
@@ -686,7 +767,7 @@ impl DbManager {
}
}
// Made global or project-level: its saved passwords move along.
Some(n) if n.global != o.global => {
Some(n) if n.global != o.global && n.duck_lake.is_none() && o.duck_lake.is_none() => {
for k in &keys {
if let Some(p) = self.store_of(&o).get(k) {
self.store_of(n).set(k, &p)?;
@@ -768,6 +849,9 @@ impl DbManager {
/// the data source saves passwords (`None` forgets it).
pub async fn set_password(&self, id: &str, password: Option<String>, save: bool) -> IdeResult<()> {
let source = self.sources()?.into_iter().find(|s| s.id == id);
if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) {
return reject_duck_lake_password(password.as_deref());
}
let (store, key) = match source.as_ref() {
Some(source) => (self.store_of(source), self.password_key(source)),
None => (&self.saved_passwords, id.to_owned()),
@@ -778,7 +862,11 @@ impl DbManager {
/// [`DbManager::set_password`] for the SSH password / key passphrase.
/// A data source using an SSH configuration sets that configuration's secret.
pub async fn set_ssh_secret(&self, id: &str, secret: Option<String>, save: bool) -> IdeResult<()> {
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
let source = self.sources()?.into_iter().find(|s| s.id == id);
if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) {
return reject_duck_lake_password(secret.as_deref());
}
let config = source.and_then(|s| s.ssh).map(|s| s.config);
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
return self.ssh.set_secret(&c, secret, save);
@@ -823,6 +911,9 @@ impl DbManager {
}
async fn password(&self, source: &DataSource) -> Option<String> {
if source.duck_lake.is_some() {
return None;
}
match self
.secret(source, self.password_key(source), source.driver != DbDriver::Sqlite && source.save_password)
.await
@@ -931,6 +1022,10 @@ impl DbManager {
purpose: route::RouteUse,
) -> IdeResult<String> {
let source = &source.resolved()?;
if source.duck_lake.is_some() {
reject_duck_lake_password(password.as_deref())?;
reject_duck_lake_password(ssh_secret.as_deref())?;
}
let password = match password {
Some(p) => Some(p),
None => self.password(source).await,
@@ -1287,13 +1382,7 @@ impl DbManager {
})
.collect();
if driver == DbDriver::Jdbc {
return Ok(TableDetails {
comment: None,
columns,
indexes: vec![],
foreign_keys: vec![],
triggers: vec![],
});
return Ok(TableDetails { columns, ..Default::default() });
}
let mut indexes: Vec<IndexInfo> = Vec::new();
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
@@ -1360,7 +1449,18 @@ impl DbManager {
),
None => None,
};
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
if let Some(q) = sql::table_properties(driver, schema, table) {
match catalog_rows(pool, &q).await {
Ok(rows) => {
if let Some(row) = rows.into_iter().next() {
read_table_properties(&mut details, row);
}
}
Err(e) => tracing::warn!("table properties: {}", e.message),
}
}
Ok(details)
}
/// The object privileges granted on `table`; empty, without a query, on the engines
+1 -1
Переглянути файл
@@ -154,7 +154,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
.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() })
Ok(TableDetails { comment, columns, foreign_keys, ..Default::default() })
}
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
+86
Переглянути файл
@@ -11,6 +11,7 @@ use std::collections::{BTreeMap, HashSet};
use std::path::Path;
pub(crate) const FILE: &str = "data-sources.toml";
pub(crate) const DUCKDB_URL: &str = "jdbc:duckdb:";
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
@@ -306,6 +307,25 @@ pub struct DbExternalTunnel {
pub arguments: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum DbDuckLakeKind {
File,
Secret,
}
/// How to open an existing DuckLake catalog read-only through DuckDB.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DbDuckLake {
pub kind: DbDuckLakeKind,
/// A local catalog file or an existing DuckDB secret name.
pub value: String,
/// An existing local data directory overriding the catalog's data path.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data_path: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase", default)]
pub struct DataSource {
@@ -346,6 +366,8 @@ pub struct DataSource {
pub properties: Vec<DbProperty>,
/// Snowflake settings (`None`: not a Snowflake data source, or all defaults).
pub snowflake: Option<DbSnowflake>,
#[serde(skip_serializing_if = "Option::is_none")]
pub duck_lake: Option<DbDuckLake>,
/// Stored app-wide and listed in every project. Implied by the file it is read from,
/// so not written to it.
pub global: bool,
@@ -386,6 +408,7 @@ impl Default for DataSource {
introspection: DbIntrospection::default(),
properties: Vec::new(),
snowflake: None,
duck_lake: None,
global: false,
plugin_owner: None,
plugin_source_id: None,
@@ -513,7 +536,69 @@ pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
Ok(parsed)
}
pub(crate) fn duck_lake_path(value: &str, relative: bool) -> IdeResult<&Path> {
let path = Path::new(value);
if value.trim().is_empty()
|| value.contains(['\0', '\r', '\n'])
|| value.starts_with("//")
|| value.starts_with('\\')
|| (!path.is_absolute() && (!relative || value.starts_with('/') || value.contains(':')))
{
return Err(IdeError::invalid("Choose a local DuckLake path on the database host"));
}
Ok(path)
}
impl DataSource {
pub(crate) fn validate_duck_lake(&self) -> IdeResult<()> {
let Some(lake) = &self.duck_lake else { return Ok(()) };
if self.driver != DbDriver::Jdbc
|| self.vendor != "duckdb"
|| self.url != DUCKDB_URL
|| self.url_only
|| !self.read_only
|| self.plugin_owner.is_some()
{
return Err(IdeError::invalid("Existing DuckLake catalogs require a read-only DuckDB JDBC data source"));
}
if !self.user.is_empty()
|| self.save_password
|| self.ssh.is_some()
|| self.external_tunnel.is_some()
|| !self.properties.is_empty()
{
return Err(IdeError::invalid(
"DuckLake uses its catalog file or named secret without JDBC credentials, properties or tunnels",
));
}
if self.options.transaction != DbTxMode::Auto
|| !self.options.default_schema.is_empty()
|| !self.options.time_zone.is_empty()
|| !self.options.startup_script.is_empty()
{
return Err(IdeError::invalid("DuckLake does not use JDBC session overrides"));
}
match lake.kind {
DbDuckLakeKind::File => {
duck_lake_path(&lake.value, true)?;
}
DbDuckLakeKind::Secret => {
let mut chars = lake.value.bytes();
if !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == b'_')
|| !chars.all(|c| c.is_ascii_alphanumeric() || c == b'_')
{
return Err(IdeError::invalid(
"Enter an existing DuckLake secret name using letters, digits or underscores",
));
}
}
}
if let Some(path) = lake.data_path.as_deref().filter(|path| !path.is_empty()) {
duck_lake_path(path, false)?;
}
Ok(())
}
pub(crate) fn select_database(&mut self, database: Option<&str>) {
if let Some(db) = database {
// The configured schema belongs to the configured database.
@@ -536,6 +621,7 @@ impl DataSource {
/// database, user, SSL and driver properties come from the URL (properties
/// of the Advanced tab still apply after the URL's).
pub fn resolved(&self) -> IdeResult<DataSource> {
self.validate_duck_lake()?;
if self.driver == DbDriver::Jdbc {
if !self.url.starts_with("jdbc:") {
return Err(IdeError::invalid("Enter a JDBC URL starting with jdbc:"));
+31 -1
Переглянути файл
@@ -236,6 +236,29 @@ pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<Stri
}
}
/// One row: `owner, tablespace, access method, storage options (name=value per line),
/// partition key, persistence (p/u/t)` of a table. `None` for the engines whose tables have none
/// of these the IDE reads (all but PostgreSQL).
pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
// `reltablespace` 0 is the database's default tablespace; the TOAST table's options are
// set as `toast.name`.
DbDriver::Postgres => Some(format!(
"SELECT pg_get_userbyid(c.relowner), COALESCE(ts.spcname, (SELECT dt.spcname FROM pg_database d \
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
am.amname, array_to_string(array_cat(c.reloptions, \
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
pg_get_partkeydef(c.oid), c.relpersistence \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
WHERE n.nspname = {s} AND c.relname = {t} AND c.relkind IN ('r', 'p')"
)),
_ => None,
}
}
/// Rows: `index name, unique (0/1), column, key` (one row per indexed column, in order); `key` is
/// `p` for the primary key's index, `u` for a unique constraint's, NULL otherwise (ClickHouse: absent).
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
@@ -812,7 +835,12 @@ pub fn sqlite_trigger_event(sql: &str) -> (String, String) {
pub fn postgres_legacy(sql: &str) -> Option<String> {
let legacy = sql
.replace("CASE WHEN p.prokind = 'p' THEN 'procedure' ELSE 'function' END", "'function'")
.replace("p.prokind IN ('f', 'p')", "NOT p.proisagg AND NOT p.proiswindow");
.replace("p.prokind IN ('f', 'p')", "NOT p.proisagg AND NOT p.proiswindow")
// Table access methods (PostgreSQL 12) and partitioned tables (10).
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
.replace("am.amname", "NULL")
.replace("pg_get_partkeydef(c.oid)", "NULL")
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
(legacy != sql).then_some(legacy)
}
@@ -1534,5 +1562,7 @@ mod tests {
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
let properties = postgres_legacy(&table_properties(pg, "s", "t").unwrap()).unwrap();
assert!(!properties.contains("relam") && !properties.contains("partkeydef"), "{properties}");
}
}
+579
Переглянути файл
@@ -0,0 +1,579 @@
//! A read-only equality join of explicitly selected source tables on the project host.
use crate::jdbc::JdbcPool;
use crate::workspace_input::{
self, WorkspaceInput, WorkspaceInputColumn, WorkspaceInputLimits, WorkspaceInputRequest, WorkspaceInputType,
};
use crate::{DbDriver, DbManager, QueryResult, sql};
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::io::{BufWriter, Write};
use std::time::{Duration, Instant};
use tempfile::{NamedTempFile, TempPath};
const MAX_TABLES: usize = 8;
const MAX_RESULT_ROWS: usize = 100_000;
const MAX_RESULT_COLUMNS: usize = 256;
const WORKSPACE_INPUT_LIMITS: WorkspaceInputLimits =
WorkspaceInputLimits { max_rows: 100_000, max_cell_bytes: 1_048_576, max_bytes: 16_777_216 };
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinRelation")]
pub struct WorkspaceJoinRelation {
pub source_id: String,
pub database: String,
pub schema: String,
pub table: String,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinColumn")]
pub struct WorkspaceJoinColumn {
pub relation: u32,
pub column: String,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinCondition")]
pub struct WorkspaceJoinCondition {
/// The right relation is the next table in the chain.
pub left: WorkspaceJoinColumn,
pub right_column: String,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinProjection")]
pub struct WorkspaceJoinProjection {
pub relation: u32,
/// None expands this relation's columns in source order.
pub column: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinPlan")]
pub struct WorkspaceJoinPlan {
pub tables: Vec<WorkspaceJoinRelation>,
pub joins: Vec<WorkspaceJoinCondition>,
/// None expands all relations in FROM/JOIN order.
pub projection: Option<Vec<WorkspaceJoinProjection>>,
}
fn validate_plan(
table_count: usize,
joins: &[WorkspaceJoinCondition],
projection: Option<&[WorkspaceJoinProjection]>,
) -> IdeResult<()> {
if !(2..=MAX_TABLES).contains(&table_count) || joins.len() + 1 != table_count {
return Err(IdeError::invalid("A workspace JOIN needs 2 to 8 tables and one equality per JOIN"));
}
let valid_column = |name: &str| !name.is_empty() && name.len() <= 255 && !name.contains('\0');
for (index, link) in joins.iter().enumerate() {
if link.left.relation as usize > index || !valid_column(&link.left.column) || !valid_column(&link.right_column)
{
return Err(IdeError::invalid("Each JOIN must compare a column of its new table with an earlier table"));
}
}
if let Some(projection) = projection
&& (projection.is_empty()
|| projection.len() > MAX_RESULT_COLUMNS
|| projection.iter().any(|item| {
item.relation as usize >= table_count || item.column.as_deref().is_some_and(|name| !valid_column(name))
}))
{
return Err(IdeError::invalid("Invalid workspace SELECT columns"));
}
Ok(())
}
struct StagedTable {
path: TempPath,
longest_row: usize,
columns: Vec<WorkspaceInputColumn>,
}
impl WorkspaceInputType {
fn is_integer(self) -> bool {
use WorkspaceInputType::*;
matches!(self, Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64)
}
fn duckdb_type(self) -> String {
use WorkspaceInputType::*;
match self {
Boolean => "BOOLEAN",
Int8 => "TINYINT",
Int16 => "SMALLINT",
Int32 => "INTEGER",
Int64 => "BIGINT",
UInt8 => "UTINYINT",
UInt16 => "USMALLINT",
UInt32 => "UINTEGER",
UInt64 => "UBIGINT",
Float32 => "FLOAT",
Float64 => "DOUBLE",
Decimal { precision, scale } => return format!("DECIMAL({precision},{scale})"),
Text => "VARCHAR",
Date => "DATE",
Time => "TIME",
Timestamp => "TIMESTAMP",
TimestampTz => "TIMESTAMPTZ",
Uuid => "UUID",
}
.into()
}
}
fn stage(input: WorkspaceInput, cancel: &CancellationToken) -> IdeResult<StagedTable> {
let mut file = NamedTempFile::new()?;
let mut longest_row = 1;
{
let mut out = BufWriter::new(file.as_file_mut());
for row in input.rows {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if row.len() != input.columns.len() {
return Err(IdeError::invalid("Incomplete workspace input row"));
}
let mut bytes = row.len(); // separators and newline
for (column, cell) in row.into_iter().enumerate() {
if column > 0 {
out.write_all(b",")?;
}
bytes += 2; // quotes or the NULL marker
if let Some(value) = cell {
bytes += value.len();
out.write_all(b"\"")?;
let mut pieces = value.split('"');
out.write_all(pieces.next().unwrap_or_default().as_bytes())?;
for piece in pieces {
bytes += 1;
out.write_all(b"\"\"")?;
out.write_all(piece.as_bytes())?;
}
out.write_all(b"\"")?;
} else {
out.write_all(br"\N")?;
}
}
longest_row = longest_row.max(bytes);
out.write_all(b"\n")?;
}
out.flush()?;
}
Ok(StagedTable { path: file.into_temp_path(), longest_row, columns: input.columns })
}
impl StagedTable {
fn quoted_path(&self) -> IdeResult<String> {
self.path
.to_str()
.map(|p| sql::quote_literal(DbDriver::Jdbc, p))
.ok_or_else(|| IdeError::invalid("The workspace temporary directory needs a UTF-8 path"))
}
fn scan(&self, path: &str) -> String {
// Synthetic column names also preserve case-distinct names from the source.
let columns = self
.columns
.iter()
.enumerate()
.map(|(i, c)| format!("'c{i}':'{}'", c.data_type.duckdb_type()))
.collect::<Vec<_>>()
.join(",");
let line = self.longest_row;
// The single-threaded reader only needs one complete CSV record per buffer.
let buffer = line.max(64 * 1024);
format!(
r#"read_csv({path},columns={{{columns}}},auto_detect=false,header=false,delim=',',quote='"',escape='"',nullstr='\N',allow_quoted_nulls=false,parallel=false,max_line_size={line},buffer_size={buffer})"#
)
}
fn column(&self, name: &str) -> IdeResult<usize> {
self.columns
.iter()
.position(|c| c.name == name)
.ok_or_else(|| IdeError::invalid(format!("Unknown workspace column: {name}")))
}
}
fn staging_columns<'a>(
table_count: usize,
joins: &'a [WorkspaceJoinCondition],
projection: Option<&'a [WorkspaceJoinProjection]>,
) -> Vec<Option<Vec<&'a str>>> {
let Some(projection) = projection else {
return vec![None; table_count];
};
let mut columns: Vec<Option<Vec<&str>>> = vec![Some(Vec::new()); table_count];
for item in projection {
let selected = &mut columns[item.relation as usize];
match (&item.column, selected) {
(Some(name), Some(selected)) => selected.push(name),
(None, selected) => *selected = None,
_ => {}
}
}
for (index, link) in joins.iter().enumerate() {
if let Some(selected) = &mut columns[link.left.relation as usize] {
selected.push(&link.left.column);
}
if let Some(selected) = &mut columns[index + 1] {
selected.push(&link.right_column);
}
}
for selected in columns.iter_mut().flatten() {
selected.sort_unstable();
selected.dedup();
}
columns
}
fn result_projection(
tables: &[StagedTable],
selection: Option<&[WorkspaceJoinProjection]>,
) -> IdeResult<Vec<(usize, usize)>> {
let mut fields = Vec::new();
match selection {
Some(selection) => {
for item in selection {
let relation = item.relation as usize;
let table = &tables[relation];
match &item.column {
Some(name) => fields.push((relation, table.column(name)?)),
None => fields.extend((0..table.columns.len()).map(|column| (relation, column))),
}
}
}
None => {
for (relation, table) in tables.iter().enumerate() {
fields.extend((0..table.columns.len()).map(|column| (relation, column)));
}
}
}
if fields.len() > MAX_RESULT_COLUMNS {
return Err(IdeError::invalid("Workspace result exceeds 256 columns"));
}
Ok(fields)
}
async fn join(
engine: &JdbcPool,
tables: &[StagedTable],
joins: &[WorkspaceJoinCondition],
selection: Option<&[WorkspaceJoinProjection]>,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
use std::fmt::Write as _;
let fields = result_projection(tables, selection)?;
let names = fields.iter().map(|(relation, column)| format!("r{relation}.c{column}")).collect::<Vec<_>>().join(", ");
let paths = tables.iter().map(StagedTable::quoted_path).collect::<IdeResult<Vec<_>>>()?;
let mut query = format!("SELECT {names} FROM {} r0", tables[0].scan(&paths[0]));
for (index, condition) in joins.iter().enumerate() {
let left_relation = condition.left.relation as usize;
let right_relation = index + 1;
let left = &tables[left_relation];
let right = &tables[right_relation];
let li = left.column(&condition.left.column)?;
let ri = right.column(&condition.right_column)?;
let (a, b) = (left.columns[li].data_type, right.columns[ri].data_type);
// DuckDB compares mixed integer widths and signs exactly, up to BIGINT against UBIGINT.
if a != b && !(a.is_integer() && b.is_integer()) {
return Err(IdeError::invalid("Choose integer join columns or columns of the same type and precision"));
}
write!(
query,
" INNER JOIN {} r{right_relation} ON r{left_relation}.c{li}=r{right_relation}.c{ri}",
right.scan(&paths[right_relation]),
)
.unwrap();
}
write!(query, " LIMIT {}", MAX_RESULT_ROWS + 1).unwrap();
for setting in [
"SET threads=1",
"SET memory_limit='96MiB'",
"SET temp_directory=''",
"SET max_temp_directory_size='0B'",
&format!("SET allowed_paths=[{}]", paths.join(",")),
"SET enable_external_access=false",
"SET lock_configuration=true",
] {
engine.query(setting, 0, 0, cancel).await?;
}
let mut result = engine.query(&query, 0, MAX_RESULT_ROWS, cancel).await?;
if result.has_more {
return Err(IdeError::invalid("Workspace result exceeds 100,000 rows"));
}
if result.columns.len() != fields.len() {
return Err(IdeError::invalid("Unexpected workspace result columns"));
}
for (display, (relation, column)) in result.columns.iter_mut().zip(fields) {
display.name.clone_from(&tables[relation].columns[column].name);
}
result.statement.clear();
Ok(result)
}
#[cfg(test)]
fn two_table_join(keys: [&str; 2]) -> WorkspaceJoinCondition {
WorkspaceJoinCondition {
left: WorkspaceJoinColumn { relation: 0, column: keys[0].into() },
right_column: keys[1].into(),
}
}
impl DbManager {
#[cfg(test)]
pub(crate) async fn workspace_join_pair_for_test(
&self,
driver: &str,
tables: [&WorkspaceInputRequest; 2],
keys: [&str; 2],
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let joins = [two_table_join(keys)];
validate_plan(tables.len(), &joins, None)?;
self.execute_workspace_join(driver, &tables, &joins, None, cancel).await
}
/// The caller retains the bounded result for paging. Reading another page never reruns the sources.
pub async fn workspace_join(
&self,
driver: &str,
plan: WorkspaceJoinPlan,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
validate_plan(plan.tables.len(), &plan.joins, plan.projection.as_deref())?;
let tables: Vec<_> = plan
.tables
.into_iter()
.map(|table| WorkspaceInputRequest {
source_id: table.source_id,
database: table.database,
schema: table.schema,
table: table.table,
limits: WORKSPACE_INPUT_LIMITS,
})
.collect();
let tables: Vec<_> = tables.iter().collect();
self.execute_workspace_join(driver, &tables, &plan.joins, plan.projection.as_deref(), cancel).await
}
async fn execute_workspace_join(
&self,
driver: &str,
tables: &[&WorkspaceInputRequest],
joins: &[WorkspaceJoinCondition],
projection: Option<&[WorkspaceJoinProjection]>,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let _run =
self.workspace_run.try_lock().map_err(|_| IdeError::invalid("A workspace query is already running"))?;
let start = Instant::now();
let child = cancel.child_token();
let run = async {
let cancel = &child;
let mut prepared = Vec::with_capacity(tables.len());
for table in tables {
let input = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
input = workspace_input::prepare_table(self, table) => input?,
};
prepared.push(input);
}
let selection = staging_columns(tables.len(), joins, projection);
let mut staged = Vec::with_capacity(tables.len());
let engine = tokio::select! {
biased;
() = cancel.cancelled() => return Err(IdeError::cancelled()),
engine = self.workspace_engine(driver) => engine?,
};
let result = async {
let mut remaining_rows = 200_000;
let mut remaining_bytes = 32 * 1024 * 1024;
for (mut table, columns) in prepared.into_iter().zip(&selection) {
let limits = &mut table.request.limits;
limits.max_rows = limits.max_rows.min(remaining_rows);
limits.max_bytes = limits.max_bytes.min(remaining_bytes);
let input = workspace_input::read_prepared_table(self, table, columns.as_deref(), cancel).await?;
remaining_rows -= input.rows.len();
remaining_bytes -= input.bytes;
let cancellation = cancel.clone();
let table = tokio::task::spawn_blocking(move || stage(input, &cancellation))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
staged.push(table);
}
join(&engine, &staged, joins, projection, cancel).await
}
.await;
// Windows cannot remove a staged file while the JDBC process still has it open.
engine.close().await;
drop(staged);
let mut result = result?;
result.elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
Ok(result)
};
tokio::pin!(run);
let stopped = tokio::select! {
biased;
() = cancel.cancelled() => IdeError::cancelled(),
result = &mut run => return result,
() = tokio::time::sleep(Duration::from_secs(90)) => IdeError::new(ide_core::error::ErrorKind::TimedOut, "Workspace query timed out"),
};
child.cancel();
// Let the source or JDBC bridge deliver cancellation before dropping its connection.
let _ = tokio::time::timeout(Duration::from_secs(15), run).await;
Err(stopped)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DbJdbcDriver;
fn input(values: &[(&str, Option<&str>)]) -> WorkspaceInput {
WorkspaceInput {
columns: vec![
WorkspaceInputColumn {
name: "key".into(),
data_type: WorkspaceInputType::Decimal { precision: 32, scale: 6 },
},
WorkspaceInputColumn { name: "text".into(), data_type: WorkspaceInputType::Text },
],
rows: values.iter().map(|(k, v)| vec![Some(k.to_string()), v.map(str::to_owned)]).collect(),
bytes: 0,
}
}
#[test]
fn workspace_join_chain_links_must_target_an_earlier_table() -> IdeResult<()> {
let first = two_table_join(["key", "key"]);
let second = two_table_join(["key", "id"]);
let links = [first, second];
validate_plan(3, &links, None)?;
let over_limit: Vec<_> = (0..8).map(|_| two_table_join(["key", "key"])).collect();
assert!(validate_plan(9, &over_limit, None).is_err());
validate_plan(8, &over_limit[..7], None)?;
assert!(validate_plan(4, &links, None).is_err());
assert!(validate_plan(3, &links, Some(&[])).is_err());
let invalid = WorkspaceJoinProjection { relation: 3, column: None };
assert!(validate_plan(3, &links, Some(&[invalid])).is_err());
let mut links = links;
links[0].left.relation = 1;
assert!(validate_plan(3, &links, None).is_err());
Ok(())
}
#[test]
fn staging_preserves_null_and_csv_text_and_removes_the_file_on_drop() -> IdeResult<()> {
let cancel = CancellationToken::new();
let table = stage(input(&[("1", None), ("2", Some("")), ("3", Some("a,\"b\"\nc"))]), &cancel)?;
let path = table.path.to_path_buf();
assert_eq!(std::fs::read_to_string(&path)?, "\"1\",\\N\n\"2\",\"\"\n\"3\",\"a,\"\"b\"\"\nc\"\n");
drop(table);
assert!(!path.exists());
cancel.cancel();
assert!(stage(input(&[("1", None)]), &cancel).is_err());
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
async fn workspace_engine_joins_exact_keys_nulls_and_empty_inputs() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let root = tmp.path();
let db = DbManager::new(
root.join("project"),
root.join("passwords"),
root.join("history"),
std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh"))),
)
.with_global_sources(root.join("global"));
db.save_jdbc_driver(DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("driver fixture")],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
})?;
let cancel = CancellationToken::new();
let mut signed = input(&[("-1", None), ("9007199254740993", None), ("9223372036854775807", None)]);
signed.columns[0].data_type = WorkspaceInputType::Int64;
let mut unsigned = input(&[
("18446744073709551615", None),
("9007199254740992", None),
("9007199254740993", None),
("9223372036854775807", None),
]);
unsigned.columns[0].data_type = WorkspaceInputType::UInt64;
let tables = [stage(signed, &cancel)?, stage(unsigned, &cancel)?];
let engine = db.workspace_engine("duck").await?;
let output = join(&engine, &tables, &[two_table_join(["key", "key"])], None, &cancel).await?;
let mut matches: Vec<_> = output.rows.iter().map(|row| (row[0].as_deref(), row[2].as_deref())).collect();
matches.sort_unstable();
assert_eq!(
matches,
[
(Some("9007199254740993"), Some("9007199254740993")),
(Some("9223372036854775807"), Some("9223372036854775807")),
]
);
engine.close().await;
let wide = "a,\n\"b\"".repeat(32 * 1024);
let left = stage(input(&[("0", None), ("1", Some(&wide)), ("2", Some("short"))]), &cancel)?;
let right = stage(input(&[("1", Some(&wide))]), &cancel)?;
let engine = db.workspace_engine("duck").await?;
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
assert_eq!(output.rows.len(), 1);
assert_eq!(output.rows[0][1].as_deref(), Some(wide.as_str()));
assert_eq!(output.rows[0][3].as_deref(), Some(wide.as_str()));
engine.close().await;
for empty in [false, true] {
let left =
stage(input(&[("9007199254740993.000001", None), ("9007199254740993.000002", Some(""))]), &cancel)?;
let mut right =
input(&[("9007199254740993.000001", Some("a,\"b\"\nc")), ("9007199254740993.000002", Some(r"\N"))]);
if empty {
right.rows.clear();
}
let engine = db.workspace_engine("duck").await?;
let right = stage(right, &cancel)?;
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
assert_eq!(
output.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
["key", "text", "key", "text"]
);
let mut rows = output.rows;
rows.sort();
if empty {
assert!(rows.is_empty());
} else {
assert_eq!(rows.len(), 2);
assert_eq!(
rows[0],
[
Some("9007199254740993.000001".into()),
None,
Some("9007199254740993.000001".into()),
Some("a,\"b\"\nc".into())
]
);
assert_eq!(
rows[1],
[
Some("9007199254740993.000002".into()),
Some("".into()),
Some("9007199254740993.000002".into()),
Some(r"\N".into())
]
);
}
engine.close().await;
}
Ok(())
}
}
File diff suppressed because it is too large. Load diff
+134
Переглянути файл
@@ -0,0 +1,134 @@
#!/usr/bin/env bash
# Requires Docker, curl and Cargo. To exercise the JOIN and its cancellation as well
# as source reads, install Java 17+ and set DUCKDB_JDBC_JAR to an absolute JAR path.
# Usage: bash crates/ide-db/tests/fixtures/workspace.sh [command args...]
set -euo pipefail
cd "$(dirname "$0")/../../../.."
fixtures=$(mktemp -d "${TMPDIR:-/tmp}/openidea-workspace.XXXXXXXX")
pg=
ch=
cleanup() {
if [[ -n "$ch" ]]; then docker stop -t 2 "$ch" >/dev/null || true; fi
if [[ -n "$pg" ]]; then docker stop -t 2 "$pg" >/dev/null || true; fi
rm -f "$fixtures/users.xml"
rmdir "$fixtures"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
cat > "$fixtures/users.xml" <<'XML'
<clickhouse>
<profiles>
<workspace_strict>
<readonly>1</readonly>
<max_threads>1</max_threads>
<max_memory_usage>134217728</max_memory_usage>
<max_rows_to_read>100000</max_rows_to_read>
<max_execution_time>20</max_execution_time>
</workspace_strict>
<workspace_break>
<readonly>1</readonly>
<result_overflow_mode>break</result_overflow_mode>
</workspace_break>
<workspace_cap>
<readonly>1</readonly>
<max_result_rows>2</max_result_rows>
</workspace_cap>
</profiles>
<users>
<fixture_writer>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>default</profile>
<quota>default</quota>
</fixture_writer>
<fixture_strict>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>workspace_strict</profile>
<quota>default</quota>
</fixture_strict>
<fixture_break>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>workspace_break</profile>
<quota>default</quota>
</fixture_break>
<fixture_cap>
<no_password/>
<networks><ip>::/0</ip></networks>
<profile>workspace_cap</profile>
<quota>default</quota>
</fixture_cap>
</users>
</clickhouse>
XML
chmod 644 "$fixtures/users.xml"
pg=$(docker run --rm -d -p 127.0.0.1::5432 --cpus 1 --memory 320m \
--tmpfs /var/lib/postgresql/data:rw,size=128m \
-e POSTGRES_HOST_AUTH_METHOD=trust postgres:17-alpine)
ch=$(docker run --rm -d -p 127.0.0.1::8123 --cpus 1 --memory 1536m \
--tmpfs /var/lib/clickhouse --tmpfs /var/log/clickhouse-server \
--mount "type=bind,source=$fixtures/users.xml,target=/etc/clickhouse-server/users.d/workspace-fixture.xml,readonly" \
clickhouse/clickhouse-server:25.8.12.129)
WORKSPACE_PG_PORT=$(docker port "$pg" 5432/tcp | sed 's/^127\.0\.0\.1://')
WORKSPACE_CH_PORT=$(docker port "$ch" 8123/tcp | sed 's/^127\.0\.0\.1://')
export WORKSPACE_PG_PORT WORKSPACE_CH_PORT
ch_http="http://127.0.0.1:$WORKSPACE_CH_PORT"
ready() {
for ((attempt = 0; attempt < 45; ++attempt)); do
if "$@" >/dev/null 2>&1; then return 0; fi
sleep 1
done
printf 'Workspace fixture did not become ready: %s\n' "$1" >&2
return 1
}
ready docker exec "$pg" pg_isready -h 127.0.0.1 -U postgres
ready curl -fsS --max-time 1 "$ch_http/ping"
docker exec -i "$pg" psql -h 127.0.0.1 -U postgres -Xq -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE "exact data" ("exact key" numeric(32,6), id bigint, ts timestamp(6) with time zone, label text);
INSERT INTO "exact data" VALUES
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456+03', E'a,b"c\nd'),
(100000000000000000002.000001, 9007199254740994, NULL, ''),
(NULL, 9007199254740995, NULL, NULL);
CREATE TABLE "empty data" (LIKE "exact data");
CREATE TABLE "unsupported data" (payload jsonb);
CREATE VIEW "fixture view" AS SELECT * FROM "exact data";
SQL
ch_sql() {
curl -fsS --max-time 5 --user fixture_writer: --data-binary "$1" "$ch_http/"
}
ch_sql "CREATE TABLE default.\"exact data\" (
\"exact key\" Nullable(Decimal(32,6)), id Int64, ts Nullable(DateTime64(6, 'Europe/Moscow')), label Nullable(String)
) ENGINE=Memory"
ch_sql "INSERT INTO default.\"exact data\" VALUES
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456', 'a,b\"c\\nd'),
(100000000000000000002.000001, 9007199254740994, NULL, ''),
(NULL, 9007199254740995, NULL, NULL)"
ch_sql 'CREATE TABLE default."empty data" AS default."exact data" ENGINE=Memory'
ch_sql 'CREATE TABLE default."unsupported data" (payload Array(String)) ENGINE=Memory'
ch_sql 'CREATE VIEW default."fixture view" AS SELECT * FROM default."exact data"'
ch_sql 'CREATE TABLE default."unsigned data" (id UInt64) ENGINE=Memory'
ch_sql 'INSERT INTO default."unsigned data" VALUES (9007199254740992), (9007199254740993), (18446744073709551615)'
ch_sql 'CREATE TABLE default."overflow data" (id Int64) ENGINE=Memory'
ch_sql 'INSERT INTO default."overflow data" VALUES (1), (2), (3), (4), (5)'
export WORKSPACE_CH_USER=fixture_writer
if (( $# > 0 )); then
"$@"
else
test_name=workspace_input::tests::native_workspace_sources_are_exact_and_fail_on_limits
cargo test --locked -p ide-db --lib "$test_name" -- --ignored
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib "$test_name" -- --ignored
cargo test --locked -p ide-db --lib clickhouse_workspace_refuses_truncated_reads -- --ignored
if [[ -n "${DUCKDB_JDBC_JAR:-}" ]]; then
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib workspace_join_chains_four_live_engines -- --ignored
fi
fi
+183 -24
Переглянути файл
@@ -1,5 +1,7 @@
use ide_core::{CancellationToken, IdeResult};
use ide_db::{ConsoleId, DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
use ide_db::{
ConsoleId, DataSource, DbDriver, DbDuckLake, DbDuckLakeKind, DbJdbcDriver, DbManager, DbProperty, SortKey,
};
use std::{path::Path, sync::Arc};
fn manager(dir: &Path) -> DbManager {
@@ -8,6 +10,158 @@ fn manager(dir: &Path) -> DbManager {
.with_global_sources(dir.join("global"))
}
fn duck_lake_source(catalog: &str) -> DataSource {
DataSource {
id: "lake".into(),
name: "DuckLake".into(),
driver: DbDriver::Jdbc,
vendor: "duckdb".into(),
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
read_only: true,
duck_lake: Some(DbDuckLake { kind: DbDuckLakeKind::File, value: catalog.into(), data_path: None }),
..Default::default()
}
}
fn duck_lake_driver(jar: String) -> DbJdbcDriver {
DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![jar],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
}
}
#[tokio::test]
async fn duck_lake_settings_are_validated_and_covered_by_project_approval() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let jar = tmp.path().join("fixture.jar");
std::fs::write(&jar, [])?;
let db = manager(tmp.path());
let profile = duck_lake_driver(jar.display().to_string());
let source = duck_lake_source("lake/catalog.ducklake");
let mut other_profile = profile.clone();
other_profile.class_name = "test.NotDuckDB".into();
db.save_jdbc_driver(other_profile)?;
assert!(db.approve_ducklake_source(&source).is_err());
let directory = tmp.path().join("create");
assert!(db.create_ducklake("duck", directory.to_str().unwrap()).await.is_err());
assert!(!directory.exists());
db.save_jdbc_driver(profile)?;
assert!(db.approve_ducklake_source(&DataSource { duck_lake: None, ..source.clone() }).is_err());
let mut invalid_secret = source.clone();
invalid_secret.duck_lake =
Some(DbDuckLake { kind: DbDuckLakeKind::Secret, value: "key=value".into(), data_path: None });
let mut data_path = source.clone();
data_path.duck_lake.as_mut().unwrap().data_path = Some("s3://example/ducklake".into());
let mut scripted = source.clone();
scripted.options.startup_script = "CREATE TABLE t (n int)".into();
for invalid in [
invalid_secret,
data_path,
scripted,
DataSource { driver: DbDriver::Sqlite, ..source.clone() },
DataSource { url: "jdbc:duckdb:unrelated.duckdb".into(), ..source.clone() },
DataSource { read_only: false, ..source.clone() },
DataSource { save_password: true, ..source.clone() },
DataSource {
properties: vec![DbProperty { name: "access_mode".into(), value: "READ_WRITE".into() }],
..source.clone()
},
] {
assert!(invalid.resolved().is_err());
assert!(db.save_sources(vec![invalid.clone()]).await.is_err());
assert!(db.approve_ducklake_source(&invalid).is_err());
}
assert!(db.sources()?.is_empty());
db.approve_ducklake_source(&DataSource { global: true, ..source.clone() })?;
db.save_sources(vec![source.clone()]).await?;
assert_eq!(db.source("lake")?, source);
let err = db.pool("lake").await.err().expect("global validation must not approve a project connection");
assert!(err.message.contains("Review this project"));
assert!(db.set_password("lake", Some("unused".into()), true).await.is_err());
assert!(db.test(&source, Some("unused".into()), None).await.is_err());
db.approve_ducklake_source(&source)?;
let mut changed = source;
changed.duck_lake.as_mut().unwrap().value = "another/catalog.ducklake".into();
db.save_sources(vec![changed]).await?;
let err = db.pool("lake").await.err().expect("new catalog path must be approved");
assert!(err.message.contains("Review this project"));
assert!(serde_json::from_value::<DbDuckLake>(serde_json::json!({"kind":"create", "value":"lake"})).is_err());
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR, DuckLake extension access, and Java 17+"]
async fn duck_lake_creates_only_explicitly_and_reopens_read_only() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR");
db.save_jdbc_driver(duck_lake_driver(jar))?;
let source = duck_lake_source("lake's files/catalog.ducklake");
let directory = tmp.path().join("project").join("lake's files");
let path = directory.to_str().unwrap();
db.save_sources(vec![source.clone()]).await?;
let err = db.test(&source, None, None).await.expect_err("Test must not create a missing catalog");
assert!(err.message.contains("does not exist"), "{}", err.message);
assert!(!directory.exists());
db.approve_ducklake_source(&source)?;
assert!(db.pool("lake").await.is_err());
assert!(!directory.exists());
db.create_ducklake("duck", path).await?;
assert!(directory.join("catalog.ducklake").is_file());
let err = db.create_ducklake("duck", path).await.expect_err("Create must reject an existing directory");
assert!(err.message.contains("already exists"), "{}", err.message);
assert!(db.test(&source, None, None).await?.contains("DuckDB"));
let db = manager(tmp.path());
assert_eq!(db.source("lake")?, source);
let cancel = CancellationToken::new();
let console = ConsoleId::new("window", "/lake.sql");
for scope in [None, Some(console)] {
let result = db
.execute_in_console(
"lake",
"SELECT readonly FROM duckdb_databases() WHERE database_name = current_database() AND type = 'ducklake'",
0,
1,
&cancel,
None,
scope,
)
.await?;
assert_eq!(result.rows, [vec![Some("true".into())]]);
assert!(
db.execute_in_console("lake", "CREATE TABLE main.rejected(id INTEGER)", 0, 1, &cancel, None, scope)
.await
.is_err(),
"the attached catalog must be read-only"
);
}
assert!(db.schemas("lake").await?.contains(&"main".into()));
assert!(db.tables("lake", "main").await?.is_empty());
let databases = db.databases("lake").await?;
assert_eq!(databases.current, "openidea_lake");
assert!(databases.names.contains(&databases.current));
let catalog = db.database_catalog("lake", &databases.current).await?;
assert!(catalog.iter().any(|schema| schema.name == "main" && schema.tables.is_empty()));
db.release_target_console(console, Some("lake")).await?;
db.disconnect("lake").await;
let global = DataSource { id: "global-lake".into(), global: true, ..source };
db.approve_ducklake_source(&global)?;
db.save_sources(vec![global]).await?;
assert!(db.schemas("global-lake").await?.contains(&"main".into()));
db.disconnect("global-lake").await;
Ok(())
}
#[tokio::test]
async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
@@ -278,34 +432,39 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
..Default::default()
};
let cancel = CancellationToken::new();
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
let nodes = db.explain("test", join, &cancel, None).await?;
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
assert!(batch.message.contains("one statement"));
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
assert_eq!(
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
[vec![Some("1".into())]]
);
db.disconnect("test").await;
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
db.disconnect("test").await;
for url in ["jdbc:duckdb:", "jdbc:duckdb:memory:default"] {
source.url = url.into();
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
assert_eq!(
db.execute("test", "select id from session_items", 1, &cancel).await?.rows,
[vec![Some("42".into())]]
);
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
let nodes = db.explain("test", join, &cancel, None).await?;
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
assert!(batch.message.contains("one statement"));
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
assert_eq!(
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
[vec![Some("1".into())]]
);
db.disconnect("test").await;
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
db.disconnect("test").await;
}
source.read_only = true;
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:", "jdbc:duckdb:memory:default"] {
source.url = url.into();
let err = db.test(&source, None, None).await.unwrap_err();
assert!(err.message.contains("existing database file"), "{}", err.message);
+70 -1
Переглянути файл
@@ -2,7 +2,7 @@
//! `OPENIDEA_TEST_POSTGRES=host:port:user:password` names a throwaway server.
use ide_core::{CancellationToken, IdeResult};
use ide_db::{DataSource, DbDriver, DbManager};
use ide_db::{DataSource, DbDriver, DbManager, DbPersistence};
fn server() -> Option<(String, u16, String, String)> {
endpoint("OPENIDEA_TEST_POSTGRES")
@@ -813,6 +813,75 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
Ok(())
}
/// Modify Table's properties: owner, tablespace, access method, storage options (the TOAST
/// table's too), partition key and persistence, read again after the statements it runs.
#[tokio::test]
async fn table_details_read_the_storage_properties() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
for stmt in [
"DROP SCHEMA IF EXISTS oi_props CASCADE",
"DROP ROLE IF EXISTS oi_props_owner",
"CREATE ROLE oi_props_owner",
"CREATE SCHEMA oi_props",
"CREATE UNLOGGED TABLE oi_props.bulk (id INT, v TEXT) WITH (fillfactor = 70, toast.autovacuum_enabled = false)",
"CREATE TABLE oi_props.events (id INT, at DATE) PARTITION BY RANGE (at)",
"CREATE VIEW oi_props.recent AS SELECT 1 AS n",
] {
db.execute("p", stmt, 10, &c).await?;
}
let owner = db.execute("p", "SELECT current_user", 1, &c).await?.rows[0][0].clone().unwrap();
let default_tablespace = db
.execute(
"p",
"SELECT t.spcname FROM pg_database d JOIN pg_tablespace t ON t.oid = d.dattablespace \
WHERE d.datname = current_database()",
1,
&c,
)
.await?
.rows[0][0]
.clone();
let options = |pairs: &[(&str, &str)]| Some(pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect());
let bulk = db.table_details("p", "oi_props", "bulk").await?;
assert_eq!(bulk.owner.as_deref(), Some(owner.as_str()));
assert_eq!(bulk.tablespace, default_tablespace);
assert_eq!(bulk.access_method.as_deref(), Some("heap"));
assert_eq!(bulk.storage_options, options(&[("fillfactor", "70"), ("toast.autovacuum_enabled", "false")]));
assert_eq!(bulk.partitioning, None);
assert_eq!(bulk.persistence, Some(DbPersistence::Unlogged));
let events = db.table_details("p", "oi_props", "events").await?;
assert_eq!(events.partitioning.as_deref(), Some("RANGE (at)"));
assert_eq!(events.storage_options, options(&[]));
assert_eq!(events.persistence, Some(DbPersistence::Permanent));
// A view has none of a table's storage.
let recent = db.table_details("p", "oi_props", "recent").await?;
assert_eq!((recent.owner, recent.storage_options, recent.persistence), (None, None, None));
// The statements Modify Table generates (objects.ts `tablePropertiesSql`).
for stmt in [
"alter table oi_props.bulk set logged;",
"alter table oi_props.bulk reset (toast.autovacuum_enabled);",
"alter table oi_props.bulk set (fillfactor = 50, autovacuum_enabled = false);",
"alter table oi_props.bulk set tablespace pg_default;",
"alter table oi_props.bulk owner to oi_props_owner;",
] {
db.execute("p", stmt, 10, &c).await?;
}
let bulk = db.table_details("p", "oi_props", "bulk").await?;
assert_eq!(bulk.owner.as_deref(), Some("oi_props_owner"));
assert_eq!(bulk.tablespace.as_deref(), Some("pg_default"));
assert_eq!(bulk.storage_options, options(&[("fillfactor", "50"), ("autovacuum_enabled", "false")]));
assert_eq!(bulk.persistence, Some(DbPersistence::Permanent));
for stmt in ["DROP SCHEMA oi_props CASCADE", "DROP ROLE oi_props_owner"] {
db.execute("p", stmt, 10, &c).await?;
}
Ok(())
}
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
/// the other schemas, and the tables sorting last lost theirs (#6118).
#[tokio::test]
+28 -2
Переглянути файл
@@ -404,12 +404,19 @@ impl Host {
self.mcp_agent_runs.forget_window(window);
self.debugger.forget_breakpoints(self.owner_window(window));
self.external_logs.write().remove(self.owner_window(window));
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
let owner = self.owner_window(window);
let (project, requests) = {
// A request registering after the drain must not resolve the old project.
let mut project_requests = self.project_requests.write();
let mut projects = self.projects.write();
(projects.remove(window), project_requests.remove(owner).unwrap_or_default())
};
for request in requests {
self.cancel_request(request);
}
// After the cancels: a capture or open still running then discards what it registers.
ops::heap::close_window_snapshots(self, window);
let project = self.projects.write().remove(window)?;
let project = project?;
project.closed.cancel();
if let Some(plugins) = self.plugin_host() {
if self.windows_for_root(&project.root).is_empty() {
@@ -791,6 +798,25 @@ impl Host {
let exe = self.global_settings.read_effective(|s| s.vcs.git.executable.trim().to_owned());
ide_vcs::set_default_git_executable((!exe.is_empty()).then(|| Path::new(&exe)));
}
/// Settings › Version Control › Git › Enable Git integration, as it applies to `window`
/// (its project's effective value, the global one without a project).
pub fn git_enabled(&self, window: &str) -> bool {
match self.project(window) {
Ok(project) => project.git_enabled(),
Err(_) => self.global_settings.read_effective(|s| s.vcs.git.enabled),
}
}
/// Fails while Git integration is switched off for `window`: commands that start git
/// outside the project's repositories (clone, init, an external log) check it first.
pub fn ensure_git_enabled(&self, window: &str) -> IdeResult<()> {
if self.git_enabled(window) {
Ok(())
} else {
Err(ide_core::IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"))
}
}
}
#[cfg(test)]
+2
Переглянути файл
@@ -251,6 +251,7 @@ fn git_status() -> Tool {
Returns porcelain-style index/worktree status codes and summary counters.
By default all Git repositories are returned.",
|call| async move {
call.host.ensure_git_enabled(&call.window)?;
let include_untracked = call.flag("includeUntracked", true)?;
let include_ignored = call.flag("includeIgnored", false)?;
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
@@ -360,6 +361,7 @@ By default all Git repositories are returned.",
fn git_diff() -> Tool {
Tool::new("git_diff", "Read a Git diff for a file or the working tree. staged=true compares the index with HEAD; otherwise compares disk with the index. Unsaved editor text is not part of this diff.", |call| async move {
call.host.ensure_git_enabled(&call.window)?;
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
let path = wanted.as_deref().map(|p| call.resolve_inside(p)).transpose()?.unwrap_or_else(|| call.root().to_path_buf());
let root = find_git_root(call.root(), &path).ok_or_else(|| IdeError::not_found("No git repository found"))?;
+20 -2
Переглянути файл
@@ -947,12 +947,27 @@ pub fn route(spec: &[Entry], id: &str) -> Option<MenuRoute> {
/// `entries` without the action `id` (and a separator it leaves doubled or trailing).
pub fn without_action(entries: Vec<Entry>, id: &str) -> Vec<Entry> {
without(entries, &|e| e == id)
}
/// `entries` without the submenus and actions [`MenuConfig::hidden`] lists.
pub fn without_hidden(entries: Vec<Entry>, config: &MenuConfig) -> Vec<Entry> {
if config.hidden.is_empty() {
return entries;
}
without(entries, &|id| config.hidden.iter().any(|h| h == id))
}
/// `entries` without the actions and submenus whose id `drop` matches, and the separators
/// left dangling.
fn without(entries: Vec<Entry>, drop: &dyn Fn(&str) -> bool) -> Vec<Entry> {
let mut out: Vec<Entry> = Vec::with_capacity(entries.len());
for e in entries {
match e {
Entry::Action { id: a, .. } if a == id => {}
Entry::Action { id: a, .. } if drop(a) => {}
Entry::Submenu { id: sid, .. } if drop(sid) => {}
Entry::Submenu { id: sid, label, children } => {
out.push(Entry::Submenu { id: sid, label, children: without_action(children, id) })
out.push(Entry::Submenu { id: sid, label, children: without(children, drop) })
}
Entry::Separator if matches!(out.last(), None | Some(Entry::Separator)) => {}
e => out.push(e),
@@ -996,6 +1011,9 @@ pub struct MenuConfig {
/// Ids of the toggle actions currently on.
#[serde(default)]
pub checked: Vec<String>,
/// Ids of submenus and actions left out of the menu (the Git menu while Git integration is off).
#[serde(default)]
pub hidden: Vec<String>,
}
/// An item of a frontend-listed menu slot.
+148
Переглянути файл
@@ -7,6 +7,7 @@ use crate::Host;
use ide_command::command;
use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath, RequestId};
use ide_db::split::SqlStatement;
use ide_db::workspace::WorkspaceJoinPlan;
use ide_db::{
CompletionModel, ConsoleId, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange,
HistoryEntry, PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
@@ -15,6 +16,27 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
#[command(trust = trusted)]
pub async fn db_workspace_join(
host: &Host,
window: &str,
request: RequestId,
driver: String,
plan: WorkspaceJoinPlan,
) -> IdeResult<QueryResult> {
let cancel = host.begin_project_request(window, request);
let result = async {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let db = host.project(window)?.db.clone();
db.workspace_join(&driver, plan, &cancel).await
}
.await;
host.end_request(request);
result
}
/// One statement of a console run.
#[derive(Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -33,6 +55,11 @@ pub enum ExecutionEvent {
Done { error: Option<IdeError> },
}
#[command(trust = trusted)]
pub fn db_approve_ducklake_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
host.project(window)?.db.approve_ducklake_source(&source)
}
#[command(trust = trusted)]
pub fn db_approve_jdbc_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
host.project(window)?.db.approve_jdbc_source(&source)
@@ -75,6 +102,12 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
sources_changed(host, window)
}
#[command(trust = trusted)]
pub async fn db_create_ducklake(host: &Host, window: &str, jdbc_driver: String, directory: String) -> IdeResult<()> {
let db = host.project(window)?.db.clone();
db.create_ducklake(&jdbc_driver, &directory).await
}
#[command(trust = trusted)]
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
// The project's user-created folders and their data source members.
@@ -829,6 +862,7 @@ pub async fn server_version(host: &Host, window: &str, id: &str) -> IdeResult<u3
ide_command::domain!(
db:
db_apply_edits,
db_workspace_join,
db_completion,
db_connect,
db_connected,
@@ -836,6 +870,7 @@ ide_command::domain!(
db_consoles_dir,
db_consoles,
db_create_database,
db_create_ducklake,
db_database_catalog,
db_catalog_table_details,
db_catalog_table_page,
@@ -851,6 +886,7 @@ ide_command::domain!(
db_history,
db_jdbc_driver_classes,
db_jdbc_drivers,
db_approve_ducklake_source,
db_approve_jdbc_source,
db_save_jdbc_driver,
db_remove_jdbc_driver,
@@ -911,6 +947,118 @@ mod tests {
host
}
fn workspace_test_plan() -> WorkspaceJoinPlan {
use ide_db::workspace::{WorkspaceJoinColumn, WorkspaceJoinCondition, WorkspaceJoinRelation};
let relation = |id: &str| WorkspaceJoinRelation {
source_id: id.into(),
database: "default".into(),
schema: "default".into(),
table: "items".into(),
};
WorkspaceJoinPlan {
tables: vec![relation("left"), relation("right")],
joins: vec![WorkspaceJoinCondition {
left: WorkspaceJoinColumn { relation: 0, column: "id".into() },
right_column: "id".into(),
}],
projection: None,
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn workspace_join_respects_an_early_cancel() {
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let request = RequestId(1);
host.cancel_request(request);
let error = db_workspace_join(&host, "main", request, "no driver installed".into(), workspace_test_plan())
.await
.unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn workspace_join_cannot_resolve_a_project_after_its_requests_are_drained() {
use std::time::{Duration, Instant};
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let window = "main";
let active = host.begin_project_request(window, RequestId(1));
std::thread::scope(|threads| {
// Hold close at heap cleanup, which follows cancellation of registered requests.
let heap = host.heap_windows.lock();
let close = threads.spawn(|| host.close_project_detached(window));
let deadline = Instant::now() + Duration::from_secs(3);
while !active.is_cancelled() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
let drained = active.is_cancelled();
let detached = host.project(window).is_err();
drop(heap);
close.join().unwrap();
assert!(drained, "close did not reach the cancellation step");
assert!(detached, "close drained its requests while the old project was still available");
});
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
async fn workspace_join_stops_when_its_project_closes() {
use std::time::Duration;
let temp = tempfile::tempdir().unwrap();
let host = host_with_sqlite(&temp).await;
let window = "main";
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let sources = ["left", "right"].map(|id| DataSource {
id: id.into(),
name: format!("ClickHouse fixture {id}"),
driver: DbDriver::Clickhouse,
host: "127.0.0.1".into(),
port: Some(listener.local_addr().unwrap().port()),
..Default::default()
});
db_save_sources(&host, window, sources.into()).await.unwrap();
host.project(window)
.unwrap()
.db
.save_jdbc_driver(ide_db::DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: Some("duckdb".into()),
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("official JDBC fixture")],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
})
.unwrap();
for (request, close_project) in [(RequestId(2), false), (RequestId(3), true)] {
let join = db_workspace_join(&host, window, request, "duck".into(), workspace_test_plan());
tokio::pin!(join);
// Accept the source connection and leave it open without replying.
let (socket, _) = tokio::select! {
result = &mut join => panic!("workspace ended before reaching the source: {result:?}"),
peer = tokio::time::timeout(Duration::from_secs(15), listener.accept()) => peer.unwrap().unwrap(),
};
if close_project {
host.close_project_detached(window);
} else {
host.cancel_request(request);
}
let stopped = tokio::time::timeout(Duration::from_secs(3), &mut join).await;
if stopped.is_err() {
host.cancel_request(request);
let _ = tokio::time::timeout(Duration::from_secs(5), &mut join).await;
}
let error = stopped.expect("workspace JOIN did not stop after cancellation").unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
assert!(!host.project_requests.read().values().flatten().any(|entry| *entry == request));
drop(socket);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "requires a disposable loopback PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT"]
async fn postgres_console_commands_keep_commit_result_reads_and_release_scoped() {
+40
Переглянути файл
@@ -515,6 +515,17 @@ pub async fn debug_step(host: &Host, session: DebugSessionId, thread_id: i64, ki
host.debugger.step(session, thread_id, kind).await
}
/// Step Over / Into Instruction: a step by one machine instruction.
#[command(trust = trusted)]
pub async fn debug_step_instruction(
host: &Host,
session: DebugSessionId,
thread_id: i64,
kind: StepKind,
) -> IdeResult<()> {
host.debugger.step_instruction(session, thread_id, kind).await
}
#[command(trust = trusted)]
pub async fn debug_run_to(
host: &Host,
@@ -557,6 +568,32 @@ pub async fn debug_evaluate_in(
host.debugger.evaluate_in(session, frame_id, expression, context).await
}
/// Memory View: `count` bytes from `offset` bytes after `memory_reference` (a variable's,
/// an evaluation result's or an earlier read's address).
#[command(trust = trusted)]
pub async fn debug_read_memory(
host: &Host,
session: DebugSessionId,
memory_reference: String,
offset: i64,
count: u32,
) -> IdeResult<ide_dap::MemoryBlock> {
host.debugger.read_memory(session, memory_reference, offset, count).await
}
/// Disassembly view: `count` instructions from `before` instructions ahead of `memory_reference`
/// (a frame's instruction pointer or an instruction's address).
#[command(trust = trusted)]
pub async fn debug_disassemble(
host: &Host,
session: DebugSessionId,
memory_reference: String,
before: u32,
count: u32,
) -> IdeResult<Vec<ide_dap::Instruction>> {
host.debugger.disassemble(session, memory_reference, before, count).await
}
/// Last known verification states of a file's breakpoints (refetch on `breakpointsChanged`).
#[command(trust = trusted)]
pub fn debug_breakpoint_states(host: &Host, path: PathBuf) -> IdeResult<Vec<BreakpointState>> {
@@ -1066,6 +1103,7 @@ ide_command::domain!(
debug_capabilities,
debug_completions,
debug_data_breakpoint_info,
debug_disassemble,
debug_evaluate,
debug_evaluate_in,
debug_exception_filters,
@@ -1083,6 +1121,7 @@ ide_command::domain!(
debug_jvm_thread_dump,
debug_listen_for_jvm,
debug_pause,
debug_read_memory,
debug_redefine_classes,
debug_replace_breakpoints,
debug_resolve_variable,
@@ -1103,6 +1142,7 @@ ide_command::domain!(
debug_step,
debug_step_in_target,
debug_step_in_targets,
debug_step_instruction,
debug_stop,
debug_threads,
debug_unity_processes,
+21 -17
Переглянути файл
@@ -158,24 +158,28 @@ pub async fn fs_read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult<
// Runs on the blocking pool: on a network share (`\\wsl.localhost`) every stat is slow.
let project = host.project(window);
host.blocking(move || {
let excludes = project
.map(|p| {
// An attached project's folders follow its own exclusions.
let root = p.root_of(&path);
let globs = p.exclude_globs_in(&root);
// `read_dir` matches relative to the enclosing repository: re-anchor
// root patterns (`/build`) when the project is a repo subfolder.
let repo = root.ancestors().find(|d| d.join(".git").exists());
match repo.and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
Some(rel) => {
let rel = rel.to_string_lossy().replace('\\', "/");
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
}
None => globs,
let Ok(p) = project else { return ide_vfs::read_dir(&path, &[]) };
// An attached project's folders follow its own exclusions.
let root = p.root_of(&path);
let globs = p.exclude_globs_in(&root);
// `read_dir` matches relative to the enclosing repository: re-anchor
// root patterns (`/build`) when the project is a repo subfolder. The
// watcher already found the project folder's repository; on a network
// share each `.git` probe up the tree is a round trip.
let repo = if root == p.root && p.watcher.root() == p.root {
p.watcher.repo_root().map(Path::to_path_buf)
} else {
root.ancestors().find(|d| d.join(".git").exists()).map(Path::to_path_buf)
};
let excludes =
match repo.as_deref().and_then(|r| root.strip_prefix(r).ok()).filter(|rel| !rel.as_os_str().is_empty()) {
Some(rel) => {
let rel = rel.to_string_lossy().replace('\\', "/");
globs.into_iter().map(|g| if g.starts_with('/') { format!("/{rel}{g}") } else { g }).collect()
}
})
.unwrap_or_default();
ide_vfs::read_dir(&path, &excludes)
None => globs,
};
p.watcher.read_dir(&path, &excludes)
})
.await
}
+17
Переглянути файл
@@ -18,6 +18,9 @@ use std::path::{Path, PathBuf};
/// primary repository (a folder holding several repositories is not one itself).
fn root(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<PathBuf> {
let project = host.project(window)?;
if !project.git_enabled() {
return Err(IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"));
}
let repos = project.repos();
match repo {
Some(at) => match repos.at_root(&at) {
@@ -220,6 +223,7 @@ mod tests {
use crate::rpc::Dispatcher;
use crate::{Host, HostConfig};
use ide_core::error::ErrorKind;
use ide_workspace::SettingsScope;
use std::path::Path;
use std::sync::Arc;
@@ -272,4 +276,17 @@ mod tests {
let outsider = root(&host, "main", Some(dir.path().join("other"))).unwrap_err();
assert_eq!(outsider.kind, ErrorKind::Unavailable);
}
#[tokio::test]
async fn refuses_gh_while_git_integration_is_off() {
let dir = tempfile::tempdir().unwrap();
let host = test_host(dir.path());
let proj_dir = dir.path().join("repo");
std::fs::create_dir_all(&proj_dir).unwrap();
host.global_settings.set(SettingsScope::Global, "vcs.git.enabled", serde_json::json!(false)).unwrap();
host.open_project("main", &proj_dir).unwrap();
let err = root(&host, "main", None).unwrap_err();
assert_eq!(err.kind, ErrorKind::Unavailable);
assert!(err.message.contains("Git integration is disabled"), "{}", err.message);
}
}
+39 -1
Переглянути файл
@@ -4,12 +4,14 @@ use super::pytest_fixtures::{
fixture_usages, rename_fixture,
};
use super::python_stubs::{
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
PythonStubLinks, counterpart_candidates, interpreter_site_packages, match_declarations, module_name, site_packages,
stub_path,
};
use crate::Host;
use crate::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId};
use ide_index::python_library::{PythonImportCandidate, PythonLibraries};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
@@ -499,6 +501,41 @@ pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos
.await
}
static PYTHON_LIBRARIES: std::sync::LazyLock<PythonLibraries> = std::sync::LazyLock::new(Default::default);
/// Imports that bind `name` from the packages installed in the interpreter of the Python document
/// `doc` (its workspace member's, else the project's): PyCharm's "Import this name" for library
/// symbols, which basedpyright offers for the project and the standard library only. The first
/// request indexes the interpreter's `site-packages` in the background, and a change there
/// re-indexes it; a request waits for the index until cancelled.
#[command(trust = always)]
pub async fn nav_python_library_imports(
host: &Host,
window: &str,
doc: DocId,
name: String,
request: RequestId,
) -> IdeResult<Vec<PythonImportCandidate>> {
let project = host.project(window)?;
let syntax = host.syntax();
let config_dir = host.config_dir.clone();
let token = host.begin_request(request);
let result = blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.language.as_str() != "python" {
return Ok(Vec::new());
}
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&snap.path)) else {
return Ok(Vec::new());
};
let roots = interpreter_site_packages(&python);
Ok(PYTHON_LIBRARIES.index(&roots, &syntax, &token).map(|index| index.candidates(&name)).unwrap_or_default())
})
.await;
host.end_request(request);
result
}
/// Find Usages of the pytest fixture at `pos` (its definition, or a place asking for it): every
/// test and fixture parameter, `usefixtures` and `getfixturevalue` string that gets it.
/// None when `pos` names no fixture. Cancellable.
@@ -593,6 +630,7 @@ ide_command::domain!(
nav_pytest_fixture_target,
nav_pytest_fixture_usages,
nav_pytest_fixtures,
nav_python_library_imports,
nav_python_stubs,
nav_resolve_module,
path_completions,
+9 -3
Переглянути файл
@@ -149,7 +149,8 @@ pub fn settings_set(
/// Effective source / test / resource / excluded roots of the window's project:
/// auto-detected from build files, overridden by Settings › Project Structure.
#[command(trust = always)]
/// Off the UI thread: Gradle source roots may walk the project for builds, slow on a share.
#[command(trust = always, desktop_body = spawn)]
pub fn project_roots(host: &Host, window: &str) -> IdeResult<ide_workspace::ProjectRoots> {
Ok(host.project(window)?.roots())
}
@@ -436,8 +437,13 @@ pub fn set_settings(
}
});
}
// Directory Mappings change which repositories the project has.
if key == "vcs" || key == "vcs.mappings" || key.starts_with("vcs.mappings.") {
// Directory Mappings and Enable Git integration change which repositories the project has.
if key == "vcs"
|| key == "vcs.mappings"
|| key.starts_with("vcs.mappings.")
|| key == "vcs.git"
|| key == "vcs.git.enabled"
{
let affected = affected();
host.runtime.spawn_blocking(move || {
for project in affected {
+2 -3
Переглянути файл
@@ -3,7 +3,7 @@
//! plugins' `pytest11` entry points, pytest's own `_pytest` package), for Go to Declaration
//! and completion of fixture names.
use super::python_stubs::site_packages;
use super::python_stubs::interpreter_site_packages as python_site_packages;
use crate::Project;
use ide_core::{FileEdit, IdeError, IdeResult, IpcPath, LanguageId, Location, Pos, Range, TextEdit, WorkspaceEdit};
use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures};
@@ -623,8 +623,7 @@ fn glob_match(pattern: &str, name: &str) -> bool {
fn interpreter_site_packages(project: &Project) -> Vec<PathBuf> {
let settings = project.settings.effective();
let Some(python) = ide_sdk::apply::python_interpreter(&project.root, &settings) else { return Vec::new() };
let prefix = ide_sdk::venv_of(&python).or_else(|| python.parent()?.parent().map(Path::to_path_buf));
prefix.map(|p| site_packages(&p)).unwrap_or_default()
python_site_packages(&python)
}
/// `pkg.mod` → `pkg/mod.py` or `pkg/mod/__init__.py` in the first folder that has it.
+29
Переглянути файл
@@ -56,6 +56,19 @@ pub(crate) fn site_packages(venv: &Path) -> Vec<PathBuf> {
out
}
/// The `site-packages` of the interpreter `python`, found on disk without running it: in the
/// environment holding its `bin` / `Scripts` folder (a virtualenv, a conda environment, an install
/// prefix), else in its own folder (a conda environment on Windows keeps `python.exe` at its root).
pub(crate) fn interpreter_site_packages(python: &Path) -> Vec<PathBuf> {
let home = python.parent();
[home.and_then(Path::parent), home]
.into_iter()
.flatten()
.map(site_packages)
.find(|p| !p.is_empty())
.unwrap_or_default()
}
/// The dotted module of a Python file, from the innermost `search` folder holding it
/// (`src/a/b.py` → `a.b`, `site-packages/a/__init__.py` → `a`).
pub(crate) fn module_name(path: &Path, search: &[PathBuf]) -> Option<String> {
@@ -227,4 +240,20 @@ mod tests {
links.iter().map(|l| (l.name.as_str(), l.range.start.line, l.target.start.line)).collect();
assert_eq!(names, [("f", 0, 2), ("C", 4, 5), ("C.__init__", 5, 6), ("C.m", 6, 7)]);
}
#[test]
fn interpreter_site_packages_of_venvs_and_conda_environments() {
let dir = tempfile::tempdir().unwrap();
let unix = dir.path().join("envs/langchain");
std::fs::create_dir_all(unix.join("lib/python3.13/site-packages")).unwrap();
assert_eq!(interpreter_site_packages(&unix.join("bin/python")), [unix.join("lib/python3.13/site-packages")]);
// Windows: `.venv\Scripts\python.exe`, and conda's `<env>\python.exe`.
let venv = dir.path().join(".venv");
std::fs::create_dir_all(venv.join("Lib/site-packages")).unwrap();
assert_eq!(interpreter_site_packages(&venv.join("Scripts/python.exe")), [venv.join("Lib/site-packages")]);
let conda = dir.path().join("miniconda/envs/data");
std::fs::create_dir_all(conda.join("Lib/site-packages")).unwrap();
assert_eq!(interpreter_site_packages(&conda.join("python.exe")), [conda.join("Lib/site-packages")]);
assert!(interpreter_site_packages(&dir.path().join("nowhere/bin/python")).is_empty());
}
}
+1
Переглянути файл
@@ -45,6 +45,7 @@ fn frame(line: u32) -> StackFrame {
line,
column: 8,
presentation_hint: None,
instruction_pointer_reference: None,
}
}
+5
Переглянути файл
@@ -911,6 +911,7 @@ pub async fn vcs_log_users(host: &Host, window: &str, repo: Option<PathBuf>) ->
#[command(trust = always)]
pub async fn vcs_open_external_log(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
host.ensure_git_enabled(window)?;
let path = dunce::canonicalize(path)?;
let repo = Repo::discover(&path)?.ok_or_else(|| ide_core::IdeError::unavailable("folder is not a Git worktree"))?;
let root = repo.root().to_path_buf();
@@ -2002,6 +2003,9 @@ pub async fn vcs_clone(
on_output: Channel<String>,
) -> IdeResult<()> {
let settings = host.global_settings.effective();
if !settings.vcs.git.enabled {
return Err(ide_core::IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"));
}
let recurse_submodules = settings.vcs.git.clone_submodules;
let cancel = host.begin_request(request);
let result = tokio::task::spawn_blocking(move || {
@@ -2020,6 +2024,7 @@ pub async fn vcs_clone(
/// detected again before it returns, so the new one is known to the next command.
#[command(trust = always)]
pub async fn vcs_init(host: &Host, window: &str, dir: PathBuf) -> IdeResult<()> {
host.ensure_git_enabled(window)?;
let project = host.project(window).ok();
let git = project.as_ref().and_then(|p| p.git_executable());
blocking(move || {
+24
Переглянути файл
@@ -155,6 +155,11 @@ pub trait PluginWorkspace: Send + Sync {
fn git_executable(&self, _root: &Path) -> Option<PathBuf> {
None
}
/// Settings › Version Control › Git › Enable Git integration of the project at `root`:
/// off, plugins find no repository there.
fn git_enabled(&self, _root: &Path) -> bool {
true
}
/// Root of the project open in `window`.
fn project_of(&self, window: &str) -> Option<PathBuf>;
/// Windows showing the open project at `root`, the most recently focused first.
@@ -1584,6 +1589,9 @@ pub(super) fn commit_draft(
if cancel.is_cancelled() {
return Err(HostError::Cancelled);
}
if !workspace.git_enabled(&repo.root.0) {
return Err(HostError::Failed("Git integration is disabled".into()));
}
let Some(r) = ide_vcs::Repo::discover(&repo.root.0).map_err(failed)? else {
return Err(HostError::NotFound(format!("{} is not in a git repository", repo.root.0.display())));
};
@@ -2633,6 +2641,9 @@ impl HostApi for PluginApi {
}
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError> {
if self.shared.workspace().is_some_and(|w| !w.git_enabled(root)) {
return Ok(Vec::new());
}
let Some(repo) = ide_vcs::Repo::discover(root).map_err(failed)? else { return Ok(Vec::new()) };
plugin_remotes(&repo)
}
@@ -4053,6 +4064,13 @@ impl PluginWorkspace for HostWorkspace {
HostWorkspace::project_covering(self, root)?.git_executable()
}
fn git_enabled(&self, root: &Path) -> bool {
match HostWorkspace::project_covering(self, root) {
Some(project) => project.git_enabled(),
None => self.0.upgrade().is_none_or(|host| host.global_settings.read_effective(|s| s.vcs.git.enabled)),
}
}
fn project_of(&self, window: &str) -> Option<PathBuf> {
self.0.upgrade()?.project(window).ok().map(|p| p.root.clone())
}
@@ -5144,6 +5162,9 @@ impl PluginApi {
/// Status needs it there: a restricted repository is read without its config, so it knows
/// no upstream. The other reads use [`Self::read_repo`] and never execute.
fn repo(&self, root: &Path) -> Result<Option<ide_vcs::Repo>, HostError> {
if self.shared.workspace().is_some_and(|w| !w.git_enabled(root)) {
return Ok(None);
}
let repo = ide_vcs::Repo::discover(root).map_err(failed)?;
if let Some(repo) = &repo
&& let Some(workspace) = self.shared.workspace()
@@ -5158,6 +5179,9 @@ impl PluginApi {
if !self.shared.workspace().is_some_and(|w| w.trusted(root)) {
return Err(HostError::Failed("the project is in Restricted Mode: git does not run there".into()));
}
if self.shared.workspace().is_some_and(|w| !w.git_enabled(root)) {
return Ok(None);
}
let repo = ide_vcs::Repo::discover(root).map_err(failed)?;
if let Some(repo) = &repo {
repo.set_execution_allowed(false);
+14
Переглянути файл
@@ -141,6 +141,8 @@ impl Host {
self.environment.direnv_opened(&root, &sink);
}
let settings = SettingsStore::load(&self.config_dir, Some(&root));
// Builds may have changed while no watcher was looking.
ide_build::gradle::forget_build_dirs(&root);
let detected_roots = Arc::new(RwLock::new(ide_workspace::roots::detect(&root)));
let member_excludes: MemberExcludes = Arc::new(RwLock::new(member_excludes(&settings, &root)));
let excludes = exclude_globs(&root, &settings.effective(), &detected_roots.read(), &member_excludes.read());
@@ -505,6 +507,7 @@ impl Host {
// Build files / conventional folders changed: re-detect roots.
let touched = changed.iter().chain(&batch.removed).filter_map(|p| p.strip_prefix(&root).ok());
if touched.into_iter().any(ide_workspace::roots::affects_roots) {
ide_build::gradle::forget_build_dirs(&root);
let fresh = ide_workspace::roots::detect(&root);
if *detected_roots.read() != fresh {
// Detected excluded folders (`target`, `build`) leave the index too.
@@ -762,6 +765,8 @@ impl Host {
{
let weak = Arc::downgrade(&project);
project.agents.set_git_executable_hook(Arc::new(move || weak.upgrade()?.git_executable()));
let weak = Arc::downgrade(&project);
project.agents.set_git_enabled_hook(Arc::new(move || weak.upgrade().is_some_and(|p| p.git_enabled())));
}
self.insert_project(window, project.clone());
for (key, text, dirty) in &carried {
@@ -1131,6 +1136,10 @@ fn scan_repositories(
/// The project-open scan and the watcher's rescan share these skip rules.
fn discover_repositories(root: &Path, settings: &SettingsStore, build_cache: &Path, trusted: bool) -> IdeResult<Repos> {
let settings = settings.effective();
// Git integration off: the project has no repositories, so nothing runs git for it.
if !settings.vcs.git.enabled {
return Ok(Repos::default());
}
let found = detect_repositories(root, &settings, build_cache, trusted)?;
let mappings = &settings.vcs.mappings;
if mappings.is_empty() {
@@ -1179,6 +1188,11 @@ impl Project {
);
}
/// Settings › Version Control › Git › Enable Git integration (effective value).
pub fn git_enabled(&self) -> bool {
self.settings.read_effective(|s| s.vcs.git.enabled)
}
/// Settings › Version Control › Git › Path to Git executable, this project's value (its own
/// layer over the global one); `None` when it is empty or the project is not trusted.
/// Every git started for the project runs it: the project's repositories carry it, and work
+1
Переглянути файл
@@ -19,6 +19,7 @@ use std::time::Duration;
mod data;
mod filter;
mod matching;
pub mod python_library;
mod store;
mod worker;
+441
Переглянути файл
@@ -0,0 +1,441 @@
//! Import candidates for a name from a Python interpreter's installed packages (PyCharm's
//! "Import this name" for library symbols). basedpyright offers import fixes for the project's
//! own symbols and the standard library only; this index covers `site-packages`.
//!
//! Every public module of the installed packages is read once: its `__all__`, else its public
//! top-level definitions ([`Syntax::python_exports`]). Indexes are shared by every request for
//! the same folders and rebuilt in the background when one of the folders changes: installing,
//! upgrading or removing a package adds or removes entries there (its `.dist-info` at least).
use ide_core::CancellationToken;
use ide_language::Syntax;
use parking_lot::{Condvar, Mutex};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
/// Modules read at most: a very large environment is indexed in part rather than for minutes.
const MAX_MODULES: usize = 60_000;
/// Package nesting below `site-packages` that is still walked.
const MAX_DEPTH: usize = 8;
/// Candidates returned for one name.
const MAX_CANDIDATES: usize = 10;
/// An import that binds a name: `from module import name`, or `import module` without `name`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PythonImportCandidate {
pub module: String,
pub name: Option<String>,
}
/// The public names of the modules below some `site-packages` folders.
#[derive(Debug, Default)]
pub struct PythonLibraryIndex {
modules: Vec<String>,
/// Name → the modules exporting it (indexes into `modules`).
names: HashMap<String, Vec<u32>>,
/// Importable top-level modules and packages.
top_level: HashSet<String>,
}
/// A module found on disk and the file its names are read from (none for an extension module
/// without a stub).
struct Source {
module: String,
file: Option<PathBuf>,
/// A folder without `__init__` holding modules: `from google import protobuf`, not `import google`.
namespace: bool,
}
impl PythonLibraryIndex {
/// Indexes the modules of `roots`, in `sys.path` order (the first folder holding a top-level
/// name wins). None when `cancel` fired first.
pub fn scan(roots: &[PathBuf], syntax: &Syntax, cancel: &CancellationToken) -> Option<Self> {
let mut sources = Vec::new();
let mut taken = HashSet::new();
for root in roots {
let mut found = Vec::new();
walk(root, "", 0, &mut found, cancel);
for source in found {
let top = source.module.split('.').next().unwrap_or_default();
// A package shadowed by an earlier folder is not importable from this one.
if taken.contains(top) || sources.len() >= MAX_MODULES {
continue;
}
sources.push(source);
}
// Namespace packages span folders (`google.protobuf` here, `google.api` there).
taken.extend(sources.iter().filter(|s| !s.namespace && !s.module.contains('.')).map(|s| s.module.clone()));
}
if cancel.is_cancelled() {
return None;
}
let exports: Vec<Vec<String>> = sources
.par_iter()
.map(|s| match &s.file {
Some(file) if !cancel.is_cancelled() => std::fs::metadata(file)
.ok()
.filter(|m| m.len() <= crate::MAX_SYMBOL_FILE)
.and_then(|_| std::fs::read_to_string(file).ok())
.map(|text| syntax.python_exports(&text))
.unwrap_or_default(),
_ => Vec::new(),
})
.collect();
if cancel.is_cancelled() {
return None;
}
let mut index = Self::default();
let ids: HashMap<&str, u32> = sources.iter().enumerate().map(|(i, s)| (s.module.as_str(), i as u32)).collect();
for (i, (source, names)) in sources.iter().zip(exports).enumerate() {
let module = &source.module;
index.modules.push(module.clone());
for name in names {
index.names.entry(name).or_default().push(i as u32);
}
match module.rsplit_once('.') {
// `from matplotlib import pyplot`
Some((parent, last)) => {
if let Some(&parent) = ids.get(parent) {
index.names.entry(last.to_owned()).or_default().push(parent);
}
}
None if !source.namespace => {
index.top_level.insert(module.clone());
}
None => {}
}
}
for modules in index.names.values_mut() {
modules.sort_unstable();
modules.dedup();
}
Some(index)
}
/// The imports that bind `name`: `import name` for a top-level module, then the modules that
/// export it, the shortest module path first (a package re-exporting a name before the
/// submodule defining it).
pub fn candidates(&self, name: &str) -> Vec<PythonImportCandidate> {
let mut out = Vec::new();
if self.top_level.contains(name) {
out.push(PythonImportCandidate { module: name.to_owned(), name: None });
}
let mut modules: Vec<&String> =
self.names.get(name).into_iter().flatten().map(|&i| &self.modules[i as usize]).collect();
let key = |m: &String| (m.matches('.').count(), m.len());
modules.sort_by(|a, b| key(a).cmp(&key(b)).then_with(|| a.cmp(b)));
out.extend(
modules.into_iter().map(|m| PythonImportCandidate { module: m.clone(), name: Some(name.to_owned()) }),
);
out.truncate(MAX_CANDIDATES);
out
}
}
/// A Python identifier that is not private (`_name`).
fn public_identifier(name: &str) -> bool {
let mut chars = name.chars();
chars.next().is_some_and(|c| c.is_alphabetic()) && chars.all(|c| c == '_' || c.is_alphanumeric())
}
/// The public modules below `dir` (the package `prefix`, empty for a `site-packages` folder).
fn walk(dir: &Path, prefix: &str, depth: usize, out: &mut Vec<Source>, cancel: &CancellationToken) {
if depth > MAX_DEPTH || out.len() >= MAX_MODULES || cancel.is_cancelled() {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else { return };
// Module name → (`.py`, `.pyi`, extension module); packages → their folder.
let mut files: BTreeMap<String, (Option<PathBuf>, Option<PathBuf>, bool)> = BTreeMap::new();
let mut packages: BTreeMap<String, PathBuf> = BTreeMap::new();
for entry in entries.flatten() {
let path = entry.path();
let file_name = entry.file_name().to_string_lossy().into_owned();
if path.is_dir() {
// `pkg-stubs` (PEP 561 stub-only package) holds the stubs of `pkg`.
let name = if depth == 0 { file_name.strip_suffix("-stubs").unwrap_or(&file_name) } else { &file_name };
if public_identifier(name) && !matches!(name, "test" | "tests") {
let stubs = name.len() != file_name.len();
// Stubs win over the package itself.
if stubs || !packages.contains_key(name) {
packages.insert(name.to_owned(), path);
}
}
continue;
}
let (stem, kind) = if let Some(stem) = file_name.strip_suffix(".pyi") {
(stem, 1)
} else if let Some(stem) = file_name.strip_suffix(".py") {
(stem, 0)
} else if file_name.ends_with(".so") || file_name.ends_with(".pyd") {
// `name.cpython-313-darwin.so`, `name.abi3.so`, `name.pyd`
(file_name.split('.').next().unwrap_or_default(), 2)
} else {
continue;
};
if !public_identifier(stem) {
continue;
}
let slot = files.entry(stem.to_owned()).or_default();
match kind {
0 => slot.0 = Some(path),
1 => slot.1 = Some(path),
_ => slot.2 = true,
}
}
let qualified = |name: &str| if prefix.is_empty() { name.to_owned() } else { format!("{prefix}.{name}") };
for (name, (py, pyi, extension)) in files {
if out.len() >= MAX_MODULES {
return;
}
if packages.contains_key(&name) {
continue;
}
let file = pyi.or(py);
if file.is_some() || extension {
out.push(Source { module: qualified(&name), file, namespace: false });
}
}
for (name, path) in packages {
let init = ["__init__.pyi", "__init__.py"].iter().map(|f| path.join(f)).find(|p| p.is_file());
let module = qualified(&name);
let at = out.len();
let package = init.is_some();
out.push(Source { module: module.clone(), file: init, namespace: !package });
walk(&path, &module, depth + 1, out, cancel);
// A folder without `__init__` is a namespace package only when it holds modules.
if !package && out.len() == at + 1 {
out.pop();
}
}
}
/// The indexes of every set of `site-packages` folders asked for, shared by all requests.
#[derive(Default)]
pub struct PythonLibraries {
builds: Mutex<HashMap<Vec<PathBuf>, Arc<Build>>>,
}
struct Build {
/// Modification times of the folders when the build started.
stamp: Vec<Option<SystemTime>>,
/// None while building; then the index (None when it failed or was cancelled).
result: Mutex<Option<Option<Arc<PythonLibraryIndex>>>>,
done: Condvar,
cancel: CancellationToken,
}
impl Build {
fn finish(&self, index: Option<PythonLibraryIndex>) {
*self.result.lock() = Some(index.map(Arc::new));
self.done.notify_all();
}
}
/// Marks a build finished even when the indexing thread panics.
struct Finish(Arc<Build>);
impl Drop for Finish {
fn drop(&mut self) {
if self.0.result.lock().is_none() {
self.0.finish(None);
}
}
}
impl PythonLibraries {
/// The index of `roots`. The first request, and the first after a folder changed, starts a
/// build on its own thread; a request only waits for it, until `cancel` fires (None then).
pub fn index(
&self,
roots: &[PathBuf],
syntax: &Arc<Syntax>,
cancel: &CancellationToken,
) -> Option<Arc<PythonLibraryIndex>> {
if roots.is_empty() {
return Some(Arc::default());
}
let build = self.build(roots, syntax);
let mut result = build.result.lock();
loop {
if let Some(index) = &*result {
return index.clone();
}
if cancel.is_cancelled() {
return None;
}
build.done.wait_for(&mut result, Duration::from_millis(50));
}
}
fn build(&self, roots: &[PathBuf], syntax: &Arc<Syntax>) -> Arc<Build> {
let stamp = stamp(roots);
let mut builds = self.builds.lock();
if let Some(build) = builds.get(roots).filter(|b| b.stamp == stamp) {
return build.clone();
}
let build =
Arc::new(Build { stamp, result: Mutex::new(None), done: Condvar::new(), cancel: CancellationToken::new() });
if let Some(old) = builds.insert(roots.to_vec(), build.clone()) {
old.cancel.cancel();
}
let (job, roots, syntax) = (Finish(build.clone()), roots.to_vec(), syntax.clone());
// When the thread cannot start, dropping `job` finishes the build without an index.
let _ = std::thread::Builder::new().name("python-library-index".into()).spawn(move || {
let index = PythonLibraryIndex::scan(&roots, &syntax, &job.0.cancel);
job.0.finish(index);
});
build
}
}
fn stamp(roots: &[PathBuf]) -> Vec<Option<SystemTime>> {
roots.iter().map(|r| std::fs::metadata(r).and_then(|m| m.modified()).ok()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn write(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
fn candidates(index: &PythonLibraryIndex, name: &str) -> Vec<String> {
index
.candidates(name)
.into_iter()
.map(|c| match c.name {
Some(name) => format!("from {} import {name}", c.module),
None => format!("import {}", c.module),
})
.collect()
}
/// The shapes of the report: a name re-exported by a package's `__all__` from a submodule,
/// and names defined in a public submodule only.
fn site_packages() -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
write(root, "langchain/__init__.py", "");
write(
root,
"langchain/agents/__init__.py",
"from langchain.agents.factory import create_agent\n__all__ = ['create_agent']\n",
);
write(root, "langchain/agents/factory.py", "def create_agent(): pass\ndef _private(): pass\n");
write(root, "matplotlib/__init__.py", "def use(): pass\n");
write(root, "matplotlib/figure.py", "class Figure: pass\nclass SubFigure: pass\n");
write(root, "matplotlib/colors.py", "class Normalize: pass\n");
write(root, "matplotlib/pyplot.py", "def figure(): pass\n");
write(root, "matplotlib/_private_module.py", "class Hidden: pass\n");
write(root, "matplotlib/tests/test_figure.py", "class Figure: pass\n");
write(root, "numpy/__init__.pyi", "class ndarray: ...\n");
write(root, "numpy/__init__.py", "class ndarray: pass\nclass only_in_source: pass\n");
write(root, "six.py", "def add_metaclass(): pass\n");
write(root, "_cffi_backend.cpython-313-darwin.so", "");
write(root, "orjson.cpython-313-x86_64-linux-gnu.so", "");
write(root, "requests-stubs/__init__.pyi", "def get(url: str) -> None: ...\n");
write(root, "requests/__init__.py", "def get(url): pass\ndef untyped(): pass\n");
write(root, "google/protobuf/__init__.py", "");
write(root, "google/protobuf/message.py", "class Message: pass\n");
write(root, "langchain-1.0.dist-info/METADATA", "");
dir
}
fn scan(roots: &[PathBuf]) -> PythonLibraryIndex {
PythonLibraryIndex::scan(roots, &Syntax::new(), &CancellationToken::new()).unwrap()
}
#[test]
fn indexes_the_public_names_of_installed_modules() {
let dir = site_packages();
let index = scan(&[dir.path().to_path_buf()]);
assert_eq!(
candidates(&index, "create_agent"),
["from langchain.agents import create_agent", "from langchain.agents.factory import create_agent"]
);
assert_eq!(candidates(&index, "Figure"), ["from matplotlib.figure import Figure"]);
assert_eq!(candidates(&index, "Normalize"), ["from matplotlib.colors import Normalize"]);
assert_eq!(candidates(&index, "pyplot"), ["from matplotlib import pyplot"]);
assert_eq!(candidates(&index, "add_metaclass"), ["from six import add_metaclass"]);
assert_eq!(candidates(&index, "Message"), ["from google.protobuf.message import Message"]);
// Top-level modules and extension modules are imported as a whole.
assert_eq!(candidates(&index, "matplotlib"), ["import matplotlib"]);
assert_eq!(candidates(&index, "orjson"), ["import orjson"]);
assert_eq!(candidates(&index, "six"), ["import six"]);
// A namespace package is not offered; its subpackage is.
assert_eq!(candidates(&index, "google"), Vec::<String>::new());
assert_eq!(candidates(&index, "protobuf"), ["from google import protobuf"]);
}
#[test]
fn leaves_out_private_and_test_modules_and_prefers_stubs() {
let dir = site_packages();
let index = scan(&[dir.path().to_path_buf()]);
for hidden in ["_private", "Hidden", "_cffi_backend", "_private_module", "tests", "only_in_source", "untyped"] {
assert_eq!(candidates(&index, hidden), Vec::<String>::new(), "{hidden}");
}
assert_eq!(candidates(&index, "ndarray"), ["from numpy import ndarray"]);
assert_eq!(candidates(&index, "get"), ["from requests import get"]);
}
#[test]
fn an_earlier_folder_shadows_a_package_of_a_later_one() {
let (first, second) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
write(first.path(), "pkg/__init__.py", "def new(): pass\n");
write(second.path(), "pkg/__init__.py", "def old(): pass\n");
write(second.path(), "other.py", "def thing(): pass\n");
let index = scan(&[first.path().to_path_buf(), second.path().to_path_buf()]);
assert_eq!(candidates(&index, "new"), ["from pkg import new"]);
assert_eq!(candidates(&index, "old"), Vec::<String>::new());
assert_eq!(candidates(&index, "thing"), ["from other import thing"]);
}
#[test]
fn a_cancelled_scan_has_no_result() {
let dir = site_packages();
let cancel = CancellationToken::new();
cancel.cancel();
assert!(PythonLibraryIndex::scan(&[dir.path().to_path_buf()], &Syntax::new(), &cancel).is_none());
}
#[test]
fn builds_are_shared_and_redone_when_a_folder_changes() {
let dir = site_packages();
let roots = vec![dir.path().to_path_buf()];
let (libraries, syntax, cancel) =
(PythonLibraries::default(), Arc::new(Syntax::new()), CancellationToken::new());
let first = libraries.index(&roots, &syntax, &cancel).unwrap();
assert!(Arc::ptr_eq(&first, &libraries.index(&roots, &syntax, &cancel).unwrap()));
assert!(first.candidates("installed_later").is_empty());
// `pip install`: a new top-level entry changes the folder's modification time.
std::thread::sleep(Duration::from_millis(20));
write(dir.path(), "newpkg/__init__.py", "def installed_later(): pass\n");
let file = fs::File::open(dir.path()).unwrap();
file.set_modified(SystemTime::now() + Duration::from_secs(5)).ok();
let second = libraries.index(&roots, &syntax, &cancel).unwrap();
assert!(!Arc::ptr_eq(&first, &second));
assert_eq!(candidates(&second, "installed_later"), ["from newpkg import installed_later"]);
}
#[test]
fn a_cancelled_request_stops_waiting() {
let dir = site_packages();
let cancel = CancellationToken::new();
cancel.cancel();
let libraries = PythonLibraries::default();
// Either the build finished first or the request gave up; it never blocks.
let _ = libraries.index(&[dir.path().to_path_buf()], &Arc::new(Syntax::new()), &cancel);
assert!(libraries.index(&[], &Arc::new(Syntax::new()), &cancel).is_some());
}
}
+95 -24
Переглянути файл
@@ -182,7 +182,9 @@ impl Shared {
let snapshot_started = Instant::now();
let fast = self.try_fast_start();
let snapshot_elapsed = snapshot_started.elapsed();
if let Err(reason) = fast {
if fast.is_err() && self.is_cancelled() {
// Closing: the stat loops stopped early, and a fallback walk would only stall the close.
} else if let Err(reason) = fast {
let snapshot_guard = SystemTime::now();
let walk_started = Instant::now();
let found = self.walk_roots(None);
@@ -276,13 +278,24 @@ impl Shared {
}
let root = filter.root();
let validation_started = Instant::now();
for i in 0..snapshot.dirs_len() {
let rel = snapshot.dir(i);
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
let Ok(meta) = std::fs::symlink_metadata(&path) else { return Err("directory changed") };
if !meta.is_dir() || mtime_of(&meta) != snapshot.dir_mtime(i) {
return Err("directory changed");
}
// In parallel: on a network share each stat is a round trip.
let cancelled = &self.cancelled;
let dirs_valid = INDEX_POOL.install(|| {
(0..snapshot.dirs_len()).into_par_iter().all(|i| {
if cancelled.load(Ordering::Relaxed) {
return false;
}
let rel = snapshot.dir(i);
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
std::fs::symlink_metadata(&path)
.is_ok_and(|meta| meta.is_dir() && mtime_of(&meta) == snapshot.dir_mtime(i))
})
});
if self.is_cancelled() {
return Err("cancelled");
}
if !dirs_valid {
return Err("directory changed");
}
let external = crate::store::external_ignore_candidates(root);
let saved_external: Vec<&str> = (0..snapshot.ignore_len())
@@ -309,28 +322,56 @@ impl Shared {
}
let validation_elapsed = validation_started.elapsed();
let build_started = Instant::now();
let entries: Vec<Option<(FileEntry, Vec<StoredSymbol>)>> = INDEX_POOL.install(|| {
(0..snapshot.len())
.into_par_iter()
.map(|i| {
let path = root.join(snapshot.rel(i));
let meta = std::fs::symlink_metadata(&path).ok()?;
if !meta.is_file() || mtime_of(&meta) != snapshot.mtime(i) || meta.len() != snapshot.size(i) {
// Files are checked against their folder's listing, one per folder: on Windows the
// listing carries each entry's metadata, so a share costs a round trip per folder
// instead of one per file. Elsewhere `DirEntry::metadata` is the same `lstat`.
let mut by_dir: HashMap<&str, Vec<usize>> = HashMap::new();
for i in 0..snapshot.len() {
let rel = snapshot.rel(i);
if !safe_rel(rel) {
return Err("file changed");
}
let dir = rel.rfind('/').map_or("", |at| &rel[..at]);
by_dir.entry(dir).or_default().push(i);
}
let by_dir: Vec<(&str, Vec<usize>)> = by_dir.into_iter().collect();
let entries: Option<Vec<Vec<Indexed>>> = INDEX_POOL.install(|| {
by_dir
.par_iter()
.map(|(dir, files)| {
if cancelled.load(Ordering::Relaxed) {
return None;
}
Some(snapshot.entry(i, root))
let path = if dir.is_empty() { root.to_owned() } else { root.join(dir) };
let listed: HashMap<std::ffi::OsString, std::fs::Metadata> = std::fs::read_dir(&path)
.ok()?
.filter_map(|e| {
let e = e.ok()?;
Some((e.file_name(), e.metadata().ok()?))
})
.collect();
files
.iter()
.map(|&i| {
let rel = snapshot.rel(i);
let name = rel.rfind('/').map_or(rel, |at| &rel[at + 1..]);
let meta = listed.get(std::ffi::OsStr::new(name))?;
if !meta.is_file() || mtime_of(meta) != snapshot.mtime(i) || meta.len() != snapshot.size(i)
{
return None;
}
Some(snapshot.entry(i, root))
})
.collect::<Option<Vec<_>>>()
})
.collect()
});
let built = build_started.elapsed();
if entries.iter().any(Option::is_none) {
return Err("file changed");
}
let validated = entries;
let mut entries = Vec::with_capacity(validated.len());
for entry in validated {
entries.push(entry.expect("validated above"));
if self.is_cancelled() {
return Err("cancelled");
}
let Some(entries) = entries else { return Err("file changed") };
let entries: Vec<(FileEntry, Vec<StoredSymbol>)> = entries.into_iter().flatten().collect();
let dirs: Vec<(Box<str>, PathBuf, u32)> = (0..snapshot.dirs_len())
.filter_map(|i| {
let rel = snapshot.dir(i);
@@ -1108,6 +1149,9 @@ impl Shared {
type ContentHash = [u8; 32];
/// A file validated on a warm start, with its stored symbols.
type Indexed = (FileEntry, Vec<StoredSymbol>);
/// `Some(prev_hash)` when `f` is missing or stale in `d` (`None` inner hash when
/// the file must be parsed fresh); `None` when `d` is already current for `f`.
fn prev_hash_if_stale(d: &IndexData, f: &Found) -> Option<Option<ContentHash>> {
@@ -1438,6 +1482,32 @@ mod metric_tests {
assert_eq!(index_files(&shared, found[..1].iter(), true).symbol_extractions, 1);
}
#[test]
fn warm_start_checks_files_against_their_folder_listing() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir_all(root.join("src/deep")).unwrap();
let root = dunce::canonicalize(root).unwrap();
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
std::fs::write(root.join("src/lib.rs"), "pub fn a() {}\n").unwrap();
std::fs::write(root.join("src/deep/b.rs"), "pub fn b() {}\n").unwrap();
let cache = dir.path().join("cache");
let open = || {
let mut index = shared(&root);
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
index
};
open().scan(None, &[], None, SystemTime::now()).unwrap();
let index = open();
assert_eq!(index.try_fast_start(), Ok(()));
assert_eq!(index.data.read().file_count, 3);
// Same folder mtime, a different size: only the listing's metadata can tell.
let dir_mtime = std::fs::metadata(root.join("src/deep")).unwrap().modified().unwrap();
std::fs::write(root.join("src/deep/b.rs"), "pub fn b() { /* longer */ }\n").unwrap();
std::fs::File::open(root.join("src/deep")).and_then(|f| f.set_modified(dir_mtime)).ok();
assert_eq!(open().try_fast_start(), Err("file changed"));
}
#[test]
fn reopened_cache_counts_metadata_reuse() {
let dir = tempfile::tempdir().unwrap();
@@ -1533,7 +1603,8 @@ mod metric_tests {
index.run(true);
});
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
assert_eq!(index.data.read().file_count, 1);
// The project is closing: its validation stops instead of statting the rest of a tree.
assert_eq!(index.data.read().file_count, 0);
assert_eq!(count.load(Ordering::Relaxed), 0);
}
+1
Переглянути файл
@@ -12,6 +12,7 @@ pub(crate) mod lines;
mod literals;
mod outline;
mod php_align;
mod python_exports;
mod python_facts;
mod python_fixtures;
mod python_imports;
+314
Переглянути файл
@@ -0,0 +1,314 @@
//! The names a Python module offers to `from module import name`, for import suggestions of
//! library symbols: its `__all__`, else its public top-level definitions.
use crate::{LanguageId, Syntax};
use tree_sitter::{Node, Tree};
impl Syntax {
/// The public names of a Python module `text`, sorted: the names its `__all__` lists, else its
/// top-level functions, classes, assignments and type aliases, and the names it re-exports
/// as `import a as a` / `from m import a as a` (the stub convention). Top-level `if` / `try`
/// / `with` blocks count as top level. Names with a leading underscore are left out.
pub fn python_exports(&self, text: &str) -> Vec<String> {
self.analyze(&LanguageId::new("python"), text, |_, tree, text| Some(exports(tree, text))).unwrap_or_default()
}
}
#[derive(Default)]
struct Exports {
/// The literal names of `__all__`; None when the module has none.
all: Option<Vec<String>>,
/// `__all__` is also built from something other than literals (`other.__all__ + [...]`).
dynamic: bool,
defined: Vec<String>,
}
fn exports(tree: &Tree, text: &str) -> Vec<String> {
let mut found = Exports::default();
found.block(tree.root_node(), text);
let mut names = match found.all {
Some(all) if found.dynamic => all.into_iter().chain(found.defined).collect(),
Some(all) => all,
None => found.defined,
};
names.retain(|n| is_public(n));
names.sort();
names.dedup();
names
}
impl Exports {
fn block(&mut self, node: Node, text: &str) {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
self.statement(child, text);
}
}
fn statement(&mut self, node: Node, text: &str) {
match node.kind() {
"function_definition" | "class_definition" | "type_alias_statement" => {
if let Some(name) = node.child_by_field_name("name").filter(|n| n.kind() == "identifier") {
self.defined.push(src(name, text).to_owned());
} else if let Some(left) = node.child_by_field_name("left") {
// `type X = ...`: the alias is the `left` type.
self.defined.push(src(left, text).to_owned());
}
}
"decorated_definition" => {
if let Some(definition) = node.child_by_field_name("definition") {
self.statement(definition, text);
}
}
"expression_statement" => {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
self.expression(child, text);
}
}
"import_statement" | "import_from_statement" => self.reexports(node, text),
"block" => self.block(node, text),
"if_statement"
| "elif_clause"
| "else_clause"
| "try_statement"
| "except_clause"
| "except_group_clause"
| "finally_clause"
| "with_statement" => {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
if matches!(
child.kind(),
"block"
| "elif_clause"
| "else_clause"
| "except_clause"
| "except_group_clause"
| "finally_clause"
) {
self.statement(child, text);
}
}
}
_ => {}
}
}
fn expression(&mut self, node: Node, text: &str) {
match node.kind() {
"assignment" => {
let (Some(left), right) = (node.child_by_field_name("left"), node.child_by_field_name("right")) else {
return;
};
if src(left, text) == "__all__" {
if let Some(right) = right {
self.all = Some(Vec::new());
self.extend_all(right, text);
}
return;
}
self.targets(left, text);
// `a = b = 1`
if let Some(right) = right.filter(|r| r.kind() == "assignment") {
self.expression(right, text);
}
}
"augmented_assignment" => {
let left = node.child_by_field_name("left");
if left.is_some_and(|l| src(l, text) == "__all__")
&& let Some(right) = node.child_by_field_name("right")
{
self.extend_all(right, text);
}
}
// `__all__.extend([...])`, `__all__.append("name")`
"call" => {
let function = node.child_by_field_name("function").map(|f| src(f, text));
if !matches!(function, Some("__all__.extend" | "__all__.append")) {
return;
}
let Some(args) = node.child_by_field_name("arguments") else { return };
let mut cursor = args.walk();
for arg in args.named_children(&mut cursor) {
self.extend_all(arg, text);
}
}
_ => {}
}
}
/// Names bound by an assignment target: `a`, `a, b`, `(a, b)`, `[a, b]`.
fn targets(&mut self, node: Node, text: &str) {
match node.kind() {
"identifier" => self.defined.push(src(node, text).to_owned()),
"pattern_list" | "tuple_pattern" | "list_pattern" => {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
self.targets(child, text);
}
}
_ => {}
}
}
/// Adds the string literals of `node` (a list, tuple, string or a `+` of them) to `__all__`.
fn extend_all(&mut self, node: Node, text: &str) {
let all = self.all.get_or_insert_with(Vec::new);
match node.kind() {
"string" => match string_value(node, text) {
Some(name) => all.push(name),
None => self.dynamic = true,
},
"list" | "tuple" | "parenthesized_expression" | "binary_operator" => {
let mut cursor = node.walk();
let children: Vec<Node> = node.named_children(&mut cursor).collect();
for child in children {
self.extend_all(child, text);
}
}
_ => self.dynamic = true,
}
}
/// `import a as a` and `from m import a as a`: re-exported in a stub, and by convention in a module.
fn reexports(&mut self, node: Node, text: &str) {
let mut cursor = node.walk();
for item in node.children_by_field_name("name", &mut cursor) {
if item.kind() != "aliased_import" {
continue;
}
let (Some(name), Some(alias)) = (item.child_by_field_name("name"), item.child_by_field_name("alias"))
else {
continue;
};
if src(name, text) == src(alias, text) {
self.defined.push(src(alias, text).to_owned());
}
}
}
}
/// The content of a plain string literal; none for f-strings and strings with escapes.
fn string_value(node: Node, text: &str) -> Option<String> {
let mut cursor = node.walk();
let parts: Vec<Node> = node.children(&mut cursor).collect();
let start = parts.iter().find(|p| p.kind() == "string_start")?;
let end = parts.iter().find(|p| p.kind() == "string_end")?;
if src(*start, text).chars().any(|c| matches!(c, 'f' | 'F' | 'b' | 'B'))
|| parts.iter().any(|p| matches!(p.kind(), "interpolation" | "escape_sequence"))
{
return None;
}
text.get(start.end_byte()..end.start_byte()).map(str::to_owned)
}
fn is_public(name: &str) -> bool {
let mut chars = name.chars();
chars.next().is_some_and(|c| c.is_alphabetic()) && chars.all(|c| c == '_' || c.is_alphanumeric())
}
fn src<'a>(node: Node, text: &'a str) -> &'a str {
text.get(node.byte_range()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
fn exports(text: &str) -> Vec<String> {
Syntax::new().python_exports(text)
}
#[test]
fn without_all_the_public_top_level_definitions() {
let text = "\
\"\"\"Docs.
Example = 1 inside a docstring
\"\"\"
import os
from typing import Any
from .colors import Normalize as Normalize
import numpy as np
CONSTANT = 1
_private = 2
a, (b, _c) = 1, (2, 3)
x = y = 0
annotated: int = 3
type Alias = int
def function(): pass
async def coroutine(): pass
@decorator
class Figure:
nested = 1
def method(self): pass
def _helper(): pass
if sys.version_info >= (3, 11):
def modern(): pass
else:
def legacy(): pass
try:
from fast import speedup
except ImportError:
def speedup(): pass
";
assert_eq!(
exports(text),
[
"Alias",
"CONSTANT",
"Figure",
"Normalize",
"a",
"annotated",
"b",
"coroutine",
"function",
"legacy",
"modern",
"speedup",
"x",
"y"
]
);
}
#[test]
fn all_lists_the_exports() {
// `langchain/agents/__init__.py`: the name is defined in a private submodule.
let text = "\
from langchain.agents.factory import create_agent
from langchain.agents.middleware.types import AgentState
__all__ = [
\"AgentState\",
\"create_agent\",
]
def not_exported(): pass
";
assert_eq!(exports(text), ["AgentState", "create_agent"]);
assert_eq!(
exports("__all__ = ('a',)\n__all__ += ['b']\n__all__.extend(['c'])\n__all__.append('d')\n"),
["a", "b", "c", "d"]
);
assert_eq!(exports("__all__ = ['a', '_b'] + ['c']\n"), ["a", "c"]);
}
#[test]
fn a_computed_all_adds_the_definitions() {
let text = "from .core import *\nfrom . import core\n__all__ = core.__all__ + ['extra']\ndef extra(): pass\ndef more(): pass\n";
assert_eq!(exports(text), ["extra", "more"]);
}
#[test]
fn an_empty_all_exports_nothing() {
assert!(exports("__all__ = []\ndef hidden(): pass\n").is_empty());
}
}
+37 -1
Переглянути файл
@@ -157,8 +157,32 @@ impl DiskSpelling {
type Entries = (BTreeMap<String, Entry>, HashSet<String>);
/// Stat checks for a work tree on a network share: mtime and size only.
///
/// A share's index is usually written by git on the server too, whose inode, owner and change
/// time never match what Windows reports for the same file (inode 0, creation time). Every
/// tracked file would then fail the stat check and be read in full to compare its content,
/// over the network, on each status; and the index written back would fail the same way for
/// git on the server.
const NETWORK_STAT_CONFIG: [(&str, &str); 2] = [("core.checkStat", "minimal"), ("core.trustCTime", "false")];
fn on_network(r: &Repo) -> bool {
ide_core::network_path::is_network_path(r.root())
}
fn gix_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
let repo = r.gix()?;
let mut repo = r.gix()?;
if on_network(r) {
use gix::config::tree::{Core, Key};
let mut config = repo.config_snapshot_mut();
let keys: [&'static dyn Key; 2] = [&Core::CHECK_STAT, &Core::TRUST_C_TIME];
for (key, (_, value)) in keys.into_iter().zip(NETWORK_STAT_CONFIG) {
if let Err(e) = config.set_value(key, value) {
tracing::debug!("{}: {e}", key.logical_name());
}
}
config.commit().map_err(gx)?;
}
let mut map: BTreeMap<String, Entry> = BTreeMap::new();
let mut conflicts: HashSet<String> = HashSet::new();
@@ -273,12 +297,22 @@ fn read_only() -> [(&'static str, &'static std::ffi::OsStr); 1] {
[("GIT_OPTIONAL_LOCKS", std::ffi::OsStr::new("0"))]
}
/// `-c` options for [`NETWORK_STAT_CONFIG`] when the work tree is on a network share.
fn network_args(r: &Repo) -> Vec<String> {
if !on_network(r) {
return Vec::new();
}
NETWORK_STAT_CONFIG.iter().flat_map(|(key, value)| ["-c".to_owned(), format!("{key}={value}")]).collect()
}
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
/// In Restricted Mode git compares content without the repository's clean/process
/// filters and doesn't ask submodules for their own status (which runs their config).
fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
let overrides = crate::cli::filter_overrides(r.root(), &ide_core::CancellationToken::new())?;
let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect();
let network = network_args(r);
args.extend(network.iter().map(String::as_str));
args.extend(["status", "--porcelain=v2", "-z", "--untracked-files=all"]);
if !crate::execution_allowed() {
args.push("--ignore-submodules=dirty");
@@ -292,6 +326,8 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeResult<Entries> {
let overrides = crate::cli::filter_overrides(r.root(), &ide_core::CancellationToken::new())?;
let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect();
let network = network_args(r);
args.extend(network.iter().map(String::as_str));
args.extend(["--literal-pathspecs", "status", "--porcelain=v2", "-z", "--untracked-files=all"]);
if !crate::execution_allowed() {
args.push("--ignore-submodules=dirty");
+28 -8
Переглянути файл
@@ -124,6 +124,16 @@ pub fn natural_cmp(a: &str, b: &str) -> Ordering {
///
/// Inside an archive (`<archive>!/<entry>`, or the archive file itself) lists its entries.
pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
read_dir_with(dir, excludes, None)
}
/// [`read_dir`] matching `.gitignore` / `.ignore` with `shared` rules (a watcher's, kept current by its
/// events) instead of rules looked up afresh: on a network share each lookup is several round trips.
pub(crate) fn read_dir_with(
dir: &Path,
excludes: &[String],
shared: Option<&rules::GitignoreStack>,
) -> IdeResult<Vec<FileEntry>> {
if let Some((archive, entry)) = split_archive_path(dir) {
return read_archive_dir(&archive, &entry);
}
@@ -133,27 +143,37 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
if !fs::metadata(dir)?.is_dir() {
return Err(IdeError::invalid(format!("{} is not a directory", dir.display())));
}
let gitignore = rules::GitignoreStack::cached(dir);
let fresh;
let gitignore = match shared {
Some(shared) => shared,
None => {
fresh = rules::GitignoreStack::cached(dir);
&fresh
}
};
let base = gitignore.repo_root().unwrap_or(dir).to_path_buf();
let excludes = ExcludeMatcher::new(excludes);
let paths: Vec<PathBuf> = fs::read_dir(dir)?
let listed: Vec<fs::DirEntry> = fs::read_dir(dir)?
.filter_map(|entry| match entry {
Ok(e) => Some(e.path()),
Ok(e) => Some(e),
Err(e) => {
tracing::debug!("read_dir {}: {e}", dir.display());
None
}
})
.collect();
// One stat per entry dominates a large folder (and every stat is a round trip on a network
// share): stat in parallel; small folders stay on this thread.
let mut entries: Vec<(bool, FileEntry)> = paths
// On Windows `DirEntry::metadata` comes with the listing (FindNextFileW) at no further
// cost; a separate stat per entry was one network round trip each on an SMB share.
// Elsewhere it is one `lstat` per entry: stat in parallel; small folders stay on this thread.
let mut entries: Vec<(bool, FileEntry)> = listed
.into_par_iter()
.with_min_len(256)
.filter_map(|path| {
.filter_map(|entry| {
let path = entry.path();
let name = path.file_name()?.to_string_lossy().into_owned();
let lmeta = fs::symlink_metadata(&path).ok()?;
// Does not follow symlinks, like `symlink_metadata`.
let lmeta = entry.metadata().ok()?;
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
match fs::metadata(&path) {
Ok(m) => {
+22 -3
Переглянути файл
@@ -58,6 +58,7 @@ type Emit = Arc<dyn Fn(&FsBatch) + Send + Sync>;
/// `on_change` (used by the index) with the same batch. Stops when dropped;
/// no callback runs after `drop` returns.
pub struct Watcher {
root: PathBuf,
inner: Inner,
excludes: SharedExcludes,
rules: Arc<GitignoreStack>,
@@ -116,7 +117,7 @@ impl Watcher {
(Self::start_polling(&root, filter, emit, mode)?, Some(e.message))
}
};
Ok(Self { inner, excludes: shared, rules, polling })
Ok(Self { root, inner, excludes: shared, rules, polling })
}
/// Why changes are polled for instead of reported by the OS; `None` when they are.
@@ -144,6 +145,24 @@ impl Watcher {
self.rules.invalidate_tree(self.rules.repo_root().unwrap_or(Path::new("/")));
}
/// The watched directory (canonical).
pub fn root(&self) -> &Path {
&self.root
}
/// Repository enclosing the watched root, if any.
pub fn repo_root(&self) -> Option<&Path> {
self.rules.repo_root()
}
/// [`crate::read_dir`] reusing this watcher's ignore rules for directories below its root.
/// They are invalidated by the watcher's own events, so expanding folder after folder does not
/// look for `.git` and re-read every `.gitignore` up to the repository root each time.
pub fn read_dir(&self, dir: &Path, excludes: &[String]) -> IdeResult<Vec<crate::FileEntry>> {
let shared = dir.starts_with(&self.root).then_some(&*self.rules);
crate::read_dir_with(dir, excludes, shared)
}
/// Number of OS-level watches (1 in recursive and flat mode).
pub fn watch_count(&self) -> usize {
self.inner.state.watched.lock().len()
@@ -2224,7 +2243,7 @@ mod tests {
let (excludes, rules) = (filter.excludes.clone(), filter.gitignore.clone());
let emit: Emit = Arc::new(move |b: &FsBatch| batches.lock().push(b.clone()));
let inner = Watcher::start_polling(root, filter, emit, WatchMode::default()).unwrap();
Watcher { inner, excludes, rules, polling: Some("cannot start file watcher".into()) }
Watcher { root: root.to_path_buf(), inner, excludes, rules, polling: Some("cannot start file watcher".into()) }
}
#[test]
@@ -2311,7 +2330,7 @@ mod tests {
notify::Config::default(),
)
.unwrap();
let watcher = Watcher { inner, excludes, rules, polling: None };
let watcher = Watcher { root: root.clone(), inner, excludes, rules, polling: None };
assert!(watcher.polling().is_none(), "the OS watcher did start");
let deadline = Instant::now() + Duration::from_secs(10);
while watcher.unwatched_reason().is_none() && Instant::now() < deadline {
+39
Переглянути файл
@@ -311,6 +311,45 @@ fn wait_for(events: &Mutex<Vec<FsBatch>>, pred: impl Fn(&[FsBatch]) -> bool) ->
false
}
#[test]
fn watcher_read_dir_reuses_its_ignore_rules() {
let (_t, r) = root();
write(&r.join(".git/HEAD"), "ref: refs/heads/main\n");
write(&r.join(".gitignore"), "*.log\n");
write(&r.join("sub/a.log"), "x");
write(&r.join("sub/b.txt"), "x");
let sink: SharedSink = Arc::new(|_| {});
let watcher = Watcher::start(&r, vec![], sink, Box::new(|_| {})).unwrap();
assert_eq!(watcher.root(), r);
assert_eq!(watcher.repo_root(), Some(r.as_path()));
let ignored = |entries: Vec<FileEntry>| -> BTreeSet<String> {
entries.into_iter().filter(|e| e.ignored).map(|e| e.name).collect()
};
let listed = watcher.read_dir(&r.join("sub"), &[]).unwrap();
assert_eq!(ignored(listed.clone()), BTreeSet::from(["a.log".to_string()]));
let plain = read_dir(&r.join("sub"), &[]).unwrap();
assert_eq!(
listed.iter().map(|e| (&e.name, e.kind, e.size, e.ignored)).collect::<Vec<_>>(),
plain.iter().map(|e| (&e.name, e.kind, e.size, e.ignored)).collect::<Vec<_>>(),
);
// The watcher's events keep the shared rules current.
std::thread::sleep(Duration::from_millis(300));
write(&r.join(".gitignore"), "*.txt\n");
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let now = ignored(watcher.read_dir(&r.join("sub"), &[]).unwrap());
if now == BTreeSet::from(["b.txt".to_string()]) {
break;
}
assert!(Instant::now() < deadline, "still ignored: {now:?}");
std::thread::sleep(Duration::from_millis(50));
}
// Outside the watched folder: rules of its own.
let (_o, other) = root();
write(&other.join("x.log"), "x");
assert!(watcher.read_dir(&other, &[]).unwrap().iter().all(|e| !e.ignored));
}
#[test]
fn watcher_reports_changes() {
let (_t, r) = root();
+66 -19
Переглянути файл
@@ -18,6 +18,30 @@ pub const PYTHON_FILES: &[&str] = &["pyproject.toml", "setup.py", "setup.cfg", "
const SKIP_DIRS: &[&str] =
&["node_modules", "target", "build", "dist", "out", "venv", "__pycache__", "vendor", "bower_components"];
/// Skipped folders that are never a virtual environment: not probed for its markers.
const NEVER_ENV_DIRS: &[&str] = &[
".git",
".hg",
".svn",
".jj",
".idea",
".vscode",
".gradle",
".mvn",
".github",
".cache",
".next",
".nuxt",
"node_modules",
"target",
"build",
"dist",
"out",
"__pycache__",
"vendor",
"bower_components",
];
/// A Python virtual environment (`python -m venv`, virtualenv, uv) or conda environment,
/// whatever it is named: its packages are dependencies, not modules of the project.
/// Returns the file that marks it.
@@ -99,7 +123,34 @@ pub fn detect(root: &Path) -> Vec<SourceFolder> {
break;
}
let dir = if rel.is_empty() { root.to_path_buf() } else { root.join(&rel) };
if crate::unity::is_project(&dir) {
// The listing alone decides which markers to probe: on a network share every
// probe is a round trip, and most folders have none of them.
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
let mut files: Vec<String> = Vec::new();
let mut dirs: Vec<String> = Vec::new();
let mut names: Vec<String> = Vec::new();
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
match e.file_type() {
Ok(t) if t.is_dir() => dirs.push(name.clone()),
Ok(t) if t.is_file() => files.push(name.clone()),
_ => {}
}
names.push(name);
}
let named = |n: &str| names.iter().any(|x| x == n);
// A virtual environment is excluded, not searched (its packages ship build files).
if !rel.is_empty()
&& (named("pyvenv.cfg") || named("conda-meta"))
&& let Some(marker) = virtual_env_marker(&dir)
{
if !out.iter().any(|r| r.path == rel) {
let from = join(&rel, marker);
out.push(SourceFolder { path: rel, kind: RootKind::Excluded, detected_from: Some(from) });
}
continue;
}
if named("Assets") && named("ProjectSettings") && crate::unity::is_project(&dir) {
for (name, kind) in
[("Assets", RootKind::Source), ("Packages", RootKind::Source), ("ProjectSettings", RootKind::Resources)]
{
@@ -122,17 +173,6 @@ pub fn detect(root: &Path) -> Vec<SourceFolder> {
// Assets and PackageCache may contain arbitrary build files; they aren't nested modules.
continue;
}
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
let mut files: Vec<String> = Vec::new();
let mut dirs: Vec<String> = Vec::new();
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
match e.file_type() {
Ok(t) if t.is_dir() => dirs.push(name),
Ok(t) if t.is_file() => files.push(name),
_ => {}
}
}
dirs.sort();
let before = out.len();
module_roots(root, &rel, &files, &mut out);
@@ -146,18 +186,19 @@ pub fn detect(root: &Path) -> Vec<SourceFolder> {
if found.iter().any(|f| *f == child || f.is_empty() && name == "src") {
continue;
}
if let Some(marker) = virtual_env_marker(&root.join(&child)) {
if !out.iter().any(|r| r.path == child) {
// Skipping discovery is not an exclusion: marked hidden/conventional
// environments (`.venv`, `venv`) still need an explicit root for index and
// watcher filtering. Folders searched below are checked once listed.
if name.starts_with('.') || SKIP_DIRS.contains(&name.as_str()) {
if !NEVER_ENV_DIRS.contains(&name.as_str())
&& let Some(marker) = virtual_env_marker(&root.join(&child))
&& !out.iter().any(|r| r.path == child)
{
let from = join(&child, marker);
out.push(SourceFolder { path: child, kind: RootKind::Excluded, detected_from: Some(from) });
}
continue;
}
// Skipping discovery is not an exclusion: marked hidden/conventional
// environments still need an explicit root for index and watcher filtering.
if name.starts_with('.') || SKIP_DIRS.contains(&name.as_str()) {
continue;
}
queue.push_back((child, depth + 1));
}
}
@@ -601,6 +642,12 @@ mod tests {
);
}
#[test]
fn the_project_folder_itself_is_not_an_excluded_environment() {
let dir = tree(&["pyvenv.cfg", "requirements.txt", "pkg/pyvenv.cfg", "pkg/lib/setup.py"]);
assert_eq!(summary(&detect(dir.path())), vec!["[email protected]", "pkg=Excluded@pkg/pyvenv.cfg"]);
}
#[test]
fn marked_environment_detection_preserves_source_roots_and_user_overrides() {
let dir = tree(&["Cargo.toml", "src/pyvenv.cfg", ".venv/pyvenv.cfg", ".conda/conda-meta/history"]);
+28
Переглянути файл
@@ -30,6 +30,14 @@ Choose **New › Data Source › DuckDB**. In **Manage Drivers…**, add the [of
Choose **File** to open an existing database or create a new file, **In memory** for a temporary database that lasts until disconnect, or **JDBC URL** to enter a DuckDB URL directly. To inspect an existing file without changing it, enable **Read-only** in **Options**. The official driver applies this setting when it opens the file.
### DuckLake
Choose **DuckLake** in the DuckDB connection dialog. Select **Catalog file** to browse to an existing catalog, or **DuckDB secret** to enter the name of a DuckDB secret of type `ducklake` configured on the database host. The secret must be available to new JDBC sessions on that host, including after reconnect. On first use, DuckDB installs and loads its official DuckLake extension. See the [DuckLake connection guide](https://ducklake.select/docs/stable/duckdb/usage/connecting) for catalog and storage options.
OpenIDEA attaches the selected catalog read-only and leaves its metadata version unchanged. To enforce read-only access across the SQL console, give the database account and storage credentials read permissions only. Leave **Data directory** empty to use the storage location recorded in the catalog. If you moved the Parquet files, you can point to their existing directory on the database host.
To initialize an empty local lake, choose **Create New DuckLake…** and confirm a new directory name. OpenIDEA creates `catalog.ducklake` there and selects it in the dialog. Use **Test Connection** to check access and **OK** to save the source.
## JDBC drivers
For presets with a built-in driver, **Driver** defaults to **Built-in** in the **General** tab. Use **Manage Drivers…** to view or add JDBC profiles for that data source type. Select the profile from **Driver** to use JDBC while keeping the source type and icon. **Go to Driver** opens the selected profile and its JAR list. Choose **New › Data Source › Custom JDBC** for databases without a preset, or open its **Manage Drivers…** to see all profiles and change their associated types.
@@ -201,6 +209,26 @@ Closing a selected result activates its left neighbor, or its right neighbor if
Console results are editable the same way when the query is a plain select from one table that includes the primary key. Tables without a primary key, joins, aggregates, `UNION` queries, read-only data sources and ClickHouse results are read-only.
## Join tables across data sources
In a trusted project, open **Query Workspace** in the Database tree. Type `#` to see saved PostgreSQL and ClickHouse connections, SQLite files and DuckDB JDBC files. Choose a source and type `.` to complete a table. If two connections share a name, give them distinct names under **Workspace Settings › SQL aliases**. The workspace uses an [installed DuckDB JDBC driver](#duckdb) on the project host.
```sql
SELECT a.id, a.join_key, g.region, t.channel
FROM #accounts.public.customers AS a
JOIN #events.events.purchases AS e ON a.id = e.customer_id
JOIN #geo.main.region_map AS g ON a.id = g.id
JOIN #labels.main.tags AS t ON g.zone = t.zone;
```
A SELECT can join two to eight tables. Each inner JOIN compares one column from its table with one column from an earlier table. Select individual columns, `alias.*`, or `*`. Specifying columns limits the source reads to those columns and the JOIN keys. Integer keys can have different sizes and signs. Other key types must match, including precision and scale for decimals.
Press **⌘Enter** (macOS) or **Ctrl+Enter** (Windows and Linux) to run the statement at the caret. Select several complete statements to run them in order, or use **Execute Script** for the whole editor. Each completed statement gets its own elapsed time and result tab. You can stop a batch and page through the completed results.
Each statement reads its inputs through independent read-only connections and joins them in a fresh in-memory DuckDB on the project host. Temporary staging files are removed when the run ends. A source with a startup script is ineligible. To keep temporary tables between statements in a regular console, create a [DuckDB data source](#duckdb) and select **In memory**.
Each input allows up to 100,000 rows, 128 columns, 16 MiB of data and 1 MiB per value. Combined inputs allow up to 200,000 rows and 32 MiB per statement. A result allows up to 100,000 rows, 256 columns and a 16 MiB JDBC reply. If a limit is exceeded, the statement fails and the batch stops.
## Export and import
The export button offers **Export Data…** and quick copies: **Copy as CSV**, **Copy as TSV**, **Copy as JSON**, **Copy as SQL Inserts**, **Copy as Markdown** and **Copy as One-Row**. The **Export Data** dialog adds **Transpose**, column and row headers, a preview, **Copy to Clipboard** and **Export to File**. Export covers the rows that are loaded (the current page).
+1
Переглянути файл
@@ -90,6 +90,7 @@ With **Shell integration** on, zsh, bash and fish report the current directory a
| **Mouse reporting** | on | Off: programs can't capture the mouse. |
| **Copy to clipboard on selection** | off | |
| **Paste on middle mouse button click** | on | |
| **Paste on right click** | off | On: right-click pastes; Ctrl or Shift + right-click opens the context menu. |
| **Move focus to the Editor with Escape** | off | Otherwise `Esc` goes to the shell. |
| **Override IDE shortcuts** | on | See above. |
| **Shell integration** | on | |
+28
Переглянути файл
@@ -30,6 +30,14 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行
选择 **文件** 可打开已有数据库或创建新文件,选择 **内存** 可创建断开连接后即释放的临时数据库,选择 **JDBC URL** 可直接输入 DuckDB URL。要以只读方式检查已有文件,请在 **选项** 中启用 **只读**。官方驱动会在打开文件时应用此设置。
### DuckLake
在 DuckDB 连接对话框中选择 **DuckLake**。选择 **目录文件** 可浏览已有的目录文件,也可以选择 **DuckDB 密钥**,输入数据库主机上已配置的 `ducklake` 类型密钥名称。该密钥必须可供数据库主机上的新 JDBC 会话使用,包括断线重连后的会话。首次使用时,DuckDB 会安装并加载官方 DuckLake 扩展。有关目录和存储选项,请参阅 [DuckLake 连接指南](https://ducklake.select/docs/stable/duckdb/usage/connecting)。
OpenIDEA 以只读方式挂载所选目录,并保留现有的元数据版本。要在整个 SQL 控制台中限制写入,请只为数据库账户和存储凭据授予读取权限。将 **数据目录** 留空即可使用目录中记录的存储位置。如果移动了 Parquet 文件,请指定数据库主机上已有的数据目录。
要创建本地空湖,请选择 **新建 DuckLake…**,指定并确认一个尚不存在的目录。OpenIDEA 会在其中创建 `catalog.ducklake` 并在对话框中选中该文件。点击 **测试连接** 检查访问权限,再点击 **确定** 保存数据源。
## JDBC 驱动
对于提供内置驱动的预设,**常规** 选项卡中的 **驱动** 默认为 **内置**。通过 **管理驱动…** 查看或添加该数据源类型的 JDBC 驱动配置。在 **驱动** 中选中配置后,数据源会使用 JDBC,同时保留原有类型及图标。选择 **转到驱动** 可查看所选配置及其 JAR 文件。对于没有预设的数据库,请选择 **新建 › 数据源 › 自定义 JDBC**。也可以在其中选择 **管理驱动…** 查看所有配置并修改关联类型。
@@ -200,6 +208,26 @@ FROM sales_archive.main.orders;
如果控制台查询是对单表的简单 select 且包含主键,结果同样可以编辑。没有主键的表、连接查询、聚合、`UNION` 查询、只读数据源和 ClickHouse 的结果都是只读的。
## 跨数据源联接表
在受信任的项目中,从数据库树打开**查询工作区**。输入 `#` 可查看已保存的 PostgreSQL 和 ClickHouse 连接、SQLite 文件及 DuckDB JDBC 文件。选定数据源后,输入 `.` 可补全表名。如果两个连接重名,可在**工作区设置 › SQL 别名**中分别指定别名。工作区使用项目主机上[已安装的 DuckDB JDBC 驱动](#duckdb)。
```sql
SELECT a.id, a.join_key, g.region, t.channel
FROM #accounts.public.customers AS a
JOIN #events.events.purchases AS e ON a.id = e.customer_id
JOIN #geo.main.region_map AS g ON a.id = g.id
JOIN #labels.main.tags AS t ON g.zone = t.zone;
```
一条 SELECT 可以联接两到八张表。每个内联接的条件是该表的一列与先前引入的某张表的一列相等。可以指定要返回的列,也可以使用 `alias.*` 或 `*`。指定列时,只从源表读取这些列和联接键。整数键允许位宽和符号不同。其他类型的键必须匹配,十进制数的精度和小数位数也要一致。
按 **⌘Enter**(macOS)或 **Ctrl+Enter**(Windows 和 Linux)运行光标所在的语句。选中多条完整语句可依次运行。也可以使用**执行脚本**运行整个编辑器中的语句。每条已完成的语句都有独立的耗时和结果标签页。停止批次后,仍可翻页查看已完成的结果。
每条语句通过独立的只读连接读取源表,并在项目主机上的临时内存 DuckDB 中执行联接。运行结束时会删除暂存文件。配置了启动脚本的数据源不可用。要在普通控制台中跨语句保留临时表,请创建 [DuckDB 数据源](#duckdb)并选择**内存**。
每个输入最多允许 100,000 行、128 列和 16 MiB 数据,单个值上限为 1 MiB。每条语句的所有输入合计最多允许 200,000 行和 32 MiB。结果最多允许 100,000 行、256 列,JDBC 响应上限为 16 MiB。超出限制时,该语句会报错,批次随即停止。
## 导出与导入
导出按钮提供 **导出数据…** 以及快速复制:**Copy as CSV**、**Copy as TSV**、**Copy as JSON**、**Copy as SQL Inserts**、**Copy as Markdown** 和 **Copy as One-Row**。**导出数据** 对话框还支持 **转置**、列标题和行标题、预览、**复制到剪贴板** 和 **导出到文件**。导出范围是已加载的行(当前页)。
+1
Переглянути файл
@@ -90,6 +90,7 @@ OpenIDEA 会按项目记住终端标签页:各自的目录、自定义名称
| **鼠标报告** | 开 | 关闭后程序无法捕获鼠标。 |
| **选择时复制到剪贴板** | 关 | |
| **点击鼠标中键时粘贴** | 开 | |
| **右键单击时粘贴** | 关 | 开启后右键单击直接粘贴;按住 Ctrl 或 Shift 右键单击仍打开上下文菜单。 |
| **按 Escape 将焦点移到编辑器** | 关 | 关闭时 `Esc` 发给 Shell。 |
| **覆盖 IDE 快捷键** | 开 | 见上文。 |
| **Shell 集成** | 开 | |
+65
Переглянути файл
@@ -104,6 +104,71 @@ test("Select All takes the whole buffer, not just the mounted rows", async ({ pa
expect(copied).toMatch(/output 499$/);
});
test("moves a caret with IDEA's console keys instead of scrolling to either end", async ({ page }) => {
const log = await consoleOutput(page);
await page.evaluate(() => document.getElementById("splash")?.remove());
await log.evaluate((el) => {
el.scrollTop = 200 * 20;
});
const row = log.locator('[data-index="205"]');
await expect(row).toBeVisible();
const box = (await row.boundingBox())!;
await page.mouse.click(box.x + 30, box.y + box.height / 2);
const caret = () =>
page.evaluate(() => {
const s = window.getSelection()!;
const row = (s.focusNode as Node | null)?.parentElement?.closest("[data-index]");
return { row: Number(row?.getAttribute("data-index")), offset: s.focusOffset, text: s.toString() };
});
const top = await log.evaluate((el) => el.scrollTop);
await page.keyboard.press("End");
expect(await caret()).toEqual({ row: 205, offset: 10, text: "" });
expect(await log.evaluate((el) => el.scrollTop)).toBe(top);
// The arrows (also bound in the Git log) and ⌘← / ⌘→ reach the console through the keymap.
for (const [key, row, offset] of [
["ArrowLeft", 205, 9],
["ArrowRight", 205, 10],
["ArrowRight", 206, 0],
["ArrowLeft", 205, 10],
["ArrowUp", 204, 10],
["ArrowDown", 205, 10],
["Meta+ArrowLeft", 205, 0],
["Meta+ArrowRight", 205, 10],
] as const) {
await page.keyboard.press(key);
expect(await caret(), key).toEqual({ row, offset, text: "" });
}
await page.keyboard.press("Shift+Home");
expect(await caret()).toMatchObject({ row: 205, offset: 0, text: "output 205" });
// ⇧⌘Home selects to the start without mounting the rows in between; copying takes all of them.
await page.keyboard.press("End");
await page.keyboard.press("Meta+Shift+Home");
await expect.poll(() => log.evaluate((el) => el.scrollTop)).toBe(0);
expect(await log.locator("[data-index]").count()).toBeLessThan(100);
await page.evaluate(() => {
(window as unknown as { copied: string[] }).copied = [];
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText: async (text: string) => (window as unknown as { copied: string[] }).copied.push(text) },
});
});
await page.keyboard.press("Meta+C");
const copied = () => page.evaluate(() => (window as unknown as { copied: string[] }).copied[0] ?? "");
await expect.poll(copied).toMatch(/^output 0\n[\s\S]*\noutput 205$/);
expect((await copied()).split("\n")).toHaveLength(206);
await page.keyboard.press("Meta+End");
await expect.poll(caret).toEqual({ row: 499, offset: 10, text: "" });
// PageUp moves the caret a screen up and scrolls the output with it.
const bottom = await log.evaluate((el) => el.scrollTop);
await page.keyboard.press("PageUp");
await expect.poll(async () => (await caret()).row).toBeLessThan(490);
const { row: paged } = await caret();
expect(paged).toBeGreaterThan(480);
await expect.poll(() => log.evaluate((el) => el.scrollTop)).toBe(bottom - (499 - paged) * 20);
});
/** Mount the real console over the given output, wrapped or not. */
async function consoleOf(page: Page, text: string, softWrap: boolean) {
await page.goto("/");
+766
Переглянути файл
@@ -0,0 +1,766 @@
import type { Locator, Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
async function setupWorkspace(page: Page, options: { multipleDrivers?: boolean; fullNames?: boolean } = {}) {
await stubDesktop(page);
await page.evaluate(async ({ fullNames, multipleDrivers }) => {
const store = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ store);
const sources = [
{ id: "accounts", name: fullNames ? "Accounts · PostgreSQL" : "accounts", driver: "postgres" },
{ id: "events", name: fullNames ? "Events · ClickHouse" : "events", driver: "clickhouse" },
];
const table = (schema: string, name: string, ...keys: string[]) => ({
schema,
name,
kind: "table",
columns: keys.map((name) => ({
name,
dataType: "BIGINT",
nullable: false,
primaryKey: false,
hasDefault: false,
})),
});
const completion = {
accounts: {
defaultSchema: "public",
tables: [
table("public", "customers", "id", "join_key"),
table("legacy", "customers", "archived_id"),
{ ...table("public", "customers_view"), kind: "view" },
],
foreignKeys: [],
},
events: {
defaultSchema: "events",
tables: [table("events", "purchases", "customer_id", "join_key")],
foreignKeys: [],
},
};
useDatabase.setState({ sources });
Object.assign(window.__ipc.handlers, {
db_sources: () => sources,
db_connected: () => [],
db_completion: ({ id }: { id: keyof typeof completion }) => completion[id],
db_jdbc_drivers: () =>
[
{ id: "duck", name: "DuckDB JDBC" },
{ id: "duck-local", name: "DuckDB Local" },
]
.slice(0, multipleDrivers ? 2 : 1)
.map((driver) => ({
...driver,
className: "org.duckdb.DuckDBDriver",
vendor: "duckdb",
jars: [],
urlTemplate: "jdbc:duckdb:",
})),
db_workspace_join: () => ({
statement: "",
columns: [
{ name: "id", typeName: "BIGINT" },
{ name: "customer", typeName: "VARCHAR" },
{ name: "customer_id", typeName: "BIGINT" },
{ name: "amount", typeName: "DECIMAL(32,6)" },
{ name: "note", typeName: "VARCHAR" },
],
rows: Array.from({ length: 501 }, (_, i) => {
const id = (9_007_199_254_740_993n + BigInt(i)).toString();
return [
id,
i === 500 ? "Last customer" : "Customer " + (i + 1),
id,
"123456789012345678.000001",
i === 0 ? null : "",
];
}),
hasMore: false,
affected: null,
elapsedMs: 42,
executionMs: null,
truncated: [],
}),
});
}, options);
}
async function openWorkspace(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("db.queryWorkspace");
});
return page.getByRole("region", { name: "Query Workspace" });
}
const SQL = "SELECT * FROM #accounts.public.customers a JOIN #events.events.purchases b ON a.id = b.customer_id";
async function saveWorkspaceDraft(page: Page, draft: Record<string, unknown>) {
await page.evaluate(async (draft) => {
const module = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ module);
const root = useProject.getState().project.root;
localStorage.setItem("openidea.db-workspace:" + root, JSON.stringify(draft));
}, draft);
}
async function showDatabase(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
await (await import(/* @vite-ignore */ actions)).executeAction("db.showToolWindow");
});
return page.getByRole("tree", { name: "Data sources" }).getByRole("treeitem", { name: "Query Workspace" });
}
async function settingsFor(page: Page, workspace: Locator) {
await workspace
.getByRole("toolbar", { name: "Workspace actions" })
.getByRole("button", { name: /Workspace Settings…/ })
.click();
return page.getByRole("dialog", { name: "Workspace Settings" });
}
test("joins four saved data sources without registering them in the workspace", async ({ workbench: page }, info) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const module = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ module);
const sources = [
{ id: "accounts", name: "accounts", driver: "postgres" },
{ id: "events", name: "events", driver: "clickhouse" },
{ id: "warehouse", name: "warehouse", driver: "jdbc", vendor: "duckdb", url: "jdbc:duckdb:/warehouse.duckdb" },
{ id: "lookup", name: "lookup", driver: "sqlite", file: "lookup.sqlite" },
{ id: "memory", name: "memory", driver: "jdbc", vendor: "duckdb", url: "jdbc:duckdb:memory:session" },
{ id: "arbitrary", name: "arbitrary", driver: "jdbc", url: "jdbc:other:anywhere" },
{ id: "startup", name: "startup", driver: "postgres", options: { startupScript: "SELECT 1" } },
];
useDatabase.setState({ sources, loaded: true });
window.__ipc.handlers.db_sources = () => sources;
const reply = window.__ipc.handlers.db_workspace_join;
window.__ipc.handlers.db_workspace_join = (args) => ({
...(reply?.(args) as object),
columns: [
{ name: "id", typeName: "BIGINT" },
{ name: "label", typeName: "VARCHAR" },
],
rows: [
["9007199254740993", "Retail"],
["9007199254740994", "Wholesale"],
],
});
});
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await editor.focus();
await page.screenshot({ path: info.outputPath("workspace-four-source-empty.png"), animations: "disabled" });
expect(await ipcCalls(page, "db_completion")).toHaveLength(0);
await page.keyboard.insertText("SELECT * FROM ");
await page.keyboard.insertText("#");
for (const name of ["accounts", "events", "warehouse", "lookup"]) {
await expect(page.getByRole("option", { name: new RegExp(`^#${name}`) })).toBeVisible();
}
await expect(page.getByRole("option", { name: /^#(memory|arbitrary|startup)/ })).toHaveCount(0);
await page.screenshot({ path: info.outputPath("workspace-four-source-completion.png"), animations: "disabled" });
expect(await ipcCalls(page, "db_completion")).toHaveLength(0);
await editor.press("Escape");
await editor.press("Meta+A");
await page.keyboard.insertText(
[
"SELECT a.id, l.label FROM #accounts.public.customers AS a",
"JOIN #events.events.purchases AS e ON a.id=e.customer_id",
"JOIN #warehouse.main.items AS w ON e.customer_id=w.id",
"JOIN #lookup.main.labels AS l ON l.id=w.id;",
].join("\n"),
);
await editor.press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
await expect(workspace.getByRole("dialog", { name: "Workspace Settings" })).toHaveCount(0);
await expect(workspace.getByRole("grid").getByText("Retail", { exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath("workspace-four-source-results.png"), animations: "disabled" });
expect(await ipcCalls(page, "db_workspace_join")).toMatchObject([
{
driver: "duck",
plan: {
tables: [
{ sourceId: "accounts", schema: "public", table: "customers" },
{ sourceId: "events", schema: "events", table: "purchases" },
{ sourceId: "warehouse", schema: "main", table: "items" },
{ sourceId: "lookup", schema: "main", table: "labels" },
],
joins: [
{ left: { relation: 0, column: "id" }, rightColumn: "customer_id" },
{ left: { relation: 1, column: "customer_id" }, rightColumn: "id" },
{ left: { relation: 2, column: "id" }, rightColumn: "id" },
],
projection: [
{ relation: 0, column: "id" },
{ relation: 3, column: "label" },
],
},
},
]);
expect(await ipcCalls(page, "db_completion")).toHaveLength(0);
});
test("shows the workspace before any data sources are added", async ({ workbench: page }, info) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const store = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ store);
window.__ipc.handlers.db_sources = () => [];
useDatabase.setState({ sources: [], loaded: true });
});
const node = await showDatabase(page);
await expect(node).toBeVisible();
await node.click();
await page.keyboard.press("Enter");
const workspace = page.getByRole("region", { name: "Query Workspace" });
const editor = workspace.getByLabel("Workspace SQL");
await expect(editor).toBeEmpty();
await expect(editor).toBeFocused();
await expect(workspace.locator("pre")).toContainText("FROM #source_a.schema.table_a");
await expect(workspace.getByRole("button", { name: "Insert JOIN" })).toHaveCount(0);
await expect(workspace.getByRole("button", { name: "New Data Source…" })).toBeVisible();
await expect(workspace.locator("pre")).toContainText("ON a.key = b.key");
await expect(workspace.getByRole("grid")).toHaveCount(0);
const height = await editor.evaluate((element) => element.closest(".cm-editor")!.getBoundingClientRect().height);
expect(height).toBeGreaterThan(500);
await page.screenshot({ path: info.outputPath("workspace-empty.png"), animations: "disabled" });
await page.keyboard.insertText("SELECT");
await expect(editor).toHaveText("SELECT");
await expect(workspace.locator("pre")).toHaveCount(0);
await page.setViewportSize({ width: 720, height: 620 });
await page.evaluate(async () => {
const module = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ module);
const settings = useProject.getState().settings;
useProject.setState({
settings: { ...settings, appearance: { ...settings?.appearance, theme: "dark", syncWithOs: false } },
});
});
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
await editor.press("Meta+Enter");
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await expect(
settings.getByText("Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources."),
).toBeVisible();
const dialog = (await settings.boundingBox())!;
expect(dialog.x + dialog.width).toBeLessThanOrEqual(720);
await settings.getByRole("button", { name: "New Data Source…" }).click();
const sourceDialog = page.getByRole("dialog", { name: "New Data Source", exact: true });
await expect(sourceDialog).toBeVisible();
await sourceDialog.press("Escape");
await settings.press("Escape");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
});
test("completes preferred aliases and pages the same workspace result", async ({ workbench: page }, info) => {
await setupWorkspace(page, { fullNames: true });
const node = await showDatabase(page);
await node.click({ button: "right" });
await page.getByRole("menuitem", { name: /Workspace Settings…/ }).click();
const workspace = page.getByRole("region", { name: "Query Workspace" });
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await expect(settings.getByText("In memory", { exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath("workspace-settings.png"), animations: "disabled" });
await settings.getByRole("button", { name: "SQL aliases", exact: true }).press("Enter");
await settings.getByRole("textbox", { name: /^SQL alias for Accounts/ }).fill(" acct ");
const rightAlias = settings.getByRole("textbox", { name: /^SQL alias for Events/ });
await rightAlias.fill("acct");
await expect(settings.getByRole("alert")).toHaveText("Choose a SQL alias unique to this source.");
const ok = settings.getByRole("button", { name: "OK", exact: true });
await expect(ok).toBeDisabled();
await rightAlias.fill("events");
await expect(ok).toBeEnabled();
await page.screenshot({ path: info.outputPath("workspace-aliases.png"), animations: "disabled" });
await ok.click();
const editor = workspace.getByLabel("Workspace SQL");
await expect(editor).toBeFocused();
const context = workspace.getByRole("button", {
name: /Workspace Settings.*DuckDB JDBC/,
});
await expect(context).toHaveText("DuckDB JDBC");
await workspace.getByRole("button", { name: "Insert JOIN" }).click();
await expect(editor).toContainText("#source_a.schema.table_a");
await expect(editor).toContainText("#source_b.schema.table_b");
const selection = () => page.evaluate(() => window.getSelection()?.toString());
expect(await selection()).toBe("#source_a");
await page.getByRole("option", { name: /^#acct/ }).click();
await expect(editor).toContainText("#acct.schema.table_a");
await editor.press("Tab");
expect(await selection()).toBe("#source_b");
await editor.press("Control+Space");
await page.getByRole("option", { name: /^#events/ }).click();
await editor.press("Tab");
expect(await selection()).toBe("schema.table_a");
await editor.press("Control+Space");
await page.getByRole("option", { name: /^public\.customers/ }).click();
await expect(editor).toContainText("#acct.public.customers");
await editor.press("Tab");
expect(await selection()).toBe("schema.table_b");
await editor.press("Meta+A");
await page.keyboard.insertText('SELECT * FROM #"Accounts · PostgreSQL".');
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /public\.customers/ })).toBeVisible();
await editor.press("Escape");
await editor.press("Meta+A");
await page.keyboard.insertText("SELECT * FROM #ACCT.");
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /^#ACCT\.public\.customers/ })).toBeVisible();
await editor.press("Escape");
await editor.press("Meta+A");
await page.keyboard.insertText("SELECT *\nFROM #");
await editor.press("Control+Space");
await expect(
page.getByRole("option", { name: /^#events/ }).getByText("Events · ClickHouse", { exact: true }),
).toBeVisible();
await expect(page.getByRole("option", { name: /^#left/ })).toHaveCount(0);
await expect(page.getByRole("option", { name: /^#right/ })).toHaveCount(0);
const accountOption = page.getByRole("option", { name: /^#acct/ });
await expect(accountOption.getByText("Accounts · PostgreSQL", { exact: true })).toBeVisible();
await accountOption.click();
await page.keyboard.insertText(".");
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /legacy\.customers/ })).toBeVisible();
await expect(page.getByRole("option", { name: /customers_view/ })).toHaveCount(0);
await page.screenshot({ path: info.outputPath("workspace-completion.png"), animations: "disabled" });
await page.getByRole("option", { name: /public\.customers/ }).click();
await page.keyboard.insertText(" AS a\nJOIN #events.events.");
await editor.press("Control+Space");
await page.getByRole("option", { name: /#events\.events\.purchases/ }).click();
await page.keyboard.insertText(" AS b\n ON a.");
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /archived_id|customer_id/ })).toHaveCount(0);
const keyOption = (name: string) => page.getByRole("option").filter({ has: page.getByText(name, { exact: true }) });
await expect(keyOption("id")).toBeVisible();
await keyOption("id").click();
await page.keyboard.insertText(" = b.");
await editor.press("Control+Space");
await expect(keyOption("customer_id")).toBeVisible();
await page.screenshot({ path: info.outputPath("workspace-keys.png"), animations: "disabled" });
await keyOption("customer_id").click();
await editor.press("Meta+Enter");
const grid = workspace.getByRole("grid");
await expect(grid.getByText("Customer 1", { exact: true })).toBeVisible();
await expect(grid.getByText("9007199254740993", { exact: true })).toHaveCount(2);
await expect(grid.getByText("123456789012345678.000001", { exact: true }).first()).toBeVisible();
await expect(grid.getByText("<null>", { exact: true })).toBeVisible();
expect((await ipcCalls(page, "db_workspace_join"))[0]).toMatchObject({
driver: "duck",
plan: {
tables: [
{ sourceId: "accounts", database: "", schema: "public", table: "customers" },
{ sourceId: "events", database: "", schema: "events", table: "purchases" },
],
joins: [{ left: { relation: 0, column: "id" }, rightColumn: "customer_id" }],
projection: null,
},
});
expect(await ipcCalls(page, "db_completion")).toEqual([{ id: "accounts" }, { id: "events" }]);
await workspace.getByRole("button", { name: "Next Page" }).click();
await expect(grid.getByText("Last customer", { exact: true })).toBeVisible();
await expect(workspace.getByRole("button", { name: "Next Page" })).toBeDisabled();
await workspace.getByRole("button", { name: "Previous Page" }).click();
await expect(grid.getByText("Customer 1", { exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(1);
expect(await ipcCalls(page, "db_execute")).toHaveLength(0);
await page.screenshot({ path: info.outputPath("workspace-join.png"), animations: "disabled" });
});
test("runs the selected JOIN or the one at the caret from a multi-statement draft", async ({
workbench: page,
}, info) => {
await setupWorkspace(page);
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
const second = SQL.replace("public.customers", "legacy.customers");
await editor.click();
await page.keyboard.insertText(SQL + ";\n" + second + ";");
await editor.press("Meta+Enter");
await expect.poll(async () => (await ipcCalls(page, "db_workspace_join")).length).toBe(1);
expect((await ipcCalls(page, "db_workspace_join"))[0]).toMatchObject({
plan: { tables: [{ schema: "legacy" }, { sourceId: "events" }] },
});
await editor.press("Meta+Home");
await editor.press("Shift+End");
const selected = await page.evaluate(() => window.getSelection()?.toString());
expect(selected).toBe(SQL + ";");
await workspace.getByRole("button", { name: "Run", exact: true }).click();
await expect.poll(async () => (await ipcCalls(page, "db_workspace_join")).length).toBe(2);
expect((await ipcCalls(page, "db_workspace_join"))[1]).toMatchObject({
plan: { tables: [{ schema: "public" }, { sourceId: "events" }] },
});
await page.evaluate(() => {
const reply = window.__ipc.handlers.db_workspace_join;
window.__ipc.handlers.db_workspace_join = async (args) => {
await new Promise<void>((resolve) => {
window.addEventListener("workspace-test-release", () => resolve(), { once: true });
});
const result = reply?.(args) as { rows: string[][] };
if ((args.plan as { tables: { schema: string }[] }).tables[0]!.schema === "legacy")
result.rows[0]![1] = "Legacy customer";
return result;
};
});
const release = () => page.evaluate(() => window.dispatchEvent(new Event("workspace-test-release")));
const selectionRange = () =>
editor.evaluate((element) => {
const state = (element as HTMLElement & { cmTile: { view: import("@codemirror/view").EditorView } }).cmTile.view
.state;
const { from, to } = state.selection.main;
return { from, to };
});
await editor.press("Meta+A");
const fullRange = await selectionRange();
await editor.press("Meta+Enter");
const running = workspace.locator(".cm-openidea-db-executing");
const runningText = () => running.evaluateAll((nodes) => nodes.map((node) => node.textContent).join(""));
await expect.poll(runningText).toBe(SQL);
expect(await selectionRange()).toEqual(fullRange);
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(3);
await page.screenshot({ path: info.outputPath("workspace-batch-running.png"), animations: "disabled" });
await release();
await expect.poll(runningText).toBe(second);
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(4);
await release();
await expect(workspace.getByRole("tab", { name: "Result 2", exact: true })).toBeVisible();
await expect(workspace.locator(".cm-openidea-db-run-ok")).toHaveCount(2);
const grid = workspace.getByRole("grid");
await expect(grid.getByText("Legacy customer", { exact: true })).toBeVisible();
await workspace.getByRole("tab", { name: "Result 1", exact: true }).click();
await expect(grid.getByText("Customer 1", { exact: true })).toBeVisible();
await workspace.getByRole("button", { name: "Next Page" }).click();
await expect(grid.getByText("Last customer", { exact: true })).toBeVisible();
await workspace.getByRole("tab", { name: "Result 2", exact: true }).click();
await expect(grid.getByText("Legacy customer", { exact: true })).toBeVisible();
await workspace.getByRole("tab", { name: "Result 1", exact: true }).click();
await expect(grid.getByText("Last customer", { exact: true })).toBeVisible();
await page.screenshot({ path: info.outputPath("workspace-batch-results.png"), animations: "disabled" });
const calls = await ipcCalls(page, "db_workspace_join");
expect(calls.slice(2)).toMatchObject([
{ plan: { tables: [{ schema: "public" }, { sourceId: "events" }] } },
{ plan: { tables: [{ schema: "legacy" }, { sourceId: "events" }] } },
]);
expect(await ipcCalls(page, "db_execute")).toHaveLength(0);
await editor.press("Meta+A");
await editor.press("Backspace");
await workspace.getByRole("button", { name: "Insert JOIN" }).click();
await page.getByRole("option", { name: /^#accounts/ }).click();
await editor.press("Tab");
await editor.press("Control+Space");
await page.getByRole("option", { name: /^#events/ }).click();
for (const field of ["public.customers", "events.purchases", "id", "customer_id"]) {
await editor.press("Tab");
await page.keyboard.insertText(field);
}
await editor.press("Meta+Enter");
await expect.poll(async () => (await ipcCalls(page, "db_workspace_join")).length).toBe(5);
expect((await ipcCalls(page, "db_workspace_join"))[4]).toMatchObject({
plan: { tables: [{ table: "customers" }, { sourceId: "events" }] },
});
await release();
});
test("cancels the active request and surfaces parser, source and limit errors", async ({ workbench: page }) => {
await setupWorkspace(page);
const workspace = await openWorkspace(page);
const run = workspace.getByRole("button", { name: "Run", exact: true });
const alert = workspace.getByRole("alert");
const editor = workspace.getByLabel("Workspace SQL");
await editor.click();
await editor.press("Meta+A");
await page.keyboard.insertText("DELETE FROM #accounts.public.customers");
await run.click();
await expect(alert).toHaveText("Expected SELECT in the workspace query.");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
await editor.click();
await editor.press("Meta+A");
await page.keyboard.insertText(SQL);
await page.evaluate(() => {
let active: { id: unknown; reject: (error: unknown) => void } | undefined;
window.__ipc.handlers.db_workspace_join = ({ request }) =>
new Promise((_, reject) => {
active = { id: request, reject };
});
window.__ipc.handlers.cancel_request = ({ id }) => {
if (active?.id !== id) throw new Error("Unexpected cancellation request.");
active?.reject({ kind: "cancelled", message: "Operation cancelled", data: null });
};
});
await run.click();
await expect(workspace.getByText("Running query", { exact: true })).toBeVisible();
await expect(workspace.getByRole("button", { name: /Workspace Settings…/ })).toBeDisabled();
await workspace.getByRole("button", { name: "Stop", exact: true }).click();
await expect(alert).toHaveText("Cancelled");
await expect(run).toBeEnabled();
expect(await ipcCalls(page, "cancel_request")).toEqual([
{ id: (await ipcCalls(page, "db_workspace_join"))[0]!.request },
]);
for (const message of [
"Could not connect to Events",
"Workspace input exceeds the source row limit",
"Workspace result exceeds 100,000 rows",
]) {
await page.evaluate((message) => {
window.__ipc.handlers.db_workspace_join = () => {
throw { kind: "invalidInput", message, data: null };
};
}, message);
await run.click();
await expect(alert).toHaveText(message);
await expect(workspace.getByRole("grid")).toHaveCount(0);
await expect(run).toBeEnabled();
}
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(4);
});
test("validates all selected statements before reading either source", async ({ workbench: page }) => {
await setupWorkspace(page);
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
const alert = workspace.getByRole("alert");
await editor.click();
await page.keyboard.insertText(SQL + ";\nDELETE FROM #accounts.public.customers;");
await editor.press("Meta+A");
await editor.press("Meta+Enter");
await expect(alert).toHaveText("Expected SELECT in the workspace query.");
await expect(workspace.locator(".cm-openidea-db-run-error")).toHaveCount(1);
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
await page.keyboard.insertText(Array.from({ length: 13 }, () => SQL + ";").join("\n"));
await workspace.getByRole("button", { name: "Execute Script" }).click();
await expect(alert).toHaveText("The workspace can run up to 12 statements at a time.");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
});
for (const failure of ["cancel", "error", "row budget"] as const) {
test(`stops the script after ${failure} and keeps the completed result`, async ({ workbench: page }) => {
await setupWorkspace(page);
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await editor.click();
await page.keyboard.insertText([SQL, SQL.replace("public.customers", "legacy.customers"), SQL].join(";\n") + ";");
await page.evaluate((failure) => {
const reply = window.__ipc.handlers.db_workspace_join;
window.__ipc.handlers.db_workspace_join = ({ request, plan, ...args }) => {
const result = reply?.({ request, plan, ...args }) as { rows: Array<Array<string | null>> };
if ((plan as { tables: { schema: string }[] }).tables[0]!.schema !== "legacy") return result;
if (failure === "error") throw { kind: "invalidInput", message: "Could not connect to Events", data: null };
if (failure === "row budget") return { ...result, rows: Array(100_000).fill(result.rows[0]) };
return new Promise((_, reject) => {
window.__ipc.handlers.cancel_request = ({ id }) => {
if (id !== request) throw new Error("Unexpected cancellation request.");
reject({ kind: "cancelled", message: "Operation cancelled", data: null });
};
});
};
}, failure);
await workspace.getByRole("button", { name: "Execute Script" }).click();
const result = workspace.getByRole("tab", { name: "Result 1", exact: true });
await expect(result).toBeVisible();
if (failure === "cancel") await workspace.getByRole("button", { name: "Stop", exact: true }).click();
const message = {
cancel: "Cancelled",
error: "Could not connect to Events",
"row budget": "The workspace batch exceeds the result size limit.",
}[failure];
await expect(workspace.getByRole("alert")).toHaveText(message);
await expect(workspace.locator(".cm-openidea-db-run-ok")).toHaveCount(1);
await expect(workspace.locator(".cm-openidea-db-run-error")).toHaveCount(1);
await expect(workspace.locator(".cm-openidea-db-timing")).toHaveCount(2);
await result.click();
await expect(workspace.getByRole("grid").getByText("Customer 1", { exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(2);
expect(await ipcCalls(page, "db_execute")).toHaveLength(0);
});
}
test("migrates old source slots, aliases and driver with each project's SQL", async ({ workbench: page }) => {
await setupWorkspace(page, { multipleDrivers: true });
const legacySQL = SQL.replace("#accounts", "#left").replace("#events", "#right");
await saveWorkspaceDraft(page, {
left: "accounts",
right: "events",
sourceAliases: { accounts: "acct", events: "evt" },
profile: "duck-local",
sql: legacySQL,
});
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await expect(editor).toHaveText(legacySQL);
await editor.press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toMatchObject([
{ driver: "duck-local", plan: { tables: [{ sourceId: "accounts" }, { sourceId: "events" }] } },
]);
const settings = await settingsFor(page, workspace);
const driver = settings.getByRole("button", { name: "Workspace DuckDB driver" });
await expect(driver).toHaveText("DuckDB Local");
await settings.getByText("SQL aliases", { exact: true }).click();
const accountsAlias = settings.getByRole("textbox", { name: /^SQL alias for accounts/ });
const eventsAlias = settings.getByRole("textbox", { name: /^SQL alias for events/ });
await expect(accountsAlias).toHaveValue("acct");
await expect(eventsAlias).toHaveValue("evt");
await accountsAlias.fill("customers");
await settings.getByRole("button", { name: "OK", exact: true }).click();
const close = page
.getByRole("region", { name: "Editor", exact: true })
.getByRole("button", { name: "Close Tab", exact: true });
await close.click();
await expect(workspace).toHaveCount(0);
await openWorkspace(page);
await expect(editor).toHaveText(legacySQL);
await settingsFor(page, workspace);
await settings.getByText("SQL aliases", { exact: true }).click();
await expect(accountsAlias).toHaveValue("customers");
await expect(eventsAlias).toHaveValue("evt");
await expect(driver).toHaveText("DuckDB Local");
await accountsAlias.fill("discarded");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await settingsFor(page, workspace);
await settings.getByText("SQL aliases", { exact: true }).click();
await expect(accountsAlias).toHaveValue("customers");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await close.click();
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const project = useProject.getState().project;
useProject.setState({ project: { ...project, root: project.root + "-other" } });
});
await openWorkspace(page);
await expect(editor).toBeEmpty();
await settingsFor(page, workspace);
await expect(driver).toHaveText("Select DuckDB driver");
await settings.getByText("SQL aliases", { exact: true }).click();
await expect(accountsAlias).toHaveValue("");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(1);
});
test("does not retarget a deleted legacy source to an unrelated source named left", async ({ workbench: page }) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const module = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ module);
const sources = [
{ id: "replacement", name: "left", driver: "postgres" },
{ id: "events", name: "events", driver: "clickhouse" },
];
useDatabase.setState({ sources, loaded: true });
window.__ipc.handlers.db_sources = () => sources;
});
const sql = SQL.replace("#accounts", "#left").replace("#events", "#right");
await saveWorkspaceDraft(page, { sql, left: "deleted", right: "events" });
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
const alert = workspace.getByRole("alert");
await editor.press("Meta+Enter");
await expect(alert).toHaveText("Data source left is unavailable. Type # to see available sources.");
await editor.press("Meta+A");
await page.keyboard.insertText(sql.replace("#left", '#"left"'));
await editor.press("Meta+Enter");
await expect(alert).toHaveText("Data source left is unavailable. Type # to see available sources.");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
await editor.press("Meta+A");
await page.keyboard.insertText("SELECT * FROM #");
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /^#"?left/ })).toHaveCount(0);
await page.getByRole("option", { name: "Set unique SQL aliases…" }).click();
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await settings.getByRole("textbox", { name: "SQL alias for left (PostgreSQL)" }).fill("replacement_src");
await settings.getByRole("button", { name: "OK", exact: true }).click();
await editor.press("Meta+A");
await page.keyboard.insertText(sql.replace("#left", "#replacement_src"));
await editor.press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toMatchObject([
{ plan: { tables: [{ sourceId: "replacement" }, { sourceId: "events" }] } },
]);
});
test("offers aliases when identical saved names cannot be resolved", async ({ workbench: page }) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const module = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ module);
const sources = [
{ id: "accounts", name: "Shared", driver: "postgres", host: "accounts.example" },
{ id: "events", name: "Shared", driver: "clickhouse", host: "events.example" },
];
useDatabase.setState({ sources, loaded: true });
window.__ipc.handlers.db_sources = () => sources;
});
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await editor.focus();
await page.keyboard.insertText("SELECT * FROM #");
await editor.press("Control+Space");
const aliasOption = page.getByRole("option", { name: "Set unique SQL aliases…" });
await expect(aliasOption).toBeVisible();
await expect(page.getByRole("option", { name: /^#"Shared"/ })).toHaveCount(0);
await aliasOption.click();
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await expect(settings.getByText("accounts.example", { exact: true })).toBeVisible();
await settings.getByRole("textbox", { name: "SQL alias for Shared (PostgreSQL)" }).fill("accounts");
await settings.getByRole("textbox", { name: "SQL alias for Shared (ClickHouse)" }).fill("events");
await settings.getByRole("button", { name: "OK", exact: true }).click();
await editor.press("Control+Space");
await expect(page.getByRole("option", { name: /^#accounts/ })).toBeVisible();
await expect(page.getByRole("option", { name: /^#events/ })).toBeVisible();
expect(await ipcCalls(page, "db_completion")).toHaveLength(0);
});
test("keeps unrelated queries executable when a stored alias becomes ambiguous", async ({ workbench: page }) => {
await setupWorkspace(page);
await page.evaluate(async () => {
const module = "/src/features/database/store.ts";
const { useDatabase } = await import(/* @vite-ignore */ module);
const sources = [
...useDatabase.getState().sources,
{ id: "old", name: "old", driver: "postgres" },
{ id: "new", name: "colliding", driver: "postgres" },
];
useDatabase.setState({ sources, loaded: true });
window.__ipc.handlers.db_sources = () => sources;
});
await saveWorkspaceDraft(page, { sql: SQL, sourceAliases: { old: "colliding" } });
const workspace = await openWorkspace(page);
await workspace.getByLabel("Workspace SQL").press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(1);
const settings = await settingsFor(page, workspace);
await expect(settings.getByRole("alert")).toHaveText("Choose a SQL alias unique to this source.");
await expect(settings.getByRole("button", { name: "OK", exact: true })).toBeDisabled();
});
test("asks before replacing a missing explicitly selected execution driver", async ({ workbench: page }) => {
await setupWorkspace(page);
await saveWorkspaceDraft(page, { sql: SQL, profile: "missing" });
const workspace = await openWorkspace(page);
const editor = workspace.getByLabel("Workspace SQL");
await editor.press("Meta+Enter");
const settings = page.getByRole("dialog", { name: "Workspace Settings" });
await expect(settings.getByRole("alert")).toHaveText("The saved DuckDB driver is unavailable.");
expect(await ipcCalls(page, "db_workspace_join")).toHaveLength(0);
const driver = settings.getByRole("button", { name: "Workspace DuckDB driver" });
await driver.click();
await page.getByRole("option", { name: "DuckDB JDBC" }).click();
await settings.getByRole("button", { name: "OK", exact: true }).click();
await editor.press("Meta+Enter");
await expect(workspace.getByRole("tab", { name: "Result 1", exact: true })).toBeVisible();
expect(await ipcCalls(page, "db_workspace_join")).toMatchObject([{ driver: "duck" }]);
});
+165
Переглянути файл
@@ -192,6 +192,171 @@ test("Memory gives class filtering the available toolbar width and exposes chang
await expect(changed).toBeChecked();
});
test("Memory View shows the bytes at an address expression with hex and ASCII aligned", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async (id) => {
// The reporter's `msg` (#5921) where GDB put it, 9 bytes into its row; other bytes count up.
const msg = "Hello, World!\n\0";
const at = 0x7fffffff9f69;
const h = window.__ipc.handlers;
const caps = { readMemory: true };
h.debug_capabilities = () => caps;
h.debug_evaluate_in = (args) => ({
name: args.expression,
value: '0x7fffffff9f69 "Hello, World!\\n"',
typeName: "const char *",
variablesReference: 0,
evaluateName: args.expression,
memoryReference: "0x7fffffff9f69",
});
h.debug_read_memory = (args) => {
const start = Number(args.memoryReference) + (args.offset as number);
const data = Array.from({ length: args.count as number }, (_, i) => {
const a = start + i;
return a >= at && a < at + msg.length ? msg.charCodeAt(a - at) : a & 0xff;
});
return { address: `0x${start.toString(16)}`, data, unreadableBytes: 0 };
};
const debugPath = "/src/features/debugger/state.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugPath);
adoptSession(id, { adapter: "gdb", name: "app-c", status: "paused", stops: 1, caps });
const dockPath = "/src/workbench/toolwindows/store.ts";
const layout = await import(/* @vite-ignore */ dockPath);
layout.moveToolWindow("debug", "bottom");
layout.setToolWindowSize("bottom", 360);
layout.showToolWindow("debug", true);
}, SESSION);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Memory View" }).click();
const field = debug.getByRole("textbox", { name: "Address or expression" });
await field.fill("&msg[0]");
await field.press("Enter");
const grid = debug.getByRole("grid", { name: "Memory", exact: true });
await expect(grid.getByRole("rowheader", { name: "0x00007FFFFFFF9F60" })).toBeVisible();
expect(await ipcCalls(page, "debug_read_memory")).toEqual([
{ session: SESSION, memoryReference: "0x7fffffff9f69", offset: -9, count: 256 },
]);
// Monospaced columns: each row's hex and ASCII start where the row above starts them.
const rows = grid.getByRole("row");
const left = async (row: number, cell: number) =>
(await rows.nth(row).getByRole("gridcell").nth(cell).boundingBox())!.x;
for (const cell of [0, 1]) expect(await left(2, cell)).toBeCloseTo(await left(1, cell), 0);
await expect(rows.nth(1).getByRole("gridcell").nth(1)).toHaveText("`abcdefghHello, ");
await expect(rows.nth(2).getByRole("gridcell").nth(1)).toHaveText(/^World!\.\./);
});
test("Disassembly shows the selected frame's instructions with the current one highlighted", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async (id) => {
// GDB 17.1's `disassemble /r sum` of a C program (#5922), stopped at `sum+78` on the loop line.
const SUM = 0x5555555551a7;
const code: [number, string, string][] = [
[62, "c745e000000000", "movl $0x0,-0x20(%rbp)"],
[69, "c745e400000000", "movl $0x0,-0x1c(%rbp)"],
[76, "eb26", "jmp 0x55555555521b <sum+116>"],
[78, "8b45e4", "mov -0x1c(%rbp),%eax"],
[81, "4898", "cltq"],
[83, "488d14c500000000", "lea 0x0(,%rax,8),%rdx"],
[91, "488b45d8", "mov -0x28(%rbp),%rax"],
[95, "4801d0", "add %rdx,%rax"],
[98, "488b00", "mov (%rax),%rax"],
[101, "4889c7", "mov %rax,%rdi"],
[104, "e875ffffff", "call 0x555555555189 <parse>"],
[109, "0145e0", "add %eax,-0x20(%rbp)"],
[112, "8345e401", "addl $0x1,-0x1c(%rbp)"],
[116, "8b45e4", "mov -0x1c(%rbp),%eax"],
[119, "3b45d4", "cmp -0x2c(%rbp),%eax"],
[122, "7cd2", "jl 0x5555555551f5 <sum+78>"],
[124, "8b45e0", "mov -0x20(%rbp),%eax"],
[127, "488b55f8", "mov -0x8(%rbp),%rdx"],
[131, "64482b142528000000", "sub %fs:0x28,%rdx"],
[140, "7405", "je 0x55555555523a <sum+147>"],
[142, "e836feffff", "call 0x555555555070 <__stack_chk_fail@plt>"],
[147, "c9", "leave"],
[148, "c3", "ret"],
];
const instructions = code.map(([offset, bytes, instruction]) => ({
address: `0x${(SUM + offset).toString(16)}`,
instruction,
bytes,
}));
const h = window.__ipc.handlers;
const caps = { disassemble: true, instructionStepping: true };
h.debug_capabilities = () => caps;
h.debug_disassemble = (args) => {
const at = instructions.findIndex((i) => BigInt(i.address) === BigInt(args.memoryReference as string));
const from = Math.max(0, at - (args.before as number));
return instructions.slice(from, from + (args.count as number));
};
h.debug_step_instruction = () => null;
const frame = (fid: number, name: string, line: number, pc: number) => ({
id: fid,
name,
path: "/proj/main.c",
line,
column: 0,
presentationHint: null,
instructionPointerReference: `0x${pc.toString(16)}`,
});
const debugPath = "/src/features/debugger/state.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugPath);
adoptSession(id, {
adapter: "gdb",
name: "app-c",
status: "paused",
stops: 1,
caps,
stoppedThread: 1,
selectedThread: 1,
threads: [{ id: 1, name: "main" }],
frames: [frame(0, "sum", 13, SUM + 78), frame(1, "run", 20, SUM + 109)],
selectedFrame: 0,
});
const dockPath = "/src/workbench/toolwindows/store.ts";
const layout = await import(/* @vite-ignore */ dockPath);
layout.moveToolWindow("debug", "bottom");
layout.setToolWindowSize("bottom", 360);
layout.showToolWindow("debug", true);
}, SESSION);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Disassembly" }).click();
const grid = debug.getByRole("grid", { name: "Disassembly" });
const current = grid.locator("[aria-current=location]");
await expect(current.getByRole("rowheader")).toHaveText("0x00005555555551F5");
await expect(current.getByRole("gridcell").nth(0)).toHaveText("8B 45 E4");
await expect(current.getByRole("gridcell").nth(1)).toHaveText("mov -0x1c(%rbp),%eax");
expect(await ipcCalls(page, "debug_disassemble")).toEqual([
{ session: SESSION, memoryReference: "0x5555555551f5", before: 32, count: 128 },
]);
// Monospaced columns: every row's instruction starts where the row above starts it.
const rows = grid.getByRole("row");
const left = async (row: number) => (await rows.nth(row).getByRole("gridcell").nth(1).boundingBox())!.x;
expect(await left(5)).toBeCloseTo(await left(4), 0);
await debug.getByRole("button", { name: "Step Over Instruction" }).click();
expect(await ipcCalls(page, "debug_step_instruction")).toEqual([{ session: SESSION, threadId: 1, kind: "over" }]);
// An adapter that cannot step by instruction: the button is disabled and its tooltip says why.
await page.evaluate(async (id) => {
const debugPath = "/src/features/debugger/state.ts";
const { useDebug } = await import(/* @vite-ignore */ debugPath);
useDebug.setState((st: { sessions: Record<number, object> }) => ({
sessions: {
...st.sessions,
[id]: { ...st.sessions[id], status: "paused", caps: { disassemble: true, instructionStepping: false } },
},
}));
}, SESSION);
const stepInto = debug.getByRole("button", { name: "Step Into Instruction" });
await expect(stepInto).toBeDisabled();
await stepInto.hover({ force: true });
await expect(page.getByRole("tooltip")).toContainText("Instruction stepping is not supported by gdb");
});
test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => {
await page.setViewportSize({ width: 580, height: 420 });
await stubDesktop(page);
+114
Переглянути файл
@@ -0,0 +1,114 @@
import type { DataSource_Deserialize } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("opens an existing DuckLake and creates a new one only after confirmation through mocked desktop IPC", async ({
workbench: page,
}, info) => {
const driverId = "duckdb-fixture";
const catalogFile = "/demo/sales/catalog.ducklake";
const dataPath = "/demo/sales/parquet";
const newDirectory = "/demo/new-lake";
await stubDesktop(page);
await page.evaluate(
async ({ driverId, newDirectory }) => {
let sources: DataSource_Deserialize[] = [];
Object.assign(window.__ipc.handlers, {
db_sources: () => sources,
db_connected: () => [],
db_jdbc_drivers: () => [
{
id: driverId,
vendor: "duckdb",
name: "DuckDB JDBC",
className: "org.duckdb.DuckDBDriver",
jars: ["/mock/duckdb_jdbc.jar"],
urlTemplate: "jdbc:duckdb:{file}",
},
],
file_dialog_needs_gtk: () => false,
"plugin:dialog|save": () => newDirectory,
db_test: () => "DuckDB 2.0.1 (mock)",
db_approve_ducklake_source: () => null,
db_set_password: () => null,
db_save_sources: ({ sources: next }: { sources: DataSource_Deserialize[] }) => {
sources = next;
return null;
},
db_create_ducklake: () => null,
});
const path = "/src/features/database/store.ts";
(await import(/* @vite-ignore */ path)).openSourceDialog(null);
},
{ driverId, newDirectory },
);
const draft = page.getByRole("dialog", { name: "New Data Source", exact: true });
await draft.getByRole("button", { name: "Data source type", exact: true }).click();
await page.getByRole("option", { name: "DuckDB", exact: true }).click();
await expect(draft.getByRole("button", { name: "Connection driver" })).toHaveText("DuckDB JDBC");
await draft.getByLabel("Name:", { exact: true }).fill("Sales Lake");
await draft.getByRole("button", { name: "DuckLake", exact: true }).click();
await draft.getByLabel("Catalog file:", { exact: true }).fill(catalogFile);
await draft.getByLabel("Data directory:", { exact: true }).fill(dataPath);
await expect(draft.locator("#db-url")).toHaveCount(0);
await draft.getByRole("tab", { name: "Options", exact: true }).click();
const readOnly = draft.getByRole("checkbox", { name: "Read-only", exact: true });
await expect(readOnly).toBeChecked();
await expect(readOnly).toBeDisabled();
await draft.getByRole("tab", { name: "General", exact: true }).click();
await draft.getByRole("button", { name: "Test Connection", exact: true }).click();
await expect(draft.getByRole("status")).toHaveText("Succeeded: DuckDB 2.0.1 (mock)");
const connection = {
name: "Sales Lake",
driver: "jdbc",
vendor: "duckdb",
jdbcDriver: driverId,
url: "jdbc:duckdb:",
readOnly: true,
savePassword: false,
properties: [],
duckLake: { kind: "file", value: catalogFile, dataPath },
};
expect(await ipcCalls(page, "db_test")).toEqual([
expect.objectContaining({ password: null, sshSecret: null, source: expect.objectContaining(connection) }),
]);
expect(await ipcCalls(page, "db_create_ducklake")).toHaveLength(0);
await draft.screenshot({ path: info.outputPath("ducklake-existing.png"), animations: "disabled" });
await draft.getByRole("button", { name: "OK", exact: true }).click();
await expect(draft).not.toBeVisible();
expect(await ipcCalls(page, "db_approve_ducklake_source")).toEqual([{ source: expect.objectContaining(connection) }]);
expect(await ipcCalls(page, "db_approve_jdbc_source")).toHaveLength(0);
expect(await ipcCalls(page, "db_save_sources")).toEqual([{ sources: [expect.objectContaining(connection)] }]);
await page.evaluate(async () => {
const path = "/src/features/database/store.ts";
const { openSourceDialog, useDatabase } = await import(/* @vite-ignore */ path);
openSourceDialog(useDatabase.getState().sources[0]);
});
const reopened = page.getByRole("dialog", { name: "Data Source: Sales Lake", exact: true });
const file = reopened.getByLabel("Catalog file:", { exact: true });
await expect(file).toHaveValue(catalogFile);
await expect(reopened.getByLabel("Data directory:", { exact: true })).toHaveValue(dataPath);
const create = reopened.getByRole("button", { name: "Create New DuckLake…", exact: true });
const confirmation = page.getByRole("dialog", { name: "Create New DuckLake", exact: true });
await create.click();
await expect(confirmation).toContainText(newDirectory);
await expect(confirmation).toContainText("The directory must not already exist.");
expect(await ipcCalls(page, "db_create_ducklake")).toHaveLength(0);
await confirmation.screenshot({ path: info.outputPath("ducklake-create-confirmation.png"), animations: "disabled" });
await confirmation.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(confirmation).not.toBeVisible();
await expect(file).toHaveValue(catalogFile);
expect(await ipcCalls(page, "db_create_ducklake")).toHaveLength(0);
await create.click();
await confirmation.getByRole("button", { name: "Create", exact: true }).click();
await expect(reopened.getByRole("status")).toHaveText("DuckLake created. The data source opens it read-only.");
await expect(file).toHaveValue(newDirectory + "/catalog.ducklake");
await expect(reopened.getByLabel("Data directory:", { exact: true })).toHaveValue("");
expect(await ipcCalls(page, "db_create_ducklake")).toEqual([{ jdbcDriver: driverId, directory: newDirectory }]);
expect(await ipcCalls(page, "db_save_sources")).toHaveLength(1);
expect(await ipcCalls(page, "db_test")).toHaveLength(1);
await reopened.screenshot({ path: info.outputPath("ducklake-created.png"), animations: "disabled" });
});
+34
Переглянути файл
@@ -967,6 +967,40 @@ test("visible Markdown reflows during a tool window drag and distant blocks catc
await expect.poll(() => width(far)).toBe(await width(near));
});
test("Cut Line Backward cuts from the previous line start to the primary caret", async ({ workbench: page }) => {
const path = "/dev/acme-api/cut-backward.ts";
await page.evaluate(async (filePath) => {
const backendModule = "/src/editor/core/backend.ts";
const servicesModule = "/src/workbench/contributions.ts";
const [{ docBackend }, { editorService }] = await Promise.all([
import(/* @vite-ignore */ backendModule),
import(/* @vite-ignore */ servicesModule),
]);
docBackend().files.set(filePath, "first\nsecond\nthird");
await editorService().openFile(filePath);
}, path);
const editor = page.locator('.cm-editor[data-language="TypeScript"]').last();
await expect(editor.locator(".cm-content")).toBeVisible();
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
const content = document.querySelector(".cm-editor .cm-content") as HTMLElement & {
cmTile: { view: { dispatch: (transaction: object) => void; focus: () => void } };
};
content.cmTile.view.dispatch({ selection: { anchor: 15 } });
content.cmTile.view.focus();
await executeAction("code.cutLineBackward");
});
await expect(editor.locator(".cm-line")).toHaveText(["first", "ird"]);
const history = await page.evaluate(async () => {
const historyModule = "/src/editor/core/clipboardHistory.ts";
const { clipboardHistory } = await import(/* @vite-ignore */ historyModule);
return clipboardHistory().map((entry: { text: string }) => entry.text);
});
expect(history[0]).toBe("second\nth");
});
test("visible Markdown reflows during a drag even when the viewport observer has not marked it", async ({
workbench: page,
}) => {
+37
Переглянути файл
@@ -201,3 +201,40 @@ test("File Structure prefers matches inside the caret symbol", async ({ workbenc
await expect(tree.getByRole("treeitem", { name: "loadChild", selected: true })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "load", exact: true })).toHaveAttribute("aria-selected", "false");
});
test("F4 jumps to the filtered File Structure symbol", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(async () => {
const range = { start: { line: 6, col: 4 }, end: { line: 6, col: 13 } };
window.__ipc.handlers.doc_outline = () => [
{
name: "separate",
kind: "method",
range,
selection_range: range,
children: [],
},
];
window.__ipc.handlers.lsp_type_hierarchy = () => [];
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("navigate.fileStructure");
});
const dialog = page.getByRole("dialog", { name: "File Structure" });
const filter = dialog.getByRole("textbox", { name: "Filter symbols" });
await filter.fill("separate");
await expect(dialog.getByRole("treeitem", { name: "separate", selected: true })).toBeVisible();
await filter.press("F4");
await expect(dialog).toBeHidden();
await expect
.poll(async () =>
page.evaluate(async () => {
const path = "/src/features/search/common/tracking.ts";
const { useTracking } = await import(/* @vite-ignore */ path);
return useTracking.getState().caret;
}),
)
.toMatchObject({ line: 6, col: 4 });
});
+27
Переглянути файл
@@ -92,4 +92,31 @@ test("file history puts commit details below the revisions and keeps directory h
await expect(earlier).toHaveAttribute("aria-selected", "true");
await expect.poll(async () => (await revisions.boundingBox())!.height).toBeCloseTo(resized, 0);
await expect(details).toContainText("Add the weekly total");
await page.evaluate(async () => {
const servicesModule = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ servicesModule);
const service = editorService();
service.openFile = async (path: string) => {
(window as unknown as { __revisionOpen: string }).__revisionOpen = path;
return null;
};
});
const changedFile = page.getByRole("tree", { name: "Changed files" }).getByRole("treeitem", {
name: "build.gradle.kts",
});
await changedFile.click({ button: "right" });
const openRevision = page.getByRole("menuitem", { name: "Open Repository Version" });
await expect(openRevision).toBeEnabled();
await openRevision.click();
await expect
.poll(async () =>
page.evaluate(async () => {
const virtualDocsModule = "/src/platform/virtualDocs.ts";
const { gitRevisionOf } = await import(/* @vite-ignore */ virtualDocsModule);
const uri = (window as unknown as { __revisionOpen?: string }).__revisionOpen;
return uri ? gitRevisionOf(uri) : null;
}),
)
.toEqual({ repo: "/dev/acme-api", revision: "2".padStart(40, "0"), path: "build.gradle.kts" });
});
+21
Переглянути файл
@@ -415,3 +415,24 @@ test("multiline symbol names stay inside their Search Everywhere row", async ({
expect(label!.y + label!.height).toBeLessThanOrEqual(bounds!.y + bounds!.height);
}
});
test("previewable Search Everywhere results inspect on single click and open on double click", async ({
workbench: page,
}) => {
const dialog = await searchFiles(page);
const first = dialog.getByRole("option").first();
await first.click();
await expect(dialog).toBeVisible();
await expect(dialog.getByRole("region", { name: "Preview", exact: true })).toBeVisible();
await first.dblclick();
await expect(dialog).toBeHidden();
});
test("Search Everywhere opens a previewable result on single click when preview is off", async ({
workbench: page,
}) => {
const dialog = await searchFiles(page);
await dialog.getByRole("button", { name: "Preview", exact: true }).click();
await dialog.getByRole("option").first().click();
await expect(dialog).toBeHidden();
});
+16 -1
Переглянути файл
@@ -1,6 +1,6 @@
import type { EditorView } from "@codemirror/view";
import type { Locator } from "@playwright/test";
import { expect, test } from "./fixtures";
import { expect, stubDesktop, stubSettingsWrites, test } from "./fixtures";
function codeStart(line: Locator) {
return line.evaluate((element) => {
@@ -19,6 +19,8 @@ function codeStart(line: Locator) {
}
test("Sticky Lines follows editor text, line numbers and the viewport below Find", async ({ workbench: page }) => {
await stubDesktop(page);
await stubSettingsWrites(page);
await page.setViewportSize({ width: 1200, height: 760 });
const header = "for (const value of entries)";
const path = "/dev/acme-api/sticky-layout.ts";
@@ -126,4 +128,17 @@ test("Sticky Lines follows editor text, line numbers and the viewport below Find
await find.press("Escape");
await pinned.locator(".cm-openidea-stickyText").click({ position: { x: 32, y: 4 } });
await expect(content.locator(".cm-activeLine")).toContainText(header);
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("editor.disableStickyLinesForLanguage");
});
await expect(sticky).toHaveCount(0);
const disabled = await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
return useProject.getState().settings?.editor?.codeEditing?.stickyLinesDisabledLanguages;
});
expect(disabled).toContain("typescript");
});
+35
Переглянути файл
@@ -118,6 +118,41 @@ for (const { width, split } of [{ width: 220 }, { width: 280 }, { width: 520 },
});
}
test("Paste on right click pastes on a plain right-click and keeps the menu on Shift+right-click", async ({
workbench: page,
}) => {
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
await page.evaluate(async () => {
const layout = await import("/src/workbench/toolwindows/store.ts" as string);
layout.showToolWindow("terminal", true);
});
const output = terminal.getByRole("tabpanel").locator(".xterm");
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
await page.evaluate(async () => {
const { useProject } = await import("/src/platform/project.ts" as string);
const settings = useProject.getState().settings ?? {};
useProject.setState({
settings: { ...settings, terminal: { ...settings.terminal, rightClickPaste: true } },
});
const { activeSession } = await import("/src/features/terminal/store.ts" as string);
const session = activeSession();
const w = window as unknown as { __pastes: number };
w.__pastes = 0;
session.pasteClipboard = () => {
w.__pastes += 1;
return Promise.resolve();
};
});
const menu = page.getByRole("menu", { name: "Context menu" });
await output.click({ button: "right", position: { x: 25, y: 50 } });
await expect.poll(() => page.evaluate(() => (window as unknown as { __pastes: number }).__pastes)).toBe(1);
await expect(menu).toBeHidden();
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
await output.click({ button: "right", modifiers: ["Shift"], position: { x: 25, y: 50 } });
await expect(menu.getByRole("menuitem", { name: /^Paste/ })).toBeVisible();
expect(await page.evaluate(() => (window as unknown as { __pastes: number }).__pastes)).toBe(1);
});
test("wide terminal search leaves the grid in place and avoids covering the active match", async ({
workbench: page,
}) => {
Бінарний файл не відображається.
+25 -10
Переглянути файл
@@ -26,10 +26,12 @@ final class MultiplexBridge {
private final ConcurrentMap<Integer, Session> sessions = new ConcurrentHashMap<>();
// Closing drivers still count towards the cap until their Connection.close returns.
private final Set<Session> live = ConcurrentHashMap.newKeySet();
private record Settings(List<String> parameters, boolean duckLake) {}
// Reserve before large writes and encodings, not while JDBC executes. This keeps
// frame copies and encoding temporaries within the 192 MiB JVM's headroom.
private final Semaphore largeReplies = new Semaphore(1, true);
private volatile List<String> settings;
private volatile Settings settings;
private final AtomicBoolean stopping = new AtomicBoolean();
MultiplexBridge(DataInputStream input, DataOutputStream output) {
@@ -97,8 +99,9 @@ final class MultiplexBridge {
session.canceller.shutdown();
}
private Connection connect(List<String> options) throws Exception {
if (!options.get(0).equals("org.duckdb.DuckDBDriver")) return OpenIdeaJdbc.connect(options);
private Connection connect(Settings options) throws Exception {
if (!options.parameters().get(0).equals(OpenIdeaJdbc.DUCKDB_CLASS))
return OpenIdeaJdbc.connect(options.parameters());
// A second DuckDB login would create a different unnamed in-memory database.
// Call duplicate on the service worker so it never races another operation
// on the same JDBC Connection.
@@ -106,7 +109,18 @@ final class MultiplexBridge {
if (service == null) throw new SQLException("The DuckDB service connection is unavailable");
return service.worker.submit(() -> {
Connection source = service.jdbc.connection;
return (Connection) source.getClass().getMethod("duplicate").invoke(source);
Connection duplicate = (Connection) source.getClass().getMethod("duplicate").invoke(source);
// Attachments are shared by DuckDB, but the current catalog is connection-local.
if (options.duckLake()) {
try (var statement = duplicate.createStatement()) {
statement.execute("USE " + OpenIdeaJdbc.DUCKLAKE_CATALOG);
} catch (SQLException failure) {
try { duplicate.close(); }
catch (SQLException closeFailure) { failure.addSuppressed(closeFailure); }
throw failure;
}
}
return duplicate;
}).get();
}
@@ -124,12 +138,13 @@ final class MultiplexBridge {
return;
}
boolean open = op.equals("open");
List<String> options = settings;
boolean duckLake = op.equals("openDuckLake");
boolean open = op.equals("open") || duckLake;
Settings options = settings;
if (open) {
boolean valid = connection == SERVICE
? fields.size() >= 6 && fields.size() % 2 == 0
: fields.size() == 1 && options != null;
? (duckLake ? fields.size() == 9 : fields.size() >= 6 && fields.size() % 2 == 0)
: !duckLake && fields.size() == 1 && options != null;
if (!valid || session != null) {
send(id, status("Invalid JDBC connection open request"));
return;
@@ -138,7 +153,7 @@ final class MultiplexBridge {
send(id, status("JDBC connection limit reached. Close a console or wait for its connection to finish closing, then try again."));
return;
}
if (connection == SERVICE) options = List.copyOf(fields.subList(1, fields.size()));
if (connection == SERVICE) options = new Settings(List.copyOf(fields.subList(1, fields.size())), duckLake);
session = new Session(connection);
sessions.put(connection, session);
live.add(session);
@@ -161,7 +176,7 @@ final class MultiplexBridge {
}
private void schedule(Session session, OpenIdeaJdbc.Work work, List<String> fields,
boolean open, List<String> options) {
boolean open, Settings options) {
session.worker.execute(() -> {
try (var buffer = new ReplyBuffer(largeReplies)) {
var answer = session.jdbc.reply(work, fields,
+148 -6
Переглянути файл
@@ -4,6 +4,12 @@ package ai.openidea.jdbc;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
@@ -11,6 +17,9 @@ import java.util.concurrent.atomic.AtomicReference;
public final class OpenIdeaJdbc {
static final int LIMIT = 16 * 1024 * 1024;
static final String DUCKDB_CLASS = "org.duckdb.DuckDBDriver";
private static final String DUCKDB_MEMORY = "jdbc:duckdb:";
static final String DUCKLAKE_CATALOG = "openidea_lake";
Connection connection;
boolean catalogs;
boolean namespaceKnown;
@@ -68,7 +77,7 @@ public final class OpenIdeaJdbc {
if (!a.get(2).isEmpty()) props.setProperty("user", a.get(2));
if (!a.get(3).isEmpty()) props.setProperty("password", a.get(3));
boolean readOnly = Boolean.parseBoolean(a.get(4));
boolean duckDbReadOnly = readOnly && className.equals("org.duckdb.DuckDBDriver") && url.startsWith("jdbc:duckdb:");
boolean duckDbReadOnly = readOnly && className.equals(DUCKDB_CLASS) && url.startsWith(DUCKDB_MEMORY);
if (duckDbReadOnly) {
// DuckDB fixes its access mode at open, and options in the URL take precedence.
for (String key : props.stringPropertyNames()) checkDuckDbReadOnly(key, props.getProperty(key));
@@ -104,9 +113,7 @@ public final class OpenIdeaJdbc {
private void open(List<String> args, DataOutputStream out, OpenConnection opener) throws Exception {
Connection opened = opener.open(args);
try {
var m = opened.getMetaData();
header(out, "version", "quote");
row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString());
openMetadata(opened, out);
connection = opened;
} catch (Exception | LinkageError failure) {
try { opened.close(); } catch (SQLException ignored) {}
@@ -118,6 +125,138 @@ public final class OpenIdeaJdbc {
if (connection != null) connection.close();
}
private static void openMetadata(Connection connection, DataOutputStream out) throws SQLException, IOException {
var m = connection.getMetaData();
header(out, "version", "quote");
row(out, m.getDatabaseProductName() + " " + m.getDatabaseProductVersion(), m.getIdentifierQuoteString());
}
private static class DuckLakeUnavailable extends SQLException {
DuckLakeUnavailable(String message) { super(message); }
}
private static Path absoluteLakePath(String value) throws DuckLakeUnavailable {
try {
Path path = Path.of(value);
if (path.isAbsolute()) return path;
} catch (InvalidPathException ignored) {}
throw new DuckLakeUnavailable("DuckLake requires an absolute local path on the database host.");
}
private static BasicFileAttributes lakePathAttributes(Path path, String description) throws DuckLakeUnavailable {
try {
return Files.readAttributes(path, BasicFileAttributes.class);
} catch (NoSuchFileException ignored) {
throw new DuckLakeUnavailable("The DuckLake " + description + " does not exist on the database host.");
} catch (IOException | SecurityException ignored) {
throw new DuckLakeUnavailable("The DuckLake " + description + " could not be accessed on the database host. Check permissions.");
}
}
private static String sqlLiteral(String value) {
return "'" + value.replace("'", "''") + "'";
}
void openDuckLake(Work work, List<String> a, DataOutputStream out) throws Exception {
if (a.size() != 8 || !a.get(0).equals(DUCKDB_CLASS) || !a.get(1).equals(DUCKDB_MEMORY)
|| !a.get(2).isEmpty() || !a.get(3).isEmpty())
throw new DuckLakeUnavailable("DuckLake requires a standard DuckDB connection without JDBC overrides.");
if (connection != null)
throw new DuckLakeUnavailable("DuckLake requires a new JDBC session.");
String mode = a.get(5), value = a.get(6), dataPath = a.get(7);
boolean create = mode.equals("create"), secret = mode.equals("secret");
boolean readOnly = !create;
if (!create && !secret && !mode.equals("file"))
throw new DuckLakeUnavailable("Choose to open a DuckLake file or secret, or create a new DuckLake.");
if (!a.get(4).equals(Boolean.toString(readOnly)))
throw new DuckLakeUnavailable("Existing DuckLake catalogs must be opened read-only, and creation uses a separate session.");
if (create && !dataPath.isEmpty())
throw new DuckLakeUnavailable("New DuckLake catalogs use their default data location.");
Path catalog = null;
if (secret) {
if (!value.matches("[A-Za-z_][A-Za-z0-9_]*"))
throw new DuckLakeUnavailable("Enter an existing DuckLake secret name using letters, digits or underscores.");
} else {
catalog = absoluteLakePath(value);
if (!create && !lakePathAttributes(catalog, "catalog file").isRegularFile())
throw new DuckLakeUnavailable("Choose a regular DuckLake catalog file on the database host.");
}
if (!dataPath.isEmpty() && !lakePathAttributes(absoluteLakePath(dataPath), "data directory").isDirectory())
throw new DuckLakeUnavailable("Choose a DuckLake data directory on the database host.");
Driver driver = Class.forName(DUCKDB_CLASS).asSubclass(Driver.class).getConstructor().newInstance();
Connection session = driver.connect(DUCKDB_MEMORY, new Properties());
if (session == null) throw new UnsupportedUrl();
boolean directoryCreated = false;
String recovery = " If the directory contains catalog.ducklake, try opening it. Otherwise choose a new directory.";
String failure = "DuckLake could not load the official extension. Check the DuckDB version and extension access.";
try {
try (Statement st = session.createStatement()) {
work.begin(st);
st.execute("INSTALL ducklake FROM core");
st.execute("LOAD ducklake");
if (secret) {
failure = "DuckLake could not resolve the named secret on the database host.";
try (var lookup = session.prepareStatement(
"SELECT 1 FROM duckdb_secrets() WHERE name = ? AND type = 'ducklake'")) {
work.begin(lookup);
lookup.setString(1, value);
try (var matches = lookup.executeQuery()) {
if (!matches.next())
throw new DuckLakeUnavailable("The named DuckLake secret was not found on the database host.");
}
}
work.begin(st);
}
if (create) {
failure = "DuckLake could not create the new directory. Check its parent and permissions.";
try {
Files.createDirectory(catalog);
} catch (FileAlreadyExistsException ignored) {
throw new DuckLakeUnavailable("The DuckLake directory already exists." + recovery);
}
directoryCreated = true;
catalog = catalog.resolve("catalog.ducklake");
work.begin(st);
}
failure = create ? "DuckLake could not initialize the new catalog. Check the new directory."
: "DuckLake could not open the catalog read-only. Check its metadata and data access.";
String location = secret ? value : catalog.toString();
String options = create ? "CREATE_IF_NOT_EXISTS true" : "READ_ONLY, CREATE_IF_NOT_EXISTS false";
if (!dataPath.isEmpty()) options += ", DATA_PATH " + sqlLiteral(dataPath) + ", OVERRIDE_DATA_PATH true";
st.execute("ATTACH " + sqlLiteral("ducklake:" + location) + " AS " + DUCKLAKE_CATALOG
+ " (" + options + ", AUTOMATIC_MIGRATION false)");
st.execute("USE " + DUCKLAKE_CATALOG);
try (var db = st.executeQuery("SELECT readonly FROM duckdb_databases() WHERE database_name = '"
+ DUCKLAKE_CATALOG + "' AND database_name = current_database() AND type = 'ducklake'")) {
if (!db.next() || db.getBoolean(1) != readOnly) throw new DuckLakeUnavailable(failure);
}
work.begin(st);
}
openMetadata(session, out);
// Only a read-only session is published for later requests.
if (create) {
failure = "DuckLake could not finish creating the catalog. Check the new directory.";
session.close();
} else {
connection = session;
}
} catch (Exception | LinkageError e) {
String message = work.isCancelled() ? (create ? "DuckLake creation cancelled." : "DuckLake connection cancelled.")
: e instanceof DuckLakeUnavailable ? e.getMessage() : failure;
if (directoryCreated) message += " The new directory was kept." + recovery;
throw new DuckLakeUnavailable(message);
} finally {
if (connection != session) {
try { session.close(); } catch (SQLException ignored) {}
}
}
}
static String pattern(DatabaseMetaData m, String literal) throws SQLException {
String escape = m.getSearchStringEscape();
if (escape == null || escape.isEmpty()) return literal;
@@ -290,6 +429,8 @@ public final class OpenIdeaJdbc {
statement = st;
}
synchronized boolean isCancelled() { return cancelled; }
void cancel() {
Statement st;
synchronized (this) {
@@ -340,6 +481,7 @@ public final class OpenIdeaJdbc {
reply.writeBoolean(true);
switch (op) {
case "open" -> open(a, reply, opener);
case "openDuckLake" -> openDuckLake(work, a, reply);
case "catalogs" -> catalogs(reply);
case "schemas" -> schemas(a.isEmpty() ? null : a.get(0), reply);
case "tables", "columns", "schemaColumns" -> metadata(op, a, reply);
@@ -404,11 +546,11 @@ public final class OpenIdeaJdbc {
if ((e instanceof ClassNotFoundException || e instanceof NoClassDefFoundError)
&& e.getMessage() != null && e.getMessage().matches("[A-Za-z0-9_.$/]+")) {
text(reply, "JDBC class " + e.getMessage() + " was not found. Check the driver class and include its dependency JARs.");
} else if (e instanceof ReadOnlyUnavailable) {
} else if (e instanceof ReadOnlyUnavailable || e instanceof DuckLakeUnavailable) {
text(reply, e.getMessage());
} else if (e instanceof UnsupportedUrl) {
text(reply, "The selected JDBC driver does not accept this URL");
} else if (op.equals("open")) {
} else if (op.equals("open") || op.equals("openDuckLake")) {
// Login exceptions may contain properties or credentials embedded in a vendor URL.
String state = e instanceof SQLException ? ((SQLException)e).getSQLState() : null;
text(reply, "JDBC connection failed (" + e.getClass().getSimpleName()
+38
Переглянути файл
@@ -185,6 +185,17 @@ public class SelfTest {
return bytes;
}
static void rejectedLake(DataOutputStream out, DataInputStream in, int connection, String expected, String... fields)
throws IOException {
sendOn(out, 40, connection, fields);
try (var response = new DataInputStream(new ByteArrayInputStream(expect(in, 40, 0).data()))) {
assert !response.readBoolean();
String message = new String(response.readNBytes(response.readInt()), StandardCharsets.UTF_8);
assert message.contains(expected) : message;
assert !message.contains("private-token") : message;
}
}
static void sendOn(DataOutputStream out, long id, int connection, String... fields) throws IOException {
out.writeLong(id);
out.writeInt(connection);
@@ -227,6 +238,33 @@ public class SelfTest {
try (var out = new DataOutputStream(child.getOutputStream());
var in = new DataInputStream(child.getInputStream());
var log = child.errorReader()) {
String duckdb = "org.duckdb.DuckDBDriver", memory = "jdbc:duckdb:";
rejectedLake(out, in, 0, "standard DuckDB connection", "openDuckLake", Fixture.class.getName(), memory,
"", "", "true", "secret", "sample", "");
rejectedLake(out, in, 0, "standard DuckDB connection", "openDuckLake", duckdb, memory + ";private-token",
"", "", "true", "secret", "sample", "");
rejectedLake(out, in, 0, "standard DuckDB connection", "openDuckLake", duckdb, memory,
"", "private-token", "true", "secret", "sample", "");
rejectedLake(out, in, 0, "Invalid JDBC connection open request", "openDuckLake", duckdb, memory,
"", "", "true", "secret", "sample", "", "arbitrary");
rejectedLake(out, in, 1, "Invalid JDBC connection open request", "openDuckLake", duckdb, memory,
"", "", "true", "secret", "sample", "");
rejectedLake(out, in, 0, "read-only", "openDuckLake", duckdb, memory,
"", "", "false", "file", "unused", "");
rejectedLake(out, in, 0, "absolute", "openDuckLake", duckdb, memory,
"", "", "true", "file", "relative/catalog.ducklake", "");
Path temp = Path.of(System.getProperty("java.io.tmpdir")).toAbsolutePath();
rejectedLake(out, in, 0, "regular DuckLake catalog file", "openDuckLake", duckdb, memory,
"", "", "true", "file", temp.toString(), "");
rejectedLake(out, in, 0, "does not exist", "openDuckLake", duckdb, memory,
"", "", "true", "file", temp.resolve(UUID.randomUUID() + "-private-token").toString(), "");
rejectedLake(out, in, 0, "existing DuckLake secret name", "openDuckLake", duckdb, memory,
"", "", "true", "secret", "postgresql://user:private-token@localhost/catalog", "");
rejectedLake(out, in, 0, "absolute", "openDuckLake", duckdb, memory,
"", "", "true", "secret", "sample", "s3://bucket/path");
rejectedLake(out, in, 0, "default data location", "openDuckLake", duckdb, memory,
"", "", "false", "create", "unused", "nonempty");
sendOn(out, 100, 0, "open", Fixture.class.getName(), "jdbc:fixture:", "", "", "false");
try {
expect(in, 100, 1);
+7
Переглянути файл
@@ -387,6 +387,13 @@ pub(crate) fn project_current(window: Window) -> Option<ProjectInfo> {
state.project(window.label()).ok().filter(|p| !p.light).map(|p| project_info(&p))
}
// Off the IPC thread: Gradle source roots may walk the project for builds, slow on a network share.
pub(crate) fn project_roots(window: Window) -> IdeResult<ide_workspace::ProjectRoots> {
let state = window.state::<AppState>();
state.note_ipc();
ide_host::ops::project::project_roots(&state.host, window.label())
}
// Off the IPC thread: each member's `for_project().layer(Project)` re-parses both settings layers
// and validates the merge against the whole `Settings` type, which a debug build's stack-heavy
// recursion can overflow from the WebView2 callback (see the `settings_set` note above).
+1 -1
Переглянути файл
@@ -42,7 +42,7 @@ use std::sync::LazyLock;
// Desktop bodies of project-host commands (`#[command(desktop_body = …)]`), which their derived
// adapters call.
use app::{
close_project, open_project, project_current, project_trust_remove_location, project_trust_set,
close_project, open_project, project_current, project_roots, project_trust_remove_location, project_trust_set,
project_workspace_member_set, project_workspace_members, settings_get, settings_removed_theme, settings_set,
};
use doc::doc_edit;
+1
Переглянути файл
@@ -499,6 +499,7 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<
}
let home = dirs::home_dir();
let config = menu_state.config.lock().clone();
let spec = menu::without_hidden(spec, &config);
let remote = menu_state.remote_recent.lock().clone();
menu::model(&spec, &menu::recent_items(&state.recent.list(), &remote, home.as_deref()), &config)
}
+17 -2
Переглянути файл
@@ -309,7 +309,7 @@ pub fn build<R: Runtime>(
recent: &[RecentItem],
disabled: &HashSet<String>,
) -> tauri::Result<Menu<R>> {
build_rendered(app, &render_bar(&prepared_spec(app, os), config, recent), disabled)
build_rendered(app, &render_bar(&without_hidden(prepared_spec(app, os), config), config, recent), disabled)
}
fn build_rendered<R: Runtime>(
@@ -597,7 +597,7 @@ pub fn install<R: Runtime>(app: &AppHandle<R>, menu_state: &MenuState, recent: &
let items = recent_items(recent, &menu_state.remote_recent.lock(), home.as_deref());
let config = menu_state.config.lock().clone();
let disabled = menu_state.disabled.lock().clone();
let rendered = render_bar(&prepared_spec(app, Os::current()), &config, &items);
let rendered = render_bar(&without_hidden(prepared_spec(app, Os::current()), &config), &config, &items);
let mut slot = menu_state.rendered.lock();
if slot.as_ref() == Some(&rendered) {
return;
@@ -999,6 +999,21 @@ mod tests {
}
}
#[test]
fn hidden_submenus_and_actions_leave_the_menu() {
let config = MenuConfig { hidden: vec!["git".into(), "vcs.cloneProject".into()], ..MenuConfig::default() };
for os in ALL_OS {
let all = spec(os);
assert!(all.iter().any(|e| matches!(e, Entry::Submenu { id: "git", .. })));
let spec = without_hidden(all, &config);
assert!(!spec.iter().any(|e| matches!(e, Entry::Submenu { id: "git", .. })));
let ids = action_ids(&spec);
assert!(!ids.contains(&"vcs.commit") && !ids.contains(&"vcs.cloneProject"));
assert!(ids.contains(&"file.openProject"));
}
assert_eq!(action_ids(&without_hidden(spec(Os::Linux), &MenuConfig::default())), action_ids(&spec(Os::Linux)));
}
#[test]
fn action_ids_are_unique_per_menu_bar() {
for os in ALL_OS {
+8 -1
Переглянути файл
@@ -115,6 +115,7 @@ coverage_import always project_host bin
coverage_prepare trusted project_host bindings async
cucumber_sources trusted desktop bindings async
db_apply_edits trusted project_host bindings async
db_approve_ducklake_source trusted project_host bindings sync
db_approve_external_tunnel trusted desktop bindings async
db_approve_jdbc_source trusted project_host bindings sync
db_catalog_table_details trusted project_host bindings async
@@ -126,6 +127,7 @@ db_console_path always project_host bin
db_consoles always project_host bindings sync
db_consoles_dir always project_host bindings sync
db_create_database trusted project_host bindings async
db_create_ducklake trusted project_host bindings async
db_database_catalog trusted project_host bindings async
db_databases trusted project_host bindings async
db_ddl trusted project_host bindings async
@@ -177,11 +179,13 @@ db_tool_options trusted desktop bin
db_tool_preview trusted desktop bindings sync
db_tool_version trusted desktop bindings async
db_trust_ssh_host trusted project_host bindings async
db_workspace_join trusted project_host bindings async
debug_attachable_processes always project_host bindings async
debug_breakpoint_states trusted project_host bindings sync
debug_capabilities trusted project_host bindings sync
debug_completions trusted project_host bindings async
debug_data_breakpoint_info trusted project_host bindings async
debug_disassemble trusted project_host bindings async
debug_evaluate trusted project_host bindings async
debug_evaluate_in trusted project_host bindings async
debug_exception_filters trusted project_host bindings sync
@@ -209,6 +213,7 @@ debug_jvm_memory_referrers trusted project_host bin
debug_jvm_thread_dump trusted project_host bindings async
debug_listen_for_jvm trusted project_host bindings async
debug_pause trusted project_host bindings async
debug_read_memory trusted project_host bindings async
debug_redefine_classes trusted project_host bindings async
debug_replace_breakpoints trusted project_host bindings async
debug_resolve_variable trusted project_host bindings async
@@ -229,6 +234,7 @@ debug_start trusted project_host bin
debug_step trusted project_host bindings async
debug_step_in_target trusted project_host bindings async
debug_step_in_targets trusted project_host bindings async
debug_step_instruction trusted project_host bindings async
debug_stop always project_host bindings async
debug_stream_chains trusted project_host bindings async
debug_stream_trace trusted project_host bindings async
@@ -468,6 +474,7 @@ nav_pytest_fixture_rename always project_host bin
nav_pytest_fixture_target always project_host bindings async
nav_pytest_fixture_usages always project_host bindings async
nav_pytest_fixtures always project_host bindings async
nav_python_library_imports always project_host bindings async
nav_python_stubs always project_host bindings async
nav_resolve_module always project_host bindings async
notebook_cell_docs trusted project_host bindings sync
@@ -574,7 +581,7 @@ profiler_gc_before_stop trusted desktop bin
profiler_prepare trusted desktop bindings async
project_current always project_host bindings sync
project_rename always desktop bindings sync
project_roots always project_host bindings sync
project_roots always project_host bindings spawn
project_trust_add_location always desktop bindings async
project_trust_list always project_host bindings sync
project_trust_remove_location always project_host bindings async
+181 -4
Переглянути файл
@@ -374,6 +374,7 @@ export const commands = {
/** Cucumber feature files and step definition files, for step navigation. */
cucumberSources: () => typedError<StepSource[], IdeError>(__TAURI_INVOKE("cucumber_sources")),
dbApplyEdits: (id: string, schema: string, table: string, edits: DbRowEdit[]) => typedError<number | null, IdeError>(__TAURI_INVOKE("db_apply_edits", { id, schema, table, edits })),
dbApproveDucklakeSource: (source: DataSource_Deserialize) => typedError<null, IdeError>(__TAURI_INVOKE("db_approve_ducklake_source", { source })),
/** Records the exact helper and destination reviewed in the local data-source dialog. */
dbApproveExternalTunnel: (source: DataSource_Deserialize) => typedError<null, IdeError>(__TAURI_INVOKE("db_approve_external_tunnel", { source })),
dbApproveJdbcSource: (source: DataSource_Deserialize) => typedError<null, IdeError>(__TAURI_INVOKE("db_approve_jdbc_source", { source })),
@@ -388,6 +389,7 @@ export const commands = {
/** The project view root for every data source's query consoles (`<dataDir>/consoles/db`). */
dbConsolesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_consoles_dir")),
dbCreateDatabase: (id: string, template: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_create_database", { id, template, statement })),
dbCreateDucklake: (jdbcDriver: string, directory: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_create_ducklake", { jdbcDriver, directory })),
dbDatabaseCatalog: (id: string, database: string) => typedError<DbCatalogSchema[], IdeError>(__TAURI_INVOKE("db_database_catalog", { id, database })),
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
dbDdl: (id: string, schema: string, table: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_ddl", { id, schema, table })),
@@ -463,6 +465,7 @@ export const commands = {
/** The version line of the executable at `path`. */
dbToolVersion: (path: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_tool_version", { path })),
dbTrustSshHost: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_trust_ssh_host", { id })),
dbWorkspaceJoin: (request: RequestId, driver: string, plan: DbWorkspaceJoinPlan) => typedError<DbQueryResult, IdeError>(__TAURI_INVOKE("db_workspace_join", { request, driver, plan })),
/** Attach to Process: the user's processes a debugger can attach to. */
debugAttachableProcesses: () => typedError<AttachableProcess[], IdeError>(__TAURI_INVOKE("debug_attachable_processes")),
/** Last known verification states of a file's breakpoints (refetch on `breakpointsChanged`). */
@@ -471,6 +474,11 @@ export const commands = {
/** Completions for an expression typed in Evaluate (`line` / `column` 0-based, UTF-16). */
debugCompletions: (session: DebugSessionId, frameId: number | null, text: string, line: number, column: number) => typedError<DebugCompletion[], IdeError>(__TAURI_INVOKE("debug_completions", { session, frameId, text, line, column })),
debugDataBreakpointInfo: (session: DebugSessionId, container: number, name: string, frameId: number | null) => typedError<DataBreakpointInfo, IdeError>(__TAURI_INVOKE("debug_data_breakpoint_info", { session, container, name, frameId })),
/**
* Disassembly view: `count` instructions from `before` instructions ahead of `memory_reference`
* (a frame's instruction pointer or an instruction's address).
*/
debugDisassemble: (session: DebugSessionId, memoryReference: string, before: number, count: number) => typedError<Instruction_Serialize[], IdeError>(__TAURI_INVOKE("debug_disassemble", { session, memoryReference, before, count })),
debugEvaluate: (session: DebugSessionId, frameId: number | null, expression: string) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_evaluate", { session, frameId, expression })),
/** Evaluate with an explicit DAP context: `repl`, `watch`, `hover` or `clipboard`. */
debugEvaluateIn: (session: DebugSessionId, frameId: number | null, expression: string, context: string | null) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_evaluate_in", { session, frameId, expression, context })),
@@ -531,6 +539,11 @@ export const commands = {
*/
debugListenForJvm: (request: RequestId, host: string, port: number) => typedError<number, IdeError>(__TAURI_INVOKE("debug_listen_for_jvm", { request, host, port })),
debugPause: (session: DebugSessionId, threadId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_pause", { session, threadId })),
/**
* Memory View: `count` bytes from `offset` bytes after `memory_reference` (a variable's,
* an evaluation result's or an earlier read's address).
*/
debugReadMemory: (session: DebugSessionId, memoryReference: string, offset: number, count: number) => typedError<MemoryBlock, IdeError>(__TAURI_INVOKE("debug_read_memory", { session, memoryReference, offset, count })),
/** HotSwap (Reload Changed Classes) in a java-debug session. */
debugRedefineClasses: (session: DebugSessionId) => typedError<HotSwapResult, IdeError>(__TAURI_INVOKE("debug_redefine_classes", { session })),
/** Replaces all of this window's line breakpoints with `files`. */
@@ -555,21 +568,23 @@ export const commands = {
/** Method breakpoints (all files); states aligned with `breakpoints`. */
debugSetFunctionBreakpoints: (breakpoints: FunctionBreakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_function_breakpoints", { breakpoints })),
debugSetVariable: (session: DebugSessionId, container: number, name: string, evaluateName: string | null, frameId: number | null, value: string) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_set_variable", { session, container, name, evaluateName, frameId, value })),
debugStackTrace: (session: DebugSessionId, threadId: number) => typedError<StackFrame[], IdeError>(__TAURI_INVOKE("debug_stack_trace", { session, threadId })),
debugStackTrace: (session: DebugSessionId, threadId: number) => typedError<StackFrame_Serialize[], IdeError>(__TAURI_INVOKE("debug_stack_trace", { session, threadId })),
/** Starts a session owned by this window: its events (and those of child sessions) go here only. */
debugStart: (config: LaunchConfig) => typedError<DebugSessionId, IdeError>(__TAURI_INVOKE("debug_start", { config })),
debugStep: (session: DebugSessionId, threadId: number, kind: StepKind) => typedError<null, IdeError>(__TAURI_INVOKE("debug_step", { session, threadId, kind })),
debugStepInTarget: (session: DebugSessionId, threadId: number, targetId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_step_in_target", { session, threadId, targetId })),
/** Smart Step Into: the calls on the current line of `frame_id`. */
debugStepInTargets: (session: DebugSessionId, frameId: number) => typedError<StepInTarget[], IdeError>(__TAURI_INVOKE("debug_step_in_targets", { session, frameId })),
/** Step Over / Into Instruction: a step by one machine instruction. */
debugStepInstruction: (session: DebugSessionId, threadId: number, kind: StepKind) => typedError<null, IdeError>(__TAURI_INVOKE("debug_step_instruction", { session, threadId, kind })),
debugStop: (session: DebugSessionId) => typedError<null, IdeError>(__TAURI_INVOKE("debug_stop", { session })),
/** The stream chains around `frame`'s line; `top`: it is the thread's top frame. */
debugStreamChains: (session: DebugSessionId, frame: StackFrame, top: boolean) => typedError<StreamChainInfo_Serialize[], IdeError>(__TAURI_INVOKE("debug_stream_chains", { session, frame, top })),
debugStreamChains: (session: DebugSessionId, frame: StackFrame_Deserialize, top: boolean) => typedError<StreamChainInfo_Serialize[], IdeError>(__TAURI_INVOKE("debug_stream_chains", { session, frame, top })),
/**
* Traces chain `chain_index` of [`debug_stream_chains`], whose `range` the UI showed, while the
* program runs it; cancelling `request` stops recording.
*/
debugStreamTrace: (session: DebugSessionId, request: RequestId, threadId: number, frame: StackFrame, chainIndex: number, range: Range, onProgress: Channel<TraceProgress>) => typedError<StreamTraceResult_Serialize, IdeError>(__TAURI_INVOKE("debug_stream_trace", { session, request, threadId, frame, chainIndex, range, onProgress })),
debugStreamTrace: (session: DebugSessionId, request: RequestId, threadId: number, frame: StackFrame_Deserialize, chainIndex: number, range: Range, onProgress: Channel<TraceProgress>) => typedError<StreamTraceResult_Serialize, IdeError>(__TAURI_INVOKE("debug_stream_trace", { session, request, threadId, frame, chainIndex, range, onProgress })),
/** Ends the running trace's terminal operation; `None` when no trace runs. */
debugStreamTraceAbort: (session: DebugSessionId) => typedError<{ kind: "interrupted" } | { kind: "stopped" } |
/** Suspended threads that own a monitor the terminal may be waiting for: `(thread id, name)`. */
@@ -1302,6 +1317,14 @@ export const commands = {
* fixtures visible where a fixture name goes, for completion.
*/
navPytestFixtures: (doc: DocId, pos: Pos) => typedError<PytestFixtureAt, IdeError>(__TAURI_INVOKE("nav_pytest_fixtures", { doc, pos })),
/**
* Imports that bind `name` from the packages installed in the interpreter of the Python document
* `doc` (its workspace member's, else the project's): PyCharm's "Import this name" for library
* symbols, which basedpyright offers for the project and the standard library only. The first
* request indexes the interpreter's `site-packages` in the background, and a change there
* re-indexes it; a request waits for the index until cancelled.
*/
navPythonLibraryImports: (doc: DocId, name: string, request: RequestId) => typedError<PythonImportCandidate[], IdeError>(__TAURI_INVOKE("nav_python_library_imports", { doc, name, request })),
/**
* The stub (`.pyi`) of a Python document, or the implementation of a stub, and the
* functions and classes declared in both: PyCharm's stub gutter markers.
@@ -1603,6 +1626,7 @@ export const commands = {
/**
* Effective source / test / resource / excluded roots of the window's project:
* auto-detected from build files, overridden by Settings › Project Structure.
* Off the UI thread: Gradle source roots may walk the project for builds, slow on a share.
*/
projectRoots: () => typedError<ProjectRoots, IdeError>(__TAURI_INVOKE("project_roots")),
projectTrustAddLocation: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("project_trust_add_location", { path })),
@@ -5607,6 +5631,7 @@ export type DataSource_Deserialize = {
properties?: DbProperty[],
/** Snowflake settings (`None`: not a Snowflake data source, or all defaults). */
snowflake?: DbSnowflake | null,
duckLake?: DbDuckLake_Deserialize | null,
/**
* Stored app-wide and listed in every project. Implied by the file it is read from,
* so not written to it.
@@ -5654,6 +5679,7 @@ export type DataSource_Serialize = {
properties: DbProperty[],
/** Snowflake settings (`None`: not a Snowflake data source, or all defaults). */
snowflake: DbSnowflake | null,
duckLake?: DbDuckLake_Serialize | null,
/**
* Stored app-wide and listed in every project. Implied by the file it is read from,
* so not written to it.
@@ -5767,6 +5793,29 @@ export type DbDriver = "sqlite" | "postgres" |
/** Oracle Database (pure-Rust thin driver, no client library). */
"oracle" | "snowflake" | "jdbc";
/** How to open an existing DuckLake catalog read-only through DuckDB. */
export type DbDuckLake = DbDuckLake_Serialize | DbDuckLake_Deserialize;
export type DbDuckLakeKind = "file" | "secret";
/** How to open an existing DuckLake catalog read-only through DuckDB. */
export type DbDuckLake_Deserialize = {
kind: DbDuckLakeKind,
/** A local catalog file or an existing DuckDB secret name. */
value: string,
/** An existing local data directory overriding the catalog's data path. */
dataPath?: string | null,
};
/** How to open an existing DuckLake catalog read-only through DuckDB. */
export type DbDuckLake_Serialize = {
kind: DbDuckLakeKind,
/** A local catalog file or an existing DuckDB secret name. */
value: string,
/** An existing local data directory overriding the catalog's data path. */
dataPath?: string | null,
};
export type DbDumpContent = "all" | "schemaOnly" | "dataOnly";
export type DbDumpFormat =
@@ -5950,6 +5999,9 @@ export type DbPackageInfo = {
name: string,
};
/** Whether a table's changes are written to the write-ahead log, and whether it outlives the session. */
export type DbPersistence = "permanent" | "unlogged" | "temporary";
/** Name lists hold `pg_dump` patterns (`*`, `?`, quoted names). */
export type DbPgDumpOptions = {
format: DbDumpFormat,
@@ -6186,6 +6238,24 @@ export type DbTableDetails = {
indexes: DbIndexInfo[],
foreignKeys: DbForeignKey[],
triggers: DbTriggerInfo[],
/** The role owning the table (PostgreSQL); `None` where the schema owns its tables. */
owner?: string | null,
/** The table's tablespace, the database's default one when it names none (PostgreSQL). */
tablespace?: string | null,
/**
* The table access method (PostgreSQL's `heap`, …); `None` for a partitioned table, and on
* the engines without one.
*/
accessMethod?: string | null,
/**
* The storage parameters set on the table, as `(name, value)`: PostgreSQL's reloptions,
* its TOAST table's prefixed `toast.`. `None` on the engines without any.
*/
storageOptions?: ([string, string])[] | null,
/** The partition key (`RANGE (created)`); `None` when the table isn't partitioned. */
partitioning?: string | null,
/** Whether the table is logged, unlogged or temporary (PostgreSQL). */
persistence?: DbPersistence | null,
};
/**
@@ -6262,6 +6332,37 @@ export type DbTxMode = "auto" | "manual";
export type DbVisibilityChange = { kind: "databases"; selection: DbSchemaSelection } | { kind: "schemas"; selection: DbSchemaSelection } | { kind: "databaseSchemas"; database: string; selection: DbSchemaSelection | null };
export type DbWorkspaceJoinColumn = {
relation: number,
column: string,
};
export type DbWorkspaceJoinCondition = {
/** The right relation is the next table in the chain. */
left: DbWorkspaceJoinColumn,
rightColumn: string,
};
export type DbWorkspaceJoinPlan = {
tables: DbWorkspaceJoinRelation[],
joins: DbWorkspaceJoinCondition[],
/** None expands all relations in FROM/JOIN order. */
projection: DbWorkspaceJoinProjection[] | null,
};
export type DbWorkspaceJoinProjection = {
relation: number,
/** None expands this relation's columns in source order. */
column: string | null,
};
export type DbWorkspaceJoinRelation = {
sourceId: string,
database: string,
schema: string,
table: string,
};
/** What a session's adapter supports, for enabling actions. */
export type DebugCapabilities = {
restartFrame: boolean,
@@ -6299,6 +6400,12 @@ export type DebugCapabilities = {
* Can change during the session, like `jvm_instances`.
*/
streamTrace: boolean,
/** The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View. */
readMemory: boolean,
/** The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view. */
disassemble: boolean,
/** Steps can move by one instruction ([`DebugManager::step_instruction`]). */
instructionStepping: boolean,
};
/** A completion the adapter offers for an expression (DAP `completions`). */
@@ -8304,6 +8411,11 @@ export type GitOperation_Serialize =
export type GitSaveChangesPolicy = "shelve" | "stash";
export type GitSettings = {
/**
* Git integration on: off, the IDE finds no repositories and runs no git at all
* (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI.
*/
enabled?: boolean,
annotate?: GitAnnotateSettings,
/** Show blame after the current editor line. */
inlineBlame?: boolean,
@@ -9440,6 +9552,33 @@ export type InstalledIntellijTheme = {
active: boolean,
};
/** One disassembled instruction. */
export type Instruction = Instruction_Serialize | Instruction_Deserialize;
/** One disassembled instruction. */
export type Instruction_Deserialize = {
/** Address as the adapter writes it (`0x5555…`); also a memory reference for the next request. */
address: string,
/** The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`). */
instruction: string,
/** Its machine code as hex (`488b45d8`), when the adapter sends it. */
bytes?: string | null,
/** The function it belongs to, when the adapter names it (often on the first instruction only). */
symbol?: string | null,
};
/** One disassembled instruction. */
export type Instruction_Serialize = {
/** Address as the adapter writes it (`0x5555…`); also a memory reference for the next request. */
address: string,
/** The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`). */
instruction: string,
/** Its machine code as hex (`488b45d8`), when the adapter sends it. */
bytes?: string | null,
/** The function it belongs to, when the adapter names it (often on the first instruction only). */
symbol?: string | null,
};
export type IntellijThemeFile = {
/** The `themeProvider` id (what `laf.xml` names), or the file name without `.theme.json`. */
id: string,
@@ -10960,6 +11099,14 @@ export type McpTransport = "stdio" | "http" | "sse";
*/
export type McpUiRequest = { type: "confirm"; client: string; tool: string; subject: string; project: string; detail: string | null } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string } } | { type: "runConfiguration"; config: unknown };
/** Answer of `readMemory`: `data` starts at `address`; the `unreadable_bytes` after it could not be read. */
export type MemoryBlock = {
/** Address of the first byte, as the adapter writes it (`0x7ffd…`; may be wider than 53 bits). */
address: string,
data: number[],
unreadableBytes: number,
};
export type MemoryCategory =
/** The backend and its WebView processes. */
"app" | "languageServer" |
@@ -10980,6 +11127,8 @@ export type MenuConfig = {
dynamic?: { [key in string]: DynamicItem[] },
/** Ids of the toggle actions currently on. */
checked?: string[],
/** Ids of submenus and actions left out of the menu (the Git menu while Git integration is off). */
hidden?: string[],
};
/**
@@ -12761,6 +12910,12 @@ export type PythonFacts = {
suppressions: PythonSuppression[],
};
/** An import that binds a name: `from module import name`, or `import module` without `name`. */
export type PythonImportCandidate = {
module: string,
name: string | null,
};
/** A method definition the inspections can reason about. */
export type PythonMethodFacts = {
name: string,
@@ -14452,7 +14607,9 @@ export type SshSigningKey = {
inAgent: boolean,
};
export type StackFrame = {
export type StackFrame = StackFrame_Serialize | StackFrame_Deserialize;
export type StackFrame_Deserialize = {
id: number,
name: string,
path: IpcPath | null,
@@ -14460,6 +14617,20 @@ export type StackFrame = {
column: number,
/** `subtle` frames (library/generated) are collapsed in the UI. */
presentationHint: string | null,
/** The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`). */
instructionPointerReference?: string | null,
};
export type StackFrame_Serialize = {
id: number,
name: string,
path: IpcPath | null,
line: number,
column: number,
/** `subtle` frames (library/generated) are collapsed in the UI. */
presentationHint: string | null,
/** The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`). */
instructionPointerReference?: string | null,
};
export type StagedText = {
@@ -14933,6 +15104,8 @@ export type TerminalSettings = {
mouseReporting?: boolean,
copyOnSelection?: boolean,
pasteOnMiddleClick?: boolean,
/** Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it). */
rightClickPaste?: boolean,
overrideIdeShortcuts?: boolean,
shellIntegration?: boolean,
highlightHyperlinks?: boolean,
@@ -15427,6 +15600,8 @@ export type Variable_Deserialize = {
* `variables` returns for `variables_reference` holds the value and its children.
*/
lazy?: boolean,
/** Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`). */
memoryReference?: string | null,
};
export type Variable_Serialize = {
@@ -15441,6 +15616,8 @@ export type Variable_Serialize = {
* `variables` returns for `variables_reference` holds the value and its children.
*/
lazy?: boolean,
/** Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`). */
memoryReference?: string | null,
};
/** Version Control › Confirmation. */
+5 -1
Переглянути файл
@@ -33,7 +33,7 @@ import {
import { GutterMarker, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import type { LanguageDescription } from "@codemirror/language";
import type { HunkKind } from "@/bindings";
import type { LineEnding } from "@/platform/ipc";
import type { CodeAction, LineEnding } from "@/platform/ipc";
import { create } from "zustand";
import { maybeEditorService, type EditorInput, type MenuGroupContext } from "@/workbench/contributions";
import { isSameOrInside } from "@/platform/paths";
@@ -598,7 +598,11 @@ export interface ContributedIntention {
label: string;
icon?: string;
quickFix?: boolean;
/** The preferred fix: bold, and first among the fixes. */
emphasis?: boolean;
run: () => void | Promise<void>;
/** A fallback for what the language server may offer itself: left out of ⌥↵ when one of its actions matches. */
supersededBy?: (action: CodeAction) => boolean;
}
/** A background provider has new context actions for the current document. */
+46
Переглянути файл
@@ -35,6 +35,7 @@ import {
unselectOccurrence,
} from "./cm/editing";
import {
cutLineBackward,
cutToLineEnd,
deleteToLogicalLineEnd,
deleteToLogicalLineStart,
@@ -778,6 +779,37 @@ export async function toggleSchemeSwitch(key: SchemeSwitch, on = !editorPrefs()[
}
}
/** IDEA's StickyLinesDisableForLangAction: the active document's known base language, if enabled. */
function activeStickyLinesLanguage(): string | null {
// A notebook cell has no base document: never change the last text tab's language setting.
if (!appearanceSwitches.stickyLines.on() || focusedCellEditor()) return null;
return activeSlot()?.model.info?.id || null;
}
async function disableStickyLinesForLanguage(): Promise<void> {
const language = activeStickyLinesLanguage();
if (!language) return;
const disabled = editorPrefs().codeEditing.stickyLinesDisabledLanguages;
if (disabled.includes(language)) return;
try {
useProject.setState({
settings: await call(
commands.settingsSet(
"global",
"editor.codeEditing.stickyLinesDisabledLanguages",
JSON.stringify([...disabled, language]),
),
),
});
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot change the setting",
body: e instanceof Error ? e.message : String(e),
});
}
}
const appearanceSwitch = (id: string, s: AppearanceSwitch, keywords: string[]): Action => ({
id,
title: s.title,
@@ -896,6 +928,16 @@ export function registerEditorActions(): () => void {
appearanceSwitch("editor.toggleLineNumbers", appearanceSwitches.lineNumbers, ["gutter", "hide line numbers"]),
appearanceSwitch("editor.toggleIndentGuides", appearanceSwitches.indentGuides, ["indent lines", "indentation"]),
appearanceSwitch("editor.toggleStickyLines", appearanceSwitches.stickyLines, ["sticky scroll"]),
{
id: "editor.disableStickyLinesForLanguage",
title: "Disable Sticky Lines for Language",
description: "Disable sticky lines for the current document's language without changing the global setting.",
category: "View",
keywords: ["sticky scroll", "language"],
when: "textEditorActive",
enabled: () => activeStickyLinesLanguage() !== null,
run: disableStickyLinesForLanguage,
},
appearanceSwitch("editor.toggleWhitespaces", appearanceSwitches.whitespaces, [
"render whitespace",
"spaces",
@@ -927,6 +969,10 @@ export function registerEditorActions(): () => void {
category: "Editor Actions",
keyWhen: "editorTextFocus || diffEditorFocus",
}),
edit("code.cutLineBackward", "Cut Line Backward", (v) => cutLineBackward(v), {
category: "Editor Actions",
keyWhen: "editorTextFocus || diffEditorFocus",
}),
edit("code.killToWordStart", "Kill to Word Start", (v) => killToWordStart(editorPrefs().smartKeys.camelHumps)(v), {
category: "Editor Actions",
keyWhen: "editorTextFocus || diffEditorFocus",
+87 -1
Переглянути файл
@@ -1,4 +1,12 @@
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { useContextKeys } from "@/platform/context";
import type { EditorSlot } from "./model/slot";
let activeSlot: Partial<EditorSlot> | null = null;
vi.mock("./controller", async (importOriginal) => ({
...(await importOriginal<object>()),
editorController: () => ({ activeSlot }),
}));
/** Writes the dotted key into the current settings, as the host does. */
const ipc = vi.hoisted(() => ({
@@ -29,7 +37,9 @@ beforeAll(() => {
});
afterAll(() => dispose());
afterEach(() => {
activeSlot = null;
useProject.setState({ settings: null });
useContextKeys.setState({}, true);
vi.clearAllMocks();
});
@@ -71,6 +81,82 @@ describe("editor appearance toggle actions", () => {
expect(resolveActionId("EditorGutterToggleGlobalLineNumbers")).toBe("editor.toggleLineNumbers");
expect(resolveActionId("EditorGutterToggleGlobalIndentLines")).toBe("editor.toggleIndentGuides");
expect(resolveActionId("EditorGutterToggleGlobalStickyLines")).toBe("editor.toggleStickyLines");
expect(resolveActionId("EditorStickyLinesDisableForLang")).toBe("editor.disableStickyLinesForLanguage");
});
});
describe("Disable Sticky Lines for Language", () => {
const id = "editor.disableStickyLinesForLanguage";
const key = "editor.codeEditing.stickyLinesDisabledLanguages";
const typescript = { id: "typescript", name: "TypeScript" };
const activate = (info: { id: string; name: string } | undefined) => {
activeSlot = { disposed: false, model: { info } } as never;
};
const setEditorSettings = (disabledLanguages: string[], stickyScroll = true) => {
useProject.setState({
settings: { editor: { stickyScroll, codeEditing: { stickyLinesDisabledLanguages: disabledLanguages } } } as never,
});
};
beforeEach(() => useContextKeys.setState({ textEditorActive: true }));
it("is a View action mapped from IDEA", () => {
expect(getAction(id)).toMatchObject({ title: "Disable Sticky Lines for Language", category: "View" });
expect(resolveActionId("EditorStickyLinesDisableForLang")).toBe(id);
});
it("is unavailable when global sticky lines are off", async () => {
activate(typescript);
setEditorSettings(["python"], false);
expect(await executeAction(id)).toBe(false);
expect(ipc.settingsSet).not.toHaveBeenCalled();
});
it("is unavailable without a known active document language", async () => {
setEditorSettings(["python"]);
expect(await executeAction(id)).toBe(false);
activate(undefined);
expect(await executeAction(id)).toBe(false);
expect(ipc.settingsSet).not.toHaveBeenCalled();
});
it("writes the current language id once while preserving other disabled languages", async () => {
activate(typescript);
setEditorSettings(["python", "go"]);
expect(await executeAction(id)).toBe(true);
expect(ipc.settingsSet).toHaveBeenCalledTimes(1);
expect(ipc.settingsSet).toHaveBeenCalledWith("global", key, JSON.stringify(["python", "go", "typescript"]));
expect(useProject.getState().settings?.editor).toMatchObject({
stickyScroll: true,
codeEditing: { stickyLinesDisabledLanguages: ["python", "go", "typescript"] },
});
});
it("is idempotent across repeated execution", async () => {
activate(typescript);
setEditorSettings(["python"]);
expect(await executeAction(id)).toBe(true);
expect(await executeAction(id)).toBe(true);
expect(ipc.settingsSet).toHaveBeenCalledTimes(1);
expect(ipc.settingsSet).toHaveBeenCalledWith("global", key, JSON.stringify(["python", "typescript"]));
});
it("leaves the global Show Sticky Lines toggle independent", async () => {
activate(typescript);
setEditorSettings(["python"]);
const globalToggle = getAction("editor.toggleStickyLines");
await executeAction(id);
expect(actionToggled(globalToggle)).toBe(true);
await executeAction("editor.toggleStickyLines");
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.stickyScroll", "false");
expect(actionToggled(globalToggle)).toBe(false);
expect(useProject.getState().settings?.editor).toMatchObject({
codeEditing: { stickyLinesDisabledLanguages: ["python", "typescript"] },
});
expect(await executeAction(id)).toBe(false);
});
});
+75
Переглянути файл
@@ -4,6 +4,7 @@ import { EditorView } from "@codemirror/view";
import { writeClipboardText } from "@/platform/clipboard";
import { clearClipboardHistory, clipboardHistory, recordClipboard } from "../clipboardHistory";
import {
cutLineBackward,
cutToLineEnd,
deleteToLogicalLineEnd,
deleteToLogicalLineStart,
@@ -180,6 +181,80 @@ describe("Cut up to Line End", () => {
});
});
describe("Cut Line Backward", () => {
it.each([
["from offset zero on the first line", "ab|cd\nef", "|cd\nef", "ab"],
["from the previous document line's start", "xy\nab|cd", "|cd", "xy\nab"],
["including the line break at a line start", "xy\n|cd", "|cd", "xy\n"],
["from a blank previous line", "xy\n\n|cd", "xy\n|cd", "\n"],
])("cuts %s into the clipboard and history", (_, text, after, cut) => {
expect(run(cutLineBackward, text)).toBe(after);
expect(writeClipboardText).toHaveBeenLastCalledWith(cut);
expect(clipboardHistory().map((e) => e.text)).toEqual([cut]);
});
it("cuts from the primary caret, not its selection", () => {
expect(run(cutLineBackward, "x[ab]cd\nef")).toBe("|cd\nef");
expect(writeClipboardText).toHaveBeenLastCalledWith("xab");
});
it("ignores additional carets", () => {
const v = make("a|bc\nde|fg");
cutLineBackward(v);
expect(show(v)).toBe("|bc\ndefg");
expect(writeClipboardText).toHaveBeenLastCalledWith("a");
});
it("prepends repeated backward cuts at the resulting caret to the existing entry", () => {
const v = make("first\nsecond\nthird| tail\nlast");
cutLineBackward(v);
expect(show(v)).toBe("first\n| tail\nlast");
expect(writeClipboardText).toHaveBeenLastCalledWith("second\nthird");
cutLineBackward(v);
expect(show(v)).toBe("| tail\nlast");
expect(writeClipboardText).toHaveBeenLastCalledWith("first\nsecond\nthird");
expect(clipboardHistory().map((e) => e.text)).toEqual(["first\nsecond\nthird"]);
});
it("starts a new entry after an edit, a caret move or another copy", () => {
const edited = make("a|b\nc");
cutLineBackward(edited);
edited.dispatch(edited.state.replaceSelection("x"));
cutLineBackward(edited);
expect(clipboardHistory().map((e) => e.text)).toEqual(["x", "a"]);
clearClipboardHistory();
const moved = make("a|b\ncd");
cutLineBackward(moved);
moved.dispatch({ selection: { anchor: 3 } });
cutLineBackward(moved);
expect(clipboardHistory().map((e) => e.text)).toEqual(["b\nc", "a"]);
clearClipboardHistory();
const copied = make("top\nfirst\nab|cd");
cutLineBackward(copied);
recordClipboard("other");
cutLineBackward(copied);
expect(clipboardHistory().map((e) => e.text)).toEqual(["top\n", "other", "first\nab"]);
});
it("leaves the document and clipboard alone at offset zero", () => {
const v = make("|ab");
expect(cutLineBackward(v)).toBe(true);
expect(show(v)).toBe("|ab");
expect(writeClipboardText).not.toHaveBeenCalled();
expect(clipboardHistory()).toEqual([]);
});
it("does nothing in a read-only editor", () => {
const v = make("ab|cd", true);
expect(cutLineBackward(v)).toBe(false);
expect(show(v)).toBe("ab|cd");
expect(writeClipboardText).not.toHaveBeenCalled();
expect(clipboardHistory()).toEqual([]);
});
});
describe("Kill to Word Start / End", () => {
it.each([
["the word before the caret", "foo bar|", false, "foo |", "bar"],
+24 -10
Переглянути файл
@@ -1,5 +1,5 @@
/**
* IDEA's Delete to Line Start / Delete to Line End, Cut up to Line End (⌃K on macOS),
* IDEA's Delete to Line Start / End, Cut up to Line End (⌃K on macOS), Cut Line Backward,
* Kill to Word Start / End and Hungry Backspace. They work on document lines, not on soft-wrapped rows.
*/
import { deleteBracketPair } from "@codemirror/autocomplete";
@@ -25,13 +25,24 @@ function toLineStart(state: EditorState, pos: number): Span {
return { from: pos === line.from ? Math.max(0, pos - 1) : line.from, to: pos };
}
/** The previous document line's start to the caret; the document start on the first line. */
function toPreviousLineStart(state: EditorState, pos: number): Span {
const line = state.doc.lineAt(pos);
return { from: line.number > 1 ? state.doc.line(line.number - 1).from : 0, to: pos };
}
/** `span` of each caret (or each selection, with `keepSelections`), overlaps merged. */
function spans(state: EditorState, span: (state: EditorState, pos: number) => Span, keepSelections: boolean) {
const ranges = state.selection.ranges.map((r) => {
function spans(
state: EditorState,
span: (state: EditorState, pos: number) => Span,
keepSelections: boolean,
primaryOnly = false,
) {
const ranges = (primaryOnly ? [state.selection.main] : state.selection.ranges).map((r) => {
const s = keepSelections && !r.empty ? r : span(state, r.head);
return EditorSelection.range(s.from, s.to);
});
return EditorSelection.create(ranges, state.selection.mainIndex);
return EditorSelection.create(ranges, primaryOnly ? 0 : state.selection.mainIndex);
}
function remove(view: EditorView, spans: EditorSelection, userEvent: string) {
@@ -96,20 +107,20 @@ const toWordEnd =
let lastCut: { doc: Text; pos: number; text: string } | null = null;
/**
* Cuts `span` of each caret (a selection is ignored, as in IDEA). Repeated with one caret it
* collects the cuts into one clipboard entry, like IDEA's kill ring: a `backward` cut goes before
* the collected text, any other after it.
* Cuts `span` of each caret, or only the primary caret with `primaryOnly` (a selection is ignored,
* as in IDEA). Repeated with one caret it collects the cuts into one clipboard entry, like IDEA's
* kill ring: a `backward` cut goes before the collected text, any other after it.
*/
const cutTo =
(span: (state: EditorState, pos: number) => Span, backward: boolean): Command =>
(span: (state: EditorState, pos: number) => Span, backward: boolean, primaryOnly = false): Command =>
(view) => {
const { state } = view;
if (state.readOnly) return false;
const s = spans(state, span, false);
const s = spans(state, span, false, primaryOnly);
const cut = s.ranges.filter((r) => !r.empty);
if (!cut.length) return true;
let text = cut.map((r) => state.sliceDoc(r.from, r.to)).join(state.lineBreak);
const single = state.selection.ranges.length === 1;
const single = primaryOnly || state.selection.ranges.length === 1;
const previous = lastCut;
if (
single &&
@@ -130,6 +141,9 @@ const cutTo =
/** Cuts from each caret to its line end (see `toLineEnd`). */
export const cutToLineEnd = cutTo(toLineEnd, false);
/** IDEA's Cut Line Backward: only the primary caret, from the previous line start (see `toPreviousLineStart`). */
export const cutLineBackward = cutTo(toPreviousLineStart, true, true);
/** IDEA's Kill to Word Start: cuts from the previous word start (see `toWordStart`) to each caret. */
export const killToWordStart = (camelHumps: boolean) => cutTo(toWordStart(camelHumps), true);
+24
Переглянути файл
@@ -248,6 +248,30 @@ describe("context actions a feature finds through the language server", () => {
expect(labels()).toEqual(["Enable exception breakpoint on Failure"]);
error.mockRestore();
});
it("drops a fallback the server's own fix supersedes, and lists a preferred one first", async () => {
const fallback = {
...intention("Import 'Widget' from 'lib'"),
quickFix: true,
emphasis: true,
supersededBy: (a: CodeAction) => a.title.startsWith("Import"),
};
const create = { ...intention("Create class 'Widget'"), quickFix: true };
const view = editor(async () => [create, fallback]);
const fix = (title: string) => ({ ...resolved, title, kind: "quickfix", edit: null });
lspCodeActions.mockResolvedValue({ status: "ok", data: [fix("Ignore 'Widget'")] });
await showIntentions(view);
expect(labels().slice(0, 3)).toEqual(["Import 'Widget' from 'lib'", "Create class 'Widget'", "Ignore 'Widget'"]);
closePopup();
lspCodeActions.mockResolvedValue({
status: "ok",
data: [fix("Ignore 'Widget'"), fix("Import 'Widget' from 'own'")],
});
await showIntentions(view);
expect(labels()).not.toContain("Import 'Widget' from 'lib'");
expect(labels()).toContain("Import 'Widget' from 'own'");
});
});
describe("inspection controls in ⌥↵ (issue #42)", () => {
+10 -1
Переглянути файл
@@ -20,6 +20,7 @@ import {
quickFixProviders,
intentionsChanged,
whenSynced,
type ContributedIntention,
} from "@/editor/api";
import { shortcutLabel } from "@/platform/keymap";
import { debounce, docOf, isUnavailable, lspRequest, reportLspError } from "./lsp";
@@ -541,6 +542,14 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[])
];
}
/** `intentions` without the fallbacks the server's `actions` make redundant. */
export function withoutSuperseded(
intentions: readonly ContributedIntention[],
actions: readonly CodeAction[],
): ContributedIntention[] {
return intentions.filter((i) => !i.supersededBy || !actions.some((a) => !a.disabledReason && i.supersededBy!(a)));
}
/**
* How long ⌥↵ waits for the server's actions before showing the popup with a
* progress row: the answer that arrives sooner appears at once (no flash), a
@@ -615,7 +624,7 @@ export async function showIntentions(view: EditorView) {
}),
contributedIntentionsAsync(view, asked.signal),
]);
local.push(...found);
local.push(...withoutSuperseded(found, actions ?? []));
clearTimeout(timer);
const items = actions ? itemsFor(actions) : withInspectionControls(view, listedIntentions(view, local));
if (!items.length) {
+1 -1
Переглянути файл
@@ -14,7 +14,7 @@ import { docOf } from "../../lsp";
import type { EditorDiagnostic } from "../../diagnostics";
/** Unresolved-name and missing-attribute codes of basedpyright/pyright, Ruff, ty and pyrefly. */
const UNDEFINED_NAME = new Set(["reportUndefinedVariable", "F821", "unresolved-reference", "unknown-name"]);
export const UNDEFINED_NAME = new Set(["reportUndefinedVariable", "F821", "unresolved-reference", "unknown-name"]);
const MISSING_ATTRIBUTE = new Set(["reportAttributeAccessIssue", "unresolved-attribute", "missing-attribute"]);
export interface CreateFix {
+18
Переглянути файл
@@ -1,3 +1,5 @@
import type { Text } from "@codemirror/state";
/**
* The imports an override copied from a base class needs: names its signature uses that the
* current file does not bind, imported the way the base class's file binds them.
@@ -132,3 +134,19 @@ export function placeImports(
for (const [module, names] of grouped) added.push(`from ${module} import ${names.join(", ")}`);
return { appended, added };
}
/** The changes that add `statements` to `doc`, placed by `placeImports`. */
export function importChanges(doc: Text, statements: readonly string[]): { from: number; insert: string }[] {
const lines = doc.toJSON();
const { appended, added } = placeImports(lines, statements);
const changes = [...appended].map(([n, text]) => ({ from: doc.line(n + 1).to, insert: text }));
if (added.length) {
const before = importLine(lines);
changes.push(
before < doc.lines
? { from: doc.line(before + 1).from, insert: `${added.join("\n")}\n` }
: { from: doc.length, insert: `\n${added.join("\n")}` },
);
}
return changes;
}
+3 -1
Переглянути файл
@@ -18,6 +18,7 @@ import { pythonCreateFixes } from "./createFromUsage";
import { pythonTypeHintIntentions } from "./typeHints";
import { pythonStringIntentions } from "./stringFormat";
import { pythonDocstringIntentions } from "./docstring";
import { pythonLibraryImports } from "./libraryImports";
/** Server tokens these kinds override: the kind's own classes replace the generic ones. */
const VARIABLE_KINDS = new Set<PythonSymbolKind>([
@@ -67,7 +68,8 @@ const pythonSemantics: LanguageSemantics = {
];
},
quickFixes: pythonCreateFixes,
asyncIntentions: pythonTypeHintIntentions,
asyncIntentions: async (view, signal) =>
(await Promise.all([pythonTypeHintIntentions(view, signal), pythonLibraryImports(view, signal)])).flat(),
implementMethods: implementPythonAbstractMethods,
overrideMethods: overridePythonMethods,
generate: pythonGenerateEntries,
+129
Переглянути файл
@@ -0,0 +1,129 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { setDiagnostics } from "@codemirror/lint";
import type { CodeAction } from "@/bindings";
const ipc = vi.hoisted(() => ({ navPythonLibraryImports: vi.fn(), cancelRequest: vi.fn() }));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const { pythonLibraryImports, undefinedNameAt } = await import("./libraryImports");
const { withoutSuperseded } = await import("../../intentions");
const { lspDoc } = await import("../../lsp");
const ctx = { doc: 3, path: "/p/agent.py", language: "python", uiMode: "Python", readOnly: false };
const views: EditorView[] = [];
/** `doc` with the caret on `caret` and an unresolved-name diagnostic of `code` on each of `unresolved`. */
function mount(doc: string, caret: string, unresolved: string[], code = "reportUndefinedVariable") {
const view = new EditorView({
state: EditorState.create({ doc, selection: { anchor: doc.indexOf(caret) + 1 }, extensions: [lspDoc.of(ctx)] }),
parent: document.body,
});
views.push(view);
const diagnostics = unresolved.map((name) => {
const from = doc.indexOf(name);
const message = `"${name}" is not defined`;
return {
from,
to: from + name.length,
severity: "error" as const,
message,
problem: { code, message, source: "basedpyright" },
};
});
view.dispatch(setDiagnostics(view.state, diagnostics));
return view;
}
const ok = (data: unknown) => Promise.resolve({ status: "ok", data });
const action = (title: string, kind = "quickfix"): CodeAction => ({ title, kind }) as CodeAction;
afterEach(() => {
for (const v of views.splice(0)) v.destroy();
vi.clearAllMocks();
});
describe("Python library imports", () => {
const source = "from my_model.my_model import cpa_model\nmodel = cpa_model()\n\ncreate_agent(\n model=model\n)\n";
it("finds the unresolved name at the caret, for every Python server's code", () => {
for (const code of ["reportUndefinedVariable", "F821", "unresolved-reference", "unknown-name"]) {
const view = mount(source, "create_agent", ["create_agent"], code);
expect(undefinedNameAt(view.state, view.state.selection.main.head)).toBe("create_agent");
}
const other = mount(source, "create_agent", ["create_agent"], "reportAttributeAccessIssue");
expect(undefinedNameAt(other.state, other.state.selection.main.head)).toBeNull();
});
it("offers the candidates of the installed packages and inserts the chosen import", async () => {
ipc.navPythonLibraryImports.mockReturnValue(
ok([
{ module: "langchain.agents", name: "create_agent" },
{ module: "langchain.agents.factory", name: "create_agent" },
]),
);
const view = mount(source, "create_agent", ["create_agent"]);
const found = await pythonLibraryImports(view, new AbortController().signal);
expect(ipc.navPythonLibraryImports).toHaveBeenCalledWith(3, "create_agent", expect.any(Number));
expect(found.map((i) => i.label)).toEqual([
"Import 'create_agent' from 'langchain.agents'",
"Import 'create_agent' from 'langchain.agents.factory'",
]);
expect(found.every((i) => i.quickFix)).toBe(true);
await found[0]!.run();
expect(view.state.doc.toString()).toBe(
"from my_model.my_model import cpa_model\nfrom langchain.agents import create_agent\nmodel = cpa_model()\n\n" +
"create_agent(\n model=model\n)\n",
);
});
it("adds to an import from the same module and imports a module as a whole", async () => {
ipc.navPythonLibraryImports.mockReturnValue(
ok([
{ module: "matplotlib", name: null },
{ module: "matplotlib.colors", name: "Normalize" },
]),
);
const view = mount("from matplotlib.colors import Colormap\n\nn = Normalize()\n", "Normalize", ["Normalize"]);
const found = await pythonLibraryImports(view, new AbortController().signal);
expect(found.map((i) => i.label)).toEqual([
"Import module 'matplotlib'",
"Import 'Normalize' from 'matplotlib.colors'",
]);
await found[1]!.run();
expect(view.state.doc.toString()).toBe("from matplotlib.colors import Colormap, Normalize\n\nn = Normalize()\n");
});
it("asks nothing away from an unresolved name, and cancels the request when the caret moves on", async () => {
const plain = mount(source, "model =", ["create_agent"]);
expect(await pythonLibraryImports(plain, new AbortController().signal)).toEqual([]);
expect(ipc.navPythonLibraryImports).not.toHaveBeenCalled();
let answer!: (value: unknown) => void;
ipc.navPythonLibraryImports.mockReturnValue(new Promise((resolve) => (answer = resolve)));
const view = mount(source, "create_agent", ["create_agent"]);
const asked = new AbortController();
const found = pythonLibraryImports(view, asked.signal);
asked.abort();
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.navPythonLibraryImports.mock.calls[0]![2]);
answer({ status: "error", error: { kind: "cancelled", message: "cancelled" } });
expect(await found).toEqual([]);
});
it("gives way to an import fix of the language server", async () => {
ipc.navPythonLibraryImports.mockReturnValue(ok([{ module: "collections", name: "OrderedDict" }]));
const view = mount("d = OrderedDict()\n", "OrderedDict", ["OrderedDict"]);
const found = await pythonLibraryImports(view, new AbortController().signal);
const ignore = action('Add "# pyright: ignore[reportUndefinedVariable]"');
expect(withoutSuperseded(found, [ignore])).toHaveLength(1);
expect(withoutSuperseded(found, [ignore, action('Import "OrderedDict" from "collections"')])).toEqual([]);
// Another name's import, a refactoring or a disabled action does not count.
expect(withoutSuperseded(found, [action('Import "Counter" from "collections"')])).toHaveLength(1);
expect(withoutSuperseded(found, [action("Import OrderedDict", "refactor.extract")])).toHaveLength(1);
expect(withoutSuperseded(found, [{ ...action("Import OrderedDict"), disabledReason: "no" }])).toHaveLength(1);
});
});
+76
Переглянути файл
@@ -0,0 +1,76 @@
/**
* PyCharm's "Import this name" for names from installed packages. basedpyright offers import
* fixes for the project's own symbols and the standard library only; the backend's index of
* the interpreter's site-packages supplies the rest, and a server import fix replaces them.
*/
import type { EditorState } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { forEachDiagnostic } from "@codemirror/lint";
import type { ContributedIntention } from "@/editor/api";
import type { PythonImportCandidate } from "@/bindings";
import { call, commands, isTauri, nextRequestId, type CodeAction } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { docOf } from "../../lsp";
import type { EditorDiagnostic } from "../../diagnostics";
import { UNDEFINED_NAME } from "./createFromUsage";
import { importChanges } from "./imports";
const IDENTIFIER = /^[\p{L}_][\p{L}\p{N}_]*$/u;
const IMPORT_TITLE = /\bimport\b/i;
/** The unresolved name a diagnostic reports at `pos`. */
export function undefinedNameAt(state: EditorState, pos: number): string | null {
let name: string | null = null;
forEachDiagnostic(state, (d, from, to) => {
const code = (d as EditorDiagnostic).problem?.code;
if (name || code == null || !UNDEFINED_NAME.has(code) || pos < from || pos > to) return;
const text = state.doc.sliceString(from, to);
if (IDENTIFIER.test(text)) name = text;
});
return name;
}
/** The statement a candidate adds. */
export function importStatement(c: PythonImportCandidate): string {
return c.name ? `from ${c.module} import ${c.name}` : `import ${c.module}`;
}
/** A quick fix of the server that imports `name` (basedpyright's for project and standard library names). */
function importsName(name: string) {
return (a: CodeAction) =>
(!a.kind || a.kind.startsWith("quickfix")) && IMPORT_TITLE.test(a.title) && a.title.includes(name);
}
/** ⌥↵ rows that import the unresolved name at the caret from an installed package. */
export async function pythonLibraryImports(view: EditorView, signal: AbortSignal): Promise<ContributedIntention[]> {
const doc = docOf(view);
const selection = view.state.selection.main;
if (doc?.uiMode !== "Python" || doc.readOnly || !selection.empty || !isTauri()) return [];
const name = undefinedNameAt(view.state, selection.head);
if (!name) return [];
// The first request waits for the index of the interpreter's packages; moving on cancels it.
const request = nextRequestId();
const cancel = () => void commands.cancelRequest(request);
signal.addEventListener("abort", cancel, { once: true });
let candidates: PythonImportCandidate[];
try {
candidates = await call(commands.navPythonLibraryImports(doc.doc, name, request));
} catch {
return [];
} finally {
signal.removeEventListener("abort", cancel);
}
if (signal.aborted) return [];
return candidates.map((c, i) => ({
id: `python.import:${importStatement(c)}`,
label: c.name ? tx`Import '${c.name}' from '${c.module}'` : tx`Import module '${c.module}'`,
quickFix: true,
// As in PyCharm, importing an unresolved name comes before creating it.
emphasis: i === 0,
supersededBy: importsName(name),
run: () => {
view.dispatch({ changes: importChanges(view.state.doc, [importStatement(c)]), userEvent: "input.complete" });
view.focus();
},
}));
}
+6 -12
Переглянути файл
@@ -13,7 +13,7 @@ import { docOf, lspRequest, reportLspError } from "../../lsp";
import { readFileLines, withDocument } from "../../files";
import { showHint } from "../../hint";
import { chooseMembers } from "../../memberChooser";
import { importLine, importedFrom, neededImports, placeImports, topLevelBindings } from "./imports";
import { importChanges, importedFrom, neededImports, topLevelBindings } from "./imports";
/** A Python identifier (letters of any script). */
export const ID = "[\\p{L}_][\\p{L}\\p{N}_]*";
@@ -285,17 +285,11 @@ export function insertMembers(
: placeholder
? { from: state.doc.line(bodyLines[0]!).from, to: state.doc.line(end).to, insert: stubs }
: { from: state.doc.line(end).to, insert: `\n\n${stubs}` };
const { appended, added } = placeImports(lines, imports);
const importChanges = [...appended].map(([n, text]) => ({ from: state.doc.line(n + 1).to, insert: text }));
if (added.length) {
const before = importLine(lines);
importChanges.push(
before < state.doc.lines
? { from: state.doc.line(before + 1).from, insert: `${added.join("\n")}\n` }
: { from: state.doc.length, insert: `\n${added.join("\n")}` },
);
}
view.dispatch({ changes: [...importChanges, ...extra, changes], userEvent: "input.complete", scrollIntoView: true });
view.dispatch({
changes: [...importChanges(state.doc, imports), ...extra, changes],
userEvent: "input.complete",
scrollIntoView: true,
});
}
/** A base class of the class at the caret and the methods it declares. */
+3 -1
Переглянути файл
@@ -34,6 +34,7 @@ import {
useAgentCommands,
useAgents,
} from "./store";
import { useGitEnabled } from "@/platform/gitEnabled";
import { useAgentSettings } from "./agentSettings";
import styles from "./Home.module.css";
@@ -154,7 +155,8 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input?
const agentCommands = useAgentCommands(provider?.id, null, provider?.commands ?? NO_COMMANDS);
const providerOptions: SelectOption[] = agentOptions(providers, tx, providerIcon);
// Without git under the project there are no worktrees: force the local checkout.
const isGit = project?.workspace ? repoState?.root === root && repoState.isGit : (project?.isGit ?? false);
const gitOn = useGitEnabled();
const isGit = gitOn && (project?.workspace ? repoState?.root === root && repoState.isGit : (project?.isGit ?? false));
const isolation = isGit ? draft.isolation : "local";
const base = draft.base ?? current;
const canStart =
+4
Переглянути файл
@@ -20,6 +20,7 @@ import {
useKeymap,
} from "@/platform/keymap";
import { useProject } from "@/platform/project";
import { hiddenMenuEntries, onWorkflowSettingsChange } from "@/platform/workflowSettings";
import { syncRemoteRecentMenu } from "@/platform/remote";
import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions";
import { useDistractionFree } from "@/workbench/distractionFree";
@@ -126,6 +127,7 @@ export function buildMenuConfig(os: HostOs): MenuConfig {
accelerators,
dynamic: dynamicMenuItems(),
checked: toggledActions(),
hidden: hiddenMenuEntries(),
};
}
@@ -304,6 +306,8 @@ export function installMenuBridge(): () => void {
// View › Appearance check marks and Status Bar Widgets.
if (s.settings?.appearance !== prev.settings?.appearance) push();
}),
// Settings › Git › Enable Git integration shows or hides the Git menu.
onWorkflowSettingsChange((w) => w.vcs.git.enabled, push),
];
return () => {
disposed = true;
+19
Переглянути файл
@@ -366,6 +366,9 @@
flex: 1;
min-height: 0;
}
.treeHost[data-empty] > :first-child {
flex: 0 0 32px;
}
.nodeRow {
display: flex;
align-items: center;
@@ -1054,6 +1057,22 @@
text-align: left;
overflow-wrap: anywhere;
}
.propertiesPanel {
flex: 1;
display: grid;
grid-template-columns: minmax(0, 22%) minmax(0, 1fr);
align-content: start;
align-items: center;
gap: var(--space-2) var(--space-3);
min-height: 0;
padding: 12px;
overflow: auto;
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.propertiesPanel .formLabel {
text-align: left;
}
.grantsPanel {
flex: 1;
display: flex;
+21 -18
Переглянути файл
@@ -69,7 +69,7 @@ import {
import { DB_VIEW_FOCUS, databaseTree, openTableData } from "./treeActions";
import { newMenu, nodeMenu } from "./treeMenu";
import styles from "./Database.module.css";
import { formatMessage, tx } from "@/platform/i18n";
import { formatMessage, tx, useTx } from "@/platform/i18n";
import { databaseRequest } from "./requests";
const GROUP_LABELS: Record<Group, string> = {
@@ -147,6 +147,7 @@ function groupSize(d: DbTableDetails, g: Group): number {
}
export function DatabaseView() {
const t = useTx();
const st = useDatabase();
const folders = st.separateProceduresAndFunctions ? SEPARATE_FOLDERS : FOLDERS;
const tree = useRef<TreeHandle>(null);
@@ -206,6 +207,7 @@ export function DatabaseView() {
...st.sources
.filter((source) => !grouped.has(source.id ?? ""))
.map((source): Node => ({ kind: "source", key: source.id ?? "", source })),
{ kind: "workspace", key: ":query-workspace" },
];
}, [st.folders, st.sources]);
@@ -549,6 +551,8 @@ export function DatabaseView() {
const label = (n: Node): string => {
switch (n.kind) {
case "workspace":
return t("Query Workspace");
case "source":
return n.source.pluginOwner ? `${n.source.name} (${n.source.pluginOwner})` : (n.source.name ?? "");
case "sourceFolder":
@@ -632,6 +636,8 @@ export function DatabaseView() {
const icon = (n: Node): string | undefined => {
switch (n.kind) {
case "workspace":
return "db-console";
case "source":
return sourceIcon(n.source);
case "sourceFolder":
@@ -668,25 +674,11 @@ export function DatabaseView() {
}
};
if (st.loaded && st.foldersLoaded && !st.sources.length && !st.folders.length)
return (
<div className={styles.dbView}>
<DatabaseToolbar />
<EmptyState title="No data sources">
<Button variant="ghost" onClick={() => void executeAction("db.newDataSource")}>
<T>New Data Source…</T>
</Button>
<Button variant="ghost" onClick={() => void executeAction("db.newSourceFolder")}>
<T>New Folder…</T>
</Button>
</EmptyState>
</div>
);
const empty = st.loaded && st.foldersLoaded && !st.sources.length && !st.folders.length;
return (
<div className={styles.dbView}>
<DatabaseToolbar />
<div className={styles.treeHost} ref={treeHost}>
<div className={styles.treeHost} ref={treeHost} data-empty={empty ? "" : undefined}>
<Tree<Node>
aria-label="Data sources"
focusContext={DB_VIEW_FOCUS}
@@ -785,7 +777,8 @@ export function DatabaseView() {
})
}
onActivate={(n) => {
if (n.kind === "table") openTableData(n.id, n.schema, n.table.name, n.catalog);
if (n.kind === "workspace") void executeAction("db.queryWorkspace");
else if (n.kind === "table") openTableData(n.id, n.schema, n.table.name, n.catalog);
else if (n.kind === "source") void openConsole(n.source.id ?? "");
else if (n.kind === "database" && n.catalog === undefined) void openConsole(n.id);
else {
@@ -800,6 +793,16 @@ export function DatabaseView() {
}}
speedSearch
/>
{empty && (
<EmptyState title="No data sources">
<Button variant="ghost" onClick={() => void executeAction("db.newDataSource")}>
<T>New Data Source…</T>
</Button>
<Button variant="ghost" onClick={() => void executeAction("db.newSourceFolder")}>
<T>New Folder…</T>
</Button>
</EmptyState>
)}
</div>
</div>
);
+240 -12
Переглянути файл
@@ -1,6 +1,6 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { DataSource, DbJdbcDriver, ProjectInfo } from "@/platform/ipc";
import { IpcError, type DataSource, type DbJdbcDriver, type ProjectInfo } from "@/platform/ipc";
import { registerHostPathChooser } from "@/platform/choosePath";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
@@ -11,7 +11,13 @@ import { sourceIcon, sourceLabel } from "./model";
import { newMenu, nodeMenu } from "./treeMenu";
import { useDatabase } from "./store";
const backend = vi.hoisted(() => ({ call: vi.fn(), saveSource: vi.fn(), pick: vi.fn(), pickNew: vi.fn() }));
const backend = vi.hoisted(() => ({
call: vi.fn(),
saveSource: vi.fn(),
pick: vi.fn(),
pickNew: vi.fn(),
confirm: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const request =
@@ -27,9 +33,11 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
clipboardText: request("clipboard"),
dbJdbcDriverClasses: request("classes"),
dbApproveJdbcSource: request("approve"),
dbApproveDucklakeSource: request("approveLake"),
dbSaveJdbcDriver: request("save"),
dbRemoveJdbcDriver: request("remove"),
dbTest: request("test"),
dbCreateDucklake: request("createLake"),
},
};
});
@@ -38,6 +46,10 @@ vi.mock("./store", async (importOriginal) => ({
saveSource: backend.saveSource,
}));
vi.mock("@/platform/dialog", () => ({ open: backend.pick, save: backend.pickNew }));
vi.mock("@/workbench/messages", async (importOriginal) => ({
...(await importOriginal<typeof import("@/workbench/messages")>()),
confirm: backend.confirm,
}));
const driver: DbJdbcDriver = {
id: "example-driver",
@@ -60,6 +72,7 @@ beforeEach(() => {
backend.saveSource.mockResolvedValue(undefined);
backend.pick.mockResolvedValue(driver.jars);
backend.pickNew.mockResolvedValue(null);
backend.confirm.mockResolvedValue(false);
useDatabase.setState({ sources: [], dialog: null, loaded: true });
useProject.setState({ project: null });
});
@@ -79,6 +92,201 @@ describe("DuckDB data sources", () => {
return dialog;
};
it("tests and saves an existing DuckLake file read-only", async () => {
backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "DuckDB"));
backend.pick.mockResolvedValueOnce("/tmp/warehouse.ducklake");
startDuckDb();
fireEvent.click(screen.getByRole("button", { name: "DuckLake" }));
const catalog = screen.getByLabelText("Catalog file:");
const testConnection = screen.getByRole("button", { name: "Test Connection" });
fireEvent.change(catalog, { target: { value: "relative.ducklake" } });
expect(testConnection).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Browse for DuckLake catalog" }));
await waitFor(() => expect(catalog).toHaveValue("/tmp/warehouse.ducklake"));
expect(backend.pick).toHaveBeenCalledWith(expect.objectContaining({ directory: false, multiple: false }));
expect(screen.queryByLabelText("User:")).toBeNull();
expect(screen.queryByLabelText("Password:")).toBeNull();
expect(screen.queryByRole("tab", { name: "Advanced" })).toBeNull();
fireEvent.click(screen.getByRole("tab", { name: "Options" }));
expect(screen.getByRole("checkbox", { name: "Read-only" })).toBeChecked();
expect(screen.getByRole("checkbox", { name: "Read-only" })).toBeDisabled();
fireEvent.click(testConnection);
const source = expect.objectContaining({
driver: "jdbc",
vendor: "duckdb",
jdbcDriver: duckdb.id,
url: "jdbc:duckdb:",
readOnly: true,
user: "",
savePassword: false,
properties: [],
duckLake: { kind: "file", value: "/tmp/warehouse.ducklake", dataPath: null },
});
await waitFor(() => expect(backend.call).toHaveBeenCalledWith(["test", source, null, null]));
const save = screen.getByRole("button", { name: "OK" });
await waitFor(() => expect(save).toBeEnabled());
fireEvent.click(save);
await waitFor(() => expect(backend.saveSource).toHaveBeenCalledWith(source, null, undefined));
expect(backend.call).toHaveBeenCalledWith(["approveLake", source]);
expect(backend.call.mock.calls.map(([request]) => request[0])).not.toContain("createLake");
});
it.each([
{
global: false,
kind: "protocol" as const,
message: "command db_approve_ducklake_source is not available remotely",
expected: "Update the remote OpenIDEA server to save DuckLake data sources.",
},
{
global: true,
kind: "protocol" as const,
message: "command db_approve_ducklake_source is not available remotely",
expected: "Update the remote OpenIDEA server to save DuckLake data sources.",
},
{
global: false,
kind: "invalidInput" as const,
message: "DuckLake requires a valid catalog file",
expected: "DuckLake requires a valid catalog file",
},
])("stops before saving a DuckLake when $kind approval fails (global=$global)", async (entry) => {
backend.call.mockImplementation(async ([op]) => {
if (op === "approveLake") throw new IpcError({ kind: entry.kind, message: entry.message });
return op === "list" ? [duckdb] : undefined;
});
render(
<SourceDialog
initial={{
driver: "jdbc",
vendor: "duckdb",
jdbcDriver: duckdb.id,
url: "jdbc:duckdb:",
duckLake: { kind: "file", value: "/tmp/warehouse.ducklake" },
global: entry.global,
}}
/>,
);
const save = screen.getByRole("button", { name: "OK" });
await waitFor(() => expect(save).toBeEnabled());
fireEvent.click(save);
expect(await screen.findByText(entry.expected)).toBeVisible();
expect(backend.call.mock.calls.map(([request]) => request[0])).toEqual(["list", "approveLake"]);
expect(backend.saveSource).not.toHaveBeenCalled();
});
it("restores the Lake secret and restricts data directory overrides to host paths", async () => {
backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "DuckDB"));
backend.pick.mockResolvedValueOnce("/tmp/lake-data");
render(
<SourceDialog
initial={{
driver: "jdbc",
vendor: "duckdb",
jdbcDriver: duckdb.id,
duckLake: { kind: "secret", value: "warehouse_catalog" },
url: "jdbc:duckdb:",
user: "old-user",
savePassword: true,
properties: [{ name: "threads", value: "4" }],
options: { startupScript: "setup.sql", defaultSchema: "old_schema", timeZone: "UTC", transaction: "manual" },
}}
presetPassword="synthetic-old-password"
/>,
);
expect(screen.getByRole("button", { name: "DuckLake", pressed: true })).toBeVisible();
const secret = screen.getByLabelText("Secret name:");
expect(secret).toHaveValue("warehouse_catalog");
const testConnection = screen.getByRole("button", { name: "Test Connection" });
await waitFor(() => expect(testConnection).toBeEnabled());
fireEvent.change(secret, { target: { value: "postgres:dbname=example" } });
expect(testConnection).toBeDisabled();
fireEvent.change(secret, { target: { value: "warehouse_catalog" } });
const dataDirectory = screen.getByLabelText("Data directory:");
fireEvent.change(dataDirectory, { target: { value: "s3://example/data" } });
expect(testConnection).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Browse for DuckLake data directory" }));
await waitFor(() => expect(dataDirectory).toHaveValue("/tmp/lake-data"));
expect(backend.pick).toHaveBeenCalledWith(expect.objectContaining({ directory: true, multiple: false }));
fireEvent.click(testConnection);
await waitFor(() =>
expect(backend.call).toHaveBeenCalledWith([
"test",
expect.objectContaining({
readOnly: true,
user: "",
savePassword: false,
properties: [],
options: expect.objectContaining({ startupScript: "", defaultSchema: "", timeZone: "", transaction: "auto" }),
duckLake: { kind: "secret", value: "warehouse_catalog", dataPath: "/tmp/lake-data" },
}),
null,
null,
]),
);
});
it("creates a new DuckLake only after a separate confirmation", async () => {
backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : undefined));
backend.pickNew.mockResolvedValue("/tmp/new-lake");
startDuckDb();
fireEvent.click(screen.getByRole("button", { name: "DuckLake" }));
const create = screen.getByRole("button", { name: "Create New DuckLake…" });
await waitFor(() => expect(create).toBeEnabled());
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
fireEvent.click(create);
await waitFor(() => expect(backend.confirm).toHaveBeenCalledTimes(1));
await waitFor(() => expect(create).toBeEnabled());
expect(backend.confirm).toHaveBeenCalledWith({
title: "Create New DuckLake",
message: "Create a DuckLake in '/tmp/new-lake'? The directory must not already exist.",
ok: "Create",
});
expect(backend.call.mock.calls.map(([request]) => request[0])).not.toContain("createLake");
backend.confirm.mockResolvedValueOnce(true);
fireEvent.click(create);
await waitFor(() => expect(backend.call).toHaveBeenCalledWith(["createLake", duckdb.id, "/tmp/new-lake"]));
expect(await screen.findByText("DuckLake created. The data source opens it read-only.")).toBeVisible();
expect(screen.getByLabelText("Catalog file:")).toHaveValue("/tmp/new-lake/catalog.ducklake");
const ops = backend.call.mock.calls.map(([request]) => request[0]);
expect(ops.filter((op) => op === "createLake")).toHaveLength(1);
expect(ops).not.toContain("test");
expect(backend.saveSource).not.toHaveBeenCalled();
});
it("browses DuckLake paths on the database host in a remote window", async () => {
const choose = vi
.fn()
.mockResolvedValueOnce(["/srv/project/catalog.ducklake"])
.mockResolvedValueOnce(["/srv/project/data"])
.mockResolvedValueOnce(["/srv/project/new-lake"]);
const unregister = registerHostPathChooser(choose);
useRemote.setState({ session: { root: "/srv/project", os: "linux", commands: [] } as never });
useProject.setState({ project: { root: "/srv/project" } as ProjectInfo });
try {
backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK"));
startDuckDb();
fireEvent.click(screen.getByRole("button", { name: "DuckLake" }));
fireEvent.click(screen.getByRole("button", { name: "Browse for DuckLake catalog" }));
await waitFor(() => expect(screen.getByLabelText("Catalog file:")).toHaveValue("/srv/project/catalog.ducklake"));
fireEvent.click(screen.getByRole("button", { name: "Browse for DuckLake data directory" }));
await waitFor(() => expect(screen.getByLabelText("Data directory:")).toHaveValue("/srv/project/data"));
fireEvent.click(screen.getByRole("button", { name: "Create New DuckLake…" }));
await waitFor(() => expect(backend.confirm).toHaveBeenCalled());
expect(choose).toHaveBeenNthCalledWith(1, expect.objectContaining({ directory: false }));
expect(choose).toHaveBeenNthCalledWith(2, expect.objectContaining({ directory: true }));
expect(choose).toHaveBeenNthCalledWith(3, expect.objectContaining({ save: true }));
expect(backend.pick).not.toHaveBeenCalled();
expect(backend.pickNew).not.toHaveBeenCalled();
expect(backend.call.mock.calls.map(([request]) => request[0])).not.toContain("createLake");
} finally {
unregister();
useRemote.setState({ session: null });
}
});
it("offers DuckDB in the new data source menu", () => {
const dataSource = newMenu().find((item) => "label" in item && item.label === "Data Source");
expect(dataSource && "submenu" in dataSource && dataSource.submenu).toEqual(
@@ -327,7 +535,33 @@ describe("DuckDB data sources", () => {
}
});
it("requires write access for in-memory databases", async () => {
it.each(["jdbc:duckdb::memory:;threads=1", "jdbc:duckdb:memory:default", "jdbc:duckdb::memory:local;threads=1"])(
"requires write access for the in-memory URL %s",
async (url) => {
backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK"));
render(
<SourceDialog
initial={{
driver: "jdbc",
vendor: "duckdb",
jdbcDriver: duckdb.id,
url,
urlOnly: true,
readOnly: true,
}}
/>,
);
await screen.findByText("Turn off Read-only in Options to use an in-memory DuckDB database.");
expect(screen.getByRole("button", { name: "Test Connection" })).toBeDisabled();
fireEvent.click(screen.getByRole("tab", { name: "Options" }));
const readOnly = screen.getByRole("checkbox", { name: "Read-only" });
fireEvent.click(readOnly);
expect(readOnly).toBeDisabled();
await waitFor(() => expect(screen.getByRole("button", { name: "Test Connection" })).toBeEnabled());
},
);
it("keeps read-only available for a file with a memory-like name", async () => {
backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK"));
render(
<SourceDialog
@@ -335,19 +569,13 @@ describe("DuckDB data sources", () => {
driver: "jdbc",
vendor: "duckdb",
jdbcDriver: duckdb.id,
url: "jdbc:duckdb::memory:;threads=1",
url: "jdbc:duckdb:./memory:default",
urlOnly: true,
readOnly: true,
}}
/>,
);
await screen.findByText("Turn off Read-only in Options to use an in-memory DuckDB database.");
expect(screen.getByRole("button", { name: "Test Connection" })).toBeDisabled();
fireEvent.click(screen.getByRole("tab", { name: "Options" }));
const readOnly = screen.getByRole("checkbox", { name: "Read-only" });
fireEvent.click(readOnly);
expect(readOnly).toBeDisabled();
await waitFor(() => expect(screen.getByRole("button", { name: "Test Connection" })).toBeEnabled());
fireEvent.click(await screen.findByRole("tab", { name: "Options" }));
expect(screen.getByRole("checkbox", { name: "Read-only" })).toBeEnabled();
});
it("keeps an existing generic DuckDB JDBC source generic", async () => {
+124 -5
Переглянути файл
@@ -9,6 +9,7 @@ import {
commands,
type DbColumnInfo,
type DbDriver,
type DbPersistence,
type DbSourceFolder,
type DbTableDetails,
type DbTableGrant,
@@ -46,17 +47,21 @@ import {
dropDatabaseSql,
grantMatrix,
grantsSupported,
hasTableProperties,
indexDraftOf,
keyName,
keySupport,
propertySupport,
renameDatabaseSql,
dropSql,
ident,
reference,
renameSql,
tablePropertiesOf,
truncateSql,
type ColumnDraft,
type IndexDraft,
type TableProperties,
templateOf,
type CreateOptions,
type DbObjectRef,
@@ -710,6 +715,7 @@ function ModifyTableForm({
const [comment, setComment] = useState(details?.comment ?? "");
const support = keySupport(driver);
const pkIndex = details?.indexes.find((i) => i.key === "primary")?.name;
const [properties, setProperties] = useState<TableProperties>(() => tablePropertiesOf(details));
const statements = useMemo(() => {
if (!table) {
@@ -728,8 +734,9 @@ function ModifyTableForm({
columns,
{ original: details?.comment ?? "", value: comment },
{ primaryKeyName: pkIndex, indexes },
{ original: tablePropertiesOf(details), value: properties },
);
}, [columns, indexes, driver, schema, table, name, comment, details?.comment, pkIndex]);
}, [columns, indexes, driver, schema, table, name, comment, details, pkIndex, properties]);
const current = (selected?.group === "column" && columns.find((c) => c.key === selected.key)) || null;
const currentIndex = (selected?.group === "index" && indexes.find((d) => d.key === selected.key)) || null;
@@ -812,7 +819,8 @@ function ModifyTableForm({
</div>
);
const showGrants = !!table && grantsSupported(driver);
const [tab, setTab] = useState<"columns" | "grants">("columns");
const showProperties = !!table && hasTableProperties(details);
const [tab, setTab] = useState<"columns" | "properties" | "grants">("columns");
const title = table ? `Modify Table ${table}` : "Create Table";
const typeList = `db-types-${driver}`;
@@ -866,20 +874,28 @@ function ModifyTableForm({
/>
</div>
)}
{showGrants && (
{(showGrants || showProperties) && (
<Tabs
variant="compact"
aria-label={tx("Table properties")}
activeId={tab}
onSelect={(t) => setTab(t as "columns" | "grants")}
onSelect={(t) => setTab(t as typeof tab)}
items={[
{ id: "columns", label: tx("Columns") },
{ id: "grants", label: tx("Grants") },
...(showProperties ? [{ id: "properties", label: tx("Properties") }] : []),
...(showGrants ? [{ id: "grants", label: tx("Grants") }] : []),
]}
/>
)}
{showGrants && tab === "grants" ? (
<GrantsPanel id={id} schema={schema} table={table} />
) : showProperties && tab === "properties" ? (
<PropertiesPanel
driver={driver}
details={details}
value={properties}
onChange={(p) => setProperties((v) => ({ ...v, ...p }))}
/>
) : (
<div className={styles.modifyMain}>
<div className={styles.modifyColumns}>
@@ -1120,6 +1136,109 @@ function ModifyTableForm({
);
}
const PERSISTENCE: Record<DbPersistence, string> = {
permanent: "Logged",
unlogged: "Unlogged",
temporary: "Temporary",
};
/**
* The Modify Table dialog's Properties tab: the owner, tablespace, storage options and
* persistence the engine reports (editable per `propertySupport`), its access method and partition key read-only.
*/
function PropertiesPanel({
driver,
details,
value,
onChange,
}: {
driver: DbDriver;
details: DbTableDetails | undefined;
value: TableProperties;
onChange: (p: Partial<TableProperties>) => void;
}) {
const support = propertySupport(driver);
const reported = (v: unknown) => v !== undefined && v !== null;
const original = details?.persistence;
// A temporary table can't be made permanent, nor a permanent one temporary.
const persistence: DbPersistence[] = original === "temporary" ? ["temporary"] : ["permanent", "unlogged"];
return (
<div className={styles.propertiesPanel}>
{reported(details?.owner) && (
<>
<label className={styles.formLabel} htmlFor="db-table-owner">
<T>Owner</T>
</label>
<Input
id="db-table-owner"
value={value.owner}
disabled={!support.owner}
onChange={(e) => onChange({ owner: e.target.value })}
/>
</>
)}
{reported(details?.tablespace) && (
<>
<label className={styles.formLabel} htmlFor="db-table-tablespace">
<T>Tablespace</T>
</label>
<Input
id="db-table-tablespace"
value={value.tablespace}
disabled={!support.tablespace}
onChange={(e) => onChange({ tablespace: e.target.value })}
/>
</>
)}
{reported(details?.persistence) && (
<>
<label className={styles.formLabel} htmlFor="db-table-persistence">
<T>Persistence</T>
</label>
<Select
id="db-table-persistence"
value={value.persistence}
options={persistence.map((p) => ({ value: p, label: PERSISTENCE[p] }))}
disabled={!support.persistence || original === "temporary"}
onChange={(p) => onChange({ persistence: p })}
/>
</>
)}
{reported(details?.storageOptions) && (
<>
<label className={styles.formLabel} htmlFor="db-table-options">
<T>Storage options</T>
</label>
<Input
id="db-table-options"
mono
placeholder="fillfactor=70, autovacuum_enabled=false"
value={value.storageOptions}
disabled={!support.storageOptions}
onChange={(e) => onChange({ storageOptions: e.target.value })}
/>
</>
)}
{reported(details?.accessMethod) && (
<>
<label className={styles.formLabel} htmlFor="db-table-access-method">
<T>Access method</T>
</label>
<Input id="db-table-access-method" mono value={details?.accessMethod ?? ""} readOnly disabled />
</>
)}
{reported(details?.partitioning) && (
<>
<label className={styles.formLabel} htmlFor="db-table-partitioning">
<T>Partitioning</T>
</label>
<Input id="db-table-partitioning" mono value={details?.partitioning ?? ""} readOnly disabled />
</>
)}
</div>
);
}
type GrantsState =
| { status: "loading" }
| { status: "ok"; grants: DbTableGrant[] }
+206 -32
Переглянути файл
@@ -48,17 +48,25 @@ import { DUCKDB_JDBC_PREFIX, VENDORS, blankSnowflake, sourceUrl, vendorById, ven
import { JdbcDriverProfiles, jdbcProfileOption, useJdbcDrivers } from "./JdbcDriverProfiles";
import styles from "./Database.module.css";
import { isImeKey } from "@/platform/ime";
import { confirm } from "@/workbench/messages";
type Tab = "general" | "options" | "ssh" | "schemas" | "advanced";
type ConnectionMethod = "direct" | "ssh" | "external";
type DuckDbMode = "file" | "memory" | "url";
type DuckDbMode = "file" | "memory" | "url" | "ducklake";
type DuckLake = NonNullable<DataSource["duckLake"]>;
const DUCKDB_MODES: Array<{ id: DuckDbMode; label: string }> = [
{ id: "file", label: "File" },
{ id: "memory", label: "In memory" },
{ id: "ducklake", label: "DuckLake" },
{ id: "url", label: "JDBC URL" },
];
const DUCKLAKE_CATALOGS: Array<SelectOption<DuckLake["kind"]>> = [
{ value: "file", label: "Catalog file" },
{ value: "secret", label: "DuckDB secret" },
];
const TYPES: SelectOption[] = VENDORS.map((v) => ({ value: v.id, label: v.label, icon: v.icon }));
const COLORS: Array<SelectOption<DbColor | "none">> = [
@@ -222,6 +230,13 @@ function jdbcDatabaseFile(file: string | null | undefined, root: string | undefi
return `${directory.replace(/\/+$/, "")}/${path}`;
}
function duckLakePath(path: string, root: string | undefined, projectRelative = false): string | null {
if (!path.trim() || /[\0\r\n]/.test(path) || path.startsWith("//") || path.startsWith("\\")) return null;
return absoluteDatabaseFile(path, root) || (projectRelative && root && !path.includes(":"))
? jdbcDatabaseFile(path, root)
: null;
}
function builtInTarget(s: DataSource, driver: DataSource["driver"], root: string | undefined): Partial<DataSource> {
const url = s.url ?? "";
if (driver === "sqlite") {
@@ -289,6 +304,9 @@ function FileField({
value,
placeholder,
disabled,
invalid,
browseLabel,
directory = false,
title,
onChange,
}: {
@@ -297,6 +315,9 @@ function FileField({
value: string;
placeholder?: string;
disabled?: boolean;
invalid?: boolean;
browseLabel?: string;
directory?: boolean;
title: string;
onChange: (v: string) => void;
}) {
@@ -310,14 +331,16 @@ function FileField({
id={id}
className={styles.fill}
disabled={disabled}
invalid={invalid}
value={value}
placeholder={placeholder}
onChange={(e) => onChange(e.target.value)}
/>
<Button
disabled={disabled}
aria-label={browseLabel && tx(browseLabel)}
onClick={() =>
void pickFile(title).then((f) => {
void choosePath({ directory, title: tx(title) }).then((f) => {
if (f) onChange(f);
})
}
@@ -498,7 +521,7 @@ export function SourceDialog({
const [sshSecret, setSshSecret] = useState<string | undefined>(undefined);
const [tab, setTab] = useState<Tab>("general");
const [test, setTest] = useState<{ ok: boolean; text: string; trust?: boolean; tunnel?: boolean } | null>(null);
const [busyKind, setBusy] = useState<"connecting" | "external" | null>(null);
const [busyKind, setBusy] = useState<"connecting" | "external" | "creatingLake" | null>(null);
const busy = busyKind !== null;
const [reviewRequest, setReviewRequest] = useState(0);
const reviewPanel = useRef<HTMLDivElement>(null);
@@ -531,9 +554,12 @@ export function SourceDialog({
const duckdb = vendor.id === "duckdb";
const jdbcOnly = vendor.driver === "jdbc";
const [duckDbMode, setDuckDbMode] = useState<DuckDbMode>(() => {
if (s.duckLake) return "ducklake";
if (s.urlOnly) return "url";
return !s.file && s.url === DUCKDB_JDBC_PREFIX ? "memory" : "file";
});
const lakeMode = duckdb && duckDbMode === "ducklake";
const lake: DuckLake = s.duckLake ?? { kind: "file", value: "", dataPath: null };
const savedJdbcWithPreset = initial?.driver === "jdbc" && (!genericJdbc || vendorOf(initial).driver !== "jdbc");
const jdbcProfiles = useJdbcDrivers();
const availableProfiles = jdbcProfiles.drivers?.filter((d) => genericJdbc || d.vendor === vendor.id);
@@ -541,6 +567,13 @@ export function SourceDialog({
const jdbcProfile = availableProfiles?.find((d) => d.id === selectedProfileId);
const installedJdbcProfile = jdbcProfiles.drivers?.find((d) => d.id === s.jdbcDriver);
const projectRoot = useProject((st) => st.project?.root);
const lakeValue =
lake.kind === "file"
? duckLakePath(lake.value, projectRoot, true)
: /^[A-Za-z_][A-Za-z0-9_]*$/.test(lake.value)
? lake.value
: null;
const lakeDataPath = lake.dataPath ? duckLakePath(lake.dataPath, projectRoot) : null;
const remote = useRemote((st) => st.session !== null);
const nativeUrl = nativeSource?.urlOnly ? parseSourceUrl(nativeSource.url ?? "") : null;
const nativeOptions = nativeSource?.options;
@@ -575,6 +608,10 @@ export function SourceDialog({
const loadedSchemas = useDatabase((st) => (initial?.id ? st.schemas[initial.id] : undefined));
const set = (patch: Partial<DataSource>) => setS((x) => ({ ...x, ...patch }));
const setLake = (patch: Partial<DuckLake>) => {
set({ duckLake: { ...lake, ...patch } });
setTest(null);
};
const ssh: DbSsh = { ...blankSsh(), ...s.ssh };
const sshConfigs = useWorkflowSettings((w) => w.ssh.configs);
const sshConfigId = ssh.config?.trim() ?? "";
@@ -598,7 +635,7 @@ export function SourceDialog({
const sqlite = s.driver === "sqlite";
const postgres = s.driver === "postgres";
const externalTunnel = s.externalTunnel;
const externalTunnel = lakeMode ? null : s.externalTunnel;
const setExternalTunnel = (patch: Partial<DbExternalTunnel>) =>
setS((x) => (x.externalTunnel ? { ...x, externalTunnel: { ...x.externalTunnel, ...patch } } : x));
const externalAvailable = postgres && isTauri() && !remote && !s.pluginOwner;
@@ -624,7 +661,7 @@ export function SourceDialog({
(genericJdbc
? (jdbcProfile?.name ?? tx("Custom JDBC"))
: duckdb
? (duckDbMode === "file" && fileSourceName(s.file ?? "")) || vendor.label
? (lakeMode && tx("DuckLake")) || (duckDbMode === "file" && fileSourceName(s.file ?? "")) || vendor.label
: vendor.driver === "sqlite"
? fileSourceName(s.file ?? "")
: `${database || s.user || "db"}@${host || "localhost"}`);
@@ -667,17 +704,20 @@ export function SourceDialog({
? ""
: DUCKDB_JDBC_PREFIX + duckDbFile
: duckdb
? duckDbMode === "memory"
? duckDbMode === "memory" || lakeMode
? DUCKDB_JDBC_PREFIX
: (urlDraft ?? s.url ?? "")
: fromTemplate
? renderedUrl
: (s.url ?? "");
const duckDbTarget = jdbcUrl.split(";", 1)[0]!;
const duckDbMemory =
duckdb &&
(duckDbMode === "memory" ||
(duckDbMode === "url" &&
[DUCKDB_JDBC_PREFIX, `${DUCKDB_JDBC_PREFIX}:memory:`].includes(jdbcUrl.split(";", 1)[0]!)));
(duckDbTarget === DUCKDB_JDBC_PREFIX ||
duckDbTarget.startsWith(DUCKDB_JDBC_PREFIX + "memory:") ||
duckDbTarget.startsWith(DUCKDB_JDBC_PREFIX + ":memory:"))));
const chooseProfile = (profile?: DbJdbcDriver, type = vendor) => {
setTest(null);
setConnectionSecurityConfirmed(false);
@@ -729,6 +769,7 @@ export function SourceDialog({
: /^jdbc:[^\s:]+:[^\r\n]*$/.test(jdbcUrl) &&
!jdbcUrlPlaceholder.test(jdbcUrl) &&
(!duckdb || jdbcUrl.startsWith(DUCKDB_JDBC_PREFIX));
const lakeDriver = jdbcProfile?.className === "org.duckdb.DuckDBDriver";
const valid =
(!externalTunnel ||
(!externalError &&
@@ -738,6 +779,7 @@ export function SourceDialog({
? !!jdbcProfile &&
jdbcUrlValid &&
!(duckDbMemory && s.readOnly) &&
(!lakeMode || (lakeDriver && !!lakeValue && (!lake.dataPath || !!lakeDataPath))) &&
(!reviewJdbcSecurity || connectionSecurityConfirmed)
: (!reviewBuiltinSecurity || connectionSecurityConfirmed) &&
(sqlite
@@ -759,10 +801,16 @@ export function SourceDialog({
url: jdbcUrl,
urlOnly: !duckdb || duckDbMode === "url",
...(duckdb && { file: duckDbFile }),
duckLake: lakeMode ? { kind: lake.kind, value: lakeValue ?? "", dataPath: lakeDataPath } : null,
...(lakeMode && { readOnly: true, user: "", savePassword: false, properties: [], externalTunnel: null }),
ssh: null,
options: { ...options, transaction: "auto" as const },
options: {
...options,
transaction: "auto" as const,
...(lakeMode && { startupScript: "", defaultSchema: "", timeZone: "" }),
},
}
: {}),
: { duckLake: null }),
});
const setType = (id: string, builtIn = false) => {
@@ -911,7 +959,7 @@ export function SourceDialog({
} else {
const v = await call(
request === null
? commands.dbTest(source, password ?? null, secret)
? commands.dbTest(source, lakeMode ? null : (password ?? null), secret)
: commands.dbTestExternalTunnel(request, source, password ?? null),
);
if (stillTesting()) setTest({ ok: true, text: tx`Succeeded: ${v}` });
@@ -946,16 +994,28 @@ export function SourceDialog({
setBusy("connecting");
try {
const source = { ...draft, properties: draft.properties?.filter((p) => p.name?.trim()) ?? [] };
if (jdbc && !source.global) await call(commands.dbApproveJdbcSource(source));
// An older host can discard DuckLake settings when saving a regular source.
if (source.duckLake) await call(commands.dbApproveDucklakeSource(source));
else if (jdbc && !source.global) await call(commands.dbApproveJdbcSource(source));
if (source.externalTunnel) await call(commands.dbApproveExternalTunnel(source));
await saveSource(
source,
sqlite ? undefined : password === undefined ? undefined : password || null,
lakeMode ? null : sqlite || password === undefined ? undefined : password || null,
!sshOn || sshSecret === undefined || sshUsed.auth === "openSsh" ? undefined : sshSecret || null,
);
if (useDatabase.getState().dialog === dialog) closeDialog();
} catch (e) {
setTest({ ok: false, text: e instanceof Error ? e.message : String(e) });
const unsupported =
draft.duckLake &&
e instanceof IpcError &&
e.kind === "protocol" &&
e.message === "command db_approve_ducklake_source is not available remotely";
const text = unsupported
? tx("Update the remote OpenIDEA server to save DuckLake data sources.")
: e instanceof Error
? e.message
: String(e);
setTest({ ok: false, text });
} finally {
setBusy(null);
}
@@ -972,7 +1032,7 @@ export function SourceDialog({
{ id: "options", label: "Options" },
...(sqlite || snowflake || jdbc ? [] : [{ id: "ssh" as const, label: "SSH/SSL" }]),
...(sqlite ? [] : [{ id: "schemas" as const, label: "Schemas" }]),
{ id: "advanced", label: "Advanced" },
...(lakeMode ? [] : [{ id: "advanced" as const, label: "Advanced" }]),
];
const current = tabs.some((t) => t.id === tab) ? tab : "general";
const props = duckdb
@@ -995,6 +1055,36 @@ export function SourceDialog({
}
};
const createLake = async () => {
if (busy || !lakeDriver || (reviewJdbcSecurity && !connectionSecurityConfirmed)) return;
setBusy("creatingLake");
setTest(null);
try {
const picked = await chooseSavePath({
title: tx("Choose a new DuckLake directory"),
defaultPath: jdbcDatabaseFile("ducklake", projectRoot) ?? "ducklake",
});
if (!picked) return;
const directory = duckLakePath(picked, projectRoot);
if (!directory) throw new Error(tx("Choose an absolute directory on the database host."));
const approved = await confirm({
title: "Create New DuckLake",
message: tx`Create a DuckLake in '${directory}'? The directory must not already exist.`,
ok: "Create",
});
if (!approved) return;
const path = `${directory.replace(/\/+$/, "")}/catalog.ducklake`;
const duckLake = { kind: "file" as const, value: path, dataPath: null };
await call(commands.dbCreateDucklake(selectedProfileId, directory));
set({ duckLake });
setTest({ ok: true, text: tx("DuckLake created. The data source opens it read-only.") });
} catch (e) {
setTest({ ok: false, text: e instanceof Error ? e.message : String(e) });
} finally {
setBusy(null);
}
};
const general = (
<>
<span className={styles.formLabel}>
@@ -1072,6 +1162,7 @@ export function SourceDialog({
type="button"
key={id}
aria-pressed={id === duckDbMode}
disabled={busy}
onClick={() => {
setDuckDbMode(id);
if (id === "url" && duckDbMode !== "url" && urlDraft === null) set({ url: jdbcUrl });
@@ -1122,21 +1213,102 @@ export function SourceDialog({
)}
</>
)}
<label className={styles.formLabel} htmlFor="db-url">
<T>URL:</T>
</label>
<Input
id="db-url"
mono
value={jdbcUrl}
readOnly={duckDbMode !== "url"}
invalid={duckDbMode === "url" && !!jdbcUrl && !jdbcUrlValid}
placeholder={DUCKDB_JDBC_PREFIX}
onChange={(e) => {
setUrlDraft(e.target.value);
setTest(null);
}}
/>
{lakeMode ? (
<>
<span className={styles.formLabel}>
<T>Catalog type:</T>
</span>
<Select
aria-label={tx("Catalog type")}
options={DUCKLAKE_CATALOGS}
value={lake.kind}
disabled={busy}
onChange={(kind) => setLake({ kind, value: "" })}
/>
{lake.kind === "file" ? (
<FileField
id="db-ducklake-file"
label="Catalog file:"
title="Open DuckLake Catalog"
browseLabel="Browse for DuckLake catalog"
disabled={busy}
invalid={!!lake.value && !lakeValue}
value={lake.value}
onChange={(value) => setLake({ value })}
/>
) : (
<>
<label className={styles.formLabel} htmlFor="db-ducklake-secret">
<T>Secret name:</T>
</label>
<Input
id="db-ducklake-secret"
disabled={busy}
invalid={!!lake.value && !lakeValue}
value={lake.value}
onChange={(e) => setLake({ value: e.target.value })}
/>
</>
)}
<span />
<span className={styles.formHint}>
{lake.kind === "file" ? (
<T>Choose an existing catalog file on the database host.</T>
) : (
<T>Use the name of an existing DuckDB secret of type ducklake.</T>
)}
</span>
<FileField
id="db-ducklake-data"
label="Data directory:"
title="Choose DuckLake Data Directory"
browseLabel="Browse for DuckLake data directory"
value={lake.dataPath ?? ""}
disabled={busy}
invalid={!!lake.dataPath && !lakeDataPath}
directory
onChange={(dataPath) => setLake({ dataPath })}
/>
<span />
<span className={styles.formHint}>
<T>
Optional absolute directory on the database host. Leave empty to use the catalog’s stored location.
</T>
</span>
<span />
<div className={styles.formRow}>
<Button
disabled={busy || !lakeDriver || !!(reviewJdbcSecurity && !connectionSecurityConfirmed)}
onClick={() => void createLake()}
>
<T>Create New DuckLake…</T>
</Button>
</div>
{jdbcProfile && !lakeDriver && (
<span className={styles.formFull} role="alert">
<T>DuckLake requires the official DuckDB JDBC driver.</T>
</span>
)}
</>
) : (
<>
<label className={styles.formLabel} htmlFor="db-url">
<T>URL:</T>
</label>
<Input
id="db-url"
mono
value={jdbcUrl}
readOnly={duckDbMode !== "url"}
invalid={duckDbMode === "url" && !!jdbcUrl && !jdbcUrlValid}
placeholder={DUCKDB_JDBC_PREFIX}
onChange={(e) => {
setUrlDraft(e.target.value);
setTest(null);
}}
/>
</>
)}
{duckDbMemory && (
<>
<span />
@@ -1458,8 +1630,8 @@ export function SourceDialog({
<Section title="Connection" />
<span />
<Checkbox
checked={!!s.readOnly}
disabled={duckDbMemory && !s.readOnly}
checked={lakeMode || !!s.readOnly}
disabled={lakeMode || (duckDbMemory && !s.readOnly)}
onChange={(readOnly) => set({ readOnly })}
label="Read-only"
/>
@@ -2163,7 +2335,9 @@ export function SourceDialog({
{busy && !shownTest
? busyKind === "external"
? tx("Testing external TCP tunnel and PostgreSQL connection…")
: tx("Connecting…")
: busyKind === "creatingLake"
? tx("Creating DuckLake…")
: tx("Connecting…")
: (externalError ?? shownTest?.text)}
{shownTest?.trust && (
<>
+140
Переглянути файл
@@ -0,0 +1,140 @@
.workspace {
display: flex;
height: 100%;
min-height: 0;
flex-direction: column;
background: var(--bg-editor);
}
.toolbar,
.firstRunActions,
.running,
.settingsActions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
}
.toolbar {
flex: none;
padding: var(--space-1) var(--space-2);
border-bottom: 1px solid var(--border);
gap: var(--space-0-5);
}
.context {
min-width: 0;
max-width: calc(100% - 32px);
margin-inline-start: auto;
}
.context > span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.firstRun,
.running {
color: var(--fg-muted);
}
.running {
margin-inline-start: var(--space-2);
}
.settings [role="alert"] {
color: var(--danger);
}
.settings {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: var(--space-3) var(--space-4);
}
.settings p {
margin: 0;
color: var(--fg-muted);
}
.driverMode {
margin-inline-start: var(--space-2);
color: var(--fg-muted);
}
.aliasFields {
display: grid;
gap: var(--space-2);
max-height: 260px;
overflow: auto;
padding: var(--space-2) var(--space-1) var(--space-1) 0;
}
.aliasField {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
}
.aliasName {
display: flex;
gap: var(--space-1-5);
align-items: center;
}
.aliasName > span,
.aliasName small {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.aliasName small {
display: block;
color: var(--fg-muted);
}
.field {
display: grid;
gap: var(--space-1);
min-width: 0;
}
.query {
position: relative;
flex: 1;
min-height: 90px;
overflow: hidden;
}
.editor {
height: 100%;
}
.firstRun {
position: absolute;
inset-block-start: 42px;
inset-inline-start: 44px;
max-width: calc(100% - 54px);
padding: var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-field, 6px);
background: var(--bg-island);
pointer-events: none;
}
.firstRunActions button {
pointer-events: auto;
}
.example {
margin: var(--space-2) 0;
color: var(--fg-editor);
font-family: var(--font-mono);
line-height: 1.45;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.exampleKeyword {
color: var(--syn-keyword);
}
.exampleName {
color: var(--syn-string);
}
.query[data-result] {
flex: 0 1 38%;
border-bottom: 1px solid var(--border);
}
.query :global(.cm-editor) {
height: 100%;
}
.results {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: hidden;
}
+907
Переглянути файл
@@ -0,0 +1,907 @@
import {
autocompletion,
completionKeymap,
hasNextSnippetField,
hasPrevSnippetField,
snippet,
startCompletion,
type Completion,
type CompletionSource,
} from "@codemirror/autocomplete";
import { EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { Fragment, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { findLanguageDescription, loadSupport } from "@/editor/core/cm/languages";
import { baseExtensions, compartments } from "@/editor/core/cm/setup";
import { executeAction } from "@/platform/actions";
import { tx, useTx } from "@/platform/i18n";
import { shortcutLabel } from "@/platform/keymap";
import {
call,
commands,
isCancelled,
nextRequestId,
type DataSource,
type DbQueryResult,
type RequestId,
} from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { Button, Dialog, Icon, IconButton, Input, Select, Spinner, T, Tabs, Toolbar } from "@/ui";
import type { EditorInput } from "@/workbench/contributions";
import { executionMarks, trackExecution } from "./executionMarks";
import { Grid } from "./Grid";
import { jdbcProfileOption, JdbcDriverProfiles, useJdbcDrivers } from "./JdbcDriverProfiles";
import { sourceLabel, targetOf } from "./model";
import { projectRequest } from "./requests";
import { formatElapsed } from "./resultView";
import { quoteIdent } from "./sql/complete";
import { identName, inLiteral, lex } from "./sql/lexer";
import { loadCompletion, loadSources, useDatabase } from "./store";
import { DUCKDB_JDBC_CLASS, DUCKDB_JDBC_PREFIX, vendorOf } from "./vendors";
import {
WORKSPACE_SQL_LIMIT,
workspaceJoinColumnOptions,
workspaceJoinColumnTarget,
workspaceJoinQuery,
workspaceSourceAliasError,
workspaceSourceResolver,
type WorkspaceSourceReference,
workspaceStatementRanges,
} from "./workspaceQuery";
import dbStyles from "./Database.module.css";
import styles from "./WorkspaceEditor.module.css";
const PAGE_SIZE = 500;
const MAX_BATCH_STATEMENTS = 12;
const MAX_BATCH_ROWS = 100_000;
const MAX_BATCH_BYTES = 64 * 1024 * 1024;
type WorkspaceResult = { sql: string; data: DbQueryResult; page: number };
type WorkspaceRun = { request: RequestId | null; cancelled: boolean };
// Estimate retained JS payload without serializing or copying the grid's rows.
function resultBytes(result: DbQueryResult, available: number): number {
let bytes = 0;
for (const column of result.columns) bytes += 64 + 2 * (column.name.length + column.typeName.length);
for (const row of result.rows) {
bytes += 24 + 8 * row.length;
for (const cell of row) if (cell !== null) bytes += 24 + 2 * cell.length;
if (bytes > available) break;
}
return bytes;
}
function resultLabel(n: number) {
return tx`Result ${n}`;
}
type Configuration = {
profile: string;
sourceAliases: Record<string, string>;
legacySources: { left: string; right: string };
};
type SavedSource = DataSource & { id: string };
type SourceResolver = ReturnType<typeof workspaceSourceResolver>;
function sourcePrefix(name: string) {
return "#" + quoteIdent(name, "postgres");
}
function preferredReference(ref: WorkspaceSourceReference, resolve: SourceResolver) {
if (ref.alias && resolve(ref.alias)?.id === ref.id) return sourcePrefix(ref.alias);
const prefix = sourcePrefix(ref.name);
if (resolve(ref.name, prefix.startsWith('#"'))?.id === ref.id) return prefix;
if (resolve(ref.name, true)?.id === ref.id) return '#"' + ref.name.replaceAll('"', '""') + '"';
return undefined;
}
const JOIN_TEMPLATE =
"SELECT *\nFROM ${1:#source_a}.${3:schema.table_a} AS a\nJOIN ${2:#source_b}.${4:schema.table_b} AS b\n ON a.${5:key} = b.${6:key}";
const exampleKeywords = new Set(["SELECT", "FROM", "AS", "JOIN", "ON"]);
function JoinExample() {
const sql = JOIN_TEMPLATE.replace(/\$\{\d+:([^}]+)\}/g, "$1");
const tokens = lex(sql, "postgres").tokens.filter(
(token) => token.kind === "quoted" || exampleKeywords.has(token.upper),
);
return (
<pre className={styles.example}>
<code>
{tokens.map((token, index) => (
<Fragment key={token.from}>
{sql.slice(tokens[index - 1]?.to ?? 0, token.from)}
<span className={token.kind === "quoted" ? styles.exampleName : styles.exampleKeyword}>{token.text}</span>
</Fragment>
))}
{sql.slice(tokens.at(-1)?.to ?? 0)}
</code>
</pre>
);
}
function eligible(source: DataSource): source is SavedSource {
if (!source.id || source.id.includes(":") || source.options?.startupScript?.trim()) return false;
if (source.driver === "postgres" || source.driver === "clickhouse") return true;
if (source.driver === "sqlite") return !!source.file && !source.file.includes(":memory:");
if (source.driver !== "jdbc" || vendorOf(source).id !== "duckdb") return false;
const endpoint = source.url?.split(";", 1)[0];
if (!endpoint?.startsWith(DUCKDB_JDBC_PREFIX)) return false;
const path = endpoint.slice(DUCKDB_JDBC_PREFIX.length);
return !!path && !/^[: ]|^(?:memory|md):/i.test(path) && !path.includes("://");
}
function sourceReferences(sources: SavedSource[], config: Configuration): WorkspaceSourceReference[] {
return sources.map((source) => ({
id: source.id,
name: source.name || source.id,
alias: Object.hasOwn(config.sourceAliases, source.id) ? config.sourceAliases[source.id]!.trim() : undefined,
legacy:
source.id === config.legacySources.left ? "left" : source.id === config.legacySources.right ? "right" : undefined,
}));
}
function metadataTarget(source: SavedSource, database: string) {
if (!database || database === source.database || (source.driver === "sqlite" && database === "main"))
return source.id;
if (source.driver === "postgres" || source.driver === "clickhouse")
return targetOf(source.id, database, source.database ?? null);
// A file source's completion is for its saved file only.
return null;
}
function complete(
bindings: () => {
references: WorkspaceSourceReference[];
resolve: SourceResolver;
candidates: SavedSource[];
configureAliases: () => void;
},
): CompletionSource {
return async (context) => {
const field = context.state.selection.main;
const selectingField =
context.explicit &&
!field.empty &&
field.from === context.pos &&
(hasNextSnippetField(context.state) || hasPrevSnippetField(context.state));
const end = selectingField ? field.to : context.pos;
if (end > WORKSPACE_SQL_LIMIT) return null;
const sql = context.state.sliceDoc(0, end);
const parsed = lex(sql, "postgres");
const state = inLiteral(parsed, end);
if (state === "string" || state === "comment") return null;
const { references, resolve, candidates, configureAliases } = bindings();
const current = projectRequest();
const stillCurrent = () =>
current() && !context.aborted && (!context.view || context.view.state.doc === context.state.doc);
const target = workspaceJoinColumnTarget(sql, resolve, parsed);
if (target) {
const source = candidates.find((candidate) => candidate.id === target.sourceId);
const id = source && metadataTarget(source, target.database);
if (!id) return null;
const catalog = useDatabase.getState().completion[id] ?? (await loadCompletion(id));
if (!catalog || !stillCurrent()) return null;
const updated = workspaceJoinColumnTarget(sql, bindings().resolve, parsed);
if (
updated?.sourceId !== target.sourceId ||
updated.database !== target.database ||
updated.schema !== target.schema ||
updated.table !== target.table
)
return null;
const selectingKey = selectingField && field.from === target.from;
const column = selectingKey ? { ...target, prefix: "" } : target;
return {
from: target.from,
to: selectingKey ? field.to : undefined,
options: workspaceJoinColumnOptions(column, catalog),
filter: false,
};
}
const hash = parsed.tokens.findLastIndex((token) => token.text === "#");
if (hash < 0) return null;
const tokens = parsed.tokens.slice(hash + 1);
if (tokens.some((token) => token.kind !== "quoted" && token.kind !== "word" && token.text !== ".")) return null;
const from = parsed.tokens[hash]!.from;
const prefix = sql.slice(from);
if (/\s$/.test(prefix) && state !== "quoted") return null;
if (tokens.length < 2) {
const typed = tokens[0]?.text.toLowerCase() ?? "";
const options: Completion[] = [];
const vendors = new Map(candidates.map((source) => [source.id, vendorOf(source).label]));
let needsAliases = false;
for (const ref of references) {
const preferred = preferredReference(ref, resolve);
if (!preferred) needsAliases = true;
else {
const detail = preferred === sourcePrefix(ref.name) ? vendors.get(ref.id) : ref.name;
options.push({ label: preferred, type: "namespace", detail, boost: 5 });
}
if (ref.legacy && preferred !== "#" + ref.legacy && typed && ref.legacy.startsWith(typed))
options.push({ label: "#" + ref.legacy, type: "namespace", detail: ref.name });
}
if (needsAliases) {
options.push({
label: prefix,
displayLabel: tx("Set unique SQL aliases…"),
type: "namespace",
boost: -10,
apply: configureAliases,
});
}
const selectingSource = selectingField && field.from === from;
return { from, to: selectingSource ? field.to : undefined, options, filter: !selectingSource };
}
const sourceToken = tokens[0]!;
const name = identName(sourceToken);
const quoted = sourceToken.kind === "quoted";
const ref = resolve(name, quoted);
if (!ref || tokens[1]!.text !== ".") return null;
const source = candidates.find((candidate) => candidate.id === ref.id);
const qualifier = tokens[2];
const explicitDatabase = qualifier && qualifier.text !== "." && tokens[3]?.text === "." && tokens[5]?.text === ".";
const database = explicitDatabase
? qualifier.kind === "word"
? qualifier.text.toLowerCase()
: identName(qualifier)
: "";
const id = source && metadataTarget(source, database);
if (!id) return null;
const catalog = useDatabase.getState().completion[id] ?? (await loadCompletion(id));
if (!catalog || !stillCurrent() || bindings().resolve(name, quoted)?.id !== ref.id) return null;
// Keep the user's quoted or bare source spelling, which the resolver interpreted above.
const sourcePath = sql.slice(from, sourceToken.to) + (database ? "." + quoteIdent(database, "postgres") : "");
const prefixLower = prefix.toLowerCase();
const selectingTable = selectingField && field.from === tokens[1]!.to;
const options: Completion[] = [];
for (const table of catalog.tables) {
if (table.kind !== "table") continue;
const tableName = quoteIdent(table.name, "postgres");
const schema = quoteIdent(table.schema || catalog.defaultSchema, "postgres");
const qualified = `${sourcePath}.${schema}.${tableName}`;
const direct = `${sourcePath}.${tableName}`;
const label =
selectingTable || qualified.toLowerCase().startsWith(prefixLower)
? qualified
: !database && table.schema === catalog.defaultSchema && direct.toLowerCase().startsWith(prefixLower)
? direct
: null;
if (label) {
options.push({
label: selectingTable ? label.slice(sourcePath.length + 1) : label,
type: "class",
detail: ref.name,
});
if (options.length === 100) break;
}
}
return {
from: selectingTable ? field.from : from,
to: selectingTable ? field.to : undefined,
options,
filter: false,
};
};
}
function readDraft(key: string) {
let value: Record<string, unknown> = {};
try {
const stored: unknown = JSON.parse(localStorage.getItem(key) ?? "null");
if (stored && typeof stored === "object") value = stored as Record<string, unknown>;
} catch {
/* Storage may be disabled. */
}
const legacy = value.legacySources as Partial<Configuration["legacySources"]> | null | undefined;
return {
legacySources: {
left: typeof legacy?.left === "string" ? legacy.left : typeof value.left === "string" ? value.left : "",
right: typeof legacy?.right === "string" ? legacy.right : typeof value.right === "string" ? value.right : "",
},
profile: typeof value.profile === "string" ? value.profile : "",
sourceAliases: Object.fromEntries(
value.sourceAliases && typeof value.sourceAliases === "object"
? Object.entries(value.sourceAliases).filter((entry): entry is [string, string] => typeof entry[1] === "string")
: [],
),
sql: typeof value.sql === "string" ? value.sql : "",
};
}
export function WorkspaceEditor({ input }: { input: EditorInput }) {
const t = useTx();
const storageKey = "openidea." + input.key;
const [draft] = useState(() => readDraft(storageKey));
const sources = useDatabase((state) => state.sources);
const registry = useJdbcDrivers();
const [config, setConfig] = useState<Configuration>({
legacySources: draft.legacySources,
profile: draft.profile,
sourceAliases: draft.sourceAliases,
});
const [settings, setSettings] = useState<Configuration | null>(null);
const [showAliases, setShowAliases] = useState(false);
const settingsRequested = useDatabase((state) => state.workspaceSettingsRequest === input.key);
const [manage, setManage] = useState(false);
const [empty, setEmpty] = useState(() => draft.sql.length === 0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [results, setResults] = useState<WorkspaceResult[]>([]);
const [active, setActive] = useState("feedback");
const panelId = useId();
const panel = useRef<HTMLDivElement>(null);
const host = useRef<HTMLDivElement>(null);
const view = useRef<EditorView | null>(null);
const running = useRef<WorkspaceRun | null>(null);
const candidates = useMemo(() => sources.filter(eligible), [sources]);
const drivers = registry.drivers?.filter((d) => d.vendor === "duckdb" && d.className === DUCKDB_JDBC_CLASS) ?? [];
const driverFor = (id: string) =>
id ? drivers.find((driver) => driver.id === id) : drivers.length === 1 ? drivers[0] : undefined;
const references = useMemo(() => sourceReferences(candidates, config), [candidates, config]);
const resolve = useMemo(() => workspaceSourceResolver(references, config), [references, config]);
const usableReferences = useMemo(
() => references.filter((ref) => preferredReference(ref, resolve)).length,
[references, resolve],
);
const aliasError = useMemo(() => workspaceSourceAliasError(references, resolve), [references, resolve]);
const needsAliases = usableReferences !== references.length;
const ready = !!driverFor(config.profile) && candidates.length >= 2;
const settingsError = useMemo(() => {
if (!settings) return null;
const sources = sourceReferences(candidates, settings);
return workspaceSourceAliasError(sources, workspaceSourceResolver(sources, settings));
}, [candidates, settings]);
const current = useRef({
config,
references,
resolve,
candidates,
execute: () => {},
configureAliases: () => {},
});
const openSettings = (aliases = needsAliases || !!aliasError) => {
if (running.current) return;
setShowAliases(aliases);
setSettings(config);
};
useEffect(() => {
if (!settingsRequested || busy) return;
const frame = requestAnimationFrame(() => {
useDatabase.setState({ workspaceSettingsRequest: null });
setShowAliases(needsAliases || !!aliasError);
setSettings(config);
});
return () => cancelAnimationFrame(frame);
}, [settingsRequested, busy, config, needsAliases, aliasError]);
const stop = () => {
const run = running.current;
if (!run || run.cancelled) return;
run.cancelled = true;
if (run.request !== null) void commands.cancelRequest(run.request);
};
const execute = async (script = false) => {
const editor = view.current;
if (running.current || !editor) return;
const driver = driverFor(config.profile);
if (!ready || !driver) {
openSettings();
return;
}
const state = editor.state;
const range = state.selection.main;
// Tab fields in Insert JOIN are selections for editing the template.
const selected = !script && !range.empty && !hasNextSnippetField(state) && !hasPrevSnippetField(state);
const from = selected ? range.from : 0;
const to = selected ? range.to : state.doc.length;
const submitted = selected || script;
const reportError = (message: string) => {
setError(message);
setActive("feedback");
};
if (to - from > WORKSPACE_SQL_LIMIT) {
reportError(tx("Workspace SQL exceeds 65,536 characters."));
return;
}
const sql = state.sliceDoc(from, to);
const spans = workspaceStatementRanges(sql, submitted ? undefined : range.head).map((span) => ({
from: span.from + from,
to: span.to + from,
}));
if (!spans.length) {
editor.focus();
return;
}
if (spans.length > MAX_BATCH_STATEMENTS) {
reportError(tx("The workspace can run up to 12 statements at a time."));
return;
}
const tracker = trackExecution(editor);
const queries = [];
// Validate the entire batch before the first request touches any source.
for (const span of spans) {
const text = state.sliceDoc(span.from, span.to);
try {
queries.push({ text, plan: workspaceJoinQuery(text, resolve) });
} catch (e) {
const error = e instanceof Error ? e.message : String(e);
tracker.start([span]);
tracker.update(null, [{ index: 0, error, ms: null }]);
tracker.end();
reportError(error);
return;
}
}
const activeProject = projectRequest();
const run: WorkspaceRun = { request: null, cancelled: false };
const ownsRun = () => activeProject() && running.current === run;
running.current = run;
setError("");
setResults([]);
setActive("feedback");
setBusy(true);
tracker.start(spans);
let rows = 0;
let bytes = 0;
try {
for (const [index, { text, plan }] of queries.entries()) {
if (!ownsRun()) break;
if (run.cancelled) {
reportError(tx("Cancelled"));
break;
}
const request = nextRequestId();
run.request = request;
const startedAt = Date.now();
tracker.update({ index, startedAt });
try {
// Each JOIN owns the source reads and staging until it finishes.
// oxlint-disable-next-line no-await-in-loop
const data = await call(commands.dbWorkspaceJoin(request, driver.id, plan));
if (!ownsRun()) break;
rows += data.rows.length;
bytes += resultBytes(data, MAX_BATCH_BYTES - bytes);
if (rows > MAX_BATCH_ROWS || bytes > MAX_BATCH_BYTES)
throw new Error(tx("The workspace batch exceeds the result size limit."));
tracker.update(null, [{ index, error: null, ms: data.elapsedMs ?? Date.now() - startedAt }]);
setResults((previous) => [...previous, { sql: text, page: 0, data }]);
setActive(String(index));
} catch (e) {
if (!ownsRun()) break;
const error = isCancelled(e) ? tx("Cancelled") : e instanceof Error ? e.message : String(e);
tracker.update(null, [{ index, error, ms: Date.now() - startedAt }]);
reportError(error);
break;
} finally {
run.request = null;
}
}
} finally {
if (running.current === run) {
running.current = null;
tracker.end();
setBusy(false);
}
}
};
useLayoutEffect(() => {
current.current = {
config,
references,
resolve,
candidates,
execute: () => void execute(),
configureAliases: () => openSettings(true),
};
});
useEffect(() => {
if (!useDatabase.getState().loaded) void loadSources();
if (!host.current) return;
const sql = findLanguageDescription("SQL", "workspace.sql");
const editor = new EditorView({
parent: host.current,
state: EditorState.create({
doc: draft.sql,
extensions: baseExtensions({
ctx: { doc: -1, path: "workspace.sql", language: "sql", uiMode: "SQL", readOnly: false, virtual: true },
settings: useProject.getState().settings?.editor,
info: undefined,
language: null,
docLength: draft.sql.length,
contributions: [],
extra: [
executionMarks,
autocompletion({ override: [complete(() => current.current)] }),
EditorView.updateListener.of((update) => {
if (update.docChanged) setEmpty(update.state.doc.length === 0);
}),
Prec.highest(
keymap.of([
{
key: "Mod-Enter",
run: () => {
current.current.execute();
return true;
},
},
...completionKeymap,
]),
),
Prec.highest(EditorView.contentAttributes.of({ "aria-label": tx("Workspace SQL") })),
],
}),
}),
});
view.current = editor;
const panel = editor.dom.closest("[data-editor-focus]");
const focusEditor = () => editor.focus();
panel?.addEventListener("focus", focusEditor);
if (panel) focusEditor();
const save = () => {
try {
localStorage.setItem(
storageKey,
JSON.stringify({ ...current.current.config, sql: editor.state.doc.toString() }),
);
} catch {
/* The current session remains usable without storage. */
}
};
editor.dom.addEventListener("focusout", save);
window.addEventListener("pagehide", save);
if (sql)
void loadSupport(sql).then((language) => {
if (view.current === editor && language)
editor.dispatch({ effects: compartments.language.reconfigure(language) });
});
return () => {
stop();
running.current = null;
save();
editor.dom.removeEventListener("focusout", save);
panel?.removeEventListener("focus", focusEditor);
window.removeEventListener("pagehide", save);
view.current = null;
editor.destroy();
};
}, [draft, storageKey]);
const insertJoin = () => {
const editor = view.current;
if (!editor || editor.state.doc.length) return;
snippet(JOIN_TEMPLATE)(editor, null, 0, 0);
editor.focus();
startCompletion(editor);
};
const applySettings = () => {
if (!settings || !driverFor(settings.profile) || settingsError) return;
const next = {
...settings,
sourceAliases: Object.fromEntries(
Object.entries(settings.sourceAliases)
.map(([id, alias]) => [id, alias.trim()])
.filter(([, alias]) => alias),
),
};
if (
next.profile !== config.profile ||
JSON.stringify(next.sourceAliases) !== JSON.stringify(config.sourceAliases)
) {
setConfig(next);
setResults([]);
setActive("feedback");
setError("");
}
setSettings(null);
const editor = view.current;
requestAnimationFrame(() => {
if (view.current === editor) editor?.focus();
});
};
const result = results[Number(active)];
const start = (result?.page ?? 0) * PAGE_SIZE;
const first = start + 1;
const total = result?.data.rows.length ?? 0;
const last = Math.min(start + PAGE_SIZE, total);
const hasFeedback = busy || results.length > 0 || !!error;
const setPage = (page: number) =>
setResults((previous) => previous.map((item) => (item === result ? { ...item, page } : item)));
const configureLabel = t("Workspace Settings…");
const driver = driverFor(config.profile);
const connectionContext = driver ? `${configureLabel} · ${driver.name}` : configureLabel;
const newSource = () => void executeAction("db.newDataSource");
return (
<section className={styles.workspace} aria-label={t("Query Workspace")}>
<Toolbar className={styles.toolbar} aria-label="Workspace actions">
{busy ? (
<IconButton icon="stop" title="Stop" tone="danger" onClick={stop} />
) : (
<>
<IconButton
icon="run"
title="Run"
tone="accent"
shortcut={shortcutLabel("db.execute")}
onClick={() => void execute()}
/>
<IconButton icon="gutter-run-all" title="Execute Script" onClick={() => void execute(true)} />
</>
)}
<Button
variant="ghost"
size="small"
className={styles.context}
icon="settings"
aria-label={connectionContext}
title={connectionContext}
disabled={busy}
onClick={() => openSettings()}
>
<span>{driver?.name ?? configureLabel}</span>
</Button>
</Toolbar>
<div className={styles.query} data-result={hasFeedback ? "" : undefined}>
<div className={styles.editor} ref={host} />
{empty && (
<div className={styles.firstRun}>
{candidates.length < 2 ? (
<T>Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources.</T>
) : (
<T>Type # to choose a saved data source.</T>
)}
<JoinExample />
<div className={styles.firstRunActions}>
{usableReferences >= 2 ? (
<Button variant="secondary" size="small" onClick={insertJoin}>
<T>Insert JOIN</T>
</Button>
) : candidates.length < 2 ? (
<Button variant="primary" size="small" onClick={newSource}>
<T>New Data Source…</T>
</Button>
) : (
<Button variant="primary" size="small" onClick={() => openSettings()}>
<T>Workspace Settings…</T>
</Button>
)}
</div>
</div>
)}
</div>
{hasFeedback && (
<>
<Tabs
className={dbStyles.resultTabs}
variant="compact"
aria-label={t("Results")}
activeId={active}
panelIdPrefix={panelId}
onSelect={setActive}
items={[
{ id: "feedback", label: "Feedback", icon: "db-console" },
...results.map(({ sql }, index) => ({
id: String(index),
label: resultLabel(index + 1),
icon: "db-table",
verbatim: true,
tooltip: sql,
})),
]}
focusContent={() => {
const target = panel.current?.querySelector<HTMLElement>('[role="grid"], [role="log"]');
target?.focus();
return !!target && document.activeElement === target;
}}
/>
<div
ref={panel}
className={styles.results}
role="tabpanel"
id={`${panelId}-panel-${active}`}
aria-labelledby={`${panelId}-tab-${active}`}
>
{result ? (
<>
<div className={dbStyles.fill}>
<Grid
key={`${active}-${result.page}`}
columns={result.data.columns.map((c) => ({ name: c.name, type: c.typeName }))}
rowCount={Math.min(PAGE_SIZE, result.data.rows.length - start)}
firstRowNumber={first}
value={(row, col) => result.data.rows[start + row]?.[col] ?? null}
/>
</div>
<div className={dbStyles.pagerDock}>
<Toolbar className={dbStyles.resultPager} aria-label={t("Result pages")}>
{result.data.rows.length > PAGE_SIZE ? (
<>
<IconButton
size="small"
icon="chevron-left"
title="Previous Page"
disabled={result.page === 0}
onClick={() => setPage(result.page - 1)}
/>
<span className={dbStyles.resultPagerRange}>{t`${first}-${last} of ${total}`}</span>
<IconButton
size="small"
icon="chevron-right"
title="Next Page"
disabled={start + PAGE_SIZE >= result.data.rows.length}
onClick={() => setPage(result.page + 1)}
/>
</>
) : (
<span className={dbStyles.resultPagerRange}>{t`${result.data.rows.length} rows`}</span>
)}
</Toolbar>
</div>
</>
) : (
<div role="log" tabIndex={0} className={dbStyles.output} aria-label={t("Feedback")}>
{results.map(({ data }, index) => (
<div key={index} className={dbStyles.outputLine}>
{resultLabel(index + 1)} · {t`${data.rows.length} rows`}
{data.elapsedMs !== null && ` · ${formatElapsed(data.elapsedMs)}`}
</div>
))}
{error && (
<div role="alert" className={dbStyles.outputError}>
{error}
</div>
)}
{busy && (
<div role="status" className={styles.running}>
<Spinner label={t("Running query")} /> <T>Running query</T>
</div>
)}
</div>
)}
</div>
</>
)}
{settings && (
<Dialog
open
title={t("Workspace Settings")}
width={480}
onClose={() => {
setManage(false);
setSettings(null);
}}
buttons={[
{ label: "Cancel", role: "cancel" },
{
label: "OK",
role: "default",
disabled: !driverFor(settings.profile) || !!settingsError,
onClick: applySettings,
},
]}
>
<div className={styles.settings}>
<label className={styles.field}>
<span>
<T>Workspace DuckDB driver</T>
<small className={styles.driverMode}>
<T>In memory</T>
</small>
</span>
<Select
aria-label={t("Workspace DuckDB driver")}
aria-description={t("In memory")}
value={driverFor(settings.profile)?.id ?? null}
placeholder="Select DuckDB driver"
options={drivers.map(jdbcProfileOption)}
onChange={(profile) => setSettings({ ...settings, profile })}
/>
</label>
{!settings.profile && registry.drivers && !driverFor(settings.profile) && (
<p>
<T>Choose a DuckDB JDBC driver to run workspace SQL.</T>
</p>
)}
<div className={styles.settingsActions}>
<Button variant="ghost" disabled={registry.drivers === null} onClick={() => setManage(true)}>
<T>Manage Drivers…</T>
</Button>
{registry.error && (
<Button onClick={registry.retry}>
<T>Retry</T>
</Button>
)}
</div>
{candidates.length > 0 && (
<div>
<Button
variant="ghost"
size="small"
icon={showAliases ? "chevron-down" : "chevron-right"}
aria-expanded={showAliases}
aria-controls={showAliases ? `${panelId}-aliases` : undefined}
onClick={() => setShowAliases(!showAliases)}
>
<T>SQL aliases</T>
</Button>
{showAliases && (
<div id={`${panelId}-aliases`} className={styles.aliasFields}>
<p>
<T>Use a short SQL name for a source. Leave it blank to use the connection name.</T>
</p>
{candidates.map((source) => {
const label = sourceLabel({ ...source, name: source.name || source.id });
const detail = source.file || [source.host, source.database].filter(Boolean).join(" / ");
const alias = Object.hasOwn(settings.sourceAliases, source.id)
? settings.sourceAliases[source.id]
: "";
return (
<label key={source.id} className={styles.aliasField}>
<span className={styles.aliasName} title={detail ? `${label} · ${detail}` : label}>
<Icon name={vendorOf(source).icon} size={14} />
<span>
{source.name || source.id}
{detail && <small>{detail}</small>}
</span>
</span>
<Input
aria-label={t`SQL alias for ${label}`}
aria-description={detail || undefined}
mono
value={alias}
placeholder={source.name || source.id}
onChange={(event) =>
setSettings({
...settings,
sourceAliases: { ...settings.sourceAliases, [source.id]: event.target.value },
})
}
/>
</label>
);
})}
</div>
)}
</div>
)}
{settings.profile && registry.drivers && !driverFor(settings.profile) && (
<p role="alert">
<T>The saved DuckDB driver is unavailable.</T>
</p>
)}
{settingsError && <p role="alert">{settingsError}</p>}
{registry.error && <div role="alert">{registry.error}</div>}
{candidates.length < 2 && (
<div className={styles.settingsActions}>
<p>
<T>Save at least two PostgreSQL, ClickHouse, SQLite, or file-backed DuckDB sources.</T>
</p>
<Button variant="secondary" size="small" onClick={newSource}>
<T>New Data Source…</T>
</Button>
</div>
)}
</div>
</Dialog>
)}
{settings && manage && registry.drivers && (
<JdbcDriverProfiles
drivers={registry.drivers}
selected={driverFor(settings.profile)?.id ?? ""}
sourceVendor="duckdb"
onClose={() => setManage(false)}
onSave={(d) => {
registry.setDrivers((old) => [...(old ?? []).filter((entry) => entry.id !== d.id), d]);
setSettings({ ...settings, profile: d.id });
}}
onUse={(d) => {
setSettings({ ...settings, profile: d.id });
setManage(false);
}}
onRemove={(id) => registry.setDrivers((old) => (old ?? []).filter((d) => d.id !== id))}
/>
)}
</section>
);
}
+22 -479
Переглянути файл
@@ -17,29 +17,12 @@ import {
type CompletionResult,
type CompletionSource,
} from "@codemirror/autocomplete";
import {
Compartment,
EditorSelection,
EditorState,
Facet,
Prec,
RangeSet,
type Range,
StateEffect,
StateField,
type Extension,
type Text,
type Transaction,
} from "@codemirror/state";
import { Compartment, EditorState, Facet, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import {
Decoration,
EditorView,
GutterMarker,
RectangleMarker,
ViewPlugin,
WidgetType,
gutter,
layer,
showPanel,
showTooltip,
type Panel,
@@ -47,9 +30,8 @@ import {
} from "@codemirror/view";
import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
import { createRoot } from "react-dom/client";
import { problemProviders, type ContributedProblem, type EditorDocContext } from "@/editor/api";
import { iconNode, spinnerNode } from "@/ui/iconNode";
import { call, commands, type DbSessionContext, type DbStatementOutcome, type SqlStatement } from "@/platform/ipc";
import type { EditorDocContext } from "@/editor/api";
import { call, commands, type DbSessionContext, type DbStatementOutcome } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
import { useProject } from "@/platform/project";
@@ -76,7 +58,6 @@ import {
} from "./sql/complete";
import { sqlDriverOf, type SqlDriver } from "./sql/dialect";
import { duckdbLanguage } from "./sql/duckdbHighlight";
import { unsafeMessage } from "./sql/unsafe";
import { WHOLE_FILE, sqlSupport, type SqlText } from "./sqlSupport";
import { snowflakeLanguage } from "./sql/snowflakeHighlight";
import {
@@ -107,7 +88,6 @@ import {
setManualCommit,
sourceById,
useDatabase,
type ConfirmUnsafe,
} from "./store";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
@@ -117,393 +97,48 @@ import type { ResultTab } from "./store";
/** `templates` feature's language-data key for finer template contexts. */
const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
import { formatElapsed } from "./resultView";
import { confirmUnsafe, executionMarks, runField, setPreview, trackExecution } from "./executionMarks";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { jdbcDialect } from "./vendors";
export { SQL_LANGUAGE };
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
/** Statement outcomes of the last run, kept on the text (IDEA's gutter check / error and timing). */
interface RunMark {
from: number;
to: number;
/** After the statement's `;` when it has one. */
timingAt: number;
error: string | null;
ms: number | null;
}
interface Executing {
/** Tells this run from a later one on the same console. */
token: number;
active: { index: number; startedAt: number } | null;
spans: readonly { from: number; to: number }[];
}
function activeSpan(ex: Executing | null) {
const span = ex?.active ? ex.spans[ex.active.index] : undefined;
return span && span.from < span.to ? span : undefined;
}
interface AskMark {
from: number;
to: number;
message: string;
}
interface RunState {
ask?: AskMark | null;
marks: readonly RunMark[];
/** Message of the bottom error banner (`null`: hidden). */
banner: string | null;
executing: Executing | null;
}
const setRun = StateEffect.define<RunState>();
const setAsk = StateEffect.define<AskMark | null>();
/** Saving can append the final newline without changing any submitted SQL or statement offsets. */
function savedFinalNewline(tr: Transaction): boolean {
if (!tr.docChanged || !tr.isUserEvent("input.save")) return false;
const end = tr.startState.doc.length;
let only = true;
tr.changes.iterChanges((from, to, _f, _t, insert) => {
only &&= from === end && to === end && insert.toString() === "\n";
});
return only;
}
const runField = StateField.define<RunState>({
create: () => ({ marks: [], banner: null, executing: null }),
update(value, tr) {
for (const e of tr.effects) if (e.is(setRun)) value = { ...e.value, ask: value.ask };
for (const e of tr.effects) if (e.is(setAsk)) value = { ...value, ask: e.value };
if (!tr.docChanged || savedFinalNewline(tr)) return value;
// The request runs the text it was sent; edits only move where that shows.
const ex = value.executing;
const executing = ex && {
...ex,
spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })),
};
// Editing a statement drops its mark.
const marks: RunMark[] = [];
for (const m of value.marks) {
let touched = false;
tr.changes.iterChangedRanges((a, b) => {
if (a <= m.to && b >= m.from) touched = true;
});
if (!touched)
marks.push({
...m,
from: tr.changes.mapPos(m.from),
to: tr.changes.mapPos(m.to),
timingAt: tr.changes.mapPos(m.timingAt),
});
}
return { ...value, marks, executing, ask: null };
},
provide: (f) => [
EditorView.decorations.compute([f], (state) => {
const st = state.field(f);
const ranges = [];
const active = st.executing?.active;
const span = activeSpan(st.executing);
if (active && span) {
const end = state.sliceDoc(span.to, span.to + 1) === ";" ? span.to + 1 : span.to;
const at = Math.min(end, state.doc.lineAt(span.from).to);
ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(span.from, span.to));
ranges.push(Decoration.widget({ widget: new ElapsedWidget(active.startedAt), side: 1 }).range(at));
}
for (const m of st.marks) {
if (m.error) ranges.push(Decoration.mark({ class: "cm-openidea-db-error" }).range(m.from, m.to));
if (m.ms !== null)
ranges.push(Decoration.widget({ widget: new TimingWidget(m.ms), side: 1 }).range(m.timingAt));
}
const u = st.ask;
if (u && u.from < u.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-warning" }).range(u.from, u.to));
return Decoration.set(ranges, true);
}),
showPanel.from(f, (st) => (st.ask ? askBanner(st.ask) : st.banner ? errorBanner(st.banner) : null)),
// The editor's hover shows the run errors and the unsafe-query warning like other problems.
problemProviders.compute([f], (state) => {
const st = state.field(f);
const problems: ContributedProblem[] = [];
for (const m of st.marks)
if (m.error && m.from < m.to) problems.push({ from: m.from, to: m.to, severity: "error", message: m.error });
const u = st.ask;
if (u && u.from < u.to) problems.push({ from: u.from, to: u.to, severity: "warning", message: u.message });
return () => problems;
}),
],
});
class TimingWidget extends WidgetType {
constructor(readonly ms: number) {
super();
}
eq(other: TimingWidget) {
return other.ms === this.ms;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing";
span.textContent = formatElapsed(this.ms);
return span;
}
}
/** The running time of the request, ticking until it ends. */
class ElapsedWidget extends WidgetType {
private timer: ReturnType<typeof setInterval> | undefined;
constructor(readonly startedAt: number) {
super();
}
eq(other: ElapsedWidget) {
return other.startedAt === this.startedAt;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing cm-openidea-db-elapsed";
const tick = () => {
const elapsed = formatElapsed(Date.now() - this.startedAt);
span.textContent = tx`Executing… ${elapsed}`;
};
tick();
this.timer = setInterval(tick, 100);
return span;
}
destroy() {
clearInterval(this.timer);
}
}
class ExecutingMarker extends GutterMarker {
eq(other: GutterMarker) {
return other instanceof ExecutingMarker;
}
toDOM() {
const el = spinnerNode(12, "cm-openidea-db-run-executing");
el.title = tx("Executing");
return el;
}
}
class RunMarker extends GutterMarker {
constructor(
readonly error: string | null,
readonly warning: string | null = null,
) {
super();
}
eq(other: RunMarker) {
return other.error === this.error && other.warning === this.warning;
}
toDOM() {
if (this.warning) {
const el = iconNode("warning", 14, "cm-openidea-db-run-warning");
el.dataset.tooltip = this.warning;
return el;
}
const el = iconNode(
this.error ? "error" : "check",
14,
this.error ? "cm-openidea-db-run-error" : "cm-openidea-db-run-ok",
);
el.dataset.tooltip = this.error ?? tx("Executed");
return el;
}
}
const runGutter = gutter({
class: "cm-openidea-db-gutter",
markers: (view) => {
const st = view.state.field(runField);
const doc = view.state.doc;
const active = activeSpan(st.executing);
const line = active ? doc.lineAt(active.from).from : undefined;
const unsafe = st.ask;
const unsafeLine = unsafe && unsafe.from <= doc.length ? doc.lineAt(unsafe.from).from : -1;
const ranges: Range<GutterMarker>[] = st.marks
.filter((m) => m.from <= doc.length && doc.lineAt(m.from).from !== unsafeLine)
.map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from));
if (line !== undefined && line !== unsafeLine) ranges.push(new ExecutingMarker().range(line));
if (unsafe && unsafeLine >= 0) ranges.push(new RunMarker(null, unsafe.message).range(unsafeLine));
return RangeSet.of(ranges, true);
},
});
function errorBanner(message: string) {
return (view: EditorView): Panel => {
const dom = document.createElement("div");
dom.className = "cm-openidea-db-banner";
dom.setAttribute("role", "alert");
const text = document.createElement("span");
text.className = "cm-openidea-db-banner-text";
text.textContent = message;
text.title = message;
const close = document.createElement("button");
close.type = "button";
close.className = "cm-openidea-db-banner-close";
close.setAttribute("aria-label", "Close");
close.appendChild(iconNode("close", 14));
close.onclick = () => view.dispatch({ effects: setRun.of({ ...view.state.field(runField), banner: null }) });
dom.append(text, close);
return { dom, top: false };
};
}
type AskChoice = "execute" | "suppress" | "cancel";
/** The answer to the banner a view asks with. */
const askAnswers = new WeakMap<EditorView, (choice: AskChoice) => void>();
/** Consoles whose unsafe queries run without asking (Execute and Suppress), until the app restarts. */
const unsafeSuppressed = new Set<string>();
function askBanner(mark: AskMark) {
return (view: EditorView): Panel => {
const dom = document.createElement("div");
dom.className = "cm-openidea-db-banner cm-openidea-db-banner-warning";
dom.setAttribute("role", "alert");
const text = document.createElement("span");
text.className = "cm-openidea-db-banner-text";
text.textContent = mark.message;
text.dataset.tooltip = mark.message;
const answer = (choice: AskChoice) => askAnswers.get(view)?.(choice);
const action = (label: string, choice: AskChoice) => {
const b = document.createElement("button");
b.type = "button";
b.className = "cm-openidea-db-banner-action";
b.textContent = label;
b.onclick = () => answer(choice);
return b;
};
const close = document.createElement("button");
close.type = "button";
close.className = "cm-openidea-db-banner-close";
close.setAttribute("aria-label", tx("Close"));
close.appendChild(iconNode("close", 14));
close.onclick = () => answer("cancel");
const actions = [action(tx("Execute"), "execute"), action(tx("Execute and Suppress"), "suppress")];
dom.append(text, ...actions, close);
return { dom, top: false };
};
}
/**
* Editing or closing the console while the unsafe-query banner waits cancels the run.
*/
const cancelAskOnEdit = [
EditorView.updateListener.of((u) => {
if (!u.docChanged) return;
if (u.transactions.every((tr) => !tr.docChanged || savedFinalNewline(tr))) {
const preparing = preparingViews.get(u.view);
if (preparing?.doc === u.startState.doc) preparing.doc = u.state.doc;
return;
}
if (u.startState.field(runField).ask) askAnswers.get(u.view)?.("cancel");
}),
ViewPlugin.define((view) => ({
destroy: () => {
closedViews.add(view);
askAnswers.get(view)?.("cancel");
},
})),
];
/** Views destroyed with a question open: nothing more to dispatch to them. */
const closedViews = new WeakSet<EditorView>();
/** Shows `mark` in the banner and waits for the answer. */
function ask(view: EditorView, mark: AskMark): Promise<AskChoice> {
askAnswers.get(view)?.("cancel");
return new Promise<AskChoice>((resolve) => {
askAnswers.set(view, (choice) => {
askAnswers.delete(view);
if (!closedViews.has(view) && view.state.field(runField, false)?.ask) view.dispatch({ effects: setAsk.of(null) });
resolve(choice);
});
view.dispatch({ effects: setAsk.of(mark) });
});
}
/** Shows the unsafe-query banner for `statement` and waits for the answer (true: run it). */
function confirmUnsafe(view: EditorView, path: string, current: () => boolean): ConfirmUnsafe {
return async (statement, unsafe) => {
if (!current()) return false;
if (unsafeSuppressed.has(path)) return true;
const len = view.state.doc.length;
const choice = await ask(view, {
from: Math.min(len, statement.from + unsafe.from),
to: Math.min(len, statement.from + unsafe.to),
message: unsafeMessage(unsafe),
});
if (choice === "suppress") unsafeSuppressed.add(path);
return choice !== "cancel";
};
}
let nextExecution = 0;
const preparingViews = new WeakMap<EditorView, { doc: Text }>();
export { previewRanges } from "./executionMarks";
/** Runs `from`–`to` of `view`, following each statement as it executes. */
async function executeRange(view: EditorView, path: string, from: number, to: number) {
const token = ++nextExecution;
const sent = view.state.doc;
askAnswers.get(view)?.("cancel");
const preparing = { doc: sent };
preparingViews.set(view, preparing);
const current = () =>
!closedViews.has(view) && view.state.doc === preparing.doc && preparingViews.get(view) === preparing;
const start = (statements: readonly SqlStatement[]) => {
const st = view.state.field(runField, false);
// The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced.
if (!st || !current()) return;
const spans = statements.map((st) => ({ from: st.from, to: st.to }));
const first = spans[0]!;
const last = spans[spans.length - 1]!;
const marks = st.marks.filter((mark) => mark.to <= first.from || mark.from >= last.to);
view.dispatch({ effects: setRun.of({ marks, banner: null, executing: { token, spans, active: null } }) });
};
const tracker = trackExecution(view, (error) => `[${sourceById(consoleSource(path))?.name ?? ""}] ${error}`);
try {
await executeConsole(
path,
sent.toString(),
from,
to,
start,
tracker.start,
(events) => {
const st = view.state.field(runField, false);
const ex = st?.executing;
if (!st || ex?.token !== token) return;
const last = events[events.length - 1]!;
const active = last.type === "started" ? { index: last.index, startedAt: Date.now() } : null;
const marks = [...st.marks];
let banner = st.banner;
const completed = events.filter((event) => event.type !== "started");
const spans = tracker.update(
active,
completed.map(({ index, outcome }) => ({
index,
error: outcome.error,
ms: outcome.result?.elapsedMs ?? null,
})),
);
const placed = new Map<number, DbStatementOutcome>();
for (const event of events) {
if (event.type === "started") continue;
const span = ex.spans[event.index];
if (!span || span.from >= span.to) continue;
const { from, to } = span;
const { error, result } = event.outcome;
marks.push({
from,
to,
timingAt: view.state.sliceDoc(to, to + 1) === ";" ? to + 1 : to,
error,
ms: result?.elapsedMs ?? null,
});
if (error) banner = `[${sourceById(consoleSource(path))?.name ?? ""}] ${error}`;
placed.set(event.index, { ...event.outcome, statement: { ...event.outcome.statement, ...span } });
for (const { index, outcome } of completed) {
const span = spans.get(index);
if (span) placed.set(index, { ...outcome, statement: { ...outcome.statement, ...span } });
}
view.dispatch({ effects: setRun.of({ marks, banner, executing: { ...ex, active } }) });
return placed;
},
confirmUnsafe(view, path, current),
confirmUnsafe(view, path, tracker.current),
);
} finally {
if (preparingViews.get(view) === preparing) preparingViews.delete(view);
const st = view.state.field(runField, false);
if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) });
tracker.end();
}
}
@@ -529,94 +164,6 @@ export async function explainInView(view: EditorView, path: string) {
const consolePath = Facet.define<string, string>({ combine: (v) => v[0] ?? "" });
const setPreview = StateEffect.define<readonly { from: number; to: number }[]>();
/**
* The range the console's next Execute would submit, bordered on the text (DataGrip's current
* statement border): the caret's statement, or the selection's — the statements `db_statements`
* splits that range into, the very call the run itself makes.
*/
const previewField = StateField.define<readonly { from: number; to: number }[]>({
create: () => [],
update(value, tr) {
for (const e of tr.effects) if (e.is(setPreview)) return e.value;
if (!tr.docChanged) return value;
// The preview is of the text it was computed for; edits only move where that is.
const next: { from: number; to: number }[] = [];
for (const r of value) {
const from = tr.changes.mapPos(r.from, 1);
const to = tr.changes.mapPos(r.to, -1);
if (from < to) next.push({ from, to });
}
return next;
},
});
/** The bordered ranges: a run in progress keeps its submitted range, whatever the caret does. */
export function previewRanges(state: EditorState): readonly { from: number; to: number }[] {
const ex = state.field(runField, false)?.executing;
const ranges = ex?.spans.length
? [{ from: ex.spans[0]!.from, to: ex.spans[ex.spans.length - 1]!.to }]
: (state.field(previewField, false) ?? []);
return ranges.filter((r) => r.from < r.to);
}
const PREVIEW_CLASS = "cm-openidea-db-preview";
/**
* One box around each statement's text: the union of its lines' text (indentation and trailing
* blanks left out), as tall as the statement even where it runs out of view.
*/
function previewBoxes(view: EditorView): RectangleMarker[] {
const { doc } = view.state;
const boxes: RectangleMarker[] = [];
for (const r of previewRanges(view.state)) {
let left = Infinity;
let right = -Infinity;
let offset: number | null = null;
for (const visible of view.visibleRanges) {
const from = Math.max(r.from, visible.from);
const to = Math.min(r.to, visible.to);
if (from >= to) continue;
for (let pos = from; pos <= to;) {
const line = doc.lineAt(pos);
const text = line.text;
let start = Math.max(from, line.from) - line.from;
let end = Math.min(to, line.to) - line.from;
while (start < end && /\s/.test(text[start]!)) start++;
while (end > start && /\s/.test(text[end - 1]!)) end--;
if (start < end)
for (const m of RectangleMarker.forRange(
view,
PREVIEW_CLASS,
EditorSelection.range(line.from + start, line.from + end),
)) {
left = Math.min(left, m.left);
right = Math.max(right, m.left + (m.width ?? 0));
offset ??= m.top - view.lineBlockAt(line.from).top;
}
pos = line.to + 1;
}
}
if (offset == null || right <= left) continue;
const top = view.lineBlockAt(r.from).top + offset;
const bottom = view.lineBlockAt(r.to).bottom + offset;
boxes.push(new RectangleMarker(PREVIEW_CLASS, left - 2, top, right - left + 4, bottom - top));
}
return boxes;
}
const previewLayer = layer({
above: false,
markers: previewBoxes,
update: (u) =>
u.docChanged ||
u.viewportChanged ||
u.geometryChanged ||
u.startState.field(previewField, false) !== u.state.field(previewField, false) ||
u.startState.field(runField, false)?.executing !== u.state.field(runField, false)?.executing,
});
/** How long typing pauses before the preview is split again (until then it follows the edit). */
const PREVIEW_TYPING_DELAY_MS = 150;
@@ -1531,11 +1078,7 @@ export function consoleExtension(ctx: EditorDocContext): Extension {
if (ctx.language !== SQL_LANGUAGE || ctx.virtual || ctx.readOnly) return [];
return [
consolePath.of(ctx.path),
runField,
runGutter,
cancelAskOnEdit,
previewField,
previewLayer,
executionMarks,
previewSync,
inlineField,
syncInline,
+494
Переглянути файл
@@ -0,0 +1,494 @@
import {
EditorSelection,
RangeSet,
StateEffect,
StateField,
type EditorState,
type Range,
type Text,
type Transaction,
} from "@codemirror/state";
import {
Decoration,
EditorView,
ViewPlugin,
GutterMarker,
RectangleMarker,
WidgetType,
gutter,
layer,
showPanel,
type Panel,
} from "@codemirror/view";
import { problemProviders, type ContributedProblem } from "@/editor/api";
import type { ConfirmUnsafe } from "./store";
import { unsafeMessage } from "./sql/unsafe";
import { tx } from "@/platform/i18n";
import { iconNode, spinnerNode } from "@/ui/iconNode";
import { formatElapsed } from "./resultView";
/** Statement outcomes of the last run, kept on the text (IDEA's gutter check / error and timing). */
interface RunMark {
from: number;
to: number;
/** After the statement's `;` when it has one. */
timingAt: number;
error: string | null;
ms: number | null;
}
interface Executing {
/** Tells this run from a later one on the same console. */
token: number;
active: { index: number; startedAt: number } | null;
spans: readonly { from: number; to: number }[];
}
function activeSpan(ex: Executing | null) {
const span = ex?.active ? ex.spans[ex.active.index] : undefined;
return span && span.from < span.to ? span : undefined;
}
interface AskMark {
from: number;
to: number;
message: string;
}
interface RunState {
ask?: AskMark | null;
marks: readonly RunMark[];
/** Message of the bottom error banner (`null`: hidden). */
banner: string | null;
executing: Executing | null;
}
const setRun = StateEffect.define<RunState>();
const setAsk = StateEffect.define<AskMark | null>();
/** Saving can append the final newline without changing any submitted SQL or statement offsets. */
function savedFinalNewline(tr: Transaction): boolean {
if (!tr.docChanged || !tr.isUserEvent("input.save")) return false;
const end = tr.startState.doc.length;
let only = true;
tr.changes.iterChanges((from, to, _f, _t, insert) => {
only &&= from === end && to === end && insert.toString() === "\n";
});
return only;
}
export const runField = StateField.define<RunState>({
create: () => ({ marks: [], banner: null, executing: null }),
update(value, tr) {
for (const e of tr.effects) if (e.is(setRun)) value = { ...e.value, ask: value.ask };
for (const e of tr.effects) if (e.is(setAsk)) value = { ...value, ask: e.value };
if (!tr.docChanged || savedFinalNewline(tr)) return value;
// The request runs the text it was sent; edits only move where that shows.
const ex = value.executing;
const executing = ex && {
...ex,
spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })),
};
// Editing a statement drops its mark.
const marks: RunMark[] = [];
for (const m of value.marks) {
let touched = false;
tr.changes.iterChangedRanges((a, b) => {
if (a <= m.to && b >= m.from) touched = true;
});
if (!touched)
marks.push({
...m,
from: tr.changes.mapPos(m.from),
to: tr.changes.mapPos(m.to),
timingAt: tr.changes.mapPos(m.timingAt),
});
}
return { ...value, marks, executing, ask: null };
},
provide: (f) => [
EditorView.decorations.compute([f], (state) => {
const st = state.field(f);
const ranges = [];
const active = st.executing?.active;
const span = activeSpan(st.executing);
if (active && span) {
const end = state.sliceDoc(span.to, span.to + 1) === ";" ? span.to + 1 : span.to;
const at = Math.min(end, state.doc.lineAt(span.from).to);
ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(span.from, span.to));
ranges.push(Decoration.widget({ widget: new ElapsedWidget(active.startedAt), side: 1 }).range(at));
}
for (const m of st.marks) {
if (m.error) ranges.push(Decoration.mark({ class: "cm-openidea-db-error" }).range(m.from, m.to));
if (m.ms !== null)
ranges.push(Decoration.widget({ widget: new TimingWidget(m.ms), side: 1 }).range(m.timingAt));
}
const u = st.ask;
if (u && u.from < u.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-warning" }).range(u.from, u.to));
return Decoration.set(ranges, true);
}),
showPanel.from(f, (st) => (st.ask ? askBanner(st.ask) : st.banner ? errorBanner(st.banner) : null)),
// The editor's hover shows the run errors and the unsafe-query warning like other problems.
problemProviders.compute([f], (state) => {
const st = state.field(f);
const problems: ContributedProblem[] = [];
for (const m of st.marks)
if (m.error && m.from < m.to) problems.push({ from: m.from, to: m.to, severity: "error", message: m.error });
const u = st.ask;
if (u && u.from < u.to) problems.push({ from: u.from, to: u.to, severity: "warning", message: u.message });
return () => problems;
}),
],
});
class TimingWidget extends WidgetType {
constructor(readonly ms: number) {
super();
}
eq(other: TimingWidget) {
return other.ms === this.ms;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing";
span.textContent = formatElapsed(this.ms);
return span;
}
}
/** The running time of the request, ticking until it ends. */
class ElapsedWidget extends WidgetType {
private timer: ReturnType<typeof setInterval> | undefined;
constructor(readonly startedAt: number) {
super();
}
eq(other: ElapsedWidget) {
return other.startedAt === this.startedAt;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing cm-openidea-db-elapsed";
const tick = () => {
const elapsed = formatElapsed(Date.now() - this.startedAt);
span.textContent = tx`Executing… ${elapsed}`;
};
tick();
this.timer = setInterval(tick, 100);
return span;
}
destroy() {
clearInterval(this.timer);
}
}
class ExecutingMarker extends GutterMarker {
eq(other: GutterMarker) {
return other instanceof ExecutingMarker;
}
toDOM() {
const el = spinnerNode(12, "cm-openidea-db-run-executing");
el.title = tx("Executing");
return el;
}
}
class RunMarker extends GutterMarker {
constructor(
readonly error: string | null,
readonly warning: string | null = null,
) {
super();
}
eq(other: RunMarker) {
return other.error === this.error && other.warning === this.warning;
}
toDOM() {
if (this.warning) {
const el = iconNode("warning", 14, "cm-openidea-db-run-warning");
el.dataset.tooltip = this.warning;
return el;
}
const el = iconNode(
this.error ? "error" : "check",
14,
this.error ? "cm-openidea-db-run-error" : "cm-openidea-db-run-ok",
);
el.dataset.tooltip = this.error ?? tx("Executed");
return el;
}
}
const runGutter = gutter({
class: "cm-openidea-db-gutter",
markers: (view) => {
const st = view.state.field(runField);
const doc = view.state.doc;
const active = activeSpan(st.executing);
const line = active ? doc.lineAt(active.from).from : undefined;
const unsafe = st.ask;
const unsafeLine = unsafe && unsafe.from <= doc.length ? doc.lineAt(unsafe.from).from : -1;
const ranges: Range<GutterMarker>[] = st.marks
.filter((m) => m.from <= doc.length && doc.lineAt(m.from).from !== unsafeLine)
.map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from));
if (line !== undefined && line !== unsafeLine) ranges.push(new ExecutingMarker().range(line));
if (unsafe && unsafeLine >= 0) ranges.push(new RunMarker(null, unsafe.message).range(unsafeLine));
return RangeSet.of(ranges, true);
},
});
function errorBanner(message: string) {
return (view: EditorView): Panel => {
const dom = document.createElement("div");
dom.className = "cm-openidea-db-banner";
dom.setAttribute("role", "alert");
const text = document.createElement("span");
text.className = "cm-openidea-db-banner-text";
text.textContent = message;
text.title = message;
const close = document.createElement("button");
close.type = "button";
close.className = "cm-openidea-db-banner-close";
close.setAttribute("aria-label", "Close");
close.appendChild(iconNode("close", 14));
close.onclick = () => view.dispatch({ effects: setRun.of({ ...view.state.field(runField), banner: null }) });
dom.append(text, close);
return { dom, top: false };
};
}
type AskChoice = "execute" | "suppress" | "cancel";
/** The answer to the banner a view asks with. */
const askAnswers = new WeakMap<EditorView, (choice: AskChoice) => void>();
/** Consoles whose unsafe queries run without asking (Execute and Suppress), until the app restarts. */
const unsafeSuppressed = new Set<string>();
function askBanner(mark: AskMark) {
return (view: EditorView): Panel => {
const dom = document.createElement("div");
dom.className = "cm-openidea-db-banner cm-openidea-db-banner-warning";
dom.setAttribute("role", "alert");
const text = document.createElement("span");
text.className = "cm-openidea-db-banner-text";
text.textContent = mark.message;
text.dataset.tooltip = mark.message;
const answer = (choice: AskChoice) => askAnswers.get(view)?.(choice);
const action = (label: string, choice: AskChoice) => {
const b = document.createElement("button");
b.type = "button";
b.className = "cm-openidea-db-banner-action";
b.textContent = label;
b.onclick = () => answer(choice);
return b;
};
const close = document.createElement("button");
close.type = "button";
close.className = "cm-openidea-db-banner-close";
close.setAttribute("aria-label", tx("Close"));
close.appendChild(iconNode("close", 14));
close.onclick = () => answer("cancel");
const actions = [action(tx("Execute"), "execute"), action(tx("Execute and Suppress"), "suppress")];
dom.append(text, ...actions, close);
return { dom, top: false };
};
}
/**
* Editing or closing the console while the unsafe-query banner waits cancels the run.
*/
const cancelAskOnEdit = [
EditorView.updateListener.of((u) => {
if (!u.docChanged) return;
if (u.transactions.every((tr) => !tr.docChanged || savedFinalNewline(tr))) {
const preparing = preparingViews.get(u.view);
if (preparing?.doc === u.startState.doc) preparing.doc = u.state.doc;
return;
}
if (u.startState.field(runField).ask) askAnswers.get(u.view)?.("cancel");
}),
ViewPlugin.define((view) => ({
destroy: () => {
closedViews.add(view);
askAnswers.get(view)?.("cancel");
},
})),
];
/** Views destroyed with a question open: nothing more to dispatch to them. */
const closedViews = new WeakSet<EditorView>();
/** Shows `mark` in the banner and waits for the answer. */
function ask(view: EditorView, mark: AskMark): Promise<AskChoice> {
askAnswers.get(view)?.("cancel");
return new Promise<AskChoice>((resolve) => {
askAnswers.set(view, (choice) => {
askAnswers.delete(view);
if (!closedViews.has(view) && view.state.field(runField, false)?.ask) view.dispatch({ effects: setAsk.of(null) });
resolve(choice);
});
view.dispatch({ effects: setAsk.of(mark) });
});
}
/** Shows the unsafe-query banner for `statement` and waits for the answer (true: run it). */
export function confirmUnsafe(view: EditorView, path: string, current: () => boolean): ConfirmUnsafe {
return async (statement, unsafe) => {
if (!current()) return false;
if (unsafeSuppressed.has(path)) return true;
const len = view.state.doc.length;
const choice = await ask(view, {
from: Math.min(len, statement.from + unsafe.from),
to: Math.min(len, statement.from + unsafe.to),
message: unsafeMessage(unsafe),
});
if (choice === "suppress") unsafeSuppressed.add(path);
return choice !== "cancel";
};
}
export const setPreview = StateEffect.define<readonly { from: number; to: number }[]>();
/**
* The range the console's next Execute would submit, bordered on the text (DataGrip's current
* statement border): the caret's statement, or the selection's — the statements `db_statements`
* splits that range into, the very call the run itself makes.
*/
const previewField = StateField.define<readonly { from: number; to: number }[]>({
create: () => [],
update(value, tr) {
for (const e of tr.effects) if (e.is(setPreview)) return e.value;
if (!tr.docChanged) return value;
// The preview is of the text it was computed for; edits only move where that is.
const next: { from: number; to: number }[] = [];
for (const r of value) {
const from = tr.changes.mapPos(r.from, 1);
const to = tr.changes.mapPos(r.to, -1);
if (from < to) next.push({ from, to });
}
return next;
},
});
/** The bordered ranges: a run in progress keeps its submitted range, whatever the caret does. */
export function previewRanges(state: EditorState): readonly { from: number; to: number }[] {
const ex = state.field(runField, false)?.executing;
const ranges = ex?.spans.length
? [{ from: ex.spans[0]!.from, to: ex.spans[ex.spans.length - 1]!.to }]
: (state.field(previewField, false) ?? []);
return ranges.filter((r) => r.from < r.to);
}
const PREVIEW_CLASS = "cm-openidea-db-preview";
/**
* One box around each statement's text: the union of its lines' text (indentation and trailing
* blanks left out), as tall as the statement even where it runs out of view.
*/
function previewBoxes(view: EditorView): RectangleMarker[] {
const { doc } = view.state;
const boxes: RectangleMarker[] = [];
for (const r of previewRanges(view.state)) {
let left = Infinity;
let right = -Infinity;
let offset: number | null = null;
for (const visible of view.visibleRanges) {
const from = Math.max(r.from, visible.from);
const to = Math.min(r.to, visible.to);
if (from >= to) continue;
for (let pos = from; pos <= to;) {
const line = doc.lineAt(pos);
const text = line.text;
let start = Math.max(from, line.from) - line.from;
let end = Math.min(to, line.to) - line.from;
while (start < end && /\s/.test(text[start]!)) start++;
while (end > start && /\s/.test(text[end - 1]!)) end--;
if (start < end)
for (const m of RectangleMarker.forRange(
view,
PREVIEW_CLASS,
EditorSelection.range(line.from + start, line.from + end),
)) {
left = Math.min(left, m.left);
right = Math.max(right, m.left + (m.width ?? 0));
offset ??= m.top - view.lineBlockAt(line.from).top;
}
pos = line.to + 1;
}
}
if (offset == null || right <= left) continue;
const top = view.lineBlockAt(r.from).top + offset;
const bottom = view.lineBlockAt(r.to).bottom + offset;
boxes.push(new RectangleMarker(PREVIEW_CLASS, left - 2, top, right - left + 4, bottom - top));
}
return boxes;
}
const previewLayer = layer({
above: false,
markers: previewBoxes,
update: (u) =>
u.docChanged ||
u.viewportChanged ||
u.geometryChanged ||
u.startState.field(previewField, false) !== u.state.field(previewField, false) ||
u.startState.field(runField, false)?.executing !== u.state.field(runField, false)?.executing,
});
export const executionMarks = [runField, runGutter, cancelAskOnEdit, previewField, previewLayer];
type StatementSpan = { from: number; to: number };
type RunOutcome = { index: number; error: string | null; ms: number | null };
let nextExecution = 0;
const preparingViews = new WeakMap<EditorView, { doc: Text }>();
/** Track the submitted ranges through edits, without changing the editor selection. */
export function trackExecution(view: EditorView, bannerFor?: (error: string) => string) {
const token = ++nextExecution;
const sent = view.state.doc;
askAnswers.get(view)?.("cancel");
const preparing = { doc: sent };
preparingViews.set(view, preparing);
const current = () =>
!closedViews.has(view) && view.state.doc === preparing.doc && preparingViews.get(view) === preparing;
return {
current,
start(spans: readonly StatementSpan[]) {
const st = view.state.field(runField, false);
const first = spans[0],
last = spans.at(-1);
// The offsets are into the text sent; an edit while preparing leaves them unplaced.
if (!st || !current() || !first || !last) return;
const marks = st.marks.filter((mark) => mark.to <= first.from || mark.from >= last.to);
view.dispatch({ effects: setRun.of({ marks, banner: null, executing: { token, spans, active: null } }) });
},
update(active: Executing["active"], outcomes: readonly RunOutcome[] = []) {
const st = view.state.field(runField, false);
const ex = st?.executing;
const placed = new Map<number, StatementSpan>();
if (!st || ex?.token !== token) return placed;
const marks = [...st.marks];
let banner = st.banner;
for (const { index, error, ms } of outcomes) {
const span = ex.spans[index];
if (!span || span.from >= span.to) continue;
const { from, to } = span;
marks.push({
from,
to,
timingAt: view.state.sliceDoc(to, to + 1) === ";" ? to + 1 : to,
error,
ms,
});
if (error && bannerFor) banner = bannerFor(error);
placed.set(index, span);
}
view.dispatch({ effects: setRun.of({ marks, banner, executing: { ...ex, active } }) });
return placed;
},
end() {
if (preparingViews.get(view) === preparing) preparingViews.delete(view);
const st = view.state.field(runField, false);
if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) });
},
};
}
+27 -1
Переглянути файл
@@ -19,8 +19,9 @@ import {
type TableCommandTarget,
} from "./tableEditorFocus";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { projectLocation, useRemote } from "@/platform/remote";
import {
editorService,
registerEditorKind,
registerOverlay,
registerProjectViewRoot,
@@ -246,6 +247,14 @@ export function activate(): () => void {
}),
registerDatabaseWindow(),
registerResultsDestination(),
registerEditorKind({
kind: "db-workspace",
singleton: true,
component: lazyComponent(() => import("./WorkspaceEditor").then((m) => m.WorkspaceEditor)),
title: () => tx("Query Workspace"),
icon: () => "database",
keepAlive: true,
}),
registerEditorKind({
kind: TABLE_KIND,
component: lazyComponent(() => import("./TableEditor").then((m) => m.TableEditor)),
@@ -321,6 +330,7 @@ export function activate(): () => void {
executions: {},
dialog: null,
newMenuOpen: false,
workspaceSettingsRequest: null,
});
}),
useDatabase.subscribe((s, prev) => {
@@ -367,6 +377,22 @@ export function activate(): () => void {
when: "projectOpen",
run: () => toolWindowService().show(DB_TOOL_WINDOW, true),
},
{
id: "db.queryWorkspace",
title: "Query Workspace",
category: "Tools",
icon: "database",
keywords: ["cross-database", "join", "workspace"],
when: "projectOpen",
run: async ({ arg }) => {
const location = projectLocation(useProject.getState().project?.root);
if (!location) return;
const key = "db-workspace:" + location;
const current = projectRequest();
await editorService().openInput({ kind: "db-workspace", key }, { focus: true });
if (arg === "configure" && current()) useDatabase.setState({ workspaceSettingsRequest: key });
},
},
{
id: "db.newDataSource",
title: "New Data Source…",
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more