I am trying to transform a SimpleStatement to CQL.
RegularInsert regularStatement = ...;
Map<String, Object> namedValues = new HashMap<>();
namedValues.put("a", "Hello");
namedValues.put("b", 1);
SimpleStatement statement = regularStatement.build(namedValues);
System.out.println(statement.getQuery());
System.out.println(statement.getNamedValues()); // Map<CqlIdentifier, Object>
Returns:
INSERT INTO keyspace.table (a,b) VALUES (?,?)
{a=Hello, b=1}
Which is fine, but I also need the final CQL query:
INSERT INTO keyspace.table (a,b) VALUES ('Hello',1)
I tried to bind named values to RegularInsert first, which I can use to get the CQL raw string with asCql(), and then build a SimpleStatement. But it is not working as I expected:
RegularInsert regularStatement = statementInsertWithKeyspace(database.getDatabaseName());
// Transform <String> to literal <Term>
Map<String, Term> literalNamedValues = namedValues.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> literal(e.getValue())));
regularStatement = regularStatement.values(literalNamedValues);
System.out.println(regularStatement.asCql());
SimpleStatement statement = regularStatement.values(literalNamedValues).build();
System.out.println(statement.getQuery());
System.out.println(statement.getNamedValues()); // Map<CqlIdentifier, Object>
Returns:
INSERT INTO keyspace.table (a,b) VALUES ('Hello',1)
INSERT INTO keyspace.table (a,b) VALUES ('Hello',1)
{}
How can I get the raw CQL from SimpleStatement, while preserving the CQL template (without values)?
Thank you.
Diving into, it seems that one Statement doesn't hold the bound value AND the template. The Values come from an ImmutableMap which means, once you build() the query or set the values(), the "?" get irrevokably replaced by the actual values. So if you need both 'at once', then your best bet seems to be using two Statement-Objects, one bound and one unbound.
RegularInsert regularStatement = ...;
Map<String, Object> namedValues = new HashMap<>();
namedValues.put("a", "Hello");
namedValues.put("b", 1);
// both build() and values() create new Objects
SimpleStatement statement = regularStatement.build(namedValues);
String boundStatement = regularStatement.values(namedValues).asCql();
System.out.println(statement.getQuery());
System.out.println(statement.getNamedValues()); // Map<CqlIdentifier, Object>
System.out.println(boundStatement);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With