Search in sources :

Example 1 with Update

use of com.datastax.driver.core.querybuilder.Update in project camel by apache.

the class CassandraComponentProducerTest method testRequestMessageStatement.

/**
     * Test with incoming message containing a header with RegularStatement.
     */
@Test
public void testRequestMessageStatement() throws Exception {
    if (!canTest()) {
        return;
    }
    Update.Where update = update("camel_user").with(set("first_name", bindMarker())).and(set("last_name", bindMarker())).where(eq("login", bindMarker()));
    Object response = producerTemplate.requestBodyAndHeader(new Object[] { "Claus 2", "Ibsen 2", "c_ibsen" }, CassandraConstants.CQL_QUERY, update);
    Cluster cluster = CassandraUnitUtils.cassandraCluster();
    Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
    ResultSet resultSet = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
    Row row = resultSet.one();
    assertNotNull(row);
    assertEquals("Claus 2", row.getString("first_name"));
    assertEquals("Ibsen 2", row.getString("last_name"));
    session.close();
    cluster.close();
}
Also used : ResultSet(com.datastax.driver.core.ResultSet) Cluster(com.datastax.driver.core.Cluster) Row(com.datastax.driver.core.Row) Update(com.datastax.driver.core.querybuilder.Update) Session(com.datastax.driver.core.Session) Test(org.junit.Test)

Example 2 with Update

use of com.datastax.driver.core.querybuilder.Update in project camel by apache.

the class CassandraComponentProducerUnpreparedTest method testRequestMessageStatement.

/**
     * Test with incoming message containing a header with RegularStatement.
     */
@Test
public void testRequestMessageStatement() throws Exception {
    Update.Where update = update("camel_user").with(set("first_name", "Claus 2")).and(set("last_name", "Ibsen 2")).where(eq("login", "c_ibsen"));
    Object response = producerTemplate.requestBodyAndHeader(null, CassandraConstants.CQL_QUERY, update);
    Cluster cluster = CassandraUnitUtils.cassandraCluster();
    Session session = cluster.connect(CassandraUnitUtils.KEYSPACE);
    ResultSet resultSet = session.execute("select login, first_name, last_name from camel_user where login = ?", "c_ibsen");
    Row row = resultSet.one();
    assertNotNull(row);
    assertEquals("Claus 2", row.getString("first_name"));
    assertEquals("Ibsen 2", row.getString("last_name"));
    session.close();
    cluster.close();
}
Also used : ResultSet(com.datastax.driver.core.ResultSet) Cluster(com.datastax.driver.core.Cluster) Row(com.datastax.driver.core.Row) Update(com.datastax.driver.core.querybuilder.Update) Session(com.datastax.driver.core.Session) Test(org.junit.Test)

Example 3 with Update

use of com.datastax.driver.core.querybuilder.Update in project YCSB by brianfrankcooper.

the class CassandraCQLClient method update.

/**
 * Update a record in the database. Any field/value pairs in the specified
 * values HashMap will be written into the record with the specified record
 * key, overwriting any existing values with the same field name.
 *
 * @param table
 *          The name of the table
 * @param key
 *          The record key of the record to write.
 * @param values
 *          A HashMap of field/value pairs to update in the record
 * @return Zero on success, a non-zero error code on error
 */
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
    try {
        Set<String> fields = values.keySet();
        PreparedStatement stmt = updateStmts.get(fields);
        // Prepare statement on demand
        if (stmt == null) {
            Update updateStmt = QueryBuilder.update(table);
            // Add fields
            for (String field : fields) {
                updateStmt.with(QueryBuilder.set(field, QueryBuilder.bindMarker()));
            }
            // Add key
            updateStmt.where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker()));
            stmt = session.prepare(updateStmt);
            stmt.setConsistencyLevel(writeConsistencyLevel);
            if (trace) {
                stmt.enableTracing();
            }
            PreparedStatement prevStmt = updateStmts.putIfAbsent(new HashSet(fields), stmt);
            if (prevStmt != null) {
                stmt = prevStmt;
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug(stmt.getQueryString());
            logger.debug("key = {}", key);
            for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
                logger.debug("{} = {}", entry.getKey(), entry.getValue());
            }
        }
        // Add fields
        ColumnDefinitions vars = stmt.getVariables();
        BoundStatement boundStmt = stmt.bind();
        for (int i = 0; i < vars.size() - 1; i++) {
            boundStmt.setString(i, values.get(vars.getName(i)).toString());
        }
        // Add key
        boundStmt.setString(vars.size() - 1, key);
        session.execute(boundStmt);
        return Status.OK;
    } catch (Exception e) {
        logger.error(MessageFormatter.format("Error updating key: {}", key).getMessage(), e);
    }
    return Status.ERROR;
}
Also used : ColumnDefinitions(com.datastax.driver.core.ColumnDefinitions) ByteIterator(site.ycsb.ByteIterator) ByteArrayByteIterator(site.ycsb.ByteArrayByteIterator) PreparedStatement(com.datastax.driver.core.PreparedStatement) Update(com.datastax.driver.core.querybuilder.Update) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) BoundStatement(com.datastax.driver.core.BoundStatement) DBException(site.ycsb.DBException) HashSet(java.util.HashSet)

Example 4 with Update

use of com.datastax.driver.core.querybuilder.Update in project gora by apache.

the class CassandraQueryFactory method getUpdateByQueryForNative.

/**
 * This method returns the CQL Query for UpdateByQuery method
 * refer : http://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlUpdate.html
 *
 * @param mapping        Cassandra mapping {@link CassandraMapping}
 * @param cassandraQuery Cassandra Query {@link CassandraQuery}
 * @param objects        field Objects list
 * @return CQL Query
 */
static String getUpdateByQueryForNative(CassandraMapping mapping, Query cassandraQuery, List<Object> objects) {
    Update update = QueryBuilder.update(mapping.getKeySpace().getName(), mapping.getCoreName());
    Update.Assignments updateAssignments = null;
    if (cassandraQuery instanceof CassandraQuery) {
        String[] columnNames = getColumnNames(mapping, Arrays.asList(cassandraQuery.getFields()));
        for (String column : columnNames) {
            updateAssignments = update.with(QueryBuilder.set(column, "?"));
            objects.add(((CassandraQuery) cassandraQuery).getUpdateFieldValue(mapping.getFieldFromColumnName(column).getFieldName()));
        }
    } else {
        throw new RuntimeException("Please use Cassandra Query object to invoke, UpdateByQuery method.");
    }
    return processQuery(cassandraQuery, updateAssignments, mapping, objects);
}
Also used : CassandraQuery(org.apache.gora.cassandra.query.CassandraQuery) Update(com.datastax.driver.core.querybuilder.Update)

Example 5 with Update

use of com.datastax.driver.core.querybuilder.Update in project gora by apache.

the class CassandraQueryFactory method getUpdateByQueryForAvro.

/**
 * This method returns the CQL Query for UpdateByQuery method
 * refer : http://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlUpdate.html
 *
 * @param mapping        Cassandra mapping {@link CassandraMapping}
 * @param cassandraQuery Cassandra Query {@link CassandraQuery}
 * @param objects        field Objects list
 * @return CQL Query
 */
static String getUpdateByQueryForAvro(CassandraMapping mapping, Query cassandraQuery, List<Object> objects, Schema schema) {
    Update update = QueryBuilder.update(mapping.getKeySpace().getName(), mapping.getCoreName());
    Update.Assignments updateAssignments = null;
    if (cassandraQuery instanceof CassandraQuery) {
        String[] columnNames = getColumnNames(mapping, Arrays.asList(cassandraQuery.getFields()));
        for (String column : columnNames) {
            updateAssignments = update.with(QueryBuilder.set(column, "?"));
            Field field = mapping.getFieldFromColumnName(column);
            Object value = ((CassandraQuery) cassandraQuery).getUpdateFieldValue(field.getFieldName());
            try {
                Schema schemaField = schema.getField(field.getFieldName()).schema();
                objects.add(AvroCassandraUtils.getFieldValueFromAvroBean(schemaField, schemaField.getType(), value, field));
            } catch (NullPointerException e) {
                throw new RuntimeException(field + " field couldn't find in the class " + mapping.getPersistentClass() + ".");
            }
        }
    } else {
        throw new RuntimeException("Please use Cassandra Query object to invoke, UpdateByQuery method.");
    }
    return processQuery(cassandraQuery, updateAssignments, mapping, objects);
}
Also used : Field(org.apache.gora.cassandra.bean.Field) ClusterKeyField(org.apache.gora.cassandra.bean.ClusterKeyField) PartitionKeyField(org.apache.gora.cassandra.bean.PartitionKeyField) CassandraQuery(org.apache.gora.cassandra.query.CassandraQuery) Schema(org.apache.avro.Schema) Update(com.datastax.driver.core.querybuilder.Update)

Aggregations

Update (com.datastax.driver.core.querybuilder.Update)7 ResultSet (com.datastax.driver.core.ResultSet)4 Row (com.datastax.driver.core.Row)4 Cluster (com.datastax.driver.core.Cluster)3 Session (com.datastax.driver.core.Session)3 Test (org.junit.Test)3 CassandraQuery (org.apache.gora.cassandra.query.CassandraQuery)2 BoundStatement (com.datastax.driver.core.BoundStatement)1 ColumnDefinitions (com.datastax.driver.core.ColumnDefinitions)1 PagingIterable (com.datastax.driver.core.PagingIterable)1 PreparedStatement (com.datastax.driver.core.PreparedStatement)1 Insert (com.datastax.driver.core.querybuilder.Insert)1 QueryBuilder (com.datastax.driver.core.querybuilder.QueryBuilder)1 Select (com.datastax.driver.core.querybuilder.Select)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 IUserContext (com.kloia.eventapis.api.IUserContext)1 IdCreationStrategy (com.kloia.eventapis.api.IdCreationStrategy)1 Views (com.kloia.eventapis.api.Views)1 UUIDCreationStrategy (com.kloia.eventapis.api.impl.UUIDCreationStrategy)1