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 e2495a9442a8 CAMEL-27147: camel-cassandraql - bind named markers
(:name) from a Map body (#30319)
e2495a9442a8 is described below
commit e2495a9442a8c5a6972a6e867622e43717871cee
Author: Claus Ibsen <[email protected]>
AuthorDate: Wed Nov 18 13:21:48 2026 +0100
CAMEL-27147: camel-cassandraql - bind named markers (:name) from a Map body
(#30319)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
.../apache/camel/catalog/docs/cql-component.adoc | 36 ++++++-
.../src/main/docs/cql-component.adoc | 36 ++++++-
.../component/cassandra/CassandraProducer.java | 54 ++++++++--
.../CassandraComponentProducerNamedIT.java | 116 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 6 ++
5 files changed, 231 insertions(+), 17 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/cql-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/cql-component.adoc
index f83b65b96766..7e3eb397619a 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/cql-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/cql-component.adoc
@@ -57,17 +57,26 @@ your own Cluster instance and give it to the Camel endpoint.
==== Incoming Message
-The Camel Cassandra endpoint expects a bunch of simple objects (`Object`
-or `Object[]` or `Collection<Object>`) which will be bound to the CQL
-statement as query parameters. If the message body is null, an empty array or
-an empty collection, then the CQL query will be executed without binding
parameters.
-Any other body is bound as a single parameter, so a body that is left from an
earlier
+The message body holds the values of the bind markers of the CQL statement:
+
+* A `Map` binds the named markers, such as `:login`, by name: each marker
takes the
+value of the `Map` entry of that name. The keys are matched ignoring case, as
CQL
+does for a name that is not quoted, and keys that the statement does not use
are
+ignored. A marker with no entry in the `Map` fails the message.
+* An `Object[]` or a `Collection<Object>` binds the `?` markers by position,
in order.
+* If the message body is null, an empty array or an empty collection, then the
CQL query
+will be executed without binding parameters.
+* Any other body is bound as a single parameter, so a body that is left from
an earlier
step makes a query without parameters fail: clear the body first.
+To bind a `Map` as the value of a single marker, such as for a column of type
`map`,
+wrap it in a `List`.
+
Headers:
* `CamelCqlQuery` (optional, `String` or `SimpleStatement`): CQL query
either as a plain String or built using the `QueryBuilder`.
+A `SimpleStatement` carries its own values: the message body is not bound to
it.
==== Outgoing Message
@@ -220,6 +229,23 @@ At this point, you should be able to insert data by using
a list as body
Arrays.asList("davsclaus", "Claus", "Ibsen");
----
+With named markers, the values are taken by name from a `Map` body instead,
such as
+the body unmarshalled from the JSON object `{"login": "davsclaus",
"firstName": "Claus", "lastName": "Ibsen"}`:
+
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:input
+ steps:
+ - unmarshal:
+ json: {}
+ - to:
+ uri: cql://localhost/camel_ks
+ parameters:
+ cql: "insert into camel_user(login, first_name, last_name)
values (:login, :firstName, :lastName)"
+----
+
The same approach can be used for updating or querying the table.
For example, a query with `resultSetConversionStrategy` set to `ONE` returns a
single `Row`:
diff --git a/components/camel-cassandraql/src/main/docs/cql-component.adoc
b/components/camel-cassandraql/src/main/docs/cql-component.adoc
index f83b65b96766..7e3eb397619a 100644
--- a/components/camel-cassandraql/src/main/docs/cql-component.adoc
+++ b/components/camel-cassandraql/src/main/docs/cql-component.adoc
@@ -57,17 +57,26 @@ your own Cluster instance and give it to the Camel endpoint.
==== Incoming Message
-The Camel Cassandra endpoint expects a bunch of simple objects (`Object`
-or `Object[]` or `Collection<Object>`) which will be bound to the CQL
-statement as query parameters. If the message body is null, an empty array or
-an empty collection, then the CQL query will be executed without binding
parameters.
-Any other body is bound as a single parameter, so a body that is left from an
earlier
+The message body holds the values of the bind markers of the CQL statement:
+
+* A `Map` binds the named markers, such as `:login`, by name: each marker
takes the
+value of the `Map` entry of that name. The keys are matched ignoring case, as
CQL
+does for a name that is not quoted, and keys that the statement does not use
are
+ignored. A marker with no entry in the `Map` fails the message.
+* An `Object[]` or a `Collection<Object>` binds the `?` markers by position,
in order.
+* If the message body is null, an empty array or an empty collection, then the
CQL query
+will be executed without binding parameters.
+* Any other body is bound as a single parameter, so a body that is left from
an earlier
step makes a query without parameters fail: clear the body first.
+To bind a `Map` as the value of a single marker, such as for a column of type
`map`,
+wrap it in a `List`.
+
Headers:
* `CamelCqlQuery` (optional, `String` or `SimpleStatement`): CQL query
either as a plain String or built using the `QueryBuilder`.
+A `SimpleStatement` carries its own values: the message body is not bound to
it.
==== Outgoing Message
@@ -220,6 +229,23 @@ At this point, you should be able to insert data by using
a list as body
Arrays.asList("davsclaus", "Claus", "Ibsen");
----
+With named markers, the values are taken by name from a `Map` body instead,
such as
+the body unmarshalled from the JSON object `{"login": "davsclaus",
"firstName": "Claus", "lastName": "Ibsen"}`:
+
+[source,yaml]
+----
+- route:
+ from:
+ uri: direct:input
+ steps:
+ - unmarshal:
+ json: {}
+ - to:
+ uri: cql://localhost/camel_ks
+ parameters:
+ cql: "insert into camel_user(login, first_name, last_name)
values (:login, :firstName, :lastName)"
+----
+
The same approach can be used for updating or querying the table.
For example, a query with `resultSetConversionStrategy` set to `ONE` returns a
single `Row`:
diff --git
a/components/camel-cassandraql/src/main/java/org/apache/camel/component/cassandra/CassandraProducer.java
b/components/camel-cassandraql/src/main/java/org/apache/camel/component/cassandra/CassandraProducer.java
index bb3cbe351d3a..cd670fc87660 100644
---
a/components/camel-cassandraql/src/main/java/org/apache/camel/component/cassandra/CassandraProducer.java
+++
b/components/camel-cassandraql/src/main/java/org/apache/camel/component/cassandra/CassandraProducer.java
@@ -17,8 +17,11 @@
package org.apache.camel.component.cassandra;
import java.util.Collection;
+import java.util.LinkedHashMap;
+import java.util.Map;
import com.datastax.oss.driver.api.core.CqlSession;
+import com.datastax.oss.driver.api.core.cql.ColumnDefinitions;
import com.datastax.oss.driver.api.core.cql.PreparedStatement;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
@@ -32,7 +35,8 @@ import static
org.apache.camel.utils.cassandra.CassandraUtils.isEmpty;
* Cassandra 2 CQL3 producer.
* <dl>
* <dt>In Message</dt>
- * <dd>Bound parameters: Collection of Objects, Array of Objects, Simple Object
+ * <dd>Bound parameters: Map of named values (for named markers such as {@code
:login}), Collection of Objects, Array of
+ * Objects, Simple Object
* <dd>
* <dt>Out Message</dt>
* <dd>List of all Rows
@@ -95,14 +99,16 @@ public class CassandraProducer extends DefaultProducer {
if (messageCql instanceof String && ((String) messageCql).isEmpty()) {
messageCql = null;
}
- Object[] cqlParams = getCqlParams(message);
+ // a Map body binds the markers by name, any other body by position
+ Map<?, ?> namedParams = message.getBody() instanceof Map<?, ?> map ?
map : null;
+ Object[] cqlParams = namedParams == null ? getCqlParams(message) :
null;
ResultSet resultSet;
CqlSession session = getEndpoint().getSessionHolder().getSession();
if (isPrepareStatements()) {
- resultSet = executePreparedStatement(session, messageCql,
cqlParams);
+ resultSet = executePreparedStatement(session, messageCql,
cqlParams, namedParams);
} else {
- resultSet = executeStatement(session, messageCql, cqlParams);
+ resultSet = executeStatement(session, messageCql, cqlParams,
namedParams);
}
return resultSet;
}
@@ -110,7 +116,8 @@ public class CassandraProducer extends DefaultProducer {
/**
* Execute CQL as PreparedStatement
*/
- private ResultSet executePreparedStatement(CqlSession session, Object
messageCql, Object[] cqlParams) {
+ private ResultSet executePreparedStatement(
+ CqlSession session, Object messageCql, Object[] cqlParams, Map<?,
?> namedParams) {
ResultSet resultSet;
PreparedStatement lPreparedStatement;
if (messageCql == null) {
@@ -125,7 +132,9 @@ public class CassandraProducer extends DefaultProducer {
} else {
throw new IllegalArgumentException("Invalid " +
CassandraConstants.CQL_QUERY + " header");
}
- if (isEmpty(cqlParams)) {
+ if (namedParams != null) {
+ resultSet =
session.execute(lPreparedStatement.bind(namedValues(lPreparedStatement,
namedParams)));
+ } else if (isEmpty(cqlParams)) {
resultSet = session.execute(lPreparedStatement.bind());
} else {
resultSet = session.execute(lPreparedStatement.bind(cqlParams));
@@ -136,7 +145,7 @@ public class CassandraProducer extends DefaultProducer {
/**
* Execute CQL as is
*/
- private ResultSet executeStatement(CqlSession session, Object messageCql,
Object[] cqlParams) {
+ private ResultSet executeStatement(CqlSession session, Object messageCql,
Object[] cqlParams, Map<?, ?> namedParams) {
ResultSet resultSet = null;
String cql = null;
SimpleStatement statement = null;
@@ -154,6 +163,10 @@ public class CassandraProducer extends DefaultProducer {
}
if (statement != null) {
resultSet = session.execute(statement);
+ } else if (namedParams != null) {
+ Map<String, Object> values = new LinkedHashMap<>();
+ namedParams.forEach((name, value) ->
values.put(String.valueOf(name), value));
+ resultSet = session.execute(SimpleStatement.newInstance(cql,
values));
} else if (isEmpty(cqlParams)) {
resultSet = session.execute(cql);
} else {
@@ -163,6 +176,33 @@ public class CassandraProducer extends DefaultProducer {
return resultSet;
}
+ /**
+ * The values of the bind markers of a prepared statement, in order, taken
by name from the Map body.
+ */
+ private static Object[] namedValues(PreparedStatement statement, Map<?, ?>
namedParams) {
+ ColumnDefinitions markers = statement.getVariableDefinitions();
+ Object[] values = new Object[markers.size()];
+ for (int i = 0; i < values.length; i++) {
+ values[i] = namedValue(namedParams,
markers.get(i).getName().asInternal());
+ }
+ return values;
+ }
+
+ private static Object namedValue(Map<?, ?> namedParams, String name) {
+ if (namedParams.containsKey(name)) {
+ return namedParams.get(name);
+ }
+ // an unquoted marker such as :firstName is lower case in CQL, so
match the keys ignoring case
+ for (Map.Entry<?, ?> entry : namedParams.entrySet()) {
+ if (entry.getKey() != null &&
name.equalsIgnoreCase(entry.getKey().toString())) {
+ return entry.getValue();
+ }
+ }
+ throw new IllegalArgumentException(
+ "The Map body has no value for the bind marker :" + name + "
of the CQL statement. The keys of the body are: "
+ + namedParams.keySet());
+ }
+
@Override
public void process(Exchange exchange) throws Exception {
ResultSet resultSet = execute(exchange.getIn());
diff --git
a/components/camel-cassandraql/src/test/java/org/apache/camel/component/cassandra/integration/CassandraComponentProducerNamedIT.java
b/components/camel-cassandraql/src/test/java/org/apache/camel/component/cassandra/integration/CassandraComponentProducerNamedIT.java
new file mode 100644
index 000000000000..32777dd6be52
--- /dev/null
+++
b/components/camel-cassandraql/src/test/java/org/apache/camel/component/cassandra/integration/CassandraComponentProducerNamedIT.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.cassandra.integration;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import com.datastax.oss.driver.api.core.cql.Row;
+import org.apache.camel.CamelExecutionException;
+import org.apache.camel.Produce;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.cassandra.CassandraConstants;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A Map body binds the named markers (such as :login) of the CQL statement by
name.
+ */
+public class CassandraComponentProducerNamedIT extends BaseCassandra {
+
+ static final String CQL = "insert into camel_user(login, first_name,
last_name) values (:login, :firstName, :lastName)";
+
+ @Produce("direct:prepared")
+ ProducerTemplate prepared;
+
+ @Produce("direct:unprepared")
+ ProducerTemplate unprepared;
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ public void configure() {
+ from("direct:prepared").toF("cql://%s/%s?cql=%s", getUrl(),
KEYSPACE_NAME, CQL);
+ from("direct:unprepared")
+ .toF("cql://%s/%s?cql=%s&prepareStatements=false",
getUrl(), KEYSPACE_NAME, CQL);
+ }
+ };
+ }
+
+ private static Map<String, Object> user(String login, String firstName,
String lastName) {
+ // not in the order of the markers, and with a key the statement does
not use
+ Map<String, Object> body = new LinkedHashMap<>();
+ body.put("lastName", lastName);
+ body.put("city", "Rome");
+ body.put("firstName", firstName);
+ body.put("login", login);
+ return body;
+ }
+
+ private Row findUser(String login) {
+ return getSession().execute("select login, first_name, last_name from
camel_user where login = ?", login).one();
+ }
+
+ @Test
+ public void testPreparedBindsByName() {
+ prepared.requestBody(user("w_jiang", "Willem", "Jiang"));
+
+ Row row = findUser("w_jiang");
+ assertNotNull(row);
+ assertEquals("Willem", row.getString("first_name"));
+ assertEquals("Jiang", row.getString("last_name"));
+ }
+
+ @Test
+ public void testUnpreparedBindsByName() {
+ unprepared.requestBody(user("j_strachan", "James", "Strachan"));
+
+ Row row = findUser("j_strachan");
+ assertNotNull(row);
+ assertEquals("James", row.getString("first_name"));
+ assertEquals("Strachan", row.getString("last_name"));
+ }
+
+ @Test
+ public void testPreparedMessageCqlBindsByName() {
+ prepared.requestBodyAndHeader(Map.of("login", "c_ibsen", "first",
"Claus 2", "last", "Ibsen 2"),
+ CassandraConstants.CQL_QUERY, "update camel_user set
first_name=:first, last_name=:last where login=:login");
+
+ Row row = findUser("c_ibsen");
+ assertNotNull(row);
+ assertEquals("Claus 2", row.getString("first_name"));
+ assertEquals("Ibsen 2", row.getString("last_name"));
+ }
+
+ @Test
+ public void testPreparedMissingValueNamesTheMarker() {
+ Map<String, Object> body = Map.of("login", "g_nodet", "firstName",
"Guillaume");
+
+ CamelExecutionException e =
assertThrows(CamelExecutionException.class, () -> prepared.requestBody(body));
+
+ IllegalArgumentException cause =
assertInstanceOf(IllegalArgumentException.class, e.getCause());
+ assertTrue(cause.getMessage().contains(":lastname"),
cause.getMessage());
+ assertNull(findUser("g_nodet"));
+ }
+}
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 113492f57796..d16e9ab162e0 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -457,6 +457,12 @@ scopes are removed. Consequently, a token that has a
required scope only in `scp
`OAuthTokenValidationResult.hasScope(...)` check where it did not pass before.
Review authorization
rules that intentionally relied on ignoring `scp`.
+=== camel-cassandraql - a Map body binds the named markers
+
+The `cql` producer binds a `Map` body by name: each named marker of the
statement, such as `:login`,
+takes the value of the `Map` entry of that name. Before, a `Map` body was
bound as the value of a single
+marker. To keep that, such as for a column of type `map`, wrap the `Map` in a
`List`.
+
=== camel-mina-sftp - checking whether a file exists takes one lstat request
The `mina-sftp` component now checks whether a remote file exists
(`fileExist=Ignore|Fail|Move`, `tempFileName`,