Файли
openidea/crates/ide-host/tests/plugin_data_tools.rs
T
RuyimgByCNтаl0ng-ai bc019ace9d feat(plugins): add database schema discovery and query execution APIs (API 1.21) (#7958)
* feat(plugins): add database schema discovery and query execution APIs (API 1.21)

* docs(plugins): list API 1.21 database discovery and query additions in versioning

* fix(plugins): address database discovery/query review findings and rebuild dist

---------

Co-authored-by: l0ng-ai <[email protected]>
2026-12-04 23:38:50 +08:00

578 рядки
28 KiB
Rust

//! Database and MCP calls through a real sandboxed component.
mod common;
use ide_core::{CancellationToken, IdeEvent, event::McpUiRequest};
use ide_host::{
Host, HostConfig,
mcp::Registry,
ops,
plugins::{Consent, HostWorkspace, PluginEvent, PluginHost, WindowRequest},
};
use ide_mcp::{ToolCallError, ToolRegistry};
use ide_plugin::{Invocation, Limits};
use std::{
path::{Path, PathBuf},
sync::{Arc, Mutex},
time::Duration,
};
const ID: &str = "test.data-tools";
fn fixture() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/data-tools")
}
struct Harness {
host: Arc<Host>,
plugins: Arc<PluginHost>,
root: PathBuf,
events: Arc<Mutex<Vec<(String, IdeEvent)>>>,
requests: Arc<Mutex<Vec<(String, PluginEvent)>>>,
_tmp: tempfile::TempDir,
}
impl Harness {
fn new() -> Self {
Self::with_timeout(Duration::from_millis(250))
}
fn with_timeout(timeout: Duration) -> Self {
ide_ssh::secrets::testing::use_memory_store();
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir(&root).unwrap();
let events = Arc::new(Mutex::new(vec![]));
let out = events.clone();
let host = Arc::new(Host::new(HostConfig {
sink_for: Box::new(move |w| {
let (w, out) = (w.to_owned(), out.clone());
Arc::new(move |e| out.lock().unwrap().push((w.clone(), e)))
}),
local_data_dir: tmp.path().join("local"),
..common::host_config(tmp.path())
}));
std::fs::write(root.join("db.sqlite"), "").unwrap();
host.open_project("main", &root).unwrap();
host.open_project("second", &root).unwrap();
let requests = Arc::new(Mutex::new(vec![]));
let out = requests.clone();
let plugins = Arc::new(
PluginHost::new(
tmp.path().join("plugins"),
Arc::new(move |w: Option<&str>, e| out.lock().unwrap().push((w.unwrap_or_default().to_owned(), e))),
Limits { timeout, ..Default::default() },
)
.unwrap(),
);
plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
host.set_plugin_host(&plugins);
plugins.install_from_dir(&fixture(), &Consent::all()).unwrap();
Self { host, plugins, root, events, requests, _tmp: tmp }
}
fn invocation(&self) -> Invocation {
Invocation { client: Some("main".into()), workspace_root: Some(self.root.clone()), ..Default::default() }
}
fn run(&self, id: &str, arg: Option<&str>) -> ide_core::IdeResult<Option<String>> {
self.plugins.run_command(ID, id, arg, self.invocation())
}
/// The folder `inventory` next to the project, listed to be served without a window.
fn serve_inventory(&self) -> PathBuf {
let inventory = self.root.parent().unwrap().join("inventory");
std::fs::create_dir(&inventory).unwrap();
for (key, value) in [
("enabled", serde_json::json!(true)),
("backgroundProjects", serde_json::json!("listed")),
("backgroundProjectPaths", serde_json::json!([inventory])),
] {
let key = format!("mcpServer.{key}");
self.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
}
inventory
}
fn source(&self) -> String {
serde_json::json!({"id":"local","name":"Example","driver":"sqlite","database":self.root.join("db.sqlite").to_string_lossy(),"options":[]}).to_string()
}
}
#[tokio::test(flavor = "multi_thread")]
async fn database_calls_enforce_grants_trust_ownership_and_uninstall_lifetime() {
// Nothing here tests the command budget, and a slow runner's first calls can exceed 250 ms.
let f = Harness::with_timeout(Duration::from_secs(10));
assert!(f.run("sources", None).is_err());
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let source = f.source();
f.run("upsert", Some(&source)).unwrap();
assert_eq!(f.run("sources", None).unwrap().as_deref(), Some("[\"local\"]"));
f.run("credential", Some("never-on-disk")).unwrap();
let source = f.host.project("main").unwrap().db.plugin_source(ID, "local").unwrap();
let store = ide_db::secrets::SecretStore::new(f._tmp.path().join("data/db-passwords.json"), &f.root);
assert_eq!(store.get(&source.id).as_deref(), Some("never-on-disk"));
let file = f.root.join(".openidea/data-sources.toml");
assert!(!std::fs::read_to_string(&file).unwrap().contains("never-on-disk"));
for command in ["remove", "connect"] {
assert!(f.run(command, Some("foreign")).is_err());
}
assert!(f.events.lock().unwrap().iter().any(|(w, e)| w == "second" && matches!(e, IdeEvent::DbSourcesChanged)));
f.plugins.set_enabled(ID, false).unwrap();
assert!(file.exists());
f.plugins.set_enabled(ID, true).unwrap();
assert!(f.host.project("main").unwrap().db.plugin_source(ID, "local").is_ok());
f.host.set_mcp_executable(Some(PathBuf::from("/app/openidea")));
let command: serde_json::Value = serde_json::from_str(&f.run("stdio", None).unwrap().unwrap()).unwrap();
assert_eq!(command[1], "--mcp-stdio");
f.host.set_mcp_executable(None);
assert_eq!(f.run("stdio", None).unwrap().as_deref(), Some("null"));
// Closed project cleanup uses the host-owned journal, not only current windows.
f.host.close_project("main");
f.host.close_project("second");
f.plugins.uninstall(ID).unwrap();
assert!(ide_db::source::load(&f.root).unwrap().is_empty());
assert!(store.get(&source.id).is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn database_connect_asks_only_the_invoking_window_and_uses_normal_connection_flow() {
let f = Harness::new();
f.host.set_project_trust(&f.root, true, false).await.unwrap();
f.run("upsert", Some(&f.source())).unwrap();
let (plugins, invocation) = (f.plugins.clone(), f.invocation());
let run = tokio::task::spawn_blocking(move || plugins.run_command(ID, "connect", None, invocation));
let (window, request, source) = tokio::time::timeout(Duration::from_secs(5), async {
loop {
let found = f.requests.lock().unwrap().iter().find_map(|(w, e)| match e {
PluginEvent::WindowRequest { request_id, request: WindowRequest::DatabaseConnect { id }, .. } => {
Some((w.clone(), request_id.clone(), id.clone()))
}
_ => None,
});
if let Some(v) = found {
break v;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(window, "main");
assert!(!f.plugins.answer_command("second", &request, ide_host::plugins::CommandAnswer::Value(None)));
tokio::time::sleep(Duration::from_millis(350)).await; // Password entry can outlive the 250 ms command budget.
ops::db::db_connect(&f.host, "main", source.to_string()).await.unwrap();
f.plugins.answer_command("main", &request, ide_host::plugins::CommandAnswer::Value(None));
run.await.unwrap().unwrap();
assert!(!f.host.project("main").unwrap().db.connected().is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn mcp_listing_dispatch_confirmation_and_lifecycle_use_plugin_authority() {
let f = Harness::new();
let registry = Arc::new(Registry::new(f.host.clone()));
assert!(!registry.tools(&f.root).unwrap().iter().any(|t| t.name == "test_data_tools__write"));
assert!(registry.call(&f.root, "test_data_tools__write", "{}", CancellationToken::new()).is_err());
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let tools = registry.tools(&f.root).unwrap();
let name = "test_data_tools__echo";
assert!(tools.iter().any(|t| t.name == name && t.description.contains(ID)));
assert!(matches!(
registry.call(&f.root, name, r#"{"text":12}"#, CancellationToken::new()),
Err(ToolCallError::Failed(_))
));
let result = registry.call(&f.root, name, r#"{"text":"hello"}"#, CancellationToken::new()).unwrap();
assert!(result.contains("hello"));
let denied = registry.call(&f.root, "test_data_tools__denied", "{}", CancellationToken::new()).unwrap_err();
assert!(format!("{denied:?}").contains("process:sh"));
f.host.mcp_requests.set_ready("main", true);
let (r, root) = (registry.clone(), f.root.clone());
let call =
tokio::task::spawn_blocking(move || r.call(&root, "test_data_tools__erase", "{}", CancellationToken::new()));
let request = tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let Some(id) = f.events.lock().unwrap().iter().find_map(|(_, e)| match e {
IdeEvent::McpRequest { id, request: McpUiRequest::Confirm { .. } } => Some(*id),
_ => None,
}) {
break id;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert!(f.host.mcp_requests.answer("second", request, true, None).is_err());
f.host.mcp_requests.answer("main", request, false, None).unwrap();
assert!(call.await.unwrap().is_err());
f.plugins.set_enabled(ID, false).unwrap();
assert!(!registry.tools(&f.root).unwrap().iter().any(|t| t.name == name));
assert!(registry.call(&f.root, name, "{}", CancellationToken::new()).is_err());
f.plugins.set_enabled(ID, true).unwrap();
assert!(registry.tools(&f.root).unwrap().iter().any(|t| t.name == name));
let (r, root) = (registry.clone(), f.root.clone());
let spin =
tokio::task::spawn_blocking(move || r.call(&root, "test_data_tools__spin", "{}", CancellationToken::new()));
assert!(spin.await.unwrap().is_err(), "command budget interrupts wasm");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_destructive_plugin_tool_of_a_background_project_asks_in_a_project_window() {
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let inventory = f.serve_inventory();
f.host.trust.decide(&inventory, true, false).unwrap();
f.host.mcp_requests.set_ready("main", true);
let (registry, root) = (Registry::new(f.host.clone()), inventory.clone());
let call = tokio::task::spawn_blocking(move || {
registry.call(&root, "test_data_tools__erase", "{}", CancellationToken::new())
});
let (window, id, background) = tokio::time::timeout(Duration::from_secs(5), async {
loop {
if let Some(found) = f.events.lock().unwrap().iter().find_map(|(w, e)| match e {
IdeEvent::McpRequest { id, request: McpUiRequest::Confirm { background, .. } } => {
Some((w.clone(), *id, *background))
}
_ => None,
}) {
break found;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!((window.as_str(), background), ("main", true));
f.host.mcp_requests.answer("main", id, false, None).unwrap();
let denied = call.await.unwrap().unwrap_err();
assert!(format!("{denied:?}").contains("denied by the user"), "{denied:?}");
f.host.close_project(&ide_host::mcp::BackgroundProjects::key(&inventory));
}
#[tokio::test(flavor = "multi_thread")]
async fn plugin_tools_take_the_project_path_and_refuse_an_untrusted_project_before_it_loads() {
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let inventory = f.serve_inventory();
let registry = Registry::new(f.host.clone());
// A connection without a project of its own lists the tool with `projectPath`, which its
// calls have to pass, and the plugin's strict schema still takes the call.
let listed = registry.tools_without_project();
let echo = listed.iter().find(|t| t.name == "test_data_tools__echo").unwrap();
assert!(echo.input_schema["properties"]["projectPath"].is_object(), "{}", echo.input_schema);
let arguments = serde_json::json!({ "text": "hello", "projectPath": f.root }).to_string();
let result = registry.call(&f.root, "test_data_tools__echo", &arguments, CancellationToken::new()).unwrap();
assert!(result.contains("hello"), "{result}");
// A tool that writes refuses the untrusted folder, and nothing loads.
let refused = registry.call(&inventory, "test_data_tools__write", "{}", CancellationToken::new()).unwrap_err();
let restricted = "Project is in Restricted Mode. Trust the project to enable execution.";
assert_eq!(refused, ToolCallError::Failed(restricted.into()));
assert!(f.host.mcp_background.snapshot(&f.host, std::time::Instant::now()).is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_plugin_tool_call_holds_its_background_project_until_it_ends() {
use ide_host::mcp::{BackgroundProjects, McpBackgroundHold};
// The fixture's `spin` runs until it is cancelled or its budget ends.
let f = Harness::with_timeout(Duration::from_secs(10));
let inventory = f.serve_inventory();
let held_by = || {
let loaded = f.host.mcp_background.snapshot(&f.host, std::time::Instant::now());
loaded.into_iter().next().map(|project| project.kept_open_by)
};
let (registry, root, cancel) = (Registry::new(f.host.clone()), inventory.clone(), CancellationToken::new());
let stop = cancel.clone();
let call = tokio::task::spawn_blocking(move || registry.call(&root, "test_data_tools__spin", "{}", cancel));
tokio::time::timeout(Duration::from_secs(10), async {
while held_by() != Some(Some(McpBackgroundHold::Request)) {
tokio::task::yield_now().await;
}
})
.await
.expect("the call holds the project while the plugin runs");
stop.cancel();
assert!(call.await.unwrap().is_err());
assert_eq!(held_by(), Some(None), "the project stays loaded with nothing holding it");
f.host.close_project(&BackgroundProjects::key(&inventory));
}
#[tokio::test(flavor = "multi_thread")]
async fn database_imports_are_denied_without_the_optional_grant() {
let f = Harness::new();
f.host.set_project_trust(&f.root, true, false).await.unwrap();
f.plugins.set_capability(ID, "database.sources", false).unwrap();
for command in ["upsert", "remove", "sources", "credential", "connect"] {
let err = f.run(command, Some(&f.source())).unwrap_err();
assert!(err.message.contains("database.sources"), "{command}: {err}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn official_api_examples_install_and_render_real_component_contributions() {
// The real examples' first calls compile and scan; 250 ms is too tight on Windows runners.
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let official = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../plugins/official");
for name in ["blame-annotations", "todo-finder"] {
f.plugins.install_from_dir(&official.join(name), &Consent::all()).unwrap();
}
std::fs::write(f.root.join("notes.txt"), "TODO example\n").unwrap();
let doc = ide_plugin::ProviderDocument {
path: f.root.join("notes.txt"),
language: "text".into(),
version: 1,
text: "TODO example\n".into(),
};
assert!(eventually(|| {
f.plugins
.language_code_lenses(&doc)
.iter()
.any(|(owner, lens)| owner == "openidea.blame-annotations" && lens.command == "annotate")
}));
f.plugins.run_command("openidea.todo-finder", "find", None, f.invocation()).unwrap();
let view = f.plugins.render_view("openidea.todo-finder", "todos", None, f.invocation()).unwrap();
let ide_plugin::ViewBody::List(items) = view.body else { panic!("expected TODO list") };
assert_eq!(items.len(), 1);
assert!(items[0].label.contains("TODO example"));
#[cfg(unix)]
{
let path = std::env::join_paths([official.join("container-runner"), official.join("test-runner")]).unwrap();
f.plugins.set_program_path(Arc::new(move || Some(path.clone())));
for name in ["container-runner", "test-runner"] {
f.plugins.install_from_dir(&official.join(name), &Consent::all()).unwrap();
}
std::fs::write(f.root.join("example.tests"), "test adds\n").unwrap();
let doc =
ide_plugin::ProviderDocument { path: f.root.join("example.tests"), text: "test adds\n".into(), ..doc };
assert!(eventually(|| {
f.plugins
.language_gutter_actions(&doc, Some(&f.root))
.iter()
.any(|(owner, action)| owner == "openidea.test-runner" && action.argument.as_deref() == Some("adds"))
}));
f.plugins.refresh_run_configurations(&f.root);
let configs = f.plugins.run_detection().detect(&f.root);
assert!(configs.iter().any(|c| c.id == "plugin:openidea.test-runner:tests"));
}
}
/// Editor-path calls drop a result that misses their budget, as the first call into a cold
/// component can on a slow machine: ask again until it arrives.
fn eventually(mut ready: impl FnMut() -> bool) -> bool {
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while std::time::Instant::now() < deadline {
if ready() {
return true;
}
std::thread::sleep(std::time::Duration::from_millis(100));
}
false
}
#[tokio::test(flavor = "multi_thread")]
async fn schema_reads_user_tables_without_rows_or_credentials_and_enforces_grants() {
let f = Harness::with_timeout(Duration::from_secs(10));
let table =
serde_json::json!({"sourceId":"user-source","catalog":null,"schema":"main","table":"users"}).to_string();
assert!(f.run("table-schema", Some(&table)).is_err(), "untrusted projects are refused");
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let db = f.host.project("main").unwrap().db.clone();
db.save_sources(vec![ide_db::DataSource {
id: "user-source".into(),
name: "User-owned SQLite".into(),
driver: ide_db::DbDriver::Sqlite,
file: Some(f.root.join("db.sqlite").into()),
..Default::default()
}])
.await
.unwrap();
assert!(f.run("table-schema", Some(&table)).is_err(), "inspection never connects implicitly");
assert!(!db.is_connected("user-source"));
let cancel = CancellationToken::new();
for sql in [
"CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT NOT NULL DEFAULT 'guest', manager_id INTEGER REFERENCES users(id))",
"CREATE INDEX users_name ON users(name)",
"INSERT INTO users(name) VALUES ('private-row-value')",
] {
db.execute("user-source", sql, 100, &cancel).await.unwrap();
}
assert!(!f.host.project("second").unwrap().db.is_connected("user-source"));
assert!(
f.plugins
.run_command(
ID,
"table-schema",
Some(&table),
Invocation { client: Some("second".into()), ..f.invocation() }
)
.is_err(),
"a disconnected window cannot borrow another window's connection"
);
let response = f.run("table-schema", Some(&table)).unwrap().unwrap();
let schema: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(schema["columns"][0]["name"], "id");
assert_eq!(schema["columns"][0]["primaryKey"], true);
assert_eq!(schema["columns"][1]["nullable"], false);
assert_eq!(schema["columns"][1]["defaultValue"], "'guest'");
assert!(schema["indexes"].as_array().unwrap().iter().any(|i| i["name"] == "users_name"));
assert!(schema["foreignKeys"].as_array().unwrap().iter().any(|k| k["referencedTable"] == "users"));
let menu_argument = serde_json::json!({ "tables": [{
"sourceId": "user-source", "catalog": null, "schema": "main", "table": "users",
"kind": "table", "driver": "sqlite",
}] })
.to_string();
assert_eq!(f.run("table-schema", Some(&menu_argument)).unwrap().unwrap(), response);
assert!(!response.contains("private-row-value"));
assert!(schema.get("password").is_none() && schema.get("url").is_none() && schema.get("host").is_none());
f.plugins.set_capability(ID, "database.schema", false).unwrap();
let denied = f.run("table-schema", Some(&table)).unwrap_err();
assert!(denied.message.contains("database.schema"));
assert!(db.is_connected("user-source"), "revoking inspection leaves user connections alone");
f.plugins.set_capability(ID, "database.schema", true).unwrap();
f.host.set_project_trust(&f.root, false, false).await.unwrap();
assert!(f.run("table-schema", Some(&table)).is_err());
db.disconnect("user-source").await;
assert!(db.connected_table_details("user-source", None, "main", "users").await.is_err());
assert!(!db.is_connected("user-source"), "schema reads cannot reconnect a disconnected source");
}
#[tokio::test(flavor = "multi_thread")]
async fn schema_discovery_and_query_execution_enforce_grants_trust_and_connection_isolation() {
let f = Harness::with_timeout(Duration::from_secs(10));
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let db = f.host.project("main").unwrap().db.clone();
db.save_sources(vec![ide_db::DataSource {
id: "user-source".into(),
name: "User SQLite".into(),
driver: ide_db::DbDriver::Sqlite,
file: Some(f.root.join("db.sqlite").into()),
..Default::default()
}])
.await
.unwrap();
// Disconnected sources are never listed or queried implicitly.
let initial_sources: Vec<serde_json::Value> =
serde_json::from_str(&f.run("connected-sources", None).unwrap().unwrap()).unwrap();
assert!(initial_sources.is_empty());
assert!(f.run("list-schemas", Some("user-source")).is_err());
assert!(!db.is_connected("user-source"));
let q_req = serde_json::json!({
"sourceId": "user-source",
"sql": "SELECT id, name FROM users ORDER BY id",
"maxRows": 1
})
.to_string();
assert!(f.run("execute-query", Some(&q_req)).is_err(), "query execution never connects implicitly");
assert!(!db.is_connected("user-source"));
let cancel = CancellationToken::new();
for sql in [
"CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
"INSERT INTO users(name) VALUES ('alice'), ('bob')",
] {
db.execute("user-source", sql, 100, &cancel).await.unwrap();
}
// Window isolation: second window has no connection of its own for discovery or queries.
let second_inv = Invocation { client: Some("second".into()), ..f.invocation() };
let second_sources: Vec<serde_json::Value> = serde_json::from_str(
&f.plugins.run_command(ID, "connected-sources", None, second_inv.clone()).unwrap().unwrap(),
)
.unwrap();
assert!(second_sources.is_empty(), "a disconnected window cannot see another window's connections");
assert!(f.plugins.run_command(ID, "list-schemas", Some("user-source"), second_inv.clone()).is_err());
assert!(
f.plugins
.run_command(ID, "list-tables", Some(r#"{"sourceId":"user-source","schema":"main"}"#), second_inv.clone())
.is_err()
);
assert!(f.plugins.run_command(ID, "execute-query", Some(&q_req), second_inv).is_err());
// Schema discovery returns only non-secret identity + schemas/tables (never credentials or row data).
let sources_json = f.run("connected-sources", None).unwrap().unwrap();
let sources: Vec<serde_json::Value> = serde_json::from_str(&sources_json).unwrap();
assert_eq!(sources.len(), 1);
assert_eq!(sources[0]["sourceId"], "user-source");
assert_eq!(sources[0]["driver"], "sqlite");
assert!(!sources_json.contains("password") && !sources_json.contains("alice"));
let schemas: Vec<String> =
serde_json::from_str(&f.run("list-schemas", Some("user-source")).unwrap().unwrap()).unwrap();
assert!(schemas.iter().any(|s| s == "main"));
let tables: Vec<serde_json::Value> = serde_json::from_str(
&f.run("list-tables", Some(r#"{"sourceId":"user-source","schema":"main"}"#)).unwrap().unwrap(),
)
.unwrap();
assert!(tables.iter().any(|t| t["name"] == "users" && t["kind"] == "table"));
// Query execution respects max_rows & has_more and returns rows.
let q_res: serde_json::Value =
serde_json::from_str(&f.run("execute-query", Some(&q_req)).unwrap().unwrap()).unwrap();
assert_eq!(q_res["rows"].as_array().unwrap().len(), 1);
assert_eq!(q_res["rows"][0][1], "alice");
assert_eq!(q_res["hasMore"], true);
// Large cells are capped at 8192 UTF-16 code units.
let wide_req = serde_json::json!({
"sourceId": "user-source",
"sql": "SELECT replace(hex(zeroblob(5000)), '0', 'a')",
})
.to_string();
let wide_res: serde_json::Value =
serde_json::from_str(&f.run("execute-query", Some(&wide_req)).unwrap().unwrap()).unwrap();
assert_eq!(wide_res["rows"][0][0].as_str().unwrap().encode_utf16().count(), 8192);
// Invalid inputs (empty SQL, NUL bytes) are rejected cleanly.
for bad in [
serde_json::json!({ "sourceId": "user-source", "sql": " " }),
serde_json::json!({ "sourceId": "user-source", "sql": "SELECT 1\0" }),
serde_json::json!({ "sourceId": "user\0source", "sql": "SELECT 1" }),
] {
assert!(f.run("execute-query", Some(&bad.to_string())).is_err(), "{bad}");
}
// DDL/DML affected count works under database.query.
let dml_req = serde_json::json!({
"sourceId": "user-source",
"sql": "UPDATE users SET name = 'charlie' WHERE id = 2",
})
.to_string();
let dml_res: serde_json::Value =
serde_json::from_str(&f.run("execute-query", Some(&dml_req)).unwrap().unwrap()).unwrap();
assert_eq!(dml_res["affected"], 1);
// Background calls (client: None) see sources connected in any window of the project.
db.disconnect("user-source").await;
let second_db = f.host.project("second").unwrap().db.clone();
second_db.execute("user-source", "SELECT 1", 1, &cancel).await.unwrap();
let bg_sources: Vec<serde_json::Value> = serde_json::from_str(
&f.plugins
.run_command(ID, "connected-sources", None, Invocation { client: None, ..f.invocation() })
.unwrap()
.unwrap(),
)
.unwrap();
assert_eq!(bg_sources.len(), 1);
assert_eq!(bg_sources[0]["sourceId"], "user-source");
second_db.disconnect("user-source").await;
// Read-only sources allow SELECT but refuse writes even with database.query granted.
db.save_sources(vec![ide_db::DataSource {
id: "ro-source".into(),
name: "Read-only SQLite".into(),
driver: ide_db::DbDriver::Sqlite,
file: Some(f.root.join("db.sqlite").into()),
read_only: true,
..Default::default()
}])
.await
.unwrap();
db.execute("ro-source", "SELECT 1", 1, &cancel).await.unwrap();
let ro_select = serde_json::json!({ "sourceId": "ro-source", "sql": "SELECT count(*) FROM users" }).to_string();
let ro_update =
serde_json::json!({ "sourceId": "ro-source", "sql": "UPDATE users SET name = 'blocked'" }).to_string();
assert!(f.run("execute-query", Some(&ro_select)).is_ok());
assert!(f.run("execute-query", Some(&ro_update)).is_err(), "read-only sources must reject writes");
// Revoking `database.query` blocks queries while leaving `database.schema` discovery intact.
f.plugins.set_capability(ID, "database.query", false).unwrap();
let err = f.run("execute-query", Some(&ro_select)).unwrap_err();
assert!(err.message.contains("database.query"));
assert!(f.run("connected-sources", None).is_ok());
// Revoking project trust blocks both.
f.plugins.set_capability(ID, "database.query", true).unwrap();
f.host.set_project_trust(&f.root, false, false).await.unwrap();
assert!(f.run("connected-sources", None).is_err());
assert!(f.run("execute-query", Some(&ro_select)).is_err());
}