This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 9130915486a6 CAMEL-27950: camel-duckdb - fix JSON results of date,
timestamp and uuid columns, check all rows of an insert, and smaller fixes
(#31203)
9130915486a6 is described below
commit 9130915486a67fcb7cced6ed8ff2bc0647dd2bc9
Author: Adriano Machado <[email protected]>
AuthorDate: Wed Dec 2 05:53:50 2026 -0500
CAMEL-27950: camel-duckdb - fix JSON results of date, timestamp and uuid
columns, check all rows of an insert, and smaller fixes (#31203)
- resultFormat=JSON failed on date, timestamp and uuid columns. Temporal
values and UUID
are now ISO/text strings, BLOB is Base64, SQL arrays are JSON arrays and
structs JSON
objects. The default LIST_MAP result is unchanged.
- insert of a list of maps took the columns from the first row only; every
row must now
be a Map with the same keys, or a DuckDbException names the row.
- An unknown CamelDuckDbOperation fails with the list of valid operations.
- databasePath has the default value :memory: in the metadata.
- format=auto also infers .csv.gz, .json.gz, .jsonl, .ndjson and their .gz
variants.
Docs and a 4.25 upgrade guide entry for the insert change.
Claude Code on behalf of ammachado.
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
---
.../apache/camel/catalog/components/duckdb.json | 4 +-
.../camel/catalog/docs/duckdb-component.adoc | 14 ++-
.../component/duckdb/DuckDbEndpointUriFactory.java | 2 +-
.../org/apache/camel/component/duckdb/duckdb.json | 4 +-
.../src/main/docs/duckdb-component.adoc | 14 ++-
.../camel/component/duckdb/DuckDbEndpoint.java | 5 +-
.../component/duckdb/DuckDbInsertSupport.java | 15 ++-
.../camel/component/duckdb/DuckDbProducer.java | 16 ++-
.../component/duckdb/DuckDbResultSetMapper.java | 76 ++++++++++++-
.../camel/component/duckdb/DuckDbProducerTest.java | 119 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_25.adoc | 8 ++
.../builder/endpoint/StaticEndpointBuilders.java | 2 +
.../endpoint/dsl/DuckDbEndpointBuilderFactory.java | 5 +-
13 files changed, 266 insertions(+), 18 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/duckdb.json
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/duckdb.json
index 4f5701579df3..02aaafd4e2f4 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/duckdb.json
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/duckdb.json
@@ -44,9 +44,9 @@
"producerOut": { "carriers": [ "value" ], "javaType": "java.lang.Long",
"byOption": [ { "option": "operation", "value": "QUERY", "carriers": [ "list"
], "javaType": "java.util.List<java.util.Map<String, Object>>" }, { "option":
"operation", "value": "PING", "carriers": [ "value" ], "javaType":
"java.lang.Boolean" }, { "option": "resultFormat", "value": "JSON", "carriers":
[ "text", "value" ] } ], "description": "The count of rows written or affected
as a Long, also in the CamelDuckDb [...]
},
"properties": {
- "databasePath": { "index": 0, "kind": "path", "displayName": "Database
Path", "group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "description": "The database to use: :memory: (the default)
for an in-memory database of its own, which is dropped when the endpoint stops,
or the relative or absolute path of a database file, which DuckDB creates when
it does not exist. Not used wh [...]
+ "databasePath": { "index": 0, "kind": "path", "displayName": "Database
Path", "group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "defaultValue": ":memory:", "description": "The database to
use: :memory: (the default) for an in-memory database of its own, which is
dropped when the endpoint stops, or the relative or absolute path of a database
file, which DuckDB creates when it [...]
"batchSize": { "index": 1, "kind": "parameter", "displayName": "Batch
Size", "group": "producer", "label": "", "required": false, "type": "integer",
"javaType": "int", "deprecated": false, "autowired": false, "secret": false,
"defaultValue": 0, "description": "The number of rows that the insert operation
sends in one JDBC batch. 0 or less sends all the rows of the message body in
one batch." },
- "format": { "index": 2, "kind": "parameter", "displayName": "Format",
"group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "defaultValue": "auto", "description": "File format for copy:
csv, parquet, json or auto (inferred from the file extension)." },
+ "format": { "index": 2, "kind": "parameter", "displayName": "Format",
"group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "defaultValue": "auto", "description": "File format for copy:
csv, parquet, json or auto (inferred from the file extension: .csv, .csv.gz,
.parquet, .json, .json.gz, .jsonl, .jsonl.gz, .ndjson or .ndjson.gz)." },
"jdbcUrl": { "index": 3, "kind": "parameter", "displayName": "Jdbc Url",
"group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "description": "The JDBC URL of the database, such as
jdbc:duckdb:\/data\/analytics.db, used as is instead of the URL built from
databasePath. Not used when a DataSource is set on the component." },
"operation": { "index": 4, "kind": "parameter", "displayName":
"Operation", "group": "producer", "label": "", "required": false, "type":
"enum", "javaType": "org.apache.camel.component.duckdb.DuckDbOperation",
"enum": [ "EXECUTE", "QUERY", "INSERT", "COPY", "PING" ], "deprecated": false,
"autowired": false, "secret": false, "defaultValue": "EXECUTE", "description":
"The operation to perform: EXECUTE runs a statement that returns no rows, QUERY
a statement that returns rows, INSERT in [...]
"query": { "index": 5, "kind": "parameter", "displayName": "Query",
"group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "description": "Static SQL for the execute and query
operations. When set, it is used instead of the message body; the
CamelDuckDbQuery header takes precedence over it." },
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/duckdb-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/duckdb-component.adoc
index 2942569b1f16..4faec1b9ec2d 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/duckdb-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/duckdb-component.adoc
@@ -55,10 +55,14 @@ The producer supports:
* `execute` (default) — run DDL/DML that returns no rows
* `query` — run a SELECT and return rows as `List<Map>` (default) or JSON
(`resultFormat=JSON`)
-* `insert` — insert a `List` of `Map` rows into `table`
+* `insert` — insert a `List` of `Map` rows into `table`. Every element must be
a `Map`, and every row must have the same
+keys as the first row, otherwise the insert fails with a `DuckDbException`
* `copy` — bulk load one local file, from a `File`, a `Path` or a path as
`String` (or bytes), using DuckDB `read_csv` / `read_parquet` / `read_json`
* `ping` — `SELECT 1` connectivity check; sets `CamelDuckDbPingOk`
+The `CamelDuckDbOperation` header takes the operation name (case-insensitive);
an unknown value fails with an error
+that lists the valid operations.
+
The SQL for `execute` and `query` is taken from the `CamelDuckDbQuery` header,
else from the `query` option, else
from the message body. So when the `query` option is set, the message body is
not used as SQL.
@@ -70,6 +74,10 @@ thread safety. Prefer a shared `DataSource` when you need
concurrent producers.
== Copy sources
+With `format=auto` (the default), the format of a `copy` is inferred from the
file name: `.csv` and `.csv.gz` are read
+as CSV, `.parquet` as Parquet, and `.json`, `.json.gz`, `.jsonl`, `.jsonl.gz`,
`.ndjson` and `.ndjson.gz` as JSON. Set `format` for any other
+name.
+
The `copy` operation gives the path from the message body to the DuckDB
`read_csv`, `read_parquet` or `read_json`
function. DuckDB reads a value that starts with a URL scheme (such as
`https://` or `s3://`) as a remote file, and
expands a value with glob pattern characters (`*`, `?`, `[` or `{`) to all the
matching files. So by default `copy`
@@ -189,7 +197,9 @@ YAML::
----
====
-A query returns the rows as a `List` of `Map`, or as a JSON array with
`resultFormat=JSON`:
+A query returns the rows as a `List` of `Map`, or as a JSON array with
`resultFormat=JSON`. In the JSON array, dates,
+times, timestamps (ISO text) and UUIDs are strings, `BLOB` values are Base64
strings, lists are arrays, and structs are
+objects. A DuckDB `JSON` column is a string that holds the JSON text, not a
nested value:
[source,yaml]
----
diff --git
a/components/camel-duckdb/src/generated/java/org/apache/camel/component/duckdb/DuckDbEndpointUriFactory.java
b/components/camel-duckdb/src/generated/java/org/apache/camel/component/duckdb/DuckDbEndpointUriFactory.java
index 6bf4c051dbe6..a1ca108e49c0 100644
---
a/components/camel-duckdb/src/generated/java/org/apache/camel/component/duckdb/DuckDbEndpointUriFactory.java
+++
b/components/camel-duckdb/src/generated/java/org/apache/camel/component/duckdb/DuckDbEndpointUriFactory.java
@@ -57,7 +57,7 @@ public class DuckDbEndpointUriFactory extends
org.apache.camel.support.component
Map<String, Object> copy = copyParameters(properties);
- uri = buildPathParameter(syntax, uri, "databasePath", null, false,
copy);
+ uri = buildPathParameter(syntax, uri, "databasePath", ":memory:",
false, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
diff --git
a/components/camel-duckdb/src/generated/resources/META-INF/org/apache/camel/component/duckdb/duckdb.json
b/components/camel-duckdb/src/generated/resources/META-INF/org/apache/camel/component/duckdb/duckdb.json
index 4f5701579df3..02aaafd4e2f4 100644
---
a/components/camel-duckdb/src/generated/resources/META-INF/org/apache/camel/component/duckdb/duckdb.json
+++
b/components/camel-duckdb/src/generated/resources/META-INF/org/apache/camel/component/duckdb/duckdb.json
@@ -44,9 +44,9 @@
"producerOut": { "carriers": [ "value" ], "javaType": "java.lang.Long",
"byOption": [ { "option": "operation", "value": "QUERY", "carriers": [ "list"
], "javaType": "java.util.List<java.util.Map<String, Object>>" }, { "option":
"operation", "value": "PING", "carriers": [ "value" ], "javaType":
"java.lang.Boolean" }, { "option": "resultFormat", "value": "JSON", "carriers":
[ "text", "value" ] } ], "description": "The count of rows written or affected
as a Long, also in the CamelDuckDb [...]
},
"properties": {
- "databasePath": { "index": 0, "kind": "path", "displayName": "Database
Path", "group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "description": "The database to use: :memory: (the default)
for an in-memory database of its own, which is dropped when the endpoint stops,
or the relative or absolute path of a database file, which DuckDB creates when
it does not exist. Not used wh [...]
+ "databasePath": { "index": 0, "kind": "path", "displayName": "Database
Path", "group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "defaultValue": ":memory:", "description": "The database to
use: :memory: (the default) for an in-memory database of its own, which is
dropped when the endpoint stops, or the relative or absolute path of a database
file, which DuckDB creates when it [...]
"batchSize": { "index": 1, "kind": "parameter", "displayName": "Batch
Size", "group": "producer", "label": "", "required": false, "type": "integer",
"javaType": "int", "deprecated": false, "autowired": false, "secret": false,
"defaultValue": 0, "description": "The number of rows that the insert operation
sends in one JDBC batch. 0 or less sends all the rows of the message body in
one batch." },
- "format": { "index": 2, "kind": "parameter", "displayName": "Format",
"group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "defaultValue": "auto", "description": "File format for copy:
csv, parquet, json or auto (inferred from the file extension)." },
+ "format": { "index": 2, "kind": "parameter", "displayName": "Format",
"group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "defaultValue": "auto", "description": "File format for copy:
csv, parquet, json or auto (inferred from the file extension: .csv, .csv.gz,
.parquet, .json, .json.gz, .jsonl, .jsonl.gz, .ndjson or .ndjson.gz)." },
"jdbcUrl": { "index": 3, "kind": "parameter", "displayName": "Jdbc Url",
"group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "description": "The JDBC URL of the database, such as
jdbc:duckdb:\/data\/analytics.db, used as is instead of the URL built from
databasePath. Not used when a DataSource is set on the component." },
"operation": { "index": 4, "kind": "parameter", "displayName":
"Operation", "group": "producer", "label": "", "required": false, "type":
"enum", "javaType": "org.apache.camel.component.duckdb.DuckDbOperation",
"enum": [ "EXECUTE", "QUERY", "INSERT", "COPY", "PING" ], "deprecated": false,
"autowired": false, "secret": false, "defaultValue": "EXECUTE", "description":
"The operation to perform: EXECUTE runs a statement that returns no rows, QUERY
a statement that returns rows, INSERT in [...]
"query": { "index": 5, "kind": "parameter", "displayName": "Query",
"group": "producer", "label": "", "required": false, "type": "string",
"javaType": "java.lang.String", "deprecated": false, "autowired": false,
"secret": false, "description": "Static SQL for the execute and query
operations. When set, it is used instead of the message body; the
CamelDuckDbQuery header takes precedence over it." },
diff --git a/components/camel-duckdb/src/main/docs/duckdb-component.adoc
b/components/camel-duckdb/src/main/docs/duckdb-component.adoc
index 2942569b1f16..4faec1b9ec2d 100644
--- a/components/camel-duckdb/src/main/docs/duckdb-component.adoc
+++ b/components/camel-duckdb/src/main/docs/duckdb-component.adoc
@@ -55,10 +55,14 @@ The producer supports:
* `execute` (default) — run DDL/DML that returns no rows
* `query` — run a SELECT and return rows as `List<Map>` (default) or JSON
(`resultFormat=JSON`)
-* `insert` — insert a `List` of `Map` rows into `table`
+* `insert` — insert a `List` of `Map` rows into `table`. Every element must be
a `Map`, and every row must have the same
+keys as the first row, otherwise the insert fails with a `DuckDbException`
* `copy` — bulk load one local file, from a `File`, a `Path` or a path as
`String` (or bytes), using DuckDB `read_csv` / `read_parquet` / `read_json`
* `ping` — `SELECT 1` connectivity check; sets `CamelDuckDbPingOk`
+The `CamelDuckDbOperation` header takes the operation name (case-insensitive);
an unknown value fails with an error
+that lists the valid operations.
+
The SQL for `execute` and `query` is taken from the `CamelDuckDbQuery` header,
else from the `query` option, else
from the message body. So when the `query` option is set, the message body is
not used as SQL.
@@ -70,6 +74,10 @@ thread safety. Prefer a shared `DataSource` when you need
concurrent producers.
== Copy sources
+With `format=auto` (the default), the format of a `copy` is inferred from the
file name: `.csv` and `.csv.gz` are read
+as CSV, `.parquet` as Parquet, and `.json`, `.json.gz`, `.jsonl`, `.jsonl.gz`,
`.ndjson` and `.ndjson.gz` as JSON. Set `format` for any other
+name.
+
The `copy` operation gives the path from the message body to the DuckDB
`read_csv`, `read_parquet` or `read_json`
function. DuckDB reads a value that starts with a URL scheme (such as
`https://` or `s3://`) as a remote file, and
expands a value with glob pattern characters (`*`, `?`, `[` or `{`) to all the
matching files. So by default `copy`
@@ -189,7 +197,9 @@ YAML::
----
====
-A query returns the rows as a `List` of `Map`, or as a JSON array with
`resultFormat=JSON`:
+A query returns the rows as a `List` of `Map`, or as a JSON array with
`resultFormat=JSON`. In the JSON array, dates,
+times, timestamps (ISO text) and UUIDs are strings, `BLOB` values are Base64
strings, lists are arrays, and structs are
+objects. A DuckDB `JSON` column is a string that holds the JSON text, not a
nested value:
[source,yaml]
----
diff --git
a/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbEndpoint.java
b/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbEndpoint.java
index 2100a9ef4559..9dfd3fbd5665 100644
---
a/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbEndpoint.java
+++
b/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbEndpoint.java
@@ -76,7 +76,8 @@ public class DuckDbEndpoint extends DefaultEndpoint {
private Connection injectedConnection;
private boolean connectionOwned;
- @UriPath(description = "The database to use: :memory: (the default) for an
in-memory database of its own, which is"
+ @UriPath(defaultValue = ":memory:",
+ description = "The database to use: :memory: (the default) for an
in-memory database of its own, which is"
+ " dropped when the endpoint stops, or the
relative or absolute path of a database file,"
+ " which DuckDB creates when it does not exist.
Not used when jdbcUrl or a DataSource is"
+ " set.")
@@ -101,7 +102,7 @@ public class DuckDbEndpoint extends DefaultEndpoint {
+ " the rows of the message body in one batch.")
private int batchSize;
@UriParam(defaultValue = "auto",
- description = "File format for copy: csv, parquet, json or auto
(inferred from the file extension).")
+ description = "File format for copy: csv, parquet, json or auto
(inferred from the file extension: .csv, .csv.gz, .parquet, .json, .json.gz,
.jsonl, .jsonl.gz, .ndjson or .ndjson.gz).")
private String format = "auto";
@UriParam(defaultValue = "false",
description = "Whether to open the database in read-only mode.
The database file must exist, and an"
diff --git
a/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbInsertSupport.java
b/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbInsertSupport.java
index 64023ee0b172..705f14cad4bf 100644
---
a/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbInsertSupport.java
+++
b/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbInsertSupport.java
@@ -21,6 +21,7 @@ import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.Set;
final class DuckDbInsertSupport {
@@ -31,8 +32,10 @@ final class DuckDbInsertSupport {
if (rows.isEmpty()) {
return 0;
}
- if (!(rows.get(0) instanceof Map)) {
- throw new DuckDbException("Insert body must be a List of Map
entries when using operation=insert");
+ for (Object row : rows) {
+ if (!(row instanceof Map)) {
+ throw new DuckDbException("Insert body must be a List of Map
entries when using operation=insert");
+ }
}
@SuppressWarnings("unchecked")
List<Map<String, Object>> maps = (List<Map<String, Object>>) rows;
@@ -40,6 +43,14 @@ final class DuckDbInsertSupport {
if (columns.isEmpty()) {
throw new DuckDbException("Insert row maps must contain at least
one column");
}
+ Set<String> columnSet = maps.get(0).keySet();
+ for (int i = 1; i < maps.size(); i++) {
+ Set<String> rowColumns = maps.get(i).keySet();
+ if (!rowColumns.equals(columnSet)) {
+ throw new DuckDbException(
+ "Insert row " + i + " has different columns than row
0: " + rowColumns + " instead of " + columnSet);
+ }
+ }
String sql = buildInsertSql(table, columns);
long written = 0;
diff --git
a/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbProducer.java
b/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbProducer.java
index c02d861740be..9293b082e3c5 100644
---
a/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbProducer.java
+++
b/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbProducer.java
@@ -23,10 +23,12 @@ import java.nio.file.Path;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
+import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
@@ -170,13 +172,14 @@ public class DuckDbProducer extends DefaultProducer {
return configured;
}
String lower = path.toLowerCase(Locale.ROOT);
- if (lower.endsWith(".csv")) {
+ if (lower.endsWith(".csv") || lower.endsWith(".csv.gz")) {
return "csv";
}
if (lower.endsWith(".parquet")) {
return "parquet";
}
- if (lower.endsWith(".json")) {
+ if (lower.endsWith(".json") || lower.endsWith(".json.gz") ||
lower.endsWith(".jsonl")
+ || lower.endsWith(".jsonl.gz") || lower.endsWith(".ndjson") ||
lower.endsWith(".ndjson.gz")) {
return "json";
}
throw new DuckDbException("Could not infer copy format from file name:
" + path);
@@ -277,7 +280,14 @@ public class DuckDbProducer extends DefaultProducer {
private DuckDbOperation resolveOperation(Exchange exchange) {
String header = exchange.getIn().getHeader(DuckDbConstants.OPERATION,
String.class);
if (ObjectHelper.isNotEmpty(header)) {
- return
DuckDbOperation.valueOf(header.trim().toUpperCase(Locale.ROOT));
+ try {
+ return
DuckDbOperation.valueOf(header.trim().toUpperCase(Locale.ROOT));
+ } catch (IllegalArgumentException e) {
+ throw new DuckDbException(
+ "Unknown operation '" + header + "', expected one of: "
+ +
Arrays.stream(DuckDbOperation.values()).map(Enum::name)
+
.collect(Collectors.joining(", ")));
+ }
}
return endpoint.getOperation();
}
diff --git
a/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbResultSetMapper.java
b/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbResultSetMapper.java
index 292985cf5529..e21cd6501df3 100644
---
a/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbResultSetMapper.java
+++
b/components/camel-duckdb/src/main/java/org/apache/camel/component/duckdb/DuckDbResultSetMapper.java
@@ -16,15 +16,30 @@
*/
package org.apache.camel.component.duckdb;
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Struct;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.OffsetTime;
+import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
+import org.duckdb.DuckDBStruct;
final class DuckDbResultSetMapper {
@@ -49,9 +64,68 @@ final class DuckDbResultSetMapper {
JsonArray array = new JsonArray();
for (Map<String, Object> row : rows) {
JsonObject object = new JsonObject();
- row.forEach(object::put);
+ row.forEach((key, value) -> object.put(key, toJsonValue(value)));
array.add(object);
}
return array.toJson();
}
+
+ /**
+ * Converts a JDBC value to a type that Jsoner can serialize: temporal
values and UUID become text, binary values
+ * become Base64 text, SQL arrays become lists and structs become maps.
+ */
+ private static Object toJsonValue(Object value) {
+ if (value == null || value instanceof String || value instanceof
Number || value instanceof Boolean) {
+ return value;
+ }
+ try {
+ if (value instanceof Timestamp ts) {
+ return
DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ts.toLocalDateTime());
+ }
+ if (value instanceof Date date) {
+ return date.toLocalDate().toString();
+ }
+ if (value instanceof Time time) {
+ return
DateTimeFormatter.ISO_LOCAL_TIME.format(time.toLocalTime());
+ }
+ if (value instanceof LocalTime localTime) {
+ return DateTimeFormatter.ISO_LOCAL_TIME.format(localTime);
+ }
+ if (value instanceof OffsetDateTime offsetDateTime) {
+ return
DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime);
+ }
+ if (value instanceof OffsetTime offsetTime) {
+ return DateTimeFormatter.ISO_OFFSET_TIME.format(offsetTime);
+ }
+ if (value instanceof Blob blob) {
+ return Base64.getEncoder().encodeToString(blob.getBytes(1,
(int) blob.length()));
+ }
+ if (value instanceof byte[] bytes) {
+ return Base64.getEncoder().encodeToString(bytes);
+ }
+ if (value instanceof Array array) {
+ return toJsonValue(array.getArray());
+ }
+ if (value instanceof Struct struct) {
+ return toJsonValue(struct instanceof DuckDBStruct duckStruct
+ ? duckStruct.getMap() :
Arrays.asList(struct.getAttributes()));
+ }
+ } catch (SQLException e) {
+ throw new DuckDbException("Cannot convert a result value to JSON:
" + e.getMessage(), e);
+ }
+ if (value instanceof Map<?, ?> map) {
+ JsonObject object = new JsonObject();
+ map.forEach((k, v) -> object.put(String.valueOf(k),
toJsonValue(v)));
+ return object;
+ }
+ if (value instanceof Collection<?> collection) {
+ JsonArray array = new JsonArray();
+ collection.forEach(v -> array.add(toJsonValue(v)));
+ return array;
+ }
+ if (value instanceof Object[] objects) {
+ return toJsonValue(Arrays.asList(objects));
+ }
+ return value.toString();
+ }
}
diff --git
a/components/camel-duckdb/src/test/java/org/apache/camel/component/duckdb/DuckDbProducerTest.java
b/components/camel-duckdb/src/test/java/org/apache/camel/component/duckdb/DuckDbProducerTest.java
index a719031c1d2d..76d5570ce489 100644
---
a/components/camel-duckdb/src/test/java/org/apache/camel/component/duckdb/DuckDbProducerTest.java
+++
b/components/camel-duckdb/src/test/java/org/apache/camel/component/duckdb/DuckDbProducerTest.java
@@ -16,6 +16,7 @@
*/
package org.apache.camel.component.duckdb;
+import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -26,6 +27,7 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
+import java.util.zip.GZIPOutputStream;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.builder.RouteBuilder;
@@ -286,6 +288,123 @@ class DuckDbProducerTest extends CamelTestSupport {
assertThat(events).isEmpty();
}
+ @Test
+ void queryAsJsonSupportsDateTimestampAndUuidColumns(@TempDir Path tempDir)
{
+ String uri = jdbcEndpoint(tempDir.resolve("test.db"));
+
+ String json = template.requestBody(uri +
"&operation=query&resultFormat=JSON",
+ "SELECT DATE '2024-03-05' AS d, TIMESTAMP '2024-03-05
10:11:12' AS ts,"
+
+ " UUID '123e4567-e89b-12d3-a456-426614174000' AS id,"
+
+ " [1, 2] AS l, {'a': 1} AS s",
+ String.class);
+
+ assertThat(json).contains("\"d\":\"2024-03-05\"")
+ .contains("\"ts\":\"2024-03-05T10:11:12\"")
+ .contains("\"id\":\"123e4567-e89b-12d3-a456-426614174000\"")
+ .contains("\"l\":[1,2]")
+ .contains("\"s\":{\"a\":1}");
+ }
+
+ @Test
+ void queryAsJsonEncodesBlobAsBase64(@TempDir Path tempDir) {
+ String uri = jdbcEndpoint(tempDir.resolve("test.db"));
+
+ String json = template.requestBody(uri +
"&operation=query&resultFormat=JSON",
+ "SELECT 'abc'::BLOB AS b", String.class);
+
+ assertThat(json).contains("\"b\":\"YWJj\"");
+ }
+
+ @Test
+ void queryAsJsonKeepsSecondsAndOffsets(@TempDir Path tempDir) {
+ String uri = jdbcEndpoint(tempDir.resolve("test.db"));
+
+ String json = template.requestBody(uri +
"&operation=query&resultFormat=JSON",
+ "SELECT TIMESTAMP '2024-03-05 10:11:00' AS ts, TIME '10:11:00'
AS t,"
+
+ " TIMESTAMPTZ '2024-03-05 10:11:00+00' AS tstz,"
+
+ " TIMETZ '10:11:00+00' AS ttz",
+ String.class);
+
+ assertThat(json).contains("\"ts\":\"2024-03-05T10:11:00\"")
+ .contains("\"t\":\"10:11:00\"")
+ .containsPattern("\"tstz\":\"2024-03-05T\\d\\d:11:00[Z+-]")
+ .contains("\"ttz\":\"10:11:00Z\"");
+ }
+
+ @Test
+ void insertFailsWhenLaterRowHasDifferentKeys(@TempDir Path tempDir) {
+ String uri = jdbcEndpoint(tempDir.resolve("test.db"));
+ template.sendBody(uri + "&operation=execute", "CREATE TABLE events (id
INTEGER, name VARCHAR)");
+
+ assertThatThrownBy(() -> template.sendBody(uri +
"&operation=insert&table=events",
+ List.of(Map.of("id", 1), Map.of("id", 2, "name", "bob"))))
+ .isInstanceOf(CamelExecutionException.class)
+ .hasRootCauseInstanceOf(DuckDbException.class)
+ .rootCause().hasMessageStartingWith("Insert row 1 has
different columns than row 0")
+ .hasMessageContaining("instead of [id]");
+ }
+
+ @Test
+ void insertFailsWhenLaterElementIsNotAMap(@TempDir Path tempDir) {
+ String uri = jdbcEndpoint(tempDir.resolve("test.db"));
+ template.sendBody(uri + "&operation=execute", "CREATE TABLE events (id
INTEGER, name VARCHAR)");
+
+ assertThatThrownBy(() -> template.sendBody(uri +
"&operation=insert&table=events",
+ List.of(Map.of("id", 1), "not a map")))
+ .isInstanceOf(CamelExecutionException.class)
+ .hasRootCauseInstanceOf(DuckDbException.class)
+ .hasRootCauseMessage("Insert body must be a List of Map
entries when using operation=insert");
+ }
+
+ @Test
+ void unknownOperationHeaderListsValidValues(@TempDir Path tempDir) {
+ String uri = jdbcEndpoint(tempDir.resolve("test.db"));
+
+ assertThatThrownBy(() -> template.sendBodyAndHeader(uri, "SELECT 1",
"CamelDuckDbOperation", "bogus"))
+ .isInstanceOf(CamelExecutionException.class)
+ .hasRootCauseInstanceOf(DuckDbException.class)
+ .hasRootCauseMessage("Unknown operation 'bogus', expected one
of: EXECUTE, QUERY, INSERT, COPY, PING");
+ }
+
+ @Test
+ void copyInfersFormatFromGzipAndJsonLinesExtensions(@TempDir Path tempDir)
throws Exception {
+ String uri = jdbcEndpoint(tempDir.resolve("test.db"));
+ template.sendBody(uri + "&operation=execute", "CREATE TABLE events (id
INTEGER, name VARCHAR)");
+
+ Path gz = tempDir.resolve("data.csv.gz");
+ try (OutputStream out = new
GZIPOutputStream(Files.newOutputStream(gz))) {
+ out.write("id,name\n1,ada\n".getBytes(StandardCharsets.UTF_8));
+ }
+ Path jsonGz = tempDir.resolve("data.json.gz");
+ try (OutputStream out = new
GZIPOutputStream(Files.newOutputStream(jsonGz))) {
+
out.write("[{\"id\":4,\"name\":\"di\"}]".getBytes(StandardCharsets.UTF_8));
+ }
+ Path jsonl = tempDir.resolve("data.jsonl");
+ Files.writeString(jsonl, "{\"id\":2,\"name\":\"bob\"}\n");
+ Path jsonlGz = tempDir.resolve("data.jsonl.gz");
+ try (OutputStream out = new
GZIPOutputStream(Files.newOutputStream(jsonlGz))) {
+
out.write("{\"id\":5,\"name\":\"ed\"}\n".getBytes(StandardCharsets.UTF_8));
+ }
+ Path ndjsonGz = tempDir.resolve("data.ndjson.gz");
+ try (OutputStream out = new
GZIPOutputStream(Files.newOutputStream(ndjsonGz))) {
+
out.write("{\"id\":6,\"name\":\"flo\"}\n".getBytes(StandardCharsets.UTF_8));
+ }
+ Path ndjson = tempDir.resolve("data.ndjson");
+ Files.writeString(ndjson, "{\"id\":3,\"name\":\"cy\"}\n");
+
+ template.sendBody(uri + "&operation=copy&table=events", gz.toFile());
+ template.sendBody(uri + "&operation=copy&table=events",
jsonGz.toFile());
+ template.sendBody(uri + "&operation=copy&table=events",
jsonl.toFile());
+ template.sendBody(uri + "&operation=copy&table=events",
ndjson.toFile());
+ template.sendBody(uri + "&operation=copy&table=events",
jsonlGz.toFile());
+ template.sendBody(uri + "&operation=copy&table=events",
ndjsonGz.toFile());
+
+ @SuppressWarnings("unchecked")
+ List<Map<String, Object>> rows
+ = template.requestBody(uri + "&operation=query", "SELECT name
FROM events ORDER BY id", List.class);
+ assertThat(rows).extracting(row ->
row.get("name")).containsExactly("ada", "bob", "cy", "di", "ed", "flo");
+ }
+
private static void createEventsDatabase(Path dbFile, String name) throws
SQLException {
try (Connection connection =
DriverManager.getConnection("jdbc:duckdb:" + dbFile.toAbsolutePath());
Statement statement = connection.createStatement()) {
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
index 2ddc39a88fc6..299e31106f25 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
@@ -340,3 +340,11 @@ behaviour.
`repositoryName`, which holds the keys of the repository. Before, it ran
`FLUSHDB`, which deleted every key of the
selected Redis database, including data that does not belong to the
repository. The `flushOnStartup` option is
unchanged: it still deletes all keys of the database when the repository
starts.
+
+=== camel-duckdb - an insert of a list of maps fails when the rows have
different keys
+
+The `insert` operation of the `duckdb` producer took the columns from the keys
of the first `Map` only. A key that only
+a later row had was dropped silently, and a later element that was not a `Map`
failed with a `ClassCastException`. Now
+every element must be a `Map`, and a row whose keys differ from the keys of
the first row fails with a
+`DuckDbException` that names the row. A route that inserts rows with different
keys must give every row the same keys
+(with `null` for a missing value).
diff --git
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/StaticEndpointBuilders.java
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/StaticEndpointBuilders.java
index 6af14a358266..18a261503b94 100644
---
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/StaticEndpointBuilders.java
+++
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/StaticEndpointBuilders.java
@@ -6273,6 +6273,7 @@ public class StaticEndpointBuilders {
* its own, which is dropped when the endpoint stops, or the relative or
* absolute path of a database file, which DuckDB creates when it does not
* exist. Not used when jdbcUrl or a DataSource is set.
+ * Default value: :memory:
*
* @param path databasePath
* @return the dsl builder
@@ -6296,6 +6297,7 @@ public class StaticEndpointBuilders {
* its own, which is dropped when the endpoint stops, or the relative or
* absolute path of a database file, which DuckDB creates when it does not
* exist. Not used when jdbcUrl or a DataSource is set.
+ * Default value: :memory:
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
diff --git
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DuckDbEndpointBuilderFactory.java
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DuckDbEndpointBuilderFactory.java
index 40d81b389ad6..f1a33b3d5c81 100644
---
a/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DuckDbEndpointBuilderFactory.java
+++
b/dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DuckDbEndpointBuilderFactory.java
@@ -79,7 +79,8 @@ public interface DuckDbEndpointBuilderFactory {
}
/**
* File format for copy: csv, parquet, json or auto (inferred from the
- * file extension).
+ * file extension: .csv, .csv.gz, .parquet, .json, .json.gz, .jsonl,
+ * .jsonl.gz, .ndjson or .ndjson.gz).
*
* The option is a: <code>java.lang.String</code> type.
*
@@ -469,6 +470,7 @@ public interface DuckDbEndpointBuilderFactory {
* of its own, which is dropped when the endpoint stops, or the
relative
* or absolute path of a database file, which DuckDB creates when it
* does not exist. Not used when jdbcUrl or a DataSource is set.
+ * Default value: :memory:
*
* @param path databasePath
* @return the dsl builder
@@ -492,6 +494,7 @@ public interface DuckDbEndpointBuilderFactory {
* of its own, which is dropped when the endpoint stops, or the
relative
* or absolute path of a database file, which DuckDB creates when it
* does not exist. Not used when jdbcUrl or a DataSource is set.
+ * Default value: :memory:
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name