Merge branch 'main' into dependabot/github_actions/actions-c2723c1a7e

Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-06 03:26:07 +08:00
коміт df432b5cdf
240 files changed
+5182 -406

No files matched your search

+1 -1
Переглянути файл
@@ -4,7 +4,7 @@
`src/ui/brands/*.svg` use the unmodified logo paths from
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos; `dotnet_dark.svg` lightens .NET's purple for dark themes). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## DuckDB symbol
+53 -4
Переглянути файл
@@ -25,6 +25,8 @@ type Key = (PathBuf, PathBuf, String);
#[derive(Default)]
pub struct AgentCatalogs {
state: Mutex<State>,
/// Orders model requests by when they were made, not when they reach `state`.
tickets: std::sync::atomic::AtomicU64,
#[cfg(test)]
clock_ms: std::sync::atomic::AtomicU64,
}
@@ -49,6 +51,8 @@ struct Entry {
abort: Option<tokio::task::AbortHandle>,
flight_model: Option<String>,
requested_model: Option<String>,
/// Ticket of the newest model request applied: an older one arriving late can't supersede it.
model_ticket: u64,
model_failures: HashMap<String, ModelFailure>,
catalog: Option<CatalogData>,
}
@@ -254,11 +258,13 @@ impl AgentCatalogs {
}
let unavailable = || "The agent did not report settings for the selected model".to_owned();
let spec = shared.spec(provider).ok_or_else(unavailable)?;
// Taken now: the blocking task may run after a newer selection's request.
let ticket = self.ticket();
let flight = {
let catalogs = self.clone();
let shared = shared.clone();
let model = model.to_owned();
tokio::task::spawn_blocking(move || catalogs.request(&shared, spec, false, Some(&model)).1)
tokio::task::spawn_blocking(move || catalogs.request_with(&shared, spec, false, Some(&model), ticket).1)
.await
.map_err(|e| e.to_string())?
};
@@ -331,12 +337,49 @@ impl AgentCatalogs {
}
/// Start or join a lookup. No queued refresh can outlive the request that asked for it.
/// The model the running discovery of `provider` looks up, if one is running.
#[cfg(test)]
pub(crate) fn flight_model(&self, shared: &Shared, provider: &str) -> Option<Option<String>> {
let state = self.state.lock();
let entry = state.entries.get(&Self::key(shared, provider))?;
entry.flight.as_ref().map(|_| entry.flight_model.clone())
}
#[cfg(test)]
pub(crate) fn request_as_of(
self: &Arc<Self>,
shared: &Arc<Shared>,
spec: provider::ProviderSpec,
model: &str,
ticket: u64,
) -> Option<watch::Receiver<bool>> {
self.request_with(shared, spec, false, Some(model), ticket).1
}
pub(crate) fn ticket(&self) -> u64 {
self.tickets.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
}
pub(crate) fn request(
self: &Arc<Self>,
shared: &Arc<Shared>,
spec: provider::ProviderSpec,
force: bool,
model: Option<&str>,
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
let ticket = self.ticket();
self.request_with(shared, spec, force, model, ticket)
}
/// [`Self::request`] for a request made when `ticket` was taken. A model request older than
/// the newest one applied neither changes the requested model nor supersedes its flight.
fn request_with(
self: &Arc<Self>,
shared: &Arc<Shared>,
spec: provider::ProviderSpec,
force: bool,
model: Option<&str>,
ticket: u64,
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
let key = Self::key(shared, &spec.id);
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
@@ -388,6 +431,7 @@ impl AgentCatalogs {
abort: None,
flight_model: None,
requested_model: None,
model_ticket: 0,
model_failures: HashMap::new(),
},
);
@@ -404,10 +448,15 @@ impl AgentCatalogs {
|| (!fresh && catalog.model_option().is_none())
})
.map(str::to_owned);
if model.is_some() && entry.requested_model.as_deref() != model {
entry.requested_model = model.map(str::to_owned);
let stale = model.is_some() && ticket < entry.model_ticket;
if model.is_some() && !stale {
entry.model_ticket = ticket;
if entry.requested_model.as_deref() != model {
entry.requested_model = model.map(str::to_owned);
}
}
let superseded = model.is_some()
let superseded = !stale
&& model.is_some()
&& entry.flight.is_some()
&& (entry.flight_model.is_some() || target.is_some())
&& entry.flight_model.as_deref() != target.as_deref();
+50
Переглянути файл
@@ -4455,6 +4455,56 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl
restored.shutdown();
}
/// A model request reaches the catalogs from a blocking task, so it may arrive after a newer
/// selection's; arriving late, it must not supersede (and abort) the newer discovery.
#[tokio::test(flavor = "multi_thread")]
async fn a_late_model_request_never_supersedes_a_newer_discovery() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.model_options.lock() = HashMap::from([
("big".into(), effort_options(&["low", "high"], "high")),
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
("plain".into(), vec![]),
]);
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "claude-acp".into(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
mgr.shutdown();
let restored = Arc::new(manager(tmp.path(), agent.clone()));
let (catalogs, shared) = (restored.shared.paths.catalogs.clone(), restored.shared.clone());
let spec = || shared.spec("claude-acp").unwrap();
let late = catalogs.ticket();
let (release, gate) = std::sync::mpsc::channel();
*agent.model_config_gate.lock() = Some(gate);
let newer = {
let (catalogs, shared) = (catalogs.clone(), shared.clone());
tokio::spawn(async move { catalogs.load_levels(&shared, "claude-acp", "plain").await })
};
tokio::time::timeout(Duration::from_secs(5), async {
while agent.model_config_gate.lock().is_some() {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into())));
catalogs.request_as_of(&shared, spec(), "small", late);
assert_eq!(catalogs.flight_model(&shared, "claude-acp"), Some(Some("plain".into())), "not superseded");
release.send(()).unwrap();
assert_eq!(newer.await.unwrap().unwrap(), Vec::<AgentConfigOption>::new());
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() {
for value in [None, Some("false"), Some("true")] {
+90 -12
Переглянути файл
@@ -37,13 +37,16 @@ pub fn prepare(cmd: &mut Command) -> &mut Command {
cmd
}
/// cmd.exe drops an inherited variable longer than this outright, and batch files (`.cmd`,
/// `.bat`) always run through it.
#[cfg_attr(not(windows), allow(dead_code))]
const CMD_ENV_LIMIT: usize = 8191;
#[cfg(windows)]
fn compact_batch_path(cmd: &mut Command) {
use std::os::windows::ffi::OsStrExt;
use std::path::{Component, Prefix};
// Rust runs these files through cmd.exe, which drops inherited variables over this limit.
const CMD_ENV_LIMIT: usize = 8191;
// Rust runs these files through cmd.exe.
let extension = Path::new(cmd.get_program()).extension();
if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) {
return;
@@ -52,25 +55,80 @@ fn compact_batch_path(cmd: &mut Command) {
Some((_, path)) => path.map(OsStr::to_owned),
None => std::env::var_os("PATH"),
};
let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return };
// The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are
// missing now, keeping search precedence and leaving UNC and relative paths alone.
let dirs = std::env::split_paths(&path).filter(|dir| {
let Some(path) = path else { return };
// The IDE includes possible locations of as-yet uninstalled tools: drop the ones missing
// now, leaving UNC and relative paths alone.
let present = |dir: &Path| {
let local = dir.is_absolute()
&& matches!(dir.components().next(), Some(Component::Prefix(p))
if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)));
!local
|| !std::fs::symlink_metadata(dir)
.is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory))
});
if let Ok(compact) = std::env::join_paths(dirs)
&& compact.encode_wide().count() <= CMD_ENV_LIMIT
{
};
if let Some(compact) = compact_path_list(&path, CMD_ENV_LIMIT, present, short_path) {
cmd.env("PATH", compact);
}
}
/// The 8.3 form of `dir`, when the volume has one.
#[cfg(windows)]
fn short_path(dir: &Path) -> Option<std::path::PathBuf> {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
let mut buf = vec![0u16; wide.len()];
let len = u32::try_from(buf.len()).ok()?;
// SAFETY: both buffers are valid for their lengths and `wide` is NUL-terminated.
let written = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), len) } as usize;
// 0 is an error; a value of at least the buffer's length is the size a longer form needs.
if written == 0 || written >= buf.len() {
return None;
}
buf.truncate(written);
Some(OsString::from_wide(&buf).into())
}
/// `path` (a `PATH` list) made to fit `limit` UTF-16 units where it is longer: later
/// duplicates (without case on Windows) and directories `present` rejects are dropped, keeping
/// the search order; when that is still too long, directories take `shorten`'s form, longest
/// first, until it fits. `None` when `path` fits already or nothing got shorter.
#[cfg_attr(not(windows), allow(dead_code))]
fn compact_path_list(
path: &OsStr,
limit: usize,
present: impl Fn(&Path) -> bool,
shorten: impl Fn(&Path) -> Option<std::path::PathBuf>,
) -> Option<OsString> {
let width = |s: &OsStr| s.to_string_lossy().encode_utf16().count();
let original = width(path);
if original <= limit {
return None;
}
let mut seen = std::collections::HashSet::new();
let mut dirs: Vec<std::path::PathBuf> = std::env::split_paths(path)
.filter(|d| !d.as_os_str().is_empty() && seen.insert(path_entry_key(d)) && present(d))
.collect();
let mut joined = std::env::join_paths(&dirs).ok()?;
if width(&joined) > limit {
let mut longest: Vec<usize> = (0..dirs.len()).collect();
longest.sort_by_key(|&i| std::cmp::Reverse(width(dirs[i].as_os_str())));
let mut total = width(&joined);
for i in longest {
if total <= limit {
break;
}
if let Some(short) = shorten(&dirs[i]).filter(|s| width(s.as_os_str()) < width(dirs[i].as_os_str())) {
total -= width(dirs[i].as_os_str()) - width(short.as_os_str());
dirs[i] = short;
}
}
joined = std::env::join_paths(&dirs).ok()?;
}
(width(&joined) < original).then_some(joined)
}
/// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and
/// [`terminate_tree`] reach what it starts in turn (`gh` → `git`, `npm` → `node`, `mvnw` →
/// the JVM). A no-op elsewhere: on Windows the tree is found from the child's process id.
@@ -1295,6 +1353,26 @@ mod tests {
assert_eq!(session, pid, "the child leads its own session");
}
#[test]
fn compacts_a_path_too_long_for_cmd() {
let sep = if cfg!(windows) { ";" } else { ":" };
let join = |dirs: &[&str]| OsString::from(dirs.join(sep));
let long = |name: &str| format!("/tools/{}/{name}", "x".repeat(40));
let (a, b, c, gone) = (long("a"), long("b"), long("c"), long("gone"));
let present = |d: &Path| !d.ends_with("gone");
let never = |_: &Path| None;
// Fits already: left alone.
assert_eq!(compact_path_list(&join(&[&a, &b]), 200, present, never), None);
// Later duplicates and missing directories go, the order stays.
let path = join(&[&a, &gone, &b, &a, &format!("{b}/"), "", &c]);
assert_eq!(compact_path_list(&path, 160, present, never), Some(join(&[&a, &b, &c])));
// Still too long: the longest directories take their short form until it fits.
let shorten = |d: &Path| Some(std::path::PathBuf::from(format!("/S/{}", d.file_name()?.to_string_lossy())));
let path = join(&[&a, &format!("{b}-longer"), &c]);
assert_eq!(compact_path_list(&path, 120, present, shorten), Some(join(&[&a, "/S/b-longer", &c])));
assert_eq!(compact_path_list(&path, 60, present, shorten), Some(join(&["/S/a", "/S/b-longer", "/S/c"])));
}
#[test]
fn process_alive_tells_live_from_dead_pids() {
assert!(process_alive(std::process::id()));
+304 -1
Переглянути файл
@@ -1433,6 +1433,83 @@ impl Pool {
r
}
/// Runs exactly one statement in a driver-enforced read-only session: a write (including one
/// in a `WITH` clause) fails in the database, whatever the statement text looks like. Drivers
/// without such a session are refused rather than guarded by a keyword check. SQL that
/// [`split`](crate::split::split) reads as more than one statement is refused here as well, so
/// a direct caller cannot hand a MySQL/PostgreSQL multi-statement batch to the session.
pub async fn execute_read_only(
&self,
sql: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
let driver = self.driver();
let statements = crate::split::split(sql, driver);
if statements.len() != 1 {
return Err(IdeError::invalid(format!(
"read-only execution runs exactly one statement, but this SQL has {}",
statements.len()
)));
}
if self.transaction_read_only() {
// The pool runs every statement in a verified `BEGIN READ ONLY` transaction.
return self.execute_from(sql, 0, max_rows, cancel).await;
}
if !matches!(self, Pool::Sqlite(_) | Pool::Postgres(_) | Pool::Mysql(_) | Pool::Oracle(_)) {
return Err(read_only_unsupported(driver));
}
if driver == DbDriver::Mysql {
// The server runs executable comments and further statements that `split` reads as
// comments; the client cannot turn its multi-statement handling off.
crate::split::mysql_guard(sql)?;
}
if let Pool::Oracle(_) = self {
// Oracle commits a statement through `Held::command`, which would end the read-only
// transaction before the user's statement runs. It has its own non-committing path.
let started = Instant::now();
let mut conn = Held::acquire_own(self).await?;
let result = match &mut conn {
Held::Oracle(c) => crate::oracle::execute_read_only(c, sql, max_rows, cancel).await,
_ => unreachable!("acquired an Oracle connection"),
};
conn.discard().await;
return result.map(|fetched| query_result(sql, fetched, started));
}
// A dedicated connection keeps the transaction or PRAGMA off every pooled connection.
let mut conn = Held::acquire_own(self).await?;
if let Held::Sqlite(c) = &mut conn {
// A future dropped mid-session (a timeout, a shutdown) must close this connection
// instead of returning one with `PRAGMA query_only` still on to the pool.
c.close_on_drop();
}
if let Err(e) = open_read_only_session(&mut conn, driver, sql).await {
conn.discard().await;
return Err(e);
}
let result = match conn.execute_from(self, sql, 0, max_rows, cancel).await {
Ok(result) => result,
Err(e) => {
// A failed or cancelled statement must not return an open transaction or query_only.
conn.discard().await;
return Err(e);
}
};
match close_read_only_session(&mut conn, driver).await {
Ok(()) => {
if let Held::Sqlite(c) = &mut conn {
// The PRAGMA is off again: this connection may go back to the pool.
c.return_to_pool().await;
}
Ok(result)
}
Err(e) => {
conn.discard().await;
Err(e)
}
}
}
/// Runs `statements` in one transaction; each must change `expect_one`
/// row when flagged (table editor submits).
pub async fn transaction(&self, statements: &[(String, bool)]) -> IdeResult<u64> {
@@ -1530,6 +1607,161 @@ impl Pool {
}
}
fn driver_name(driver: DbDriver) -> &'static str {
driver.display_name()
}
pub(crate) fn read_only_unsupported(driver: DbDriver) -> IdeError {
IdeError::invalid(format!(
"{} has no read-only session: OpenIDEA refuses to run statements on it without one",
driver_name(driver)
))
}
/// Opens the driver's read-only session, then checks that the server took it.
async fn open_read_only_session(conn: &mut Held, driver: DbDriver, sql: &str) -> IdeResult<()> {
match driver {
DbDriver::Sqlite => {
conn.command("PRAGMA query_only = ON").await?;
if read_only_setting(conn, "PRAGMA query_only").await?.as_deref() != Some("1") {
return Err(IdeError::invalid("SQLite did not enter a read-only session: PRAGMA query_only is not 1"));
}
}
DbDriver::Postgres => {
conn.command("BEGIN READ ONLY").await?;
if read_only_setting(conn, "SHOW transaction_read_only").await?.as_deref() != Some("on") {
return Err(IdeError::invalid(
"PostgreSQL did not enter a read-only transaction: transaction_read_only is not on",
));
}
if let Held::Postgres(c) = conn {
// sqlx sends the statement as the UTF-8 bytes of the Rust string and decodes text
// results as UTF-8, but the server converts those bytes from `client_encoding`
// before parsing them, and the source's startup script can change that (and
// `standard_conforming_strings`) on every connection. Pin and verify both, as the
// MySQL path pins utf8mb4.
pg_read_only::pin_encoding(c).await.map_err(db_err)?;
// No transaction guard checks this dedicated session's statement, so let the
// server parse it as one command before the simple query protocol runs it.
pg_read_only::check_single_always(c, sql).await.map_err(db_err)?;
}
}
DbDriver::Mysql => {
// sqlx sends a statement as the UTF-8 bytes of the Rust string and decodes text
// results as UTF-8, but the server's parser reads those bytes as
// `character_set_client`. Pin that connection to utf8mb4 (over the source's
// `charset` and any startup script) and verify it: in an East-Asian multibyte
// charset an ASCII backslash or quote can be swallowed as the second byte of a
// character, so the server would split a statement differently than `split` does.
conn.command("SET NAMES utf8mb4").await?;
let (client, connection) = mysql_connection_charsets(conn).await?;
for (name, value) in
[("character_set_client", client.as_str()), ("character_set_connection", connection.as_str())]
{
if !mysql_charset_is_safe(value) {
return Err(IdeError::invalid(format!(
"this MySQL/MariaDB connection reads SQL as {value} ({name}): the server could read \
the statement's quotes or backslashes differently than the statement splitter, so \
a hidden second statement could run"
)));
}
}
// MySQL has no per-transaction flag to read back (`transaction_read_only` is the
// session default, which `START TRANSACTION READ ONLY` does not change). Set and
// verify the session default first, so a vendor that ignores the clause is refused;
// the statement boundary above is what keeps a second, overriding transaction out.
conn.command("SET SESSION TRANSACTION READ ONLY").await?;
if !mysql_session_read_only(conn).await? {
return Err(IdeError::invalid(
"MySQL/MariaDB did not take the read-only session: its transaction_read_only setting is off",
));
}
let mode = read_only_setting(conn, "SELECT @@SESSION.sql_mode").await?.unwrap_or_default();
if let Some(flag) = mysql_quote_mode_unsupported(&mode) {
return Err(IdeError::invalid(format!(
"this MySQL/MariaDB session sets {flag}: its quotes no longer read like the statement splitter's, \
so a hidden second statement could run"
)));
}
conn.command("START TRANSACTION READ ONLY").await?;
if !mysql_session_read_only(conn).await? {
return Err(IdeError::invalid(
"MySQL/MariaDB did not keep the read-only session: its transaction_read_only setting is off",
));
}
}
DbDriver::Oracle => unreachable!("Oracle read-only sessions run in oracle::execute_read_only"),
_ => return Err(read_only_unsupported(driver)),
}
Ok(())
}
/// The session's read-only default: `transaction_read_only` (MySQL 5.7+, MariaDB 11+), then
/// MariaDB's older `tx_read_only`. A server with neither has no read-only session to verify.
async fn mysql_session_read_only(conn: &mut Held) -> IdeResult<bool> {
for name in ["transaction_read_only", "tx_read_only"] {
let sql = format!("SELECT @@SESSION.{name}");
match read_only_setting(conn, &sql).await {
Ok(Some(value)) => {
return match value.trim().to_ascii_lowercase().as_str() {
"1" | "on" => Ok(true),
"0" | "off" => Ok(false),
other => Err(IdeError::invalid(format!("MySQL/MariaDB reported {name} as {other}"))),
};
}
Ok(None) => {}
Err(error) if error.message.contains("Unknown system variable") => {}
Err(error) => return Err(error),
}
}
Err(IdeError::invalid(
"this MySQL-compatible server has no transaction_read_only (or tx_read_only) setting, \
so its read-only session cannot be verified",
))
}
/// Whether a MySQL connection charset decodes every ASCII byte as itself, so the server reads a
/// statement the way [`split`](crate::split::split) and `mysql_guard` do. UTF-8 charsets, ASCII,
/// latin1 and binary qualify; East-Asian multibyte charsets (GBK, Big5, SJIS, CP932, GB18030,
/// EUC-KR…) can consume an ASCII byte as part of a multibyte character.
fn mysql_charset_is_safe(name: &str) -> bool {
matches!(name.trim().to_ascii_lowercase().as_str(), "utf8mb4" | "utf8mb3" | "utf8" | "ascii" | "latin1" | "binary")
}
/// The session's `character_set_client` and `character_set_connection`; `SET NAMES` sets both.
async fn mysql_connection_charsets(conn: &mut Held) -> IdeResult<(String, String)> {
let (_, rows, _, _, _) =
conn.fetch_rows("SELECT @@SESSION.character_set_client, @@SESSION.character_set_connection", 1).await?;
let row = rows
.into_iter()
.next()
.ok_or_else(|| IdeError::invalid("MySQL/MariaDB did not report its connection character set"))?;
let mut columns = row.into_iter();
Ok((columns.next().flatten().unwrap_or_default(), columns.next().flatten().unwrap_or_default()))
}
/// The sql_mode values that change how the server reads quotes; the statement splitter assumes
/// MySQL's defaults, so a session with either could split differently than the server parses.
fn mysql_quote_mode_unsupported(mode: &str) -> Option<&'static str> {
["NO_BACKSLASH_ESCAPES", "ANSI_QUOTES"]
.into_iter()
.find(|flag| mode.split(',').any(|value| value.trim().eq_ignore_ascii_case(flag)))
}
async fn read_only_setting(conn: &mut Held, sql: &str) -> IdeResult<Option<String>> {
let (_, rows, _, _, _) = conn.fetch_rows(sql, 1).await?;
Ok(rows.into_iter().next().and_then(|row| row.into_iter().next().flatten()))
}
/// Ends the read-only session a successful statement ran in.
async fn close_read_only_session(conn: &mut Held, driver: DbDriver) -> IdeResult<()> {
match driver {
DbDriver::Sqlite => conn.command("PRAGMA query_only = OFF").await,
DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle => conn.command("ROLLBACK").await,
_ => Ok(()),
}
}
/// A connection of a pool, or one opened beside it that closes when dropped.
pub enum Lease<M: ManageConnection> {
Pooled(bb8::PooledConnection<'static, M>),
@@ -1654,7 +1886,7 @@ impl Held {
fn before_statement(&mut self, sql: &str) {
let control = sql.trim().trim_end_matches(';').trim().to_ascii_uppercase();
if let Held::Mysql(c) = self {
if matches!(control.as_str(), "BEGIN" | "START TRANSACTION") {
if control == "BEGIN" || control == "START TRANSACTION" || control.starts_with("START TRANSACTION ") {
c.in_transaction = true;
return;
}
@@ -2284,4 +2516,75 @@ mod tests {
assert_eq!(bytes_text(vec![0xCA, 0xFE], Cells::Display), "0xCAFE");
assert_eq!(bytes_text(vec![b'a', 0xFF], Cells::Text), "a\u{FFFD}");
}
#[tokio::test]
async fn read_only_execution_refuses_writes_and_leaves_the_pool_usable() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("read-only.db");
std::fs::File::create(&file).unwrap();
let source = DataSource { driver: DbDriver::Sqlite, file: Some(file.into()), ..Default::default() };
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
pool.execute("CREATE TABLE t (x INTEGER)", 1, &cancel).await.unwrap();
let result = pool.execute_read_only("SELECT 1", 1, &cancel).await.unwrap();
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
let refused = pool.execute_read_only("INSERT INTO t VALUES (1)", 10, &cancel).await.unwrap_err();
assert_eq!(refused.kind, ErrorKind::InvalidInput);
assert!(refused.message.to_lowercase().contains("readonly"), "{}", refused.message);
// The guarded statement changed nothing, and the PRAGMA did not stay on the pool.
pool.execute("INSERT INTO t VALUES (2)", 1, &cancel).await.unwrap();
let rows = pool.execute("SELECT x FROM t", 10, &cancel).await.unwrap().rows;
assert_eq!(rows, vec![vec![Some("2".into())]]);
}
#[test]
fn mysql_quote_modes_that_change_lexing_are_named() {
assert_eq!(mysql_quote_mode_unsupported("ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES"), None);
assert_eq!(mysql_quote_mode_unsupported("ANSI_QUOTES,STRICT_TRANS_TABLES"), Some("ANSI_QUOTES"));
assert_eq!(mysql_quote_mode_unsupported("no_backslash_escapes"), Some("NO_BACKSLASH_ESCAPES"));
assert_eq!(mysql_quote_mode_unsupported(""), None);
}
#[test]
fn mysql_connection_charsets_that_can_swallow_ascii_are_refused() {
for safe in ["utf8mb4", "utf8mb3", "utf8", "ascii", "latin1", "binary", "UTF8MB4", " utf8mb4 "] {
assert!(mysql_charset_is_safe(safe), "{safe}");
}
for unsafe_charset in ["gbk", "big5", "sjis", "cp932", "gb18030", "euckr", "ujis", ""] {
assert!(!mysql_charset_is_safe(unsafe_charset), "{unsafe_charset}");
}
}
#[tokio::test]
async fn read_only_execution_refuses_a_second_statement() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("read-only-statements.db");
std::fs::File::create(&file).unwrap();
let source = DataSource { driver: DbDriver::Sqlite, file: Some(file.into()), ..Default::default() };
let pool = Pool::connect(&source, None, None).await.unwrap();
let cancel = CancellationToken::new();
for sql in
["SELECT 1; SELECT 2", "SELECT 1; START TRANSACTION READ WRITE; DELETE FROM t", "SELECT 1; DELETE FROM t"]
{
let refused = pool.execute_read_only(sql, 1, &cancel).await.unwrap_err();
assert_eq!(refused.kind, ErrorKind::InvalidInput, "{sql}");
assert!(refused.message.contains("exactly one statement"), "{sql}: {}", refused.message);
}
// One statement with a trailing `;` (and comments) is still one statement.
let result = pool.execute_read_only("SELECT 1; -- done", 1, &cancel).await.unwrap();
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
}
#[test]
fn drivers_without_a_read_only_session_are_refused() {
for driver in [DbDriver::SqlServer, DbDriver::Clickhouse, DbDriver::Snowflake, DbDriver::Jdbc] {
let error = read_only_unsupported(driver);
assert_eq!(error.kind, ErrorKind::InvalidInput);
assert!(error.message.contains(driver_name(driver)), "{}", error.message);
assert!(error.message.contains("no read-only session"), "{}", error.message);
}
}
}
+68 -3
Переглянути файл
@@ -2,7 +2,7 @@
use super::{Context, Held, PgConnection, PgHandle, PgReadOnly, db_err};
use ide_core::{IdeError, IdeResult};
use sqlx::{Executor, SqlSafeStr};
use sqlx::{Executor, Row, SqlSafeStr};
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
@@ -110,11 +110,64 @@ pub(super) fn startup(statements: &[String]) -> Result<(Vec<String>, Vec<String>
// validates that the text denotes a single command, including under the server's quoting rules.
pub(super) async fn check_single(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
if sql.contains(';') {
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
check_single_always(conn, sql).await?;
}
Ok(())
}
/// Prepares `sql` whatever it contains, so the server parses it as one command with its own
/// lexer before the simple query protocol runs it. The dedicated read-only connection has no
/// transaction guard; a difference between the splitter's lexing and the server's (an encoding,
/// a newline or an escape rule) then becomes a parse error instead of a hidden second statement.
pub(super) async fn check_single_always(conn: &mut PgConnection, sql: &str) -> Result<(), sqlx::Error> {
conn.prepare(sqlx::AssertSqlSafe(sql.to_owned()).into_sql_str()).await?;
Ok(())
}
/// Whether the server reports a client encoding that reads the statement's UTF-8 bytes as UTF-8
/// (it spells UTF-8 `UTF8`, and some servers `UNICODE`).
pub(super) fn utf8_client_encoding(name: &str) -> bool {
matches!(name.trim().to_ascii_uppercase().as_str(), "UTF8" | "UNICODE")
}
/// Pins the settings the statement splitter assumes and verifies the server took them. A
/// PostgreSQL server converts the statement text from `client_encoding` before parsing it, so a
/// multibyte client encoding could end a string at a different quote than `split` did; with
/// `standard_conforming_strings` off, a plain `'…'` literal takes backslash escapes `split` does
/// not read. A startup script can set either on every connection, so both are pinned per session.
pub(super) async fn pin_encoding(conn: &mut PgConnection) -> Result<(), sqlx::Error> {
// `SET LOCAL`: both callers are inside the read-only transaction, so the source's own
// session settings come back when it ends.
sqlx::raw_sql("SET LOCAL client_encoding TO 'UTF8'").execute(&mut *conn).await?;
let encoding = pg_show(conn, "SHOW client_encoding").await?;
if !utf8_client_encoding(&encoding) {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL reports client_encoding {encoding}, not UTF8: the server could read the statement's \
quotes or escapes differently than the statement splitter, so a hidden second statement could run"
)
.into(),
));
}
sqlx::raw_sql("SET LOCAL standard_conforming_strings TO on").execute(&mut *conn).await?;
let conforming = pg_show(conn, "SHOW standard_conforming_strings").await?;
if !conforming.trim().eq_ignore_ascii_case("on") {
return Err(sqlx::Error::Configuration(
format!(
"PostgreSQL reports standard_conforming_strings {conforming}, not on: the server could read a \
string's backslash differently than the statement splitter, so a hidden second statement could run"
)
.into(),
));
}
Ok(())
}
async fn pg_show(conn: &mut PgConnection, sql: &'static str) -> Result<String, sqlx::Error> {
let row = sqlx::raw_sql(sql).fetch_one(conn).await?;
row.try_get(0)
}
impl PgHandle {
pub(super) async fn start_read_only(&mut self) -> IdeResult<()> {
self.in_transaction = true;
@@ -125,6 +178,8 @@ impl PgHandle {
check_single(self, sql).await.map_err(db_err)?;
sqlx::raw_sql(sqlx::AssertSqlSafe(sql.clone())).execute(&mut **self).await.map_err(db_err)?;
}
// After the startup settings: one of them may have changed either setting.
pin_encoding(self).await.map_err(db_err)?;
self.apply_local_path().await
}
.await;
@@ -220,7 +275,17 @@ impl Held {
#[cfg(test)]
mod tests {
use super::validate;
use super::{utf8_client_encoding, validate};
#[test]
fn only_utf8_spellings_pass_the_client_encoding_check() {
for name in ["UTF8", "utf8", "Unicode", " UNICODE "] {
assert!(utf8_client_encoding(name), "{name}");
}
for name in ["GBK", "SJIS", "BIG5", "LATIN1", "SQL_ASCII", ""] {
assert!(!utf8_client_encoding(name), "{name}");
}
}
#[test]
fn names_transaction_control_and_accepts_quoted_text() {
+21
Переглянути файл
@@ -1992,6 +1992,27 @@ impl DbManager {
self.execute_from(id, statement, 0, max_rows, cancel, None).await
}
/// Runs `statement` in a driver-enforced read-only session (see [`Pool::execute_read_only`]).
/// Exactly one statement is required: SQL that splits into several is refused at the
/// connection layer, so a direct caller cannot smuggle in a second one. Not recorded in the
/// query history: it runs outside the console, only after the caller confirmed the exact
/// statement. `id` is one data source id; callers that expose this to agents must also require
/// one unqualified id and a source that is not plugin-owned.
pub async fn execute_read_only_query(
&self,
id: &str,
statement: &str,
max_rows: usize,
cancel: &CancellationToken,
) -> IdeResult<QueryResult> {
// Refuse a driver without a read-only session before opening (and connecting) its pool.
let source = self.source(id)?;
if !matches!(source.driver, DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle) {
return Err(conn::read_only_unsupported(source.driver));
}
self.pool(id).await?.execute_read_only(statement, max_rows, cancel).await
}
/// Refuses transaction control anywhere in a guarded console script before running its first statement.
pub async fn validate_script(&self, id: &str, statements: &[split::SqlStatement]) -> IdeResult<()> {
self.validate_console_script(id, statements, None).await
+95 -2
Переглянути файл
@@ -315,8 +315,10 @@ fn open(state: &State) -> Result<OracleHandle, OracleError> {
Ok(OracleHandle { conn: Some(conn), context })
}
/// Runs `f` with the connection on the blocking pool. Cancelling drops the
/// connection instead of returning it (its statement keeps running server-side).
/// Runs `f` with the connection on the blocking pool. Cancelling stops the wait and drops the
/// connection instead of returning it, but only when the blocking call ends: the driver has no
/// break API, so the statement keeps running server-side until it finishes, and closing the
/// connection then rolls its transaction back.
async fn with_conn<T>(
c: &mut OracleConnection,
cancel: &CancellationToken,
@@ -367,6 +369,53 @@ pub(crate) async fn run(
with_conn(c, cancel, move |conn| statements(conn, &state, &sql, skip, max, mode)).await
}
/// Runs one statement in a verified read-only transaction on its own connection. Auto-commit is
/// off whatever the source's mode: [`statement`] must not commit the transaction away, and the
/// transaction is always rolled back (a dropped connection rolls it back server-side too).
pub(crate) async fn execute_read_only(
c: &mut OracleConnection,
sql: &str,
max: usize,
cancel: &CancellationToken,
) -> IdeResult<Fetched> {
let sql = sql.to_owned();
with_conn(c, cancel, move |conn| {
// `SET TRANSACTION READ ONLY` must be the first statement of its transaction; a startup
// script may have left one open.
conn.rollback().map_err(|e| oracle_err(&e))?;
statement(conn, "SET TRANSACTION READ ONLY", 0, 0, Cells::Text, false)?;
verify_read_only(conn)?;
// The user's statement is the only other statement in the transaction; `split` is not
// used here, so a `;` cannot smuggle in a second one.
let result = statement(conn, &sql, 0, max, Cells::Display, false);
let rollback = conn.rollback().map_err(|e| oracle_err(&e));
match (result, rollback) {
(Ok(fetched), Ok(())) => Ok(fetched),
(Err(error), _) => Err(error),
(Ok(_), Err(error)) => Err(error),
}
})
.await
}
/// Proves the server took `SET TRANSACTION READ ONLY`: a locking read is refused in a read-only
/// transaction (`ORA-01456`). `NOWAIT` keeps the probe from waiting on another session's DUAL
/// lock if the transaction did not take; no row is locked when it did.
fn verify_read_only(conn: &mut oracledb::Connection) -> IdeResult<()> {
match conn.query_row("SELECT 1 FROM DUAL FOR UPDATE NOWAIT", &[]) {
Ok(_) => Err(IdeError::invalid("Oracle did not enter a read-only transaction: a locking read succeeded")),
Err(e) if read_only_violation(&e) => Ok(()),
Err(e) => Err(IdeError::new(
ErrorKind::PermissionDenied,
format!("Oracle did not confirm the read-only transaction: {}", oracle_err(&e).message),
)),
}
}
fn read_only_violation(e: &oracledb::Error) -> bool {
matches!(e.kind(), oracledb::ErrorKind::DbError(db) if db.code() as u32 == 1456)
}
/// The table editor's edits in one transaction.
pub(crate) async fn transaction(c: &mut OracleConnection, statements: &[(String, bool)]) -> IdeResult<u64> {
if c.state.read_only {
@@ -1028,6 +1077,50 @@ mod tests {
drop(raw);
}
/// The read-only session `execute_read_only` opens: a write and `EXPLAIN PLAN` (which writes
/// `PLAN_TABLE`) are refused by the database, and no change is left behind. Skipped unless
/// `OPENIDEA_ORACLE_TEST` names a live server.
#[tokio::test]
async fn a_read_only_session_refuses_writes_and_leaves_no_change() {
let Some(spec) = std::env::var("OPENIDEA_ORACLE_TEST").ok().filter(|s| !s.is_empty()) else { return };
let (source, password) = live_source(&spec);
let secrets = vec![source.user.clone(), source.host.clone(), source.database.clone()];
let pool = crate::conn::Pool::connect(&source, Some(&password), None).await.expect("connect");
let c = CancellationToken::new();
let table = format!("openidea_ro_{}", uuid::Uuid::new_v4().simple());
let _ = drop_if_present(&pool, &format!("table {table}")).await;
pool.rows(&format!("create table {table} (id number)"), 0).await.expect("create table");
pool.rows(&format!("insert into {table} values (1)"), 0).await.expect("insert a row");
let selected =
pool.execute_read_only(&format!("select count(*) from {table}"), 1, &c).await.expect("a query runs");
assert_eq!(selected.rows.first().and_then(|r| r.first().cloned().flatten()).as_deref(), Some("1"));
let write = pool
.execute_read_only(&format!("insert into {table} values (2)"), 1, &c)
.await
.expect_err("a write is refused in the read-only transaction");
assert!(
write.message.contains("1456") || write.message.to_ascii_lowercase().contains("read only"),
"{}",
write.message
);
let explain = pool
.execute_read_only("explain plan for select 1 from dual", 1, &c)
.await
.expect_err("EXPLAIN PLAN writes PLAN_TABLE, so the read-only transaction refuses it");
assert!(
explain.message.contains("1456") || explain.message.to_ascii_lowercase().contains("read only"),
"{}",
explain.message
);
let rows = pool.rows(&format!("select count(*) from {table}"), 1).await.expect("count after the refusals");
assert_eq!(rows.first().and_then(|r| r.first().cloned().flatten()).as_deref(), Some("1"));
let _ = drop_if_present(&pool, &format!("table {table}")).await;
pass("read-only", "a write and EXPLAIN PLAN were refused; the table kept its one row", &secrets);
}
/// An account whose only verifier is `10G` (see `DBA_USERS.PASSWORD_VERSIONS`):
/// the thin driver speaks 11G and later verifiers, so the server rejects even
/// the correct password with ORA-01017 until the account is reset
+29
Переглянути файл
@@ -31,6 +31,20 @@ pub enum DbDriver {
}
impl DbDriver {
/// The driver's name in messages and tool output.
pub fn display_name(self) -> &'static str {
match self {
DbDriver::Sqlite => "SQLite",
DbDriver::Postgres => "PostgreSQL",
DbDriver::Mysql => "MySQL",
DbDriver::SqlServer => "SQL Server",
DbDriver::Clickhouse => "ClickHouse",
DbDriver::Oracle => "Oracle",
DbDriver::Snowflake => "Snowflake",
DbDriver::Jdbc => "JDBC",
}
}
pub fn default_port(self) -> Option<u16> {
match self {
DbDriver::Sqlite | DbDriver::Jdbc => None,
@@ -766,10 +780,16 @@ fn read(path: &Path) -> IdeResult<Vec<DataSource>> {
}
fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
let mut ids = HashSet::new();
for s in sources {
if s.id.is_empty() || s.name.trim().is_empty() {
return Err(IdeError::invalid("every data source needs an id and a name"));
}
// A connection target resolves an id to the first source with it; duplicates make that
// ambiguous (and a crafted file must not redirect a console or a tool to another entry).
if !ids.insert(s.id.as_str()) {
return Err(IdeError::invalid(format!("duplicate data source id '{}'", s.id)));
}
}
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
@@ -983,6 +1003,15 @@ mod tests {
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
}
#[test]
fn saving_refuses_duplicate_ids() {
let tmp = tempfile::tempdir().unwrap();
let source = DataSource { id: "a".into(), name: "one".into(), ..Default::default() };
let duplicate = vec![source.clone(), DataSource { name: "two".into(), ..source }];
let error = save(tmp.path(), &duplicate).unwrap_err();
assert!(error.message.contains("duplicate data source id 'a'"), "{}", error.message);
}
#[test]
fn visibility_change_preserves_patterns_unavailable_names_and_other_scopes() {
let mut introspection = DbIntrospection {
+214 -4
Переглянути файл
@@ -7,6 +7,7 @@
//! Offsets are UTF-16 code units, like everything on the IPC boundary.
use crate::DbDriver;
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -316,9 +317,7 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlSt
package = false;
}
// MySQL reads `5--1` as a subtraction.
'-' if next == Some('-')
&& (!mysql || chars.get(i + 2).is_none_or(|&(_, c)| c == ' ' || c.is_ascii_control())) =>
{
'-' if next == Some('-') && (!mysql || mysql_dash_comment(chars.get(i + 2).map(|c| c.1))) => {
state = State::LineComment;
i += 1;
}
@@ -452,7 +451,9 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlSt
}
}
State::LineComment => {
if c == '\n' {
// PostgreSQL ends a `--` comment at `\r` as well as `\n` (`scan.l`:
// `non_newline [^\n\r]`); MySQL and SQLite read a bare `\r` as comment text.
if c == '\n' || (postgres && c == '\r') {
state = State::Code;
}
}
@@ -469,6 +470,128 @@ fn split_with(text: &str, driver: DbDriver, mut delimiter: String) -> (Vec<SqlSt
(out, delimiter)
}
/// MySQL starts a `--` line comment only when the character after it is an ASCII space or an
/// ASCII control character: the server checks the next byte with `my_isspace`/`my_iscntrl`.
/// A Unicode space (U+00A0, U+2000…, U+3000…) is an identifier character to the server, so it
/// must not start a comment here either. Both [`split`] and [`mysql_guard`] use this rule.
fn mysql_dash_comment(next: Option<char>) -> bool {
next.is_none_or(|c| c == ' ' || c.is_ascii_control())
}
/// Whether `/*!` or `/*M!`, whose contents a MySQL/MariaDB server runs as SQL, starts at `i`.
fn executable_comment_start(chars: &[char], i: usize) -> bool {
chars.get(i) == Some(&'/')
&& chars.get(i + 1) == Some(&'*')
&& (chars.get(i + 2) == Some(&'!')
|| (matches!(chars.get(i + 2), Some('M' | 'm')) && chars.get(i + 3) == Some(&'!')))
}
/// Refuses what a MySQL/MariaDB server runs but [`split`] reads as a comment or a literal:
/// executable comments (`/*! … */`, `/*M! … */`), whose contents the server tokenizes as SQL,
/// and `INTO OUTFILE` / `INTO DUMPFILE`, which write a file on the server. The client cannot
/// switch the server's multi-statement handling off, so a statement handed to a MySQL/MariaDB
/// read-only session must pass this first (with the default quote modes, see
/// `mysql_quote_mode_unsupported` in `conn`).
///
/// Executable comments are refused wherever they appear outside a string or a quoted identifier,
/// even inside a genuine comment: the conservative refusal cannot be bypassed if the comment
/// rules of this guard and the server ever diverge.
pub fn mysql_guard(sql: &str) -> IdeResult<()> {
let chars: Vec<char> = sql.chars().collect();
let mut state = State::Code;
// The last word outside quotes and comments, so `INTO /* … */ OUTFILE` is one clause.
let mut last = String::new();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
let next = chars.get(i + 1).copied();
if !matches!(state, State::Single | State::Double | State::Backtick) && executable_comment_start(&chars, i) {
return Err(IdeError::invalid(
"MySQL executable comments (/*! … */ and /*M! … */) are not allowed here: \
the server runs their contents as SQL",
));
}
match state {
State::Code => match c {
'\'' => state = State::Single,
'"' => state = State::Double,
'`' => state = State::Backtick,
'#' => state = State::LineComment,
'-' if next == Some('-') && mysql_dash_comment(chars.get(i + 2).copied()) => {
state = State::LineComment;
i += 1;
}
'/' if next == Some('*') => {
state = State::BlockComment;
i += 1;
}
c if c.is_alphanumeric() || c == '_' || c == '$' => {
let start = i;
while chars.get(i).is_some_and(|c| c.is_alphanumeric() || *c == '_' || *c == '$') {
i += 1;
}
let word: String = chars[start..i].iter().collect::<String>().to_ascii_uppercase();
if matches!(word.as_str(), "OUTFILE" | "DUMPFILE") && last == "INTO" {
return Err(IdeError::invalid(
"MySQL INTO OUTFILE / INTO DUMPFILE is not allowed here: it writes a file on the server",
));
}
last = word;
continue;
}
c if c.is_whitespace() => {}
_ => last.clear(),
},
State::Single => {
if c == '\\' {
i += 1;
} else if c == '\'' {
if next == Some('\'') {
i += 1;
} else {
state = State::Code;
}
}
}
State::Double => {
if c == '\\' {
i += 1;
} else if c == '"' {
if next == Some('"') {
i += 1;
} else {
state = State::Code;
}
}
}
State::Backtick => {
if c == '`' {
if next == Some('`') {
i += 1;
} else {
state = State::Code;
}
}
}
State::LineComment => {
if c == '\n' {
state = State::Code;
}
}
State::BlockComment => {
if c == '*' && next == Some('/') {
state = State::Code;
i += 1;
}
}
// MySQL quotes identifiers only with backticks.
State::Bracket => unreachable!("MySQL has no bracketed identifiers"),
}
i += 1;
}
Ok(())
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Unit {
Sql,
@@ -777,6 +900,82 @@ fn utf16_slice(text: &str, from: u32, to: u32) -> &str {
mod tests {
use super::*;
#[test]
fn mysql_executable_comments_are_refused_outside_literals() {
for sql in [
"SELECT 1 /*!50000 , 2 */",
"/*! START TRANSACTION READ WRITE; DELETE FROM t; */ SELECT 1",
"SELECT 1 /*M!100000 , 2 */",
"select 1 /*m! , 2 */",
// Also inside a genuine comment: the conservative refusal cannot be bypassed by a
// future difference between the guard's comment rules and the server's.
"SELECT 1 -- /*! hidden in a comment */",
"SELECT 1 # /*! hidden in a comment */",
"SELECT 1 /* /*! inside a block comment */",
] {
let error = mysql_guard(sql).unwrap_err();
assert!(error.message.contains("executable comments"), "{sql}: {}", error.message);
}
// The same text inside a literal or a quoted identifier is data, not code.
for sql in [
"SELECT '/*! DELETE FROM t */'",
"SELECT \"/*M! x */\", `/*! y */` FROM t",
"SELECT 'it''s /*! fine */'",
"SELECT 'a\\' /*! still text */'",
] {
mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message));
}
}
#[test]
fn mysql_dash_comment_uses_mysqls_ascii_rule_like_the_splitter() {
// U+00A0 (NO-BREAK SPACE) and other Unicode spaces do not start a `--` comment on the
// server: `--` is two minus signs and the executable comment that follows is code.
for sql in [
"SELECT 1 --\u{00a0}/*! x */",
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d; START TRANSACTION READ WRITE; DELETE FROM users; */",
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d INTO OUTFILE '/tmp/x' */",
"SELECT 1 --\u{2003}/*M! DELETE FROM users */",
] {
let error = mysql_guard(sql).unwrap_err();
assert!(error.message.contains("executable comments"), "{sql}: {}", error.message);
}
// An ASCII space, tab or control character after `--` is a comment, as before.
for sql in ["SELECT 1 -- ordinary comment\n+ 1", "SELECT 1 --\tcomment\n+ 1", "SELECT 1 --\n+ 1"] {
mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message));
}
// `split` applies the same rule: the text after `--` is code (and the `;` there splits),
// so the guard is the layer that refuses the executable comment.
assert_eq!(
texts("SELECT 5 --\u{00a0} 1; SELECT 2", DbDriver::Mysql),
vec!["SELECT 5 --\u{00a0} 1", "SELECT 2"]
);
assert_eq!(texts("SELECT 5 -- 1; SELECT 2", DbDriver::Mysql), vec!["SELECT 5 -- 1; SELECT 2"]);
}
#[test]
fn mysql_into_outfile_is_refused_outside_literals_and_comments() {
for sql in [
"SELECT * FROM t INTO OUTFILE '/tmp/x'",
"SELECT * FROM t INTO DUMPFILE '/tmp/x'",
"SELECT * FROM t INTO/**/OUTFILE '/tmp/x'",
"SELECT * FROM t INTO /* c */\n OUTFILE '/tmp/x'",
"select * from t into outfile '/tmp/x'",
] {
let error = mysql_guard(sql).unwrap_err();
assert!(error.message.contains("INTO OUTFILE"), "{sql}: {}", error.message);
}
for sql in [
"SELECT 'INTO OUTFILE /tmp/x'",
"SELECT 1 AS outfile, 2 AS dumpfile FROM t",
"SELECT 1 /* INTO OUTFILE '/tmp/x' */",
"SELECT 1 -- INTO OUTFILE '/tmp/x'",
"SELECT @outfile FROM t",
] {
mysql_guard(sql).unwrap_or_else(|e| panic!("{sql}: {}", e.message));
}
}
#[test]
fn clickhouse_session_settings_split_after_comments_and_quoted_values() {
let set = "# leading ;\n/* outer /* nested ; */ tail ; */ SET log_comment='a;b', max_threads=1";
@@ -852,6 +1051,17 @@ mod tests {
);
}
#[test]
fn postgres_line_comments_end_at_a_carriage_return_like_the_server() {
// `scan.l` reads `\r` as a newline, so the `;` after it ends the statement; MySQL and
// SQLite keep a bare `\r` inside the comment.
let sql = "SELECT 1 --\r; SELECT 2";
assert_eq!(texts(sql, DbDriver::Postgres), vec!["SELECT 1 --", "SELECT 2"]);
assert_eq!(texts(sql, DbDriver::Mysql), vec![sql]);
assert_eq!(texts(sql, DbDriver::Sqlite), vec![sql]);
assert_eq!(texts("SELECT 1 --\r\n; SELECT 2", DbDriver::Postgres), vec!["SELECT 1 --", "SELECT 2"]);
}
#[test]
fn mysql_double_quoted_strings_and_dashes() {
let sql = r#"SELECT "say \"hi; DELETE FROM b; \"", 'a''b;', "c"";", `d``;`"#;
+112 -1
Переглянути файл
@@ -2,7 +2,7 @@
//! `OPENIDEA_TEST_MYSQL=host:port:user:password` names a throwaway server.
use ide_core::{CancellationToken, IdeResult};
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbRowEdit};
use ide_db::{CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit};
const SCHEMAS: [&str; 2] = ["oi_bin_meta", "oi_数据"];
@@ -13,6 +13,14 @@ fn server() -> Option<(String, u16, String, String)> {
}
async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option<DbManager> {
manager_with_properties(tmp, startup_script, Vec::new()).await
}
async fn manager_with_properties(
tmp: &tempfile::TempDir,
startup_script: &str,
properties: Vec<DbProperty>,
) -> Option<DbManager> {
let (host, port, user, password) = server()?;
let root = tmp.path().to_path_buf();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
@@ -24,6 +32,7 @@ async fn manager(tmp: &tempfile::TempDir, startup_script: &str) -> Option<DbMana
host,
port: Some(port),
user,
properties,
options: DbOptions { startup_script: startup_script.into(), ..Default::default() },
..Default::default()
}])
@@ -435,3 +444,105 @@ async fn table_grants_list_table_privileges() -> IdeResult<()> {
}
Ok(())
}
/// The MySQL/MariaDB read-only session: a query runs; writes, executable comments and
/// `INTO OUTFILE` are refused. Skipped without `OPENIDEA_TEST_MYSQL`.
#[tokio::test]
async fn the_read_only_session_refuses_writes_and_server_side_escapes() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp, "").await else { return Ok(()) };
let c = CancellationToken::new();
let table = format!("openidea_ro_{}", uuid::Uuid::new_v4().simple());
for stmt in [
format!("DROP TABLE IF EXISTS {table}"),
format!("CREATE TABLE {table} (id INT PRIMARY KEY)"),
format!("INSERT INTO {table} VALUES (1)"),
] {
db.execute("m", &stmt, 1, &c).await?;
}
let rows = db.execute_read_only_query("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into())]]);
let write = db
.execute_read_only_query("m", &format!("INSERT INTO {table} VALUES (2)"), 1, &c)
.await
.expect_err("the read-only transaction refuses a write");
assert!(
write.message.to_ascii_lowercase().contains("read only") || write.message.contains("1792"),
"{}",
write.message
);
let comment = db
.execute_read_only_query("m", "SELECT 1 /*! , 2 */", 1, &c)
.await
.expect_err("an executable comment is refused before the server runs it");
assert!(comment.message.contains("executable comment"), "{}", comment.message);
let outfile = db
.execute_read_only_query("m", &format!("SELECT * FROM {table} INTO OUTFILE '/tmp/openidea-ro'"), 1, &c)
.await
.expect_err("INTO OUTFILE is refused");
assert!(outfile.message.contains("INTO OUTFILE"), "{}", outfile.message);
// `--` followed by a non-ASCII space is two minus signs to the server, not a comment; the
// guard must read it the same way instead of hiding the executable comment behind it.
for payload in [
"SELECT 1 --\u{00a0}/*! x */".to_owned(),
format!(
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d; START TRANSACTION READ WRITE; \
DELETE FROM {table}; */"
),
"SELECT 1 --\u{00a0}/*! FROM (SELECT 1 AS \u{00a0}) d INTO OUTFILE '/tmp/openidea-ro' */".to_owned(),
] {
let error = db
.execute_read_only_query("m", &payload, 1, &c)
.await
.expect_err("the executable comment is refused before the server runs it");
assert!(error.message.contains("executable comment"), "{payload}: {}", error.message);
}
let rows = db.execute("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into())]], "nothing else was written");
db.execute("m", &format!("DROP TABLE {table}"), 1, &c).await?;
Ok(())
}
/// A source configured with an unsafe connection charset (`charset=gbk`) cannot make the server
/// read a statement differently than the client: the read-only connection is pinned to utf8mb4,
/// so an ASCII backslash is never swallowed as the second byte of a GBK character. Skipped
/// without `OPENIDEA_TEST_MYSQL`.
#[tokio::test]
async fn the_read_only_connection_is_pinned_to_utf8mb4_whatever_the_source_charset() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) =
manager_with_properties(&tmp, "", vec![DbProperty { name: "charset".into(), value: "gbk".into() }]).await
else {
return Ok(());
};
let c = CancellationToken::new();
let charsets = db
.execute_read_only_query(
"m",
"SELECT @@SESSION.character_set_client, @@SESSION.character_set_connection",
1,
&c,
)
.await?;
assert_eq!(charsets.rows, vec![vec![Some("utf8mb4".into()), Some("utf8mb4".into())]]);
let table = format!("openidea_charset_{}", uuid::Uuid::new_v4().simple());
for stmt in [
format!("DROP TABLE IF EXISTS {table}"),
format!("CREATE TABLE {table} (id INT)"),
format!("INSERT INTO {table} VALUES (1)"),
] {
db.execute("m", &stmt, 1, &c).await?;
}
// Read as GBK, the `\` would be consumed as the second byte of a character, the string would
// end early and the tail would run as two more statements.
let payload = format!("SELECT '中\\' ; START TRANSACTION READ WRITE; DELETE FROM {table}; -- '");
db.execute_read_only_query("m", &payload, 1, &c).await?;
let rows = db.execute("m", &format!("SELECT count(*) FROM {table}"), 1, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into())]], "no hidden statement ran");
db.execute("m", &format!("DROP TABLE {table}"), 1, &c).await?;
Ok(())
}
+84
Переглянути файл
@@ -234,6 +234,90 @@ async fn postgres_read_only_is_checked_before_and_after_startup_sql() -> IdeResu
Ok(())
}
/// A data-changing statement hidden in a CTE is not a query: the read-only session refuses it
/// in the database, whatever the statement text looks like, and the table keeps its rows.
#[tokio::test]
async fn a_write_hidden_in_a_cte_is_refused_by_the_read_only_session() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
let table = format!("public.oi_cte_{}", uuid::Uuid::new_v4().simple());
for stmt in [
format!("CREATE TABLE {table} (id INT PRIMARY KEY, name TEXT)"),
format!("INSERT INTO {table} VALUES (1, 'kept')"),
] {
db.execute("p", &stmt, 10, &c).await?;
}
let statement = format!("WITH d AS (DELETE FROM {table} RETURNING *) SELECT * FROM d");
let error = db
.execute_read_only_query("p", &statement, 10, &c)
.await
.expect_err("the read-only transaction must refuse a DELETE in a CTE");
assert!(error.message.contains("25006"), "{}", error.message);
let rows = db.execute("p", &format!("SELECT id, name FROM {table} ORDER BY id"), 10, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into()), Some("kept".into())]]);
db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?;
Ok(())
}
/// PostgreSQL's scanner ends a `--` comment at `\r` as well as `\n`; the splitter must agree, so
/// a bare CR cannot hide `COMMIT; DELETE …` from the one-statement check. The hidden statements
/// would otherwise run on the dedicated `BEGIN READ ONLY` connection.
#[tokio::test]
async fn a_carriage_return_cannot_hide_a_second_statement() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
let table = format!("public.oi_cr_{}", uuid::Uuid::new_v4().simple());
for stmt in [format!("CREATE TABLE {table} (id INT PRIMARY KEY)"), format!("INSERT INTO {table} VALUES (1)")] {
db.execute("p", &stmt, 10, &c).await?;
}
let payload = format!("SELECT 1 --\r; COMMIT; DELETE FROM {table}; --");
let error = db.execute_read_only_query("p", &payload, 10, &c).await.expect_err("the hidden DELETE must not run");
assert!(error.message.contains("exactly one statement"), "{}", error.message);
let rows = db.execute("p", &format!("SELECT count(*) FROM {table}"), 10, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into())]]);
db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?;
Ok(())
}
/// A startup script can change the connection's `client_encoding`; the read-only session pins it
/// to UTF-8 anyway, so the server reads the statement's bytes exactly as the splitter did.
#[tokio::test]
async fn a_startup_script_cannot_change_the_read_only_sessions_encoding() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
let table = format!("public.oi_gbk_{}", uuid::Uuid::new_v4().simple());
for stmt in [
format!("CREATE TABLE {table} (id INT PRIMARY KEY, name TEXT)"),
format!("INSERT INTO {table} VALUES (1, 'kept')"),
] {
db.execute("p", &stmt, 10, &c).await?;
}
let mut sources = db.sources()?;
let mut source = sources[0].clone();
source.id = "gbk".into();
source.name = "GBK startup".into();
source.read_only = true;
source.options.startup_script = "SET client_encoding TO 'GBK'".into();
sources.push(source);
db.save_sources(sources).await?;
db.set_password("gbk", server().map(|(.., password)| password), false).await?;
let encoding = db.execute_read_only_query("gbk", "SELECT current_setting('client_encoding')", 1, &c).await?;
assert_eq!(encoding.rows, vec![vec![Some("UTF8".into())]]);
// In GBK the backslash before the quote is a trail byte of the preceding character, so the
// server would end the E-string early and run the hidden `COMMIT; DELETE …`.
let payload = format!("SELECT E'中\\' ; COMMIT; DELETE FROM {table}; -- '");
let result = db.execute_read_only_query("gbk", &payload, 1, &c).await?;
assert_eq!(result.rows.len(), 1, "{:?}", result.rows);
let rows = db.execute("p", &format!("SELECT id, name FROM {table}"), 10, &c).await?;
assert_eq!(rows.rows, vec![vec![Some("1".into()), Some("kept".into())]]);
db.execute("p", &format!("DROP TABLE {table}"), 10, &c).await?;
Ok(())
}
#[tokio::test]
async fn active_schema_context_drives_the_executing_connection() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
+55 -1
Переглянути файл
@@ -1,10 +1,11 @@
//! Introspection, queries and table edits against a real SQLite file.
use ide_core::{CancellationToken, IdeResult};
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
use ide_db::{
CellValue, DataSource, DbDriver, DbKeyKind, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection,
DbTableKind, DbVisibilityChange, QueryResult, SortKey,
};
use std::time::Duration;
async fn setup() -> (tempfile::TempDir, DbManager) {
let tmp = tempfile::tempdir().unwrap();
@@ -527,3 +528,56 @@ async fn data_sources_edited_on_disk_close_their_connections() -> IdeResult<()>
assert!(!db.reconcile_sources().await);
Ok(())
}
/// A read-only query whose future is dropped or cancelled mid-flight must not leave
/// `PRAGMA query_only` on a pooled connection: a later write through the pool still works.
#[tokio::test]
async fn a_dropped_or_cancelled_read_only_query_leaves_the_pool_writable() -> IdeResult<()> {
let (_tmp, db) = setup().await;
let pool = db.pool("s1").await?;
// CPU-bound and touches no table, so it holds no file lock while it runs. Large enough that
// it cannot finish within the 50 ms before the abort, even on a fast machine.
let slow = "WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM c WHERE x < 5000000) \
SELECT count(*) FROM c";
let spawn = |cancel: CancellationToken| {
let pool = pool.clone();
tokio::spawn(async move { pool.execute_read_only(slow, 1, &cancel).await })
};
// Dropped mid-query, as a timeout used to drop it.
let handle = spawn(CancellationToken::new());
tokio::time::sleep(Duration::from_millis(50)).await;
handle.abort();
let _ = handle.await;
// Cancelled mid-query, as a cancelled MCP request does.
let cancel = CancellationToken::new();
let handle = spawn(cancel.clone());
tokio::time::sleep(Duration::from_millis(50)).await;
cancel.cancel();
let error = handle.await.unwrap().expect_err("the cancelled query returns an error");
assert_eq!(error.kind, ErrorKind::Cancelled);
// Let either worker finish: a dropped session's connection must close, not return with
// query_only still on. Take every connection the pool has (4 pool + 4 console sessions) and
// read the PRAGMA, so a poisoned slot cannot hide in the unchecked rest.
tokio::time::sleep(Duration::from_millis(1500)).await;
let c = CancellationToken::new();
let mut held = Vec::new();
for _ in 0..8 {
let mut conn = ide_db::Held::acquire(&pool).await?;
let rows = conn.execute(&pool, "PRAGMA query_only", 1, &c).await?.rows;
assert_eq!(rows, vec![vec![Some("0".into())]], "a pooled connection kept query_only");
held.push(conn);
}
drop(held);
// A pool slot that kept query_only would answer SQLITE_READONLY, intermittently.
for n in 0..20 {
let sql = format!("INSERT INTO users (name) VALUES ('after{n}')");
pool.execute(&sql, 1, &c).await?;
}
let rows = pool.execute("SELECT count(*) FROM users WHERE name LIKE 'after%'", 1, &c).await?.rows;
assert_eq!(rows, vec![vec![Some("20".into())]]);
Ok(())
}
+22 -1
Переглянути файл
@@ -187,6 +187,7 @@ pub const EVENT_KINDS: &[&str] = &[
"problems-changed",
"project-closed",
"watched-files-changed",
"project-tree-expanded",
];
impl std::fmt::Display for ActivationEvent {
@@ -483,7 +484,8 @@ impl Manifest {
{
self.needs_api(&format!("`{event}`"), 18)?;
}
if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "run-started" | "run-output")) {
if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "run-started" | "run-output" | "project-tree-expanded"))
{
self.needs_api(&format!("`{event}`"), 21)?;
}
if !seen.insert(event) {
@@ -705,6 +707,10 @@ mod tests {
);
assert!(ActivationEvent::parse("on-event:document-changed").is_ok());
assert!(ActivationEvent::parse("on-event:websocket-ready").is_ok());
assert_eq!(
ActivationEvent::parse("on-event:project-tree-expanded"),
Ok(ActivationEvent::Event("project-tree-expanded".into()))
);
let err = ActivationEvent::parse("on-event:keystroke").unwrap_err();
assert!(err.contains("unknown event kind") && err.contains("action-performed"), "{err}");
assert!(ActivationEvent::parse("on-event:scheduled").is_err(), "declared with on-schedule");
@@ -1126,6 +1132,21 @@ mod net_ask_api_tests {
}
}
#[test]
fn project_tree_expanded_requires_api_1_21() {
for engine in ["^1.20", "^1.21"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\nactivation = [\"on-event:project-tree-expanded\"]\n"
);
let parsed = Manifest::parse(&manifest);
if engine == "^1.21" {
parsed.unwrap();
} else {
assert!(parsed.unwrap_err().contains("new in plugin API 1.21"), "{engine}");
}
}
}
#[test]
fn doc_files_require_api_1_18_and_relative_paths() {
for field in ["description-file", "change-notes-file"] {
+728
Переглянути файл
@@ -0,0 +1,728 @@
//! Database tools: the project's data sources, their schemas and objects, and read-only SQL.
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
use ide_core::error::ErrorKind;
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_db::{DataSource, DbDriver, DbObjectKind, DbTableKind, SchemaObjects, split};
use serde::Serialize;
use serde_json::{Value, json};
use std::future::Future;
use std::time::Duration;
const DEFAULT_MAX_ROWS: usize = 100;
const MAX_ROWS: usize = 1000;
/// UTF-16 units a cell keeps; the rest is reported in `truncated`.
const MAX_CELL_UNITS: usize = 4096;
const QUERY_TIMEOUT: Duration = Duration::from_secs(30);
/// Catalog reads can be slower than a query on a big schema; they do not run the user's SQL.
const METADATA_TIMEOUT: Duration = Duration::from_secs(60);
/// How long a cancelled or timed-out task gets to run its rollback / reset before the tool returns.
const STOP_GRACE: Duration = Duration::from_secs(5);
pub fn tools() -> Vec<Tool> {
vec![
list_database_connections(),
list_database_schemas(),
list_schema_objects(),
get_database_object_description(),
execute_sql_query(),
]
}
/// The connection a tool may use. The id must be exactly one data source's id: `DbManager`
/// resolves `<id>:<database>` by prefix and takes the first matching entry, so a colon or a
/// duplicate id could reach an entry other than the one checked here (a plugin-owned source and
/// its credentials, for example). Plugin-owned sources stay out of these tools entirely.
fn connection(call: &Call, id: &str) -> IdeResult<DataSource> {
if id.contains(':') {
return Err(IdeError::invalid(
"connectionId must be one id from list_database_connections, without a `:database` part",
));
}
let mut matches = call.project().db.sources()?.into_iter().filter(|source| source.id == id);
let Some(source) = matches.next() else {
return Err(IdeError::not_found(format!("no data source {id}")));
};
if matches.next().is_some() {
return Err(IdeError::invalid(format!(
"more than one data source has the id {id}; rename or remove one in the Database tool window"
)));
}
if source.plugin_owner.is_some() {
return Err(IdeError::not_found(format!("no data source {id}")));
}
source.resolved()
}
/// The `database` value a tool may show: an Oracle Database field can hold a TNS descriptor,
/// which embeds the host and port.
fn database_field(source: &DataSource) -> String {
let database = source.database.trim();
if source.driver == DbDriver::Oracle && (database.starts_with('(') || database.contains('=')) {
return String::new();
}
source.database.clone()
}
/// Replaces every ASCII-case-insensitive occurrence of `needle` in `haystack`. ASCII case folding
/// keeps byte lengths, so an offset found in the lowered copy is a valid boundary of the original.
fn replace_ascii_case_insensitive(haystack: &mut String, needle: &str, replacement: &str) {
let lowered = needle.to_ascii_lowercase();
let mut from = 0;
loop {
let Some(at) = haystack[from..].to_ascii_lowercase().find(&lowered) else { return };
let start = from + at;
haystack.replace_range(start..start + needle.len(), replacement);
from = start + replacement.len();
}
}
/// Replaces the data source's URL, host and user in an error before it reaches the agent: driver
/// and tunnel errors quote them (auth failures name the user, tunnel failures the host), in
/// whatever case the server reports (Oracle upper-cases user names). Percent-encoded forms are
/// redacted too, and the plain forms are matched case-insensitively.
fn redact_error(mut error: IdeError, source: &DataSource) -> IdeError {
let mut secrets = vec![source.url.trim().to_owned(), source.host.trim().to_owned(), source.user.trim().to_owned()];
for value in [source.host.trim(), source.user.trim()] {
if !value.is_empty() {
secrets.push(percent_encode(value));
}
}
for secret in secrets {
// Every configured value, however short: the tool text promises the user and host never
// appear, and a one- or two-character name is still a name.
if !secret.is_empty() {
replace_ascii_case_insensitive(&mut error.message, &secret, "<redacted>");
}
}
error
}
fn percent_encode(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
out.push(byte as char);
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
/// Runs a catalog read with the request's cancellation and a time limit. The `DbManager`
/// metadata methods take no token; dropping their future closes the connection they were using.
async fn bounded<T>(call: &Call, deadline: Duration, task: impl Future<Output = IdeResult<T>>) -> IdeResult<T> {
tokio::select! {
biased;
() = call.cancel.cancelled() => Err(IdeError::cancelled()),
result = tokio::time::timeout(deadline, task) => match result {
Ok(result) => result,
Err(_) => Err(IdeError::new(
ErrorKind::TimedOut,
format!("the database did not answer within {} seconds", deadline.as_secs()),
)),
},
}
}
/// Runs a read-only query until it finishes, the request is cancelled, or `deadline` passes. On
/// either stop the driver's token is cancelled and its cleanup (rollback, reset, close) is
/// awaited, instead of dropping the future and leaving a driver's work running.
async fn until_stopped<T>(
deadline: Duration,
cancel: &CancellationToken,
token: &CancellationToken,
task: impl Future<Output = IdeResult<T>>,
) -> IdeResult<T> {
tokio::pin!(task);
tokio::select! {
biased;
result = &mut task => result,
() = cancel.cancelled() => {
token.cancel();
let _ = tokio::time::timeout(STOP_GRACE, &mut task).await;
Err(IdeError::cancelled())
}
() = tokio::time::sleep(deadline) => {
token.cancel();
let _ = tokio::time::timeout(STOP_GRACE, &mut task).await;
Err(IdeError::new(
ErrorKind::TimedOut,
format!("the statement did not finish within {} seconds", deadline.as_secs()),
))
}
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ConnectionInfo {
id: String,
name: String,
driver: DbDriver,
database: String,
read_only: bool,
global: bool,
}
fn list_database_connections() -> Tool {
Tool::new(
"list_database_connections",
"Lists the project's database connections (data sources): `id`, `name`, `driver`, `database`,
`readOnly` and `global`. Needs a trusted project; in Restricted Mode the call is refused.
Use a connection's `id` as `connectionId` in the other database tools.
`database` is the source's configured database; it is empty when none is configured, and a source
configured only by a URL is not read here, so its URL does not appear. Global data sources are
stored app-wide, are listed in every project and carry `\"global\": true`.
Never returns passwords, secrets, URLs, hosts or user names.",
|call| async move {
call.project.require_trust()?;
let connections: Vec<_> = call
.project()
.db
.sources()?
.into_iter()
.filter(|source| source.plugin_owner.is_none())
.map(|source| {
let database = database_field(&source);
ConnectionInfo {
id: source.id,
name: source.name,
driver: source.driver,
database,
read_only: source.read_only,
global: source.global,
}
})
.collect();
Output::json(json!({ "connections": connections }))
},
)
}
fn list_database_schemas() -> Tool {
Tool::new(
"list_database_schemas",
"Lists the schemas a database connection exposes (its databases on MySQL and Oracle).
Returns `connectionId`, the configured `database`, and `schemas`. Needs a trusted project; in
Restricted Mode the call is refused.",
|call| async move {
call.project.require_trust()?;
let connection_id = call.str("connectionId")?;
let source = connection(&call, &connection_id)?;
let schemas = bounded(&call, METADATA_TIMEOUT, call.project().db.schemas(&connection_id))
.await
.map_err(|e| redact_error(e, &source))?;
Output::json(json!({
"connectionId": connection_id,
"database": database_field(&source),
"schemas": schemas,
}))
},
)
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
}
fn list_schema_objects() -> Tool {
Tool::new(
"list_schema_objects",
"Lists a schema's tables, views, materialized views, routines (functions and procedures), packages, sequences
and other objects, as `{ kind, name }`; table-like objects and routines also carry `comment`, `arguments` and
`returns` when the database has them.
Pass `kind` to filter (case-insensitive): `table`, `view`, `materializedView`, `function`, `procedure`, `package`,
`sequence`, `routine` (functions and procedures), or another object kind the database reports. An unknown kind
returns an empty list. Needs a trusted project; in Restricted Mode the call is refused.",
|call| async move {
call.project.require_trust()?;
let connection_id = call.str("connectionId")?;
let schema = call.str("schema")?;
let kind = call.opt_str("kind")?;
let source = connection(&call, &connection_id)?;
let db = &call.project().db;
let tables = bounded(&call, METADATA_TIMEOUT, db.tables(&connection_id, &schema))
.await
.map_err(|e| redact_error(e, &source))?;
let objects = bounded(&call, METADATA_TIMEOUT, db.schema_objects(&connection_id, &schema))
.await
.map_err(|e| redact_error(e, &source))?;
let objects = schema_objects(tables, objects, kind.as_deref());
Output::json(json!({
"connectionId": connection_id,
"schema": schema,
"objects": objects,
}))
},
)
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
.param(Param::required("schema", ParamType::String, "Schema name from `list_database_schemas`"))
.param(Param::optional(
"kind",
ParamType::String,
"Only objects of this kind: table, view, materializedView, function, procedure, package, sequence, routine",
))
}
fn schema_objects(tables: Vec<ide_db::TableInfo>, objects: SchemaObjects, wanted: Option<&str>) -> Vec<Value> {
let mut out = Vec::new();
for table in tables {
let kind = match table.kind {
DbTableKind::Table => "table",
DbTableKind::View => "view",
DbTableKind::MaterializedView => "materializedView",
};
if !kind_matches(wanted, kind) {
continue;
}
let mut object = json!({ "kind": kind, "name": table.name });
if let Some(comment) = table.comment {
object["comment"] = json!(comment);
}
out.push(object);
}
for routine in objects.routines {
let kind = if routine.kind == DbObjectKind::Procedure { "procedure" } else { "function" };
if !kind_matches(wanted, kind) {
continue;
}
let mut object = json!({ "kind": kind, "name": routine.name });
if !routine.arguments.is_empty() {
object["arguments"] = json!(routine.arguments);
}
if let Some(returns) = routine.returns {
object["returns"] = json!(returns);
}
out.push(object);
}
for package in objects.packages {
if kind_matches(wanted, "package") {
out.push(json!({ "kind": "package", "name": package.name }));
}
}
for sequence in objects.sequences {
if kind_matches(wanted, "sequence") {
out.push(json!({ "kind": "sequence", "name": sequence.name }));
}
}
for object in objects.others {
if kind_matches(wanted, &object.kind) {
out.push(json!({ "kind": object.kind, "name": object.name }));
}
}
out
}
fn kind_matches(wanted: Option<&str>, kind: &str) -> bool {
wanted.is_none_or(|wanted| {
wanted.eq_ignore_ascii_case(kind)
|| (wanted.eq_ignore_ascii_case("routine") && matches!(kind, "function" | "procedure"))
})
}
fn get_database_object_description() -> Tool {
Tool::new(
"get_database_object_description",
"Describes a table, view or materialized view: columns (type, nullability, default, primary key and comment),
indexes, foreign keys, triggers and the object's comment, plus the owner, tablespace, access method,
storage options and partitioning when the database reports them.
Describing routines, packages and sequences is not supported yet. Needs a trusted project; in
Restricted Mode the call is refused.",
|call| async move {
call.project.require_trust()?;
let connection_id = call.str("connectionId")?;
let schema = call.str("schema")?;
let object_name = call.str("objectName")?;
if let Some(kind) = call.opt_str("kind")?
&& !is_table_like_kind(&kind)
{
return Err(description_unsupported(&kind));
}
let source = connection(&call, &connection_id)?;
let db = &call.project().db;
let details = bounded(&call, METADATA_TIMEOUT, db.table_details(&connection_id, &schema, &object_name))
.await
.map_err(|e| redact_error(e, &source))?;
if details.columns.is_empty() {
let objects = bounded(&call, METADATA_TIMEOUT, db.schema_objects(&connection_id, &schema))
.await
.map_err(|e| redact_error(e, &source))?;
if let Some(kind) = schema_object_kind(&objects, &object_name) {
return Err(description_unsupported(kind));
}
return Err(IdeError::not_found(format!("{schema}.{object_name}")));
}
Output::json(json!({
"connectionId": connection_id,
"schema": schema,
"objectName": object_name,
"details": details,
}))
},
)
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
.param(Param::required("schema", ParamType::String, "Schema name from `list_database_schemas`"))
.param(Param::required("objectName", ParamType::String, "Table, view or materialized view name"))
.param(Param::optional(
"kind",
ParamType::String,
"Object kind from `list_schema_objects`; only table, view and materializedView are described",
))
}
fn is_table_like_kind(kind: &str) -> bool {
["table", "view", "materializedView"].iter().any(|known| kind.eq_ignore_ascii_case(known))
}
fn schema_object_kind<'a>(objects: &'a SchemaObjects, name: &str) -> Option<&'a str> {
if objects.routines.iter().any(|routine| routine.name == name) {
return Some("routine");
}
if objects.packages.iter().any(|package| package.name == name) {
return Some("package");
}
if objects.sequences.iter().any(|sequence| sequence.name == name) {
return Some("sequence");
}
objects.others.iter().find(|object| object.name == name).map(|object| object.kind.as_str())
}
fn description_unsupported(kind: &str) -> IdeError {
IdeError::invalid(format!(
"describing a {kind} is not supported yet; this tool describes tables, views and materialized views only"
))
}
fn execute_sql_query() -> Tool {
Tool::new(
"execute_sql_query",
"Runs one read-only SQL statement (SELECT, WITH or EXPLAIN) against a data source after the user confirms
the exact statement. It runs in a driver-enforced read-only session on SQLite, PostgreSQL, MySQL/MariaDB and
Oracle; other drivers are refused. Multiple statements, writes and DDL are refused. On Oracle, EXPLAIN is
refused (EXPLAIN PLAN writes PLAN_TABLE). On MySQL/MariaDB, executable comments (`/*! … */`, `/*M! … */`) and
INTO OUTFILE/INTO DUMPFILE are refused, and the connection is pinned to utf8mb4 so the server reads the
statement exactly as the splitter did. MySQL/MariaDB and MySQL-compatible servers are supported only when
they accept `SET NAMES utf8mb4` and report a read-only transaction (`transaction_read_only` or
`tx_read_only`); otherwise this tool refuses. On PostgreSQL, the connection is pinned to `client_encoding`
UTF8 with `standard_conforming_strings = on`, and the server parses the statement as one command before it
runs, so a difference from the splitter's lexing is refused rather than executed. The metadata tools are
unaffected. \"Read-only\" means no
changes to tables, views and schema through the statement; functions with server-side side effects (for
example PostgreSQL lo_export, Oracle UTL_FILE, MySQL LOAD_FILE) are outside that guarantee. Use a database
account with read-only privileges for agent access: the IDE's read-only session is defense in depth, not a
full sandbox.
Returns at most `maxRows` rows (default 100, clamped to 1000), each cell cut to 4096 UTF-16 units. The query
is cancelled after 30 seconds, with up to 5 seconds more to roll back and close. The result and errors never
include the data source URL, host or user.",
execute_query,
)
.write()
.param(Param::required("connectionId", ParamType::String, "Data source id from `list_database_connections`"))
.param(Param::required(
"sql",
ParamType::String,
"One read-only statement: SELECT, WITH or EXPLAIN; leading SQL comments are allowed",
))
.param(Param::optional(
"maxRows",
ParamType::Integer,
"Rows to return at most (default 100, clamped to 1..=1000)",
))
}
async fn execute_query(call: Call) -> IdeResult<Output> {
let connection_id = call.str("connectionId")?;
let sql = call.str("sql")?;
let max_rows = match call.opt_i64("maxRows")? {
Some(rows) => rows.clamp(1, MAX_ROWS as i64) as usize,
None => DEFAULT_MAX_ROWS,
};
let source = connection(&call, &connection_id)?;
if !matches!(source.driver, DbDriver::Sqlite | DbDriver::Postgres | DbDriver::Mysql | DbDriver::Oracle) {
return Err(IdeError::invalid(format!(
"{} has no read-only session; execute_sql_query runs on SQLite, PostgreSQL, MySQL/MariaDB and Oracle only",
source.driver.display_name()
)));
}
if source.driver == DbDriver::Mysql {
// The server executes these even though `split` reads them as comments or literals.
split::mysql_guard(&sql)?;
}
let statements = split::split(&sql, source.driver);
let statement = match statements.as_slice() {
[] => return Err(IdeError::invalid("the SQL is empty")),
[statement] => statement,
_ => {
return Err(IdeError::invalid(format!(
"exactly one statement is allowed, but the SQL has {}",
statements.len()
)));
}
};
match leading_keyword(&statement.text, source.driver) {
Some(keyword) if matches!(keyword.as_str(), "SELECT" | "WITH" | "EXPLAIN") => {
if source.driver == DbDriver::Oracle && keyword == "EXPLAIN" {
return Err(IdeError::invalid("EXPLAIN is not allowed on Oracle: EXPLAIN PLAN writes PLAN_TABLE"));
}
}
Some(keyword) => {
return Err(IdeError::invalid(format!(
"{keyword} is not allowed: execute_sql_query runs SELECT, WITH and EXPLAIN statements only"
)));
}
None => {
return Err(IdeError::invalid("execute_sql_query runs SELECT, WITH and EXPLAIN statements only"));
}
}
let database = database_field(&source);
let database = if database.is_empty() { "(default)" } else { database.as_str() };
let detail = format!("Driver: {}\nDatabase: {database}\nSQL:\n{}", source.driver.display_name(), statement.text);
call.confirm(&format!("SQL on {}", source.name), Some(detail)).await?;
let token = call.cancel.child_token();
let work = call.project().db.execute_read_only_query(&connection_id, &statement.text, max_rows, &token);
let mut result =
until_stopped(QUERY_TIMEOUT, &call.cancel, &token, work).await.map_err(|e| redact_error(e, &source))?;
result.cap_cells(MAX_CELL_UNITS);
let row_count = result.rows.len();
Output::json(json!({
"connectionId": connection_id,
"statement": result.statement,
"columns": result.columns,
"rows": result.rows,
"rowCount": row_count,
"hasMore": result.has_more,
"truncated": result.truncated,
"elapsedMs": result.elapsed_ms,
"affected": result.affected,
}))
}
/// The first keyword of `sql`, past leading whitespace and SQL comments, uppercased.
fn leading_keyword(sql: &str, driver: DbDriver) -> Option<String> {
let mut text = sql;
loop {
text = text.trim_start();
if let Some(comment) = text.strip_prefix("--") {
// PostgreSQL ends a line comment at `\r` as well as `\n` (`scan.l`), as `split` does;
// the other drivers keep a bare `\r` in the comment.
let end = comment
.char_indices()
.find(|&(_, c)| c == '\n' || (driver == DbDriver::Postgres && c == '\r'))
.map_or(comment.len(), |(at, _)| at);
text = &comment[end..];
} else if let Some(comment) = text.strip_prefix('#') {
text = comment.split_once('\n').map_or("", |(_, rest)| rest);
} else if let Some(comment) = text.strip_prefix("/*") {
text = after_block_comment(comment);
} else {
let end = text.find(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '$'))).unwrap_or(text.len());
return (end > 0).then(|| text[..end].to_ascii_uppercase());
}
}
}
/// The text after a `/*` comment, past nested block comments (`/* /* */ */`).
fn after_block_comment(mut text: &str) -> &str {
let mut depth = 1usize;
while let Some(at) = text.find(['/', '*']) {
text = &text[at..];
if let Some(rest) = text.strip_prefix("/*") {
depth += 1;
text = rest;
} else if let Some(rest) = text.strip_prefix("*/") {
depth -= 1;
text = rest;
if depth == 0 {
return text;
}
} else {
text = &text[1..];
}
}
""
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exposes_exactly_the_five_database_tools() {
let names: Vec<_> = tools().into_iter().map(|tool| tool.metadata.name).collect();
assert_eq!(
names,
[
"list_database_connections",
"list_database_schemas",
"list_schema_objects",
"get_database_object_description",
"execute_sql_query",
]
);
}
#[test]
fn only_execute_sql_query_is_not_read_only() {
for tool in tools() {
assert_eq!(tool.metadata.read_only, tool.metadata.name != "execute_sql_query", "{}", tool.metadata.name);
}
}
#[test]
fn execute_sql_query_requires_a_connection_and_a_statement() {
let tool = tools().into_iter().find(|tool| tool.metadata.name == "execute_sql_query").unwrap();
let required = tool.metadata.input_schema["required"].as_array().unwrap();
for name in ["connectionId", "sql"] {
assert!(required.iter().any(|value| value == name), "{name}");
assert_eq!(tool.metadata.input_schema["properties"][name]["type"], "string", "{name}");
}
}
#[test]
fn accepts_select_with_and_explain_past_comments() {
for sql in [
"SELECT 1",
"-- note\nSELECT 1",
"/* outer /* nested */ comment */ WITH x AS (SELECT 1) SELECT * FROM x",
" \n\t EXPLAIN SELECT 1",
] {
assert!(
matches!(leading_keyword(sql, DbDriver::Postgres).as_deref(), Some("SELECT" | "WITH" | "EXPLAIN")),
"{sql}"
);
}
}
/// PostgreSQL ends a leading `--` comment at `\r` too, like the fixed splitter.
#[test]
fn a_carriage_return_ends_a_postgres_leading_comment() {
assert_eq!(leading_keyword("-- note\rSELECT 1", DbDriver::Postgres).as_deref(), Some("SELECT"));
for driver in [DbDriver::Mysql, DbDriver::Sqlite, DbDriver::Oracle, DbDriver::SqlServer] {
assert_eq!(leading_keyword("-- note\rSELECT 1", driver), None, "{driver:?}");
}
}
#[test]
fn refuses_other_leading_keywords() {
for sql in [
"INSERT INTO t VALUES (1)",
"UPDATE t SET x = 1",
"DELETE FROM t",
"CREATE TABLE t (x INT)",
"CALL p()",
"COPY t FROM stdin",
"PRAGMA query_only = ON",
"# comment\nUPDATE t SET x = 1",
] {
let keyword = leading_keyword(sql, DbDriver::Postgres);
assert!(!matches!(keyword.as_deref(), Some("SELECT" | "WITH" | "EXPLAIN")), "{sql}: {keyword:?}");
}
}
#[test]
fn errors_hide_the_url_host_and_user() {
let source = DataSource {
driver: DbDriver::Postgres,
host: "db.example.invalid".into(),
user: "[email protected]".into(),
url_only: true,
url: "postgres://alice%40example.com:[email protected]:5432/app".into(),
..Default::default()
};
for message in [
"[28P01] password authentication failed for user \"[email protected]\"".to_owned(),
"connection to server at db.example.invalid (10.0.0.5), port 5432 failed".to_owned(),
"user alice%40example.com cannot log in".to_owned(),
"ALICE%40EXAMPLE.COM cannot log in".to_owned(),
"Alice%40Example.com cannot log in".to_owned(),
"DB.EXAMPLE.INVALID refused the connection".to_owned(),
"could not open postgres://alice%40example.com:[email protected]:5432/app".to_owned(),
] {
let error = redact_error(IdeError::invalid(message.clone()), &source);
let lower = error.message.to_ascii_lowercase();
for secret in ["alice", "db.example.invalid", "pw@db"] {
assert!(!lower.contains(secret), "{message} -> {}", error.message);
}
}
// However short: a one- or two-character name is still a configured name.
let short = DataSource { host: "q".into(), user: "ab".into(), ..Default::default() };
let error =
redact_error(IdeError::invalid("password authentication failed for user \"ab\" at q".to_owned()), &short);
assert!(!error.message.to_ascii_lowercase().contains("ab"), "{}", error.message);
assert!(!error.message.contains('q'), "{}", error.message);
assert!(error.message.contains("<redacted>"), "{}", error.message);
}
#[test]
fn an_oracle_tns_descriptor_is_not_shown_as_the_database() {
let mut source = DataSource {
driver: DbDriver::Oracle,
database: "(DESCRIPTION=(HOST=db.local))".into(),
..Default::default()
};
assert_eq!(database_field(&source), "");
source.database = "PROD=(DESCRIPTION=(HOST=db.local))".into();
assert_eq!(database_field(&source), "");
source.database = "ORCLPDB1".into();
assert_eq!(database_field(&source), "ORCLPDB1");
}
#[tokio::test]
async fn a_deadline_cancels_the_task_and_awaits_its_cleanup() {
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
let cancel = CancellationToken::new();
let token = cancel.child_token();
let cleaned = Arc::new(AtomicBool::new(false));
let task = {
let (token, cleaned) = (token.clone(), cleaned.clone());
async move {
token.cancelled().await;
cleaned.store(true, Ordering::SeqCst);
Err::<(), _>(IdeError::cancelled())
}
};
let error = until_stopped(Duration::from_millis(20), &cancel, &token, task).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::TimedOut);
assert!(cleaned.load(Ordering::SeqCst), "the task's cleanup ran before the timeout returned");
}
#[tokio::test]
async fn cancelling_the_request_cancels_the_task() {
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
let cancel = CancellationToken::new();
let token = cancel.child_token();
let cleaned = Arc::new(AtomicBool::new(false));
let task = {
let (token, cleaned) = (token.clone(), cleaned.clone());
async move {
token.cancelled().await;
cleaned.store(true, Ordering::SeqCst);
Err::<(), _>(IdeError::cancelled())
}
};
let canceller = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(20)).await;
canceller.cancel();
});
let error = until_stopped(Duration::from_secs(30), &cancel, &token, task).await.unwrap_err();
assert_eq!(error.kind, ErrorKind::Cancelled);
assert!(cleaned.load(Ordering::SeqCst), "the task's cleanup ran before the call returned");
}
#[test]
fn kind_filter_is_case_insensitive_and_routine_covers_functions_and_procedures() {
assert!(kind_matches(None, "table"));
assert!(kind_matches(Some("materializedview"), "materializedView"));
assert!(kind_matches(Some("ROUTINE"), "function"));
assert!(kind_matches(Some("routine"), "procedure"));
assert!(!kind_matches(Some("routine"), "table"));
assert!(!kind_matches(Some("stage"), "table"));
}
}
+2
Переглянути файл
@@ -2,6 +2,7 @@
mod automations;
mod background;
mod check;
mod database;
mod debug;
mod devcontainer;
mod edit;
@@ -55,6 +56,7 @@ fn tools(local_desktop: bool) -> Vec<tool::Tool> {
tools.extend(run::tools());
tools.extend(vcs::tools());
tools.extend(http::tools());
tools.extend(database::tools());
if local_desktop {
tools.extend(devcontainer::tools());
}
+6 -9
Переглянути файл
@@ -697,16 +697,12 @@ fn without_generated_helpers(locations: Vec<Location>) -> Vec<Location> {
/// Gutter markers of plugin `line-markers` providers for an open document.
#[command(trust = trusted)]
pub async fn plugin_line_markers(
host: &Host,
window: &str,
doc: DocId,
) -> IdeResult<Vec<crate::plugins::LineMarkerInfo>> {
pub async fn plugin_line_markers(host: &Host, window: &str, doc: DocId) -> IdeResult<crate::plugins::LineMarkers> {
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::LineMarkers) else {
return Ok(Vec::new());
return Ok(Default::default());
};
let markers = plugin_call(move || plugins.provide_line_markers(&d)).await.unwrap_or_default();
Ok(markers
let (markers, late) = plugin_call(move || plugins.provide_line_markers(&d)).await.unwrap_or_default();
let markers = markers
.into_iter()
.map(|(plugin_id, m)| crate::plugins::LineMarkerInfo {
plugin_id,
@@ -715,7 +711,8 @@ pub async fn plugin_line_markers(
tooltip: m.tooltip,
target: m.target.map(|l| Location { path: l.path.into(), range: l.range, uri: None }),
})
.collect())
.collect();
Ok(crate::plugins::LineMarkers { markers, late })
}
/// Where other files import the document's file (Find Usages on a file, a Vue component's
+26 -9
Переглянути файл
@@ -399,6 +399,14 @@ impl PluginHost {
plugins: Vec<Arc<LoadedPlugin>>,
f: impl FnOnce(&mut Runtime, Duration) -> Result<R, CallError> + Clone + Send + 'static,
) -> Vec<(Arc<LoadedPlugin>, R)> {
self.edit_calls_plugins_late(plugins, f).0
}
/// [`Self::edit_calls_plugins`], plus the ids of the plugins whose call was dropped as late.
fn edit_calls_plugins_late<R: Send + 'static>(
&self,
plugins: Vec<Arc<LoadedPlugin>>,
f: impl FnOnce(&mut Runtime, Duration) -> Result<R, CallError> + Clone + Send + 'static,
) -> (Vec<(Arc<LoadedPlugin>, R)>, Vec<String>) {
let (soft, hard) = (self.limits.edit_soft, self.limits.edit_hard);
let queued: Vec<_> = plugins
.into_iter()
@@ -413,13 +421,18 @@ impl PluginHost {
Some((plugin, actor, started, call))
})
.collect();
queued
let mut late = Vec::new();
let answers = queued
.into_iter()
.filter_map(|(plugin, actor, started, call)| {
let result = call.and_then(Pending::wait);
if matches!(result, Err(ActorError::SoftTimeout)) {
late.push(plugin.id().to_owned());
}
self.finish_provider_call(&plugin, &actor, started, result).map(|r| (plugin, r))
})
.collect()
.collect();
(answers, late)
}
fn edit_calls_cancellable<R: Send + 'static>(
@@ -663,14 +676,18 @@ impl PluginHost {
})
}
pub fn provide_line_markers(&self, doc: &ProviderDocument) -> Vec<(String, LineMarker)> {
/// The markers by plugin id, and the ids of the plugins too late to answer: they gave no
/// answer, not "no markers".
pub fn provide_line_markers(&self, doc: &ProviderDocument) -> (Vec<(String, LineMarker)>, Vec<String>) {
let d = Arc::new(doc.clone());
self.edit_calls(ProviderKind::LineMarkers, &doc.language, move |rt, timeout| {
rt.provide_line_markers(&d, timeout)
})
.into_iter()
.flat_map(|(p, markers)| markers.into_iter().map(move |m| (p.id().to_owned(), m)))
.collect()
let plugins = self.provider_plugins(ProviderKind::LineMarkers, &doc.language);
let (answers, late) =
self.edit_calls_plugins_late(plugins, move |rt, timeout| rt.provide_line_markers(&d, timeout));
let markers = answers
.into_iter()
.flat_map(|(p, markers)| markers.into_iter().map(move |m| (p.id().to_owned(), m)))
.collect();
(markers, late)
}
pub fn provide_semantic_tokens(&self, doc: &ProviderDocument) -> Vec<SemanticToken> {
+10
Переглянути файл
@@ -550,6 +550,16 @@ pub struct LineMarkerInfo {
pub target: Option<ide_core::Location>,
}
/// The answer of the `line-markers` providers for a document.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct LineMarkers {
pub markers: Vec<LineMarkerInfo>,
/// Plugins whose call ran past the edit-path budget and was dropped: they gave no answer,
/// so the editor keeps the markers it shows from them.
pub late: Vec<String>,
}
/// A plugin's before-commit check to run (`[[contributes.commitChecks]]`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+477
Переглянути файл
@@ -3,6 +3,7 @@ use crate::common;
use ide_core::{
CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange, event::McpUiRequest,
};
use ide_db::{DataSource, DbDriver};
use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry};
use ide_host::{Host, HostConfig};
use ide_mcp::ToolRegistry;
@@ -3144,3 +3145,479 @@ async fn automation_tools_enforce_trust_mandatory_confirm_even_in_brave_mode_and
assert_eq!(del_res["deletedId"], imported_id);
assert!(h.host.automations.get(&imported_id).is_none());
}
/// The project's SQLite data source `db`: `users` with 150 rows and a foreign key to itself,
/// the `users_name` unique index and the `named` view.
async fn sqlite_fixture(h: &Harness) {
std::fs::File::create(h.root.join("data.sqlite")).unwrap();
let db = h.host.project("main").unwrap().db.clone();
db.save_sources(vec![DataSource {
id: "db".into(),
name: "Test DB".into(),
driver: DbDriver::Sqlite,
file: Some(h.root.join("data.sqlite").into()),
..Default::default()
}])
.await
.unwrap();
let c = CancellationToken::new();
for stmt in [
"CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, manager_id INTEGER REFERENCES users(id))",
"CREATE UNIQUE INDEX users_name ON users(name)",
"CREATE VIEW named AS SELECT name FROM users",
] {
db.execute("db", stmt, 100, &c).await.unwrap();
}
let rows: Vec<String> = (1..=150).map(|id| format!("({id}, 'user{id:03}')")).collect();
db.execute("db", &format!("INSERT INTO users (id, name) VALUES {}", rows.join(", ")), 100, &c).await.unwrap();
}
/// Writes `.openidea/data-sources.toml` as a crafted repository might: `save_sources` rejects
/// duplicate ids, so a test of the tool boundary needs the file itself.
fn write_sources_file(root: &Path, sources: &[DataSource]) {
let tables: Vec<toml::Value> = sources
.iter()
.map(|source| {
let mut value = toml::Value::try_from(source).unwrap();
value.as_table_mut().unwrap().remove("global");
value
})
.collect();
let doc = toml::Value::Table(toml::map::Map::from_iter([("data-source".to_owned(), toml::Value::Array(tables))]));
std::fs::create_dir_all(root.join(".openidea")).unwrap();
std::fs::write(root.join(".openidea/data-sources.toml"), toml::to_string_pretty(&doc).unwrap()).unwrap();
}
/// Runs `name` in the project's window and allows the confirmation it asks there; the window
/// must be ready (`h.host.mcp_requests.set_ready("main", true)`).
async fn confirmed(h: &Harness, name: &str, args: Value) -> String {
h.events.lock().unwrap().clear();
let call = h.call(name, args);
let allow = async {
let id = h.request().await;
h.host.mcp_requests.answer("main", id, true, None).unwrap();
};
let (result, ()) = tokio::join!(call, allow);
result
}
/// Like [`confirmed`], for a call that must fail after the confirmation.
async fn confirmed_error(h: &Harness, name: &str, args: Value) -> String {
h.events.lock().unwrap().clear();
let call = h.error(name, args);
let allow = async {
let id = h.request().await;
h.host.mcp_requests.answer("main", id, true, None).unwrap();
};
let (result, ()) = tokio::join!(call, allow);
result
}
#[tokio::test(flavor = "multi_thread")]
async fn database_connections_are_listed_without_urls_hosts_or_credentials() {
let h = Harness::new();
sqlite_fixture(&h).await;
assert!(!h.host.project("main").unwrap().is_trusted(), "the metadata tools need a trusted project");
let refused = h.error("list_database_connections", json!({})).await;
assert!(refused.contains("Restricted Mode"), "{refused}");
h.trust().await;
let raw = h.call("list_database_connections", json!({})).await;
let listed: Value = serde_json::from_str(&raw).unwrap();
assert_eq!(
listed["connections"],
json!([{ "id": "db", "name": "Test DB", "driver": "sqlite", "database": "", "readOnly": false, "global": false }])
);
for key in ["url", "host", "user", "password"] {
assert!(!raw.contains(&format!("\"{key}\"")), "`{key}` in {raw}");
}
// A URL-only source's URL, host and user never reach the agent either.
let db = h.host.project("main").unwrap().db.clone();
let mut sources = db.sources().unwrap();
sources.push(DataSource {
id: "remote".into(),
name: "Remote".into(),
driver: DbDriver::Postgres,
url_only: true,
url: "postgres://db.example.invalid:5432/app".into(),
..Default::default()
});
db.save_sources(sources).await.unwrap();
let raw = h.call("list_database_connections", json!({})).await;
assert!(raw.contains("\"remote\""), "{raw}");
for secret in ["db.example.invalid", "5432", "app"] {
assert!(!raw.contains(secret), "`{secret}` in {raw}");
}
}
/// Global data sources are stored app-wide and listed in every project; the list marks them.
#[tokio::test(flavor = "multi_thread")]
async fn global_data_sources_are_listed_with_a_global_flag() {
let h = Harness::new();
sqlite_fixture(&h).await;
ide_db::source::save_global(
&h.host.data_dir,
&[DataSource {
id: "shared".into(),
name: "Shared".into(),
driver: DbDriver::Sqlite,
file: Some(h.root.join("data.sqlite").into()),
..Default::default()
}],
)
.unwrap();
h.trust().await;
let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap();
let connections = listed["connections"].as_array().unwrap();
let project = connections.iter().find(|c| c["id"] == "db").expect("the project source");
assert_eq!(project["global"], false, "{listed}");
let global = connections.iter().find(|c| c["id"] == "shared").expect("the global source");
assert_eq!(global["global"], true, "{listed}");
}
#[tokio::test(flavor = "multi_thread")]
async fn database_schemas_and_objects_are_listed_in_a_trusted_project() {
let h = Harness::new();
sqlite_fixture(&h).await;
for (name, args) in [
("list_database_schemas", json!({"connectionId": "db"})),
("list_schema_objects", json!({"connectionId": "db", "schema": "main"})),
] {
let refused = h.error(name, args).await;
assert!(refused.contains("Restricted Mode"), "{name}: {refused}");
}
h.trust().await;
let schemas = h.json("list_database_schemas", json!({"connectionId": "db"})).await;
assert_eq!(schemas["connectionId"], "db");
assert_eq!(schemas["schemas"], json!(["main"]));
// Tables and views are objects; the unique index is not.
let all = h.json("list_schema_objects", json!({"connectionId": "db", "schema": "main"})).await;
assert_eq!(all["objects"], json!([{"kind": "view", "name": "named"}, {"kind": "table", "name": "users"}]), "{all}");
assert!(!all.to_string().contains("users_name"), "{all}");
let views = h.json("list_schema_objects", json!({"connectionId": "db", "schema": "main", "kind": "view"})).await;
assert_eq!(views["objects"], json!([{"kind": "view", "name": "named"}]), "{views}");
}
#[tokio::test(flavor = "multi_thread")]
async fn database_object_description_reads_columns_indexes_and_foreign_keys() {
let h = Harness::new();
sqlite_fixture(&h).await;
let args = json!({"connectionId": "db", "schema": "main", "objectName": "users"});
let refused = h.error("get_database_object_description", args.clone()).await;
assert!(refused.contains("Restricted Mode"), "{refused}");
h.trust().await;
let described = h.json("get_database_object_description", args).await;
assert_eq!(
(&described["connectionId"], &described["schema"], &described["objectName"]),
(&json!("db"), &json!("main"), &json!("users"))
);
let details = &described["details"];
let columns = details["columns"].as_array().unwrap();
let names: Vec<&str> = columns.iter().map(|c| c["name"].as_str().unwrap()).collect();
assert_eq!(names, ["id", "name", "manager_id"]);
assert_eq!(columns[0]["primaryKey"], true);
assert_eq!(columns[1]["nullable"], false);
let index = details["indexes"].as_array().unwrap().iter().find(|i| i["name"] == "users_name").expect("users_name");
assert_eq!(index["unique"], true);
assert_eq!(index["columns"], json!(["name"]));
let keys = details["foreignKeys"].as_array().unwrap();
assert_eq!(keys.len(), 1, "{described}");
assert_eq!(keys[0]["columns"], json!(["manager_id"]));
assert_eq!(keys[0]["refSchema"], "main");
assert_eq!(keys[0]["refTable"], "users");
assert_eq!(keys[0]["refColumns"], json!(["id"]));
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_is_a_write_tool_that_needs_trust() {
let h = Harness::new();
sqlite_fixture(&h).await;
let untrusted = Registry::new(h.host.clone()).tools(&h.root).unwrap();
for name in
["list_database_connections", "list_database_schemas", "list_schema_objects", "get_database_object_description"]
{
assert!(untrusted.iter().any(|t| t.name == name && t.read_only), "{name} is a read tool");
}
assert!(untrusted.iter().all(|t| t.name != "execute_sql_query"), "a write tool is hidden until trust");
// The metadata tools are still listed, but their calls need trust too, not only the write tool.
for (name, args) in [
("list_database_connections", json!({})),
("list_database_schemas", json!({"connectionId": "db"})),
("list_schema_objects", json!({"connectionId": "db", "schema": "main"})),
("get_database_object_description", json!({"connectionId": "db", "schema": "main", "objectName": "users"})),
] {
let message = h.error(name, args).await;
assert!(message.contains("Restricted Mode"), "{name}: {message}");
}
// Calling it directly is refused too, not only hidden from the list.
let refused = Registry::new(h.host.clone()).call(
&h.root,
"execute_sql_query",
&json!({"connectionId": "db", "sql": "SELECT 1"}).to_string(),
CancellationToken::new(),
);
let message = match refused.expect_err("a write tool is refused in Restricted Mode") {
ide_mcp::ToolCallError::Failed(message) | ide_mcp::ToolCallError::UnknownTool(message) => message,
};
assert!(message.contains("Restricted Mode"), "{message}");
h.trust().await;
let trusted = Registry::new(h.host.clone()).tools(&h.root).unwrap();
let tool = trusted.iter().find(|t| t.name == "execute_sql_query").expect("offered once trusted");
assert!(!tool.read_only);
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_pages_rows_and_cuts_long_cells() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let page: Value = serde_json::from_str(
&confirmed(
&h,
"execute_sql_query",
json!({"connectionId": "db", "sql": "SELECT id, name FROM users ORDER BY id", "maxRows": 10}),
)
.await,
)
.unwrap();
assert_eq!(page["rowCount"], 10, "{page}");
assert_eq!(page["rows"].as_array().unwrap().len(), 10);
assert_eq!(page["hasMore"], true);
assert_eq!(page["rows"][0], json!(["1", "user001"]));
// The dialog showed the exact statement, not the raw arguments or a truncated form.
let detail = h
.events
.lock()
.unwrap()
.iter()
.find_map(|(_, event)| match event {
IdeEvent::McpRequest { request: McpUiRequest::Confirm { detail, .. }, .. } => {
Some(detail.clone().unwrap_or_default())
}
_ => None,
})
.expect("a confirmation was asked");
assert!(detail.contains("SQL:\nSELECT id, name FROM users ORDER BY id"), "{detail}");
assert!(detail.contains("Driver: SQLite"), "{detail}");
let columns: Vec<&str> = page["columns"].as_array().unwrap().iter().map(|c| c["name"].as_str().unwrap()).collect();
assert_eq!(columns, ["id", "name"]);
// Without `maxRows` the result stops at the default of 100, and says more rows exist.
let default: Value = serde_json::from_str(
&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": "SELECT id FROM users ORDER BY id"}))
.await,
)
.unwrap();
assert_eq!(default["rowCount"], 100, "{default}");
assert_eq!(default["rows"].as_array().unwrap().len(), 100);
assert_eq!(default["hasMore"], true);
// A cell longer than 4096 UTF-16 units is cut and reported in `truncated`.
let sql = format!("SELECT '{}' AS long", "x".repeat(5000));
let long: Value =
serde_json::from_str(&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": sql})).await)
.unwrap();
assert_eq!(long["rows"][0][0].as_str().unwrap().chars().count(), 4096);
let truncated = long["truncated"].as_array().unwrap();
assert_eq!(truncated.len(), 1, "{long}");
assert_eq!(truncated[0]["length"], 5000);
assert_eq!((&truncated[0]["row"], &truncated[0]["column"]), (&json!(0), &json!(0)));
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_refuses_several_statements_and_writes_before_asking() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
let several = h.error("execute_sql_query", json!({"connectionId": "db", "sql": "SELECT 1; SELECT 2"})).await;
assert!(several.contains("exactly one statement"), "{several}");
let write = h.error("execute_sql_query", json!({"connectionId": "db", "sql": "DELETE FROM users"})).await;
assert!(write.contains("DELETE is not allowed"), "{write}");
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
let count = h
.host
.project("main")
.unwrap()
.db
.execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new())
.await
.unwrap();
assert_eq!(count.rows, vec![vec![Some("150".into())]]);
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_refuses_a_driver_without_a_read_only_session_before_asking() {
let h = Harness::new();
let db = h.host.project("main").unwrap().db.clone();
db.save_sources(vec![DataSource {
id: "mssql".into(),
name: "SQL Server".into(),
driver: DbDriver::SqlServer,
host: "127.0.0.1".into(),
port: Some(1),
user: "sa".into(),
..Default::default()
}])
.await
.unwrap();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.events.lock().unwrap().clear();
// The refusal happens before a connection is opened, so no server is needed.
let error = h.error("execute_sql_query", json!({"connectionId": "mssql", "sql": "SELECT 1"})).await;
assert!(error.contains("SQL Server has no read-only session"), "{error}");
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
/// A statement that passes the `SELECT`/`WITH` allowlist but writes through a CTE is refused by the
/// driver-enforced read-only session (`PRAGMA query_only`), not by the keyword check. Unlike the
/// gated PostgreSQL test, this runs everywhere SQLite does.
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_refuses_a_cte_write_through_the_read_only_session() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let error = confirmed_error(
&h,
"execute_sql_query",
json!({"connectionId": "db", "sql": "WITH d AS (SELECT 1) DELETE FROM users"}),
)
.await;
assert!(error.to_ascii_lowercase().contains("readonly"), "{error}");
let count = h
.host
.project("main")
.unwrap()
.db
.execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new())
.await
.unwrap();
assert_eq!(count.rows, vec![vec![Some("150".into())]], "the session refused the write before it ran");
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_can_be_denied_without_changing_the_database() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
let denied =
h.error("execute_sql_query", json!({"connectionId": "db", "sql": "SELECT name FROM users ORDER BY id"}));
let deny = async {
let id = h.request().await;
h.host.mcp_requests.answer("main", id, false, None).unwrap();
};
let (error, ()) = tokio::join!(denied, deny);
assert!(error.contains("denied by the user"), "{error}");
let count = h
.host
.project("main")
.unwrap()
.db
.execute("db", "SELECT count(*) FROM users", 1, &CancellationToken::new())
.await
.unwrap();
assert_eq!(count.rows, vec![vec![Some("150".into())]]);
}
/// A crafted project file cannot route a tool to a plugin-owned source: its id is refused when
/// plugin-owned, a `:database` suffix is refused, and two entries with one id are refused.
#[tokio::test(flavor = "multi_thread")]
async fn database_tools_refuse_plugin_and_ambiguous_connection_ids() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
let file: ide_core::IpcPath = h.root.join("data.sqlite").into();
let plugin = |id: &str| DataSource {
id: id.into(),
name: "Plugin source".into(),
driver: DbDriver::Sqlite,
file: Some(file.clone()),
plugin_owner: Some("sample".into()),
plugin_source_id: Some("owned".into()),
..Default::default()
};
let user = |id: &str| DataSource {
id: id.into(),
name: "User source".into(),
driver: DbDriver::Sqlite,
file: Some(file.clone()),
..Default::default()
};
write_sources_file(
&h.root,
&[
plugin("plugin-owned"),
user("plugin-owned:database"),
// The plugin entry first: `DbManager` takes the first matching prefix.
plugin("dup"),
user("dup"),
],
);
let colon = h.error("list_database_schemas", json!({"connectionId": "plugin-owned:database"})).await;
assert!(colon.contains("without a `:database` part"), "{colon}");
let owned = h.error("list_database_schemas", json!({"connectionId": "plugin-owned"})).await;
assert!(owned.contains("no data source plugin-owned"), "{owned}");
let duplicate = h.error("list_database_schemas", json!({"connectionId": "dup"})).await;
assert!(duplicate.contains("more than one data source"), "{duplicate}");
// `list_database_connections` keeps its own filter: only the user entries appear.
let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap();
let ids: Vec<&str> = listed["connections"].as_array().unwrap().iter().map(|c| c["id"].as_str().unwrap()).collect();
assert!(!ids.contains(&"plugin-owned"), "{listed}");
}
/// Driver and tunnel errors can name the user or the host; no database tool may pass them on.
#[tokio::test(flavor = "multi_thread")]
async fn database_tool_errors_hide_the_user_host_and_url() {
let h = Harness::new();
let db = h.host.project("main").unwrap().db.clone();
db.save_sources(vec![DataSource {
id: "remote".into(),
name: "Remote".into(),
driver: DbDriver::Postgres,
user: "alice".into(),
host: "127.0.0.1".into(),
url_only: true,
url: "postgres://alice:[email protected]:1/app".into(),
..Default::default()
}])
.await
.unwrap();
let assert_hidden = |text: &str| {
for secret in ["alice", "127.0.0.1", "postgres://"] {
assert!(!text.contains(secret), "`{secret}` in {text}");
}
};
h.trust().await;
let listed = h.call("list_database_connections", json!({})).await;
assert_hidden(&listed);
let schemas = h.error("list_database_schemas", json!({"connectionId": "remote"})).await;
assert_hidden(&schemas);
h.host.mcp_requests.set_ready("main", true);
let query = confirmed_error(&h, "execute_sql_query", json!({"connectionId": "remote", "sql": "SELECT 1"})).await;
assert_hidden(&query);
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_sql_query_still_answers_a_select_on_a_read_only_data_source() {
let h = Harness::new();
sqlite_fixture(&h).await;
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
// The data source's own read-only setting is respected: queries still run, and it is listed as such.
let db = h.host.project("main").unwrap().db.clone();
let mut sources = db.sources().unwrap();
sources.iter_mut().find(|s| s.id == "db").unwrap().read_only = true;
db.save_sources(sources).await.unwrap();
let listed: Value = serde_json::from_str(&h.call("list_database_connections", json!({})).await).unwrap();
assert_eq!(listed["connections"][0]["readOnly"], true, "{listed}");
let result: Value = serde_json::from_str(
&confirmed(&h, "execute_sql_query", json!({"connectionId": "db", "sql": "SELECT count(*) AS n FROM users"}))
.await,
)
.unwrap();
assert_eq!(result["rows"], json!([["150"]]), "{result}");
}
+81 -4
Переглянути файл
@@ -3493,7 +3493,7 @@ fn official_mybatis_navigates_between_interface_and_xml() {
// skipped. The editor asks again; so does this.
let deadline = Instant::now() + Duration::from_secs(10);
let markers = loop {
let markers = f.host.provide_line_markers(&jdoc);
let markers = f.host.provide_line_markers(&jdoc).0;
if !markers.is_empty() || Instant::now() > deadline {
break markers;
}
@@ -3524,7 +3524,7 @@ fn official_mybatis_navigates_between_interface_and_xml() {
let mut times = Vec::new();
for _ in 0..20 {
let started = Instant::now();
assert_eq!(f.host.provide_line_markers(&jdoc).len(), 1);
assert_eq!(f.host.provide_line_markers(&jdoc).0.len(), 1);
times.push(started.elapsed());
}
times.sort();
@@ -6575,8 +6575,8 @@ fn marker_providers_preserve_names_and_package_paths() {
version: 1,
text: "marker-icons\nordinary\ncustom\nlegacy".into(),
};
assert!(eventually(|| f.host.provide_line_markers(&doc).len() == 4));
let markers = f.host.provide_line_markers(&doc);
assert!(eventually(|| f.host.provide_line_markers(&doc).0.len() == 4));
let markers = f.host.provide_line_markers(&doc).0;
assert_eq!(
markers.iter().map(|(_, m)| m.icon.as_deref().unwrap()).collect::<Vec<_>>(),
["run", "database", "icons/very-long-resource-marker-icon.svg", "overriding"]
@@ -8826,3 +8826,80 @@ fn custom_editor_toolbar_installs_and_validates_manifest() {
.contains("[[contributes.commands]]")
);
}
/// `misbehave` as `id`, a `line-markers` provider for `text`; with `spin`, also its `spin`
/// command, which keeps its instance busy until cancelled.
fn install_marker_provider(f: &Fixture, tmp: &Path, id: &str, spin: bool) {
let pkg = tmp.join(id);
copy_dir(&misbehave_pkg(), &pkg);
let command = if spin { "[[contributes.commands]]\nid = \"spin\"\ntitle = \"spin\"\n" } else { "" };
std::fs::write(
pkg.join("plugin.toml"),
format!(
"id = \"{id}\"\nname = \"{id}\"\nversion = \"0.0.1\"\nengines.openidea = \"^1.0\"\n\
wasm = \"dist/plugin.wasm\"\nactivation = [\"on-language:text\"]\n{command}\
[[contributes.providers]]\nkinds = [\"line-markers\"]\nlanguages = [\"text\"]\n"
),
)
.unwrap();
f.install(&pkg);
}
fn markers_doc(f: &Fixture) -> ide_plugin::ProviderDocument {
ide_plugin::ProviderDocument {
path: f.project.join("markers.txt"),
language: "text".into(),
version: 1,
text: "marker-icons\nordinary\ncustom\nlegacy".into(),
}
}
/// A call dropped by the edit-path budget is reported by plugin, not answered as "no markers";
/// a disabled plugin is not asked, so it is not reported.
#[test]
fn line_markers_report_the_plugins_too_late_to_answer() {
let f = fixture(Limits { edit_soft: Duration::ZERO, ..Limits::default() });
let tmp = tempfile::tempdir().unwrap();
install_marker_provider(&f, tmp.path(), "late-a", false);
install_marker_provider(&f, tmp.path(), "late-b", false);
let (markers, mut late) = f.host.provide_line_markers(&markers_doc(&f));
late.sort();
assert!(markers.is_empty());
assert_eq!(late, ["late-a", "late-b"]);
f.host.set_enabled("late-a", false).unwrap();
assert_eq!(f.host.provide_line_markers(&markers_doc(&f)), (Vec::new(), vec!["late-b".to_owned()]));
}
/// A call queued behind a busy instance past the budget is reported as late; the plugins that
/// answered in time keep their markers.
#[test]
fn line_markers_too_late_from_one_provider_keep_the_others() {
// A budget no runner misses, so only the call queued behind `spin` is late.
let f = fixture(Limits {
edit_soft: Duration::from_secs(1),
edit_hard: Duration::from_secs(30),
timeout: Duration::from_secs(60),
fuel: u64::MAX,
..Limits::default()
});
let tmp = tempfile::tempdir().unwrap();
install_marker_provider(&f, tmp.path(), "busy", true);
install_marker_provider(&f, tmp.path(), "on-time", false);
let doc = markers_doc(&f);
assert!(eventually(|| f.host.provide_line_markers(&doc).0.len() == 8));
std::thread::scope(|scope| {
scope.spawn(|| f.run("busy", "spin", None));
// Answered in time until `spin` runs; late from then on.
let mut answer = (Vec::new(), Vec::new());
let late_seen = eventually(|| {
answer = f.host.provide_line_markers(&doc);
!answer.1.is_empty()
});
f.host.cancel("busy");
assert!(late_seen, "never late: {answer:?}");
let (markers, late) = answer;
assert_eq!(late, ["busy"]);
assert_eq!(markers.len(), 4);
assert!(markers.iter().all(|(id, _)| id == "on-time"));
});
}
+2 -1
Переглянути файл
@@ -9678,7 +9678,8 @@ async fn a_server_is_sent_the_documents_it_registers_a_selector_for() {
let after = open_data("after.dt");
eventually(|| fw.docs.lock().contains_key(&uri_of(&after))).await;
// Its own server keeps the documents, and one the selector doesn't name stays with it alone.
assert!(own.docs.lock().contains_key(&uri_of(&after)) && own.docs.lock().contains_key(&uri_of(&unrelated)));
eventually(|| own.docs.lock().contains_key(&uri_of(&after)) && own.docs.lock().contains_key(&uri_of(&unrelated)))
.await;
assert!(!fw.docs.lock().contains_key(&uri_of(&unrelated)));
// The server list names the language among the ones it serves.
let served = h.mgr.servers().into_iter().find(|s| s.name == "fw").unwrap().languages;
+4
Переглянути файл
@@ -1281,6 +1281,10 @@ fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event {
kind: "project-closed".into(),
data: serde_json::to_string(&p).expect("path serializes"),
}),
WorkbenchEvent::ProjectTreeExpanded(paths) => wit_events::Event::Other(wit_types::Extension {
kind: "project-tree-expanded".into(),
data: serde_json::to_string(&paths).expect("paths serialize"),
}),
WorkbenchEvent::Scheduled => wit_events::Event::Scheduled,
WorkbenchEvent::Timer(id) => wit_events::Event::Other(wit_types::Extension {
kind: "timer".into(),
+9 -1
Переглянути файл
@@ -239,13 +239,16 @@ pub enum EventKind {
ProjectClosed,
/// Paths outside the project watched with `events.watch-paths` changed (API 1.18).
WatchedFilesChanged,
/// Project tree folders newly expanded, or already expanded when a plugin subscribes (API 1.21):
/// a JSON array of absolute paths (`Event::Other`).
ProjectTreeExpanded,
Scheduled,
/// A timer the plugin set with `events.schedule` fired (API 1.21); delivered without subscribing.
Timer,
}
impl EventKind {
pub const ALL: [Self; 23] = [
pub const ALL: [Self; 24] = [
Self::DocumentChanged,
Self::WebsocketReady,
Self::FileClosed,
@@ -267,6 +270,7 @@ impl EventKind {
Self::ProblemsChanged,
Self::ProjectClosed,
Self::WatchedFilesChanged,
Self::ProjectTreeExpanded,
Self::Scheduled,
Self::Timer,
];
@@ -294,6 +298,7 @@ impl EventKind {
Self::ProblemsChanged => "problems-changed",
Self::ProjectClosed => "project-closed",
Self::WatchedFilesChanged => "watched-files-changed",
Self::ProjectTreeExpanded => "project-tree-expanded",
Self::Scheduled => "scheduled",
Self::Timer => "timer",
}
@@ -489,6 +494,8 @@ pub enum WorkbenchEvent {
/// Changes to paths outside the project watched with `events.watch-paths` (API 1.18);
/// `project` is the project the watch belongs to, `generation` is unset.
WatchedFilesChanged(FilesChanged),
/// Project tree folders newly expanded, or already expanded when a plugin subscribes (API 1.21).
ProjectTreeExpanded(Vec<String>),
Scheduled,
/// A timer this plugin set with `events.schedule` fired (API 1.21): its id.
Timer(String),
@@ -518,6 +525,7 @@ impl WorkbenchEvent {
Self::ProblemsChanged => EventKind::ProblemsChanged,
Self::ProjectClosed(_) => EventKind::ProjectClosed,
Self::WatchedFilesChanged(_) => EventKind::WatchedFilesChanged,
Self::ProjectTreeExpanded(_) => EventKind::ProjectTreeExpanded,
Self::Scheduled => EventKind::Scheduled,
Self::Timer(_) => EventKind::Timer,
}
+1 -1
Переглянути файл
@@ -1824,7 +1824,7 @@ impl events::Host for StoreData {
{
return Ok(Err(to_wit(e)));
}
if matches!(kind, EventKind::RunStarted | EventKind::RunOutput)
if matches!(kind, EventKind::RunStarted | EventKind::RunOutput | EventKind::ProjectTreeExpanded)
&& let Err(e) = self.host.require_api(kind.name(), 21)
{
return Ok(Err(to_wit(e)));
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8fe67be847a6bd86dd288aa678357fd2caf28b4aa74e7067efd07961ab37ffa0
b8be10102efb9a73945b342e1077130e3ae259d318a1328aa449f3fc6d33c95d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e562434a35eca32556c79381eacd380f101f03009a6aeae0d34db893bf93ba75
75910c8950f19404d2b389c31250b38e94e0845b8406fd65086d801c3b7beb42
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3f2459f0b4b016ad28aaf4e157e43a25cda92b325ee09fbb37cccc8daa34df6b
4dd181187bc087ad2155ac92d304f50cda4fededc63b02ad57cf012f01eef3f6
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
286012eeb2145fbc92c7648e7759f1ada45e347b5421c1917cd944fc063e1863
99dbde69e800adbb3277f78b0a7ffbf6c86b387995c7cf7f7701a5cc7175f87d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4fade1b835a8823e505e195b8a616093126ef670de2618ec54baac1fcbb60ce6
4d795c1074d4be794c7327c623b0e366e1daab50778f918a42a2d38439542a12
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
bdff2d28e51e8c1eacc92a19b2a4e28581a9c5a895359187d83fecb5be3d3a85
b85013d2dac330df156621e610bcb7b529761f34891ccb0a43139caff9b806e6
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e594c6b4a22cb97c7355793c3d294b966ba10b5a79cc847e47f6019489369fde
6742d26393161e0858d7a672969d861493f36e28ae122fd3606aee570bf154f7
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
af09884fe417936b2a76a6c22842630f661e3575c3862e31cad4867a4b9f9e56
31fec64f6ce288e5514d93dd2d451ec5e00c25ca5fd6568bde636765bc980168
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ec069a728a1f3e914e7708f579fd1f7ce2dbd29e1483453696b15b75906be10e
24fb126861d1398a19a4b9a9167dc253f4f03760428013050986f94391ed4c79
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9ee77f07270b33457abb1acca9430b83c3b8a2cd21e02e82a541e65cfa60b05d
65c6e23c92a58ecb73518445eaf2f95decdd3ee434d2ba34101cd7b122881d1c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
035cb92e3fcc09302d302243f65183d1173bd04c415e2a8c5b67494ea964da26
2f5ce9268f54296994835c650667142893574c96b707410024897242370d522f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4aef5fd2f4eb1e47877f70b752764f1d1c7345abde8722ebc314748c3b9b41d2
1a1ab54e7c5939167cb5f18da6107ec812ed4ba6ff60b69b985675996cbda5a5
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1e96fa8cfefd02b486c3abc060784f703529d1b7635c4b527c4ab0717cf29146
8775c5084031dfdda65492a10dc1c3dda4de82f02121f99c4dbeb989e21d5c2f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
35fd22ae39343dc0a606d6f31149fced471397eafe713e519a1d8b3f44805948
e54e38958b56dea794b7c625c6d91465bb5f6f34c83433a5f3e0c72fdb568fec
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f70d9de39765ff84cca47030c9d7a8bca1caaadceb70d526e44821a5cbfbf6be
9986a416ae0286ef587fb068afa4017344e60e6fc798cf4b041330e223570c71
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
64140ad91c947d9b672eef867e8ce86a1fa254cf41de8786c26aa64879cc69bb
650b01742cb7a9879a121df7fc3d49d478e4e9ead6b28bd1a7773fd3112c0579
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8daca93352b13cd876045913eed114a43b66d9f4b0ec48f2992f67f1a60ac65d
4e6dde5d4ca82690739916b859c738bb1d445c5406ad8f907376206c1c0d5a04
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2990b5753169d476afd5be487cfdc26d4ffc66487a51a7a99ccd1e07c3cbd21c
0d2992306e79a9ff042d7d15bd9690d12fcc3b658055f9f629ad534c4c6f72f0
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
67233a03c58b09682303da49f3d6f209857f2ef3e910c2533a5055e233ff6096
0586a531e1c85c314960d7ac066179458ab4c20a5923c6738c3501c913452da9
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
d2f812daeae98c466e7b23450d86e583ed2db8bf7e39cd6e6005be4a0b1a08d1
10562a15fc5f231b8a68108653133c91e96e32b8c2ca1625d340151930a85081
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ac7fdaffaef9f364997ce3434410f22b776e47aa98df78febad213c1a0dda2dc
f3232db563dcf0e08325425382014713bf96f60e17f307dbc568f1facf72948c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1b54498a31ffc6c373769f780c7f8510ca62787f6d0d5eafa904dd834bcadc5b
c788f1a863f7efc73efe4611dca5ad0215c5a8c1da129a6158cf681b39fa18c3
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
286c6f6253d58245102b9797c0d80f54749bdb51e458156f79fe54885b6a76d3
d8c589d3f62c538e194b0f5a2e5db4f1be2812498a4f05f87e779535dd5ddde9
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
67584a6306508021b9dd9453ce687b8dd73dd5c0577524172bb6ef2a506a4c86
dafa503be1dd67478e8bfc309c4c485e000a9b75cb3719df56683c86f1b68564
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
983f6a29e1bc6a0535cb9aea23216505f81e85f32b7497b5366568e04ccc81fd
31381b6a31660cefaefe8b938c217711f1513bfb2445460787a4e9827407bb6e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
483cf0a847b27bd107f385b9e256b184579d798b8e9a15dd383a938f71a94d2b
856991e10d441a6044f3952e94be581b83180497cd10026b88c0221bb446d644
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9a3f69e9f7779e91106107b1fa34c13944058b8543330d55df0cc8b415d7b480
b5e27b340ea81a792f5f2ec45b0b1aa3e529bcc4e94827fbb6c5aaf09edbcf7a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5b208da2e34ba9e2ce7653b2692586e8705fd5eb1466ce996a71882998ebb249
48dddfe2f5126c9e4cfe4b5694c2e9218e4a82a29f0039ffcd2e093c0a15814a
+1 -1
Переглянути файл
@@ -1 +1 @@
cd715076bcce3606ec3bfadee5964a28e668f652c4c5219185aee05f5908b346
8bb50006dc5afe0f767a435d7f1a22c2b74fb9b84fb6b9c18213d322dce93eed
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
d77ce6b138dbba4184e63bb178147f86fc9beae2a8dd24bba28ae696e49133a4
e68e7444837b2b55611407bc8a3c37cc0e8d210f502b79db2cf3a671534ce36b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
dfbb9da1f64f162a77feba37001b1574f785603a475365450707c615d3b8e174
84f8be0119ec2ada0e319f7162abd22ea6a64d7959fd2d342074687f3ab26fde
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
9da9f094dad19091682682a241d17e4206738f2b832f4e603d8a51a54d63b701
31619ef14a44f347b01419a4851499fb0e1ed2c55a751b4d139e88914307e011
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
796e5d8bfe42c668d2688a72c2ad50053cde7f82888ac33e32f52ab4fec60be6
3a7908caa2ac93d57004e9a4dba72ae6d161a4183e921d393f9cedbe792ac839
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5ff1341eac1f6703edbf557b0b6b6d6046078c00f163f7140fe987cce7715348
4a9c229a681273e77e8ca3c429637899aa7187c855e85c668e2290c8773883ea
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
afa7550aef81aae6bc27229bed4d9b6ab4a5280c0321434954facd9bfb54a36e
755b57c427ae48315cbadd252d7e8995c05af13c8cfb30cd8b0fa9d0c8d71338
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
cf4df7af53ca6a333452a3fee0bf0687eef608dace6b70a69bfe9172f9046ad5
cc94a2dc87a04ebffae275445374290a6ff917b04ee10b21fbd1a696b79c1fe7
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ff3a5044cd50e6020ad73877e162047d2219649361480ec6ecf03267e32c5af0
073e5322210532b3cd8f53701295a378b316c5e6f02479106d85d85757f03d42
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2d2e5aad65cc1c3ac1c89762dc304e4905259d6ef864f91edf2b74c80b2073e5
16365c383dafd031032e7451c926bf27b4b92101cf7297487489b0effaee3c5a
Loaded 100 of 240 files, more files were not shown because too many files have changed in this diff. Show more