25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(dynamodb): support native PartiQL queries
CSXFanMengba8eab2cb09c
diff --git a/Cargo.lock b/Cargo.lockindex c6f7f78921..0ba5ebfd99 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2496,6 +2496,7 @@ name = "dbx-drivers"version = "0.1.0"dependencies = ["aws-sdk-dynamodb",+ "axum","base64 0.22.1","bytes","chrono",diff --git a/apps/desktop/src/components/editor/__tests__/QueryEditorPrefetch.integration.spec.ts b/apps/desktop/src/components/editor/__tests__/QueryEditorPrefetch.integration.spec.tsnew file mode 100644index 0000000000..dcbaae1a74--- /dev/null+++ b/apps/desktop/src/components/editor/__tests__/QueryEditorPrefetch.integration.spec.ts@@ -0,0 +1,52 @@+// @vitest-environment happy-dom+import { createApp, h, nextTick, reactive } from "vue";+import { createPinia, setActivePinia } from "pinia";+import { createI18n } from "vue-i18n";+import { EditorView } from "@codemirror/view";+import { afterEach, describe, expect, it, vi } from "vitest";+import QueryEditor from "../QueryEditor.vue";+import { useSettingsStore } from "@/stores/settingsStore";+import { useConnectionStore } from "@/stores/connectionStore";+import type { QueryEditorProps } from "../queryEditorTypes";++const cleanups: Array<() => void> = [];+afterEach(() => {+ for (const cleanup of cleanups.splice(0).reverse()) cleanup();+ vi.restoreAllMocks();+});++describe("QueryEditor completion prefetch integration", () => {+ it.each(["enabled", "disabled", "offline"] as const)("keeps the actual editor usable with %s prefetch", async (mode) => {+ const pinia = createPinia();+ setActivePinia(pinia);+ useSettingsStore().editorSettings.showExecutionTargetPicker = false;+ const store = useConnectionStore();+ const fetch = vi.spyOn(store, "listCompletionTables").mockResolvedValue([]);+ if (mode === "offline") fetch.mockRejectedValue(new Error("offline"));+ const props = reactive<QueryEditorProps>({ modelValue: "SELECT 1;", connectionId: "prefetch-test", database: "first", databaseType: "mysql", dialect: "mysql", tabId: "prefetch-test", prefetchCompletion: mode !== "disabled", autoFocus: false, hideExecutionControls: true });+ const host = document.createElement("div");+ document.body.append(host);+ const app = createApp({ render: () => h(QueryEditor, { ...props, "onUpdate:modelValue": (value: string) => (props.modelValue = value) }) });+ app.use(pinia);+ app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));+ cleanups.push(() => {+ app.unmount();+ host.remove();+ });+ app.mount(host);+ await vi.waitFor(() => expect(host.querySelector(".cm-editor")).not.toBeNull(), { timeout: 5000 });+ const view = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;+ expect(view.state.doc.toString()).toBe("SELECT 1;");+ if (mode === "disabled") {+ expect(fetch).not.toHaveBeenCalled();+ } else {+ expect(fetch).toHaveBeenCalledWith("prefetch-test", "first", "", expect.any(Number), undefined, false, undefined, undefined, { activateConnection: false });+ props.database = "second";+ await nextTick();+ expect(fetch).toHaveBeenCalledWith("prefetch-test", "second", "", expect.any(Number), undefined, false, undefined, undefined, { activateConnection: false });+ }+ view.dispatch({ changes: { from: view.state.doc.length, insert: " -- editable" } });+ await nextTick();+ expect(props.modelValue).toBe("SELECT 1; -- editable");+ });+});diff --git a/apps/desktop/src/lib/__tests__/database/databaseFeatureSupport.spec.ts b/apps/desktop/src/lib/__tests__/database/databaseFeatureSupport.spec.tsindex 63562a8647..cfff383373 100644--- a/apps/desktop/src/lib/__tests__/database/databaseFeatureSupport.spec.ts+++ b/apps/desktop/src/lib/__tests__/database/databaseFeatureSupport.spec.ts@@ -139,6 +139,11 @@ describe("connection query actions", () => {});describe("message queue query capabilities", () => {+ it("advertises DynamoDB PartiQL execution and query entry points", () => {+ expect(supportsQueryExecution("dynamodb")).toBe(true);+ expect(supportsConnectionQueryActions("dynamodb")).toBe(true);+ expect(supportsTransaction("dynamodb")).toBe(false);+ });it("does not advertise query execution for broker surfaces", () => {expect(supportsQueryExecution("mq")).toBe(false);expect(supportsQueryExecution("mqtt")).toBe(false);diff --git a/apps/desktop/src/lib/__tests__/sql/sqlRisk.dynamodb.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlRisk.dynamodb.spec.tsindex 17ca66dec2..2b16a65ca8 100644--- a/apps/desktop/src/lib/__tests__/sql/sqlRisk.dynamodb.spec.ts+++ b/apps/desktop/src/lib/__tests__/sql/sqlRisk.dynamodb.spec.ts@@ -2,6 +2,14 @@ import { describe, expect, it } from "vitest";import { classifySqlRisk } from "@/lib/sql/sqlRisk";describe("DynamoDB statement risk", () => {+ it("classifies PartiQL reads and mutations without relaxing existing guards", () => {+ expect(classifySqlRisk('SELECT * FROM "items" WHERE "status"=\'PENDING\'', { dialect: "dynamodb" }).risk).toBe("read");+ expect(classifySqlRisk("-- comment\nSELECT 'UPDATE' FROM \"items\"", { dialect: "dynamodb" }).risk).toBe("read");+ for (const sql of ["INSERT INTO \"items\" VALUE {'pk':'x'}", "UPDATE \"items\" SET flag=true WHERE pk='x'", "DELETE FROM \"items\" WHERE pk='x'"]) {+ expect(classifySqlRisk(sql, { dialect: "dynamodb" }).risk).toBe("write");+ }+ expect(classifySqlRisk('SELECT * FROM "items"; DELETE FROM "items" WHERE pk=\'x\'', { dialect: "dynamodb" }).risk).not.toBe("read");+ });it("treats generated scan statements as reads", () => {expect(classifySqlRisk('DBX DYNAMODB SCAN\ntable: "orders"\nlimit: 1000', { dialect: "dynamodb" }).risk).toBe("read");expect(classifySqlRisk('DBX DYNAMODB QUERY / SCAN\ntable: "orders"\nfilter:\n{"status":"SHIPPED"}', { dialect: "dynamodb" }).risk).toBe("read");diff --git a/crates/dbx-core/assets/database-drivers.manifest.json b/crates/dbx-core/assets/database-drivers.manifest.jsonindex 7e47bc6a21..f7f993ff45 100644--- a/crates/dbx-core/assets/database-drivers.manifest.json+++ b/crates/dbx-core/assets/database-drivers.manifest.json@@ -457,7 +457,7 @@"defaultPort": 8000,"supportLevel": "operate","capabilities": {- "queryExecution": false,+ "queryExecution": true,"metadataBrowse": true,"objectBrowser": false,"objectSource": false,diff --git a/crates/dbx-drivers/Cargo.toml b/crates/dbx-drivers/Cargo.tomlindex 8376f432bc..713c26d8cb 100644--- a/crates/dbx-drivers/Cargo.toml+++ b/crates/dbx-drivers/Cargo.toml@@ -79,6 +79,7 @@ tempfile = "3"windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem", "Win32_Foundation", "Win32_Security"] }[dev-dependencies]+axum = "0.8"dbx-driver-support = { path = "../dbx-driver-support", features = ["test-support"] }dbx-platform = { path = "../dbx-platform", features = ["test-support"] }mysql_common = { git = "https://github.com/t8y2/rust_mysql_common.git", rev = "47740d85a8277167a5717afac785d37b46a36296", default-features = false }diff --git a/crates/dbx-drivers/src/db/dynamodb_driver.rs b/crates/dbx-drivers/src/db/dynamodb_driver.rsindex b42a16e250..9fce6f953b 100644--- a/crates/dbx-drivers/src/db/dynamodb_driver.rs+++ b/crates/dbx-drivers/src/db/dynamodb_driver.rs@@ -1,4 +1,4 @@-use std::collections::{BTreeSet, HashMap};+use std::collections::{BTreeSet, HashMap, HashSet};use std::sync::Arc;use std::time::{Duration, Instant};@@ -348,6 +348,13 @@ pub async fn test_connection(client: &DynamoDbClient, timeout: Duration) -> Resupub async fn execute_statement(client: &DynamoDbClient, source: &str, max_rows: usize) -> Result<QueryResult, String> {let started = Instant::now();+ let header = source.lines().find(|line| !line.trim().is_empty()).unwrap_or_default().trim();+ if !header.to_ascii_uppercase().starts_with("DBX DYNAMODB") {+ // Do not expose the SDK pagination future's layout depth to public async callers.+ let execution: futures::future::BoxFuture<'_, Result<QueryResult, String>> =+ Box::pin(execute_partiql(client, source, max_rows, started));+ return execution.await;+ }let statement = parse_dynamodb_statement(source)?;match statement.operation {DynamoDbStatementOperation::Read => {@@ -393,6 +400,76 @@ pub async fn execute_statement(client: &DynamoDbClient, source: &str, max_rows:}}+fn partiql_is_read(source: &str) -> Result<bool, String> {+ use sqlparser::dialect::GenericDialect;+ use sqlparser::keywords::Keyword;+ use sqlparser::tokenizer::{Token, Tokenizer};+ let tokens = Tokenizer::new(&GenericDialect {}, source).tokenize().map_err(|error| error.to_string())?;+ match tokens.into_iter().find(|token| !matches!(token, Token::Whitespace(_))) {+ Some(Token::Word(word)) => match word.keyword {+ Keyword::SELECT => Ok(true),+ Keyword::INSERT | Keyword::UPDATE | Keyword::DELETE => Ok(false),+ _ => Err("DynamoDB PartiQL supports SELECT, INSERT, UPDATE, and DELETE statements".to_string()),+ },+ None => Err("DynamoDB statement is empty".to_string()),+ _ => Err("DynamoDB PartiQL must start with SELECT, INSERT, UPDATE, or DELETE".to_string()),+ }+}++async fn execute_partiql(+ client: &DynamoDbClient,+ source: &str,+ max_rows: usize,+ started: Instant,+) -> Result<QueryResult, String> {+ let read = partiql_is_read(source)?;+ let limit = max_rows.max(1);+ let mut documents = Vec::new();+ let mut next_token = None;+ let mut seen_tokens = HashSet::new();+ // Bound scans even when a selective WHERE keeps returning empty pages.+ for page in 0..1000 {+ let mut request = client.client.execute_statement().statement(source).set_next_token(next_token.take());+ if read {+ request = request.limit((limit - documents.len()).min(MAX_PAGE_SIZE as usize) as i32);+ }+ let output = request.send().await.map_err(|error| dynamodb_sdk_error!("DynamoDB PartiQL failed", error))?;+ let omitted_items = output.items().len() > limit - documents.len();+ for item in output.items() {+ if documents.len() == limit {+ break;+ }+ documents.push(Value::Object(attribute_map_to_json(item)?));+ }+ next_token = output.next_token().filter(|token| !token.is_empty()).map(str::to_string);+ let truncated =+ omitted_items || next_token.is_some() || output.last_evaluated_key().is_some_and(|key| !key.is_empty());+ if !read || !truncated || next_token.is_none() || documents.len() >= limit || page == 999 {+ let mut result = documents_query_result(documents, truncated, started);+ if !read {+ result.affected_rows = 1;+ }+ if truncated {+ result.messages.push(crate::types::QueryMessage {+ severity: "WARNING".to_string(),+ message: "DynamoDB PartiQL result is incomplete: row, page, or service pagination limit reached."+ .to_string(),+ code: Some("DYNAMODB_PARTIQL_TRUNCATED".to_string()),+ detail: None,+ hint: Some(+ "Increase the result row limit or use a more selective partition-key condition.".to_string(),+ ),+ });+ }+ return Ok(result);+ }+ if !seen_tokens.insert(next_token.clone().unwrap()) {+ return Err("DynamoDB PartiQL returned a repeated pagination token".to_string());+ }+ }+ unreachable!("the final page returns an explicitly truncated result")+}+fn parse_dynamodb_statement(source: &str) -> Result<DynamoDbStatement, String> {let mut lines = source.lines();let header = lines@@ -535,8 +612,10 @@ fn take_dynamodb_object_field(fields: &mut HashMap<String, String>, name: &str)}fn document_query_result(result: DocumentQueryResult, started: Instant) -> QueryResult {- let truncated = result.next_cursor.is_some();- let documents = result.documents;+ documents_query_result(result.documents, result.next_cursor.is_some(), started)+}++fn documents_query_result(documents: Vec<Value>, truncated: bool, started: Instant) -> QueryResult {let mut column_names = BTreeSet::new();for document in &documents {if let Some(object) = document.as_object() {@@ -556,7 +635,7 @@ fn document_query_result(result: DocumentQueryResult, started: Instant) -> Query.as_object().and_then(|object| object.get(column)).cloned()- .or_else(|| (column == "value").then(|| document.clone()))+ .or_else(|| (!document.is_object() && column == "value").then(|| document.clone())).unwrap_or(Value::Null)}).collect()@@ -1570,6 +1649,248 @@ fn tagged_json_to_attribute_map(value: &Value) -> Result<HashMap<String, Attribumod tests {use super::*;+ async fn partiql_test_server(+ pages: Vec<Value>,+ ) -> (DynamoDbClient, Arc<tokio::sync::Mutex<Vec<Value>>>, tokio::task::JoinHandle<()>) {+ use axum::{routing::post, Json, Router};+ use std::collections::VecDeque;+ let requests = Arc::new(tokio::sync::Mutex::new(Vec::new()));+ let recorded = requests.clone();+ let pages = Arc::new(tokio::sync::Mutex::new(VecDeque::from(pages)));+ let router = Router::new().route(+ "/",+ post(move |body: axum::body::Bytes| {+ let recorded = recorded.clone();+ let pages = pages.clone();+ async move {+ recorded.lock().await.push(serde_json::from_slice(&body).unwrap());+ (+ [(axum::http::header::CONTENT_TYPE, "application/x-amz-json-1.0")],+ Json(pages.lock().await.pop_front().expect("unexpected SDK request")),+ )+ }+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({"id":"partiql-test","name":"PartiQL test","db_type":"dynamodb","host":"127.0.0.1","port":address.port(),"username":"dummy","password":"dummy","database":"us-east-1"})).unwrap();+ let client = connect(&config, "127.0.0.1", address.port()).unwrap();+ let server = tokio::spawn(async move {+ axum::serve(listener, router).await.unwrap();+ });+ (client, requests, server)+ }++ #[tokio::test]+ async fn partiql_paginates_past_empty_filtered_pages_using_native_sdk_tokens() {+ let (client, requests, server) = partiql_test_server(vec![+ serde_json::json!({"Items":[],"NextToken":"second"}),+ serde_json::json!({"Items":[{"pk":{"S":"one"}}],"NextToken":"third"}),+ serde_json::json!({"Items":[{"pk":{"S":"two"}}]}),+ ])+ .await;+ let result = execute_statement(&client, "SELECT * FROM \"items\" WHERE flag=true", 3).await.unwrap();+ assert_eq!(result.rows, [vec![Value::String("one".into())], vec![Value::String("two".into())]]);+ assert!(!result.truncated);+ let requests = requests.lock().await;+ assert_eq!(requests.len(), 3);+ assert_eq!(requests[0]["Limit"], 3);+ assert_eq!(requests[1]["NextToken"], "second");+ assert_eq!(requests[2]["NextToken"], "third");+ assert_eq!(requests[2]["Limit"], 2);+ server.abort();+ }++ #[tokio::test]+ async fn partiql_marks_unresumable_or_capped_pages_incomplete_and_does_not_retry_writes() {+ for page in [+ serde_json::json!({"Items":[{"pk":{"S":"one"}}],"NextToken":"more"}),+ serde_json::json!({"Items":[{"pk":{"S":"one"}}],"LastEvaluatedKey":{"pk":{"S":"one"}}}),+ ] {+ let (client, requests, server) = partiql_test_server(vec![page]).await;+ let result = execute_statement(&client, "SELECT * FROM \"items\"", 1).await.unwrap();+ assert!(result.truncated);+ assert_eq!(result.rows.len(), 1);+ assert_eq!(result.messages[0].code.as_deref(), Some("DYNAMODB_PARTIQL_TRUNCATED"));+ assert_eq!(requests.lock().await.len(), 1);+ server.abort();+ }+ let (client, requests, server) = partiql_test_server(vec![serde_json::json!({})]).await;+ let result = execute_statement(&client, "INSERT INTO \"items\" VALUE {'pk':'new'}", 100).await.unwrap();+ assert_eq!(result.affected_rows, 1);+ let requests = requests.lock().await;+ assert_eq!(requests.len(), 1);+ assert!(requests[0].get("Limit").is_none());+ assert!(requests[0].get("NextToken").is_none());+ server.abort();+ }++ #[tokio::test]+ async fn partiql_rejects_repeated_continuation_tokens_instead_of_looping() {+ let (client, requests, server) =+ partiql_test_server(vec![serde_json::json!({"NextToken":"same"}), serde_json::json!({"NextToken":"same"})])+ .await;+ assert!(execute_statement(&client, "SELECT * FROM \"items\"", 100)+ .await+ .unwrap_err()+ .contains("repeated pagination token"));+ assert_eq!(requests.lock().await.len(), 2);+ server.abort();+ }++ #[test]+ fn partiql_recognizes_operations_without_treating_literals_or_comments_as_keywords() {+ assert!(partiql_is_read("-- UPDATE is only a comment\nSELECT \"name\" FROM \"items\"").unwrap());+ assert!(partiql_is_read("/* comment */ SELECT 'DELETE' FROM \"items\"").unwrap());+ for sql in [+ "INSERT INTO \"items\" VALUE {'pk':'new'}",+ "UPDATE \"items\" SET flag=true WHERE pk='x'",+ "DELETE FROM \"items\" WHERE pk='x'",+ ] {+ assert!(!partiql_is_read(sql).unwrap());+ }+ for sql in ["", "-- comment only", "DROP TABLE items", "EXEC arbitrary", "'SELECT'", "SELECT 'unclosed"] {+ assert!(partiql_is_read(sql).is_err(), "{sql}");+ }+ }++ #[test]+ fn partiql_projection_preserves_types_missing_fields_and_truncation() {+ let binary = attribute_value_to_json(&AttributeValue::B(Blob::new(vec![0, 255]))).unwrap();+ let number = attribute_value_to_json(&AttributeValue::N("12345678901234567890".into())).unwrap();+ let result = documents_query_result(+ vec![serde_json::json!({"value": binary, "number": number}), serde_json::json!({"flag": true})],+ true,+ Instant::now(),+ );+ assert_eq!(result.columns, ["flag", "number", "value"]);+ assert!(result.truncated);+ assert_eq!(result.rows[0][0], Value::Null);+ assert_eq!(result.rows[1][0], true);+ assert_eq!(result.rows[1][2], Value::Null);+ assert_eq!(result.rows[0][1], dynamodb_extended_json("number", Value::String("12345678901234567890".into())));+ assert!(!result.columns.iter().any(|column| column == "_id"));+ }++ #[tokio::test]+ #[ignore = "requires an isolated DynamoDB Local endpoint in DBX_DYNAMODB_ENDPOINT"]+ async fn live_executes_partiql_with_pagination_projection_and_singleton_writes() {+ use aws_sdk_dynamodb::types::{AttributeDefinition, BillingMode, ScalarAttributeType};+ let endpoint = std::env::var("DBX_DYNAMODB_ENDPOINT").expect("DBX_DYNAMODB_ENDPOINT is required");+ let address = endpoint+ .strip_prefix("http://127.0.0.1:")+ .expect("this write test only runs against loopback DynamoDB Local");+ let config: ConnectionConfig = serde_json::from_value(serde_json::json!({"id":"partiql-live","name":"PartiQL live","db_type":"dynamodb","host":"127.0.0.1","port":address.parse::<u16>().unwrap(),"username":"dummy","password":"dummy","database":"us-east-1"})).unwrap();+ let client = connect(&config, "127.0.0.1", config.port).unwrap();+ let table = format!("dbx_partiql_{}", uuid::Uuid::new_v4().simple());+ client+ .client+ .create_table()+ .table_name(&table)+ .billing_mode(BillingMode::PayPerRequest)+ .attribute_definitions(+ AttributeDefinition::builder()+ .attribute_name("pk")+ .attribute_type(ScalarAttributeType::S)+ .build()+ .unwrap(),+ )+ .key_schema(KeySchemaElement::builder().attribute_name("pk").key_type(KeyType::Hash).build().unwrap())+ .send()+ .await+ .unwrap();+ let outcome: Result<(), String> = async {+ for index in 0..30 {+ client+ .client+ .put_item()+ .table_name(&table)+ .item("pk", AttributeValue::S(format!("key-{index:02}")))+ .item("status", AttributeValue::S("PENDING".into()))+ .item("payload", AttributeValue::S("x".repeat(100000)))+ .item("large", AttributeValue::N("12345678901234567890".into()))+ .item("binary", AttributeValue::B(Blob::new(vec![0, 255])))+ .send()+ .await+ .map_err(|error| error.to_string())?;+ }+ // More than 1 MiB forces service-side pagination independently of the UI row cap.+ let all = execute_statement(&client, &format!("SELECT * FROM \"{table}\""), 100).await?;+ assert_eq!(all.rows.len(), 30);+ assert!(!all.truncated);+ assert!(!all.columns.iter().any(|column| column == "_id"));+ let large = all.columns.iter().position(|column| column == "large").unwrap();+ assert_eq!(+ all.rows[0][large],+ dynamodb_extended_json("number", Value::String("12345678901234567890".into()))+ );+ let pk = all.columns.iter().position(|column| column == "pk").unwrap();+ let last_key = all.rows.last().unwrap()[pk].as_str().unwrap().to_string();+ client+ .client+ .update_item()+ .table_name(&table)+ .key("pk", AttributeValue::S(last_key))+ .update_expression("SET #s = :s")+ .expression_attribute_names("#s", "status")+ .expression_attribute_values(":s", AttributeValue::S("RARE".into()))+ .send()+ .await+ .map_err(|error| error.to_string())?;+ let filtered =+ execute_statement(&client, &format!("SELECT * FROM \"{table}\" WHERE \"status\"='RARE'"), 100).await?;+ assert_eq!(filtered.rows.len(), 1);+ assert!(!filtered.truncated);+ let limited = execute_statement(&client, &format!("SELECT * FROM \"{table}\""), 15).await?;+ assert_eq!(limited.rows.len(), 15);+ assert!(limited.truncated);+ assert!(!limited.messages.is_empty());+ let projection = execute_statement(&client, &format!("SELECT \"status\" FROM \"{table}\""), 100).await?;+ assert_eq!(projection.columns, ["status"]);+ assert_eq!(projection.rows.len(), 30);+ let insert = execute_statement(+ &client,+ &format!("INSERT INTO \"{table}\" VALUE {{'pk':'partiql-write','status':'NEW'}}"),+ 100,+ )+ .await?;+ assert_eq!(insert.affected_rows, 1);+ execute_statement(+ &client,+ &format!("UPDATE \"{table}\" SET \"status\"='UPDATED' WHERE \"pk\"='partiql-write'"),+ 100,+ )+ .await?;+ let updated = execute_statement(+ &client,+ &format!("SELECT \"status\" FROM \"{table}\" WHERE \"pk\"='partiql-write'"),+ 100,+ )+ .await?;+ assert_eq!(updated.rows, [vec![Value::String("UPDATED".into())]]);+ execute_statement(&client, &format!("DELETE FROM \"{table}\" WHERE \"pk\"='partiql-write'"), 100).await?;+ assert!(execute_statement(+ &client,+ &format!("SELECT * FROM \"{table}\" WHERE \"pk\"='partiql-write'"),+ 100+ )+ .await?+ .rows+ .is_empty());+ let legacy =+ execute_statement(&client, &format!("DBX DYNAMODB SCAN\ntable: \"{table}\"\nlimit: 1"), 100).await?;+ assert_eq!(legacy.rows.len(), 1);+ assert!(execute_statement(&client, &format!("SELECT * FROM \"{table}\" WHERE"), 100)+ .await+ .unwrap_err()+ .contains("ValidationException"));+ Ok(())+ }+ .await;+ client.client.delete_table().table_name(&table).send().await.unwrap();+ outcome.unwrap();+ }+fn table_description() -> DynamoDbTableDescription {DynamoDbTableDescription {name: "orders".to_string(),diff --git a/crates/dbx-sql-core/src/query_execution_sql.rs b/crates/dbx-sql-core/src/query_execution_sql.rsindex fff9d58f4c..f39305bf98 100644--- a/crates/dbx-sql-core/src/query_execution_sql.rs+++ b/crates/dbx-sql-core/src/query_execution_sql.rs@@ -3026,6 +3026,23 @@ mod tests {}}+ #[test]+ fn classifies_dynamodb_partiql_reads_and_writes_for_read_only_protection() {+ assert!(!is_write_sql_for_database(+ "SELECT * FROM \"items\" WHERE \"status\"='PENDING'",+ DatabaseType::DynamoDb+ ));+ assert!(!is_write_sql_for_database("-- comment\nSELECT 'UPDATE' FROM \"items\"", DatabaseType::DynamoDb));+ for statement in [+ "INSERT INTO \"items\" VALUE {'pk':'x'}",+ "UPDATE \"items\" SET flag=true WHERE pk='x'",+ "DELETE FROM \"items\" WHERE pk='x'",+ "SELECT * FROM \"items\"; DELETE FROM \"items\" WHERE pk='x'",+ ] {+ assert!(is_write_sql_for_database(statement, DatabaseType::DynamoDb), "{statement}");+ }+ }+#[test]fn classifies_search_engine_rest_writes() {assert!(!is_write_sql_for_database("GET /_cluster/health", DatabaseType::Easysearch));diff --git a/crates/dbx-sql-data/src/query_result_sql.rs b/crates/dbx-sql-data/src/query_result_sql.rsindex a67ce99b5c..0419741a69 100644--- a/crates/dbx-sql-data/src/query_result_sql.rs+++ b/crates/dbx-sql-data/src/query_result_sql.rs@@ -176,6 +176,16 @@ pub fn build_query_pagination_execution_plan(pagination_row_number_column: None,single_execution: false,};+ // DynamoDB paginates ExecuteStatement with opaque API tokens, not SQL+ // LIMIT/OFFSET or derived COUNT queries. Keep PartiQL byte-for-byte intact.+ if options.database_type == Some(DatabaseType::DynamoDb) {+ plan.exact_query_row_bound = None;+ plan.single_execution = true;+ if options.pagination.offset > 0 || options.pagination.session_id.is_some() {+ plan.pagination_error = Some("DynamoDB PartiQL does not support SQL offset pagination".into());+ }+ return plan;+ }let execution_hint = options.execution_hint.as_deref().filter(|hint| !hint.trim().is_empty());let sql_server_cte =@@ -735,6 +745,7 @@ fn unsupported_pagination_type(database_type: Option<DatabaseType>) -> bool {| DatabaseType::Salesforce| DatabaseType::Solr| DatabaseType::CouchDb+ | DatabaseType::DynamoDb))}@@ -2956,6 +2967,54 @@ fn fallback_alias(index: usize) -> String {#[cfg(test)]mod tests {+ #[test]+ fn dynamodb_partiql_uses_api_bounds_without_sql_rewrites() {+ for sql in [+ "SELECT * FROM \"orders\" WHERE status = 'PAID';",+ "SELECT VALUE {'id': o.id} FROM \"orders\" o;",+ "SELECT * FROM \"orders\"; SELECT * FROM \"archive\";",+ "UPDATE \"orders\" SET status = 'PAID' WHERE id = '1';",+ ] {+ for (offset, session_id) in [(0, None), (100, None), (0, Some("opaque".into()))] {+ let plan = build_query_pagination_execution_plan(QueryPaginationExecutionPlanOptions {+ sql: sql.into(),+ query_base_sql: sql.into(),+ database_type: Some(DatabaseType::DynamoDb),+ pagination: QueryPagination { limit: 100, offset, session_id: session_id.clone() },+ use_agent_cursor: false,+ first_page_uses_actual_sql: false,+ execution_hint: None,+ });+ assert_eq!(plan.sql_to_execute, sql);+ assert!(plan.page_sql.is_none());+ assert!(plan.page_limit.is_none());+ assert!(plan.page_offset.is_none());+ assert!(plan.count_sql.is_none());+ assert!(plan.exact_query_row_bound.is_none());+ assert!(!plan.use_agent_result_session);+ assert!(plan.single_execution);+ assert_eq!(plan.pagination_error.is_some(), offset > 0 || session_id.is_some());+ }+ }+ let sql = "SELECT * FROM \"orders\"";+ assert!(+ !build_paginated_query_sql(PaginatedQuerySqlOptions {+ original_sql: sql.into(),+ database_type: Some(DatabaseType::DynamoDb),+ limit: 100,+ offset: 0,+ })+ .ok+ );+ assert!(+ !build_count_query_sql(CountQuerySqlOptions {+ original_sql: sql.into(),+ database_type: Some(DatabaseType::DynamoDb),+ })+ .ok+ );+ }+fn oceanbase_plan(sql: &str, limit: usize, offset: usize, cursor: bool) -> QueryPaginationExecutionPlan {build_query_pagination_execution_plan(QueryPaginationExecutionPlanOptions {sql: sql.into(),diff --git a/docs/content/docs/specialized-workspaces.cn.mdx b/docs/content/docs/specialized-workspaces.cn.mdxindex ad60ba0b67..ed9b0eadd7 100644--- a/docs/content/docs/specialized-workspaces.cn.mdx+++ b/docs/content/docs/specialized-workspaces.cn.mdx@@ -34,6 +34,25 @@ Redis 和 MongoDB 有独立的详细文档:连接只读时,DBX 会禁用或拒绝 Redis、MongoDB 和 GridFS 中的修改操作。危险 Redis 命令还会经过独立的命令安全分类。+## DynamoDB PartiQL++DynamoDB 连接可以通过查询编辑器执行原生 PartiQL。例如:++```sql+SELECT "pk", "status" FROM "orders" WHERE "pk" = 'order-1001';+INSERT INTO "orders" VALUE {'pk': 'order-1002', 'status': 'NEW'};+UPDATE "orders" SET "status" = 'PAID' WHERE "pk" = 'order-1002';+DELETE FROM "orders" WHERE "pk" = 'order-1002';+```++DBX 使用 AWS SDK 的 [ExecuteStatement](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ExecuteStatement.html),不将 PartiQL 翻译为其他 SQL。实际支持范围、IAM 权限及错误由 DynamoDB 决定;这不是完整关系型 SQL,不提供 JOIN、SQL 文件执行、DDL 或跨语句事务。原有 `DBX DYNAMODB SCAN` / Item 命令保持可用。++SELECT 会按服务返回的 `NextToken` 继续读取,包括过滤后没有匹配项的中间页。结果遵循编辑器行数上限,最多读取 1,000 页;达到限制或服务未提供可继续的令牌时,会标记截断并显示警告,不将部分数据报告为完整结果。`LIMIT` 不是这里的行数控制语法,应使用编辑器结果上限或更精确的条件。没有分区键条件的 SELECT 可能扫描大量数据并产生费用。++查询结果使用已返回数据的本地分页,不注入 SQL `LIMIT` / `OFFSET` 或派生表 `COUNT`;文档浏览器的游标分页不受影响。++投影结果保留 DynamoDB 的大数、二进制及嵌套类型表示,不添加用于文档编辑的合成 `_id`。单条写入不进入客户端分页循环;受影响数量表示服务确认的单条操作,并非服务返回的精确变更行数。读取和写入仍经过原有只读、生产确认、超时和取消链路。+## 搜索与文档索引Elasticsearch、Easysearch、Meilisearch 和 Manticore Search 使用面向索引与文档的浏览方式。DBX 会根据驱动返回的对象结构展示索引或集合,并提供浏览、查询和查看文档的入口。diff --git a/docs/content/docs/specialized-workspaces.mdx b/docs/content/docs/specialized-workspaces.mdxindex 1506562bc4..cb428be23c 100644--- a/docs/content/docs/specialized-workspaces.mdx+++ b/docs/content/docs/specialized-workspaces.mdx@@ -34,6 +34,25 @@ Redis and MongoDB have dedicated guides:When a connection is read-only, DBX disables or rejects mutations in Redis, MongoDB, and GridFS. Dangerous Redis commands also pass through a separate command-safety classifier.+## DynamoDB PartiQL++DynamoDB connections support native PartiQL in the query editor:++```sql+SELECT "pk", "status" FROM "orders" WHERE "pk" = 'order-1001';+INSERT INTO "orders" VALUE {'pk': 'order-1002', 'status': 'NEW'};+UPDATE "orders" SET "status" = 'PAID' WHERE "pk" = 'order-1002';+DELETE FROM "orders" WHERE "pk" = 'order-1002';+```++DBX calls the AWS SDK's [ExecuteStatement](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ExecuteStatement.html) rather than translating PartiQL into another SQL dialect. DynamoDB determines supported syntax, IAM permissions, and errors. This is not full relational SQL: JOIN, SQL-file execution, DDL, and cross-statement transactions are not enabled. Existing `DBX DYNAMODB SCAN` / Item commands remain supported.++SELECT follows service `NextToken` values, including intermediate pages with no filter matches. Results respect the editor's row cap and a 1,000-page safety bound. A reached limit or a service response without a usable continuation token marks the result truncated and emits a warning instead of presenting partial data as complete. Use the editor row cap or narrower conditions, not SQL `LIMIT`. SELECT without a partition-key condition may scan substantial data and incur charges.++Query results paginate the returned data locally, without injecting SQL `LIMIT` / `OFFSET` or derived-table `COUNT` queries. Document-browser cursor pagination is unchanged.++Projections preserve DynamoDB representations for large numbers, binary, and nested values without adding synthetic document-editing `_id` fields. Singleton writes never enter the client pagination loop; their affected count acknowledges one successful operation, not an exact changed-row count supplied by the service. Existing read-only, production-confirmation, timeout, and cancellation paths remain in effect.+## Search and Document IndexesElasticsearch, Easysearch, Meilisearch, and Manticore Search use index- and document-oriented browsing. DBX displays indexes or collections from driver metadata and provides entry points for browsing, querying, and inspecting documents.diff --git a/docs/screenshots/issue-12693-partiql-compact.png b/docs/screenshots/issue-12693-partiql-compact.pngnew file mode 100644index 0000000000..589c8dcbd4Binary files /dev/null and b/docs/screenshots/issue-12693-partiql-compact.png differdiff --git a/docs/screenshots/issue-12693-partiql-query.png b/docs/screenshots/issue-12693-partiql-query.pngnew file mode 100644index 0000000000..5cb7168514Binary files /dev/null and b/docs/screenshots/issue-12693-partiql-query.png differdiff --git a/plugins/connection-types/dynamodb.yaml b/plugins/connection-types/dynamodb.yamlindex b5bfc42392..e996c88f70 100644--- a/plugins/connection-types/dynamodb.yaml+++ b/plugins/connection-types/dynamodb.yaml@@ -11,7 +11,7 @@ skipTcpProbe: falsedefaultPort: 8000supportLevel: operatecapabilities:- queryExecution: false+ queryExecution: truemetadataBrowse: trueobjectBrowser: falseobjectSource: false