Search in sources :

Example 81 with PreparedStatement

use of com.datastax.driver.core.PreparedStatement in project ignite by apache.

the class CassandraSessionImplTest method mockPreparedStatement.

/**
 */
private static PreparedStatement mockPreparedStatement() {
    PreparedStatement ps = mock(PreparedStatement.class);
    when(ps.getVariables()).thenReturn(mock(ColumnDefinitions.class));
    when(ps.getPreparedId()).thenReturn(mock(PreparedId.class));
    when(ps.getQueryString()).thenReturn("insert into xxx");
    return ps;
}
Also used : PreparedId(com.datastax.driver.core.PreparedId) ColumnDefinitions(com.datastax.driver.core.ColumnDefinitions) PreparedStatement(com.datastax.driver.core.PreparedStatement) WrappedPreparedStatement(org.apache.ignite.cache.store.cassandra.session.WrappedPreparedStatement)

Example 82 with PreparedStatement

use of com.datastax.driver.core.PreparedStatement in project beam by apache.

the class ReadFn method processElement.

@ProcessElement
public void processElement(@Element Read<T> read, OutputReceiver<T> receiver) {
    try {
        Session session = ConnectionManager.getSession(read);
        Mapper<T> mapper = read.mapperFactoryFn().apply(session);
        String partitionKey = session.getCluster().getMetadata().getKeyspace(read.keyspace().get()).getTable(read.table().get()).getPartitionKey().stream().map(ColumnMetadata::getName).collect(Collectors.joining(","));
        String query = generateRangeQuery(read, partitionKey, read.ringRanges() != null);
        PreparedStatement preparedStatement = session.prepare(query);
        Set<RingRange> ringRanges = read.ringRanges() == null ? Collections.emptySet() : read.ringRanges().get();
        for (RingRange rr : ringRanges) {
            Token startToken = session.getCluster().getMetadata().newToken(rr.getStart().toString());
            Token endToken = session.getCluster().getMetadata().newToken(rr.getEnd().toString());
            ResultSet rs = session.execute(preparedStatement.bind().setToken(0, startToken).setToken(1, endToken));
            Iterator<T> iter = mapper.map(rs);
            while (iter.hasNext()) {
                T n = iter.next();
                receiver.output(n);
            }
        }
        if (read.ringRanges() == null) {
            ResultSet rs = session.execute(preparedStatement.bind());
            Iterator<T> iter = mapper.map(rs);
            while (iter.hasNext()) {
                receiver.output(iter.next());
            }
        }
    } catch (Exception ex) {
        LOG.error("error", ex);
    }
}
Also used : ResultSet(com.datastax.driver.core.ResultSet) PreparedStatement(com.datastax.driver.core.PreparedStatement) Token(com.datastax.driver.core.Token) Session(com.datastax.driver.core.Session)

Example 83 with PreparedStatement

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

the class CassandraCQLClient method insert.

/**
 * Insert 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.
 *
 * @param table
 *          The name of the table
 * @param key
 *          The record key of the record to insert.
 * @param values
 *          A HashMap of field/value pairs to insert in the record
 * @return Zero on success, a non-zero error code on error
 */
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
    try {
        Set<String> fields = values.keySet();
        PreparedStatement stmt = insertStmts.get(fields);
        // Prepare statement on demand
        if (stmt == null) {
            Insert insertStmt = QueryBuilder.insertInto(table);
            // Add key
            insertStmt.value(YCSB_KEY, QueryBuilder.bindMarker());
            // Add fields
            for (String field : fields) {
                insertStmt.value(field, QueryBuilder.bindMarker());
            }
            stmt = session.prepare(insertStmt);
            stmt.setConsistencyLevel(writeConsistencyLevel);
            if (trace) {
                stmt.enableTracing();
            }
            PreparedStatement prevStmt = insertStmts.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 key
        BoundStatement boundStmt = stmt.bind().setString(0, key);
        // Add fields
        ColumnDefinitions vars = stmt.getVariables();
        for (int i = 1; i < vars.size(); i++) {
            boundStmt.setString(i, values.get(vars.getName(i)).toString());
        }
        session.execute(boundStmt);
        return Status.OK;
    } catch (Exception e) {
        logger.error(MessageFormatter.format("Error inserting 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) Insert(com.datastax.driver.core.querybuilder.Insert) 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 84 with PreparedStatement

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

the class CassandraCQLClient method read.

/**
 * Read a record from the database. Each field/value pair from the result will
 * be stored in a HashMap.
 *
 * @param table
 *          The name of the table
 * @param key
 *          The record key of the record to read.
 * @param fields
 *          The list of fields to read, or null for all of them
 * @param result
 *          A HashMap of field/value pairs for the result
 * @return Zero on success, a non-zero error code on error
 */
@Override
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
    try {
        PreparedStatement stmt = (fields == null) ? readAllStmt.get() : readStmts.get(fields);
        // Prepare statement on demand
        if (stmt == null) {
            Select.Builder selectBuilder;
            if (fields == null) {
                selectBuilder = QueryBuilder.select().all();
            } else {
                selectBuilder = QueryBuilder.select();
                for (String col : fields) {
                    ((Select.Selection) selectBuilder).column(col);
                }
            }
            stmt = session.prepare(selectBuilder.from(table).where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker())).limit(1));
            stmt.setConsistencyLevel(readConsistencyLevel);
            if (trace) {
                stmt.enableTracing();
            }
            PreparedStatement prevStmt = (fields == null) ? readAllStmt.getAndSet(stmt) : readStmts.putIfAbsent(new HashSet(fields), stmt);
            if (prevStmt != null) {
                stmt = prevStmt;
            }
        }
        logger.debug(stmt.getQueryString());
        logger.debug("key = {}", key);
        ResultSet rs = session.execute(stmt.bind(key));
        if (rs.isExhausted()) {
            return Status.NOT_FOUND;
        }
        // Should be only 1 row
        Row row = rs.one();
        ColumnDefinitions cd = row.getColumnDefinitions();
        for (ColumnDefinitions.Definition def : cd) {
            ByteBuffer val = row.getBytesUnsafe(def.getName());
            if (val != null) {
                result.put(def.getName(), new ByteArrayByteIterator(val.array()));
            } else {
                result.put(def.getName(), null);
            }
        }
        return Status.OK;
    } catch (Exception e) {
        logger.error(MessageFormatter.format("Error reading key: {}", key).getMessage(), e);
        return Status.ERROR;
    }
}
Also used : ColumnDefinitions(com.datastax.driver.core.ColumnDefinitions) PreparedStatement(com.datastax.driver.core.PreparedStatement) ByteBuffer(java.nio.ByteBuffer) DBException(site.ycsb.DBException) ByteArrayByteIterator(site.ycsb.ByteArrayByteIterator) Select(com.datastax.driver.core.querybuilder.Select) ResultSet(com.datastax.driver.core.ResultSet) Row(com.datastax.driver.core.Row) HashSet(java.util.HashSet)

Example 85 with PreparedStatement

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

the class CassandraCQLClient method delete.

/**
 * Delete a record from the database.
 *
 * @param table
 *          The name of the table
 * @param key
 *          The record key of the record to delete.
 * @return Zero on success, a non-zero error code on error
 */
@Override
public Status delete(String table, String key) {
    try {
        PreparedStatement stmt = deleteStmt.get();
        // Prepare statement on demand
        if (stmt == null) {
            stmt = session.prepare(QueryBuilder.delete().from(table).where(QueryBuilder.eq(YCSB_KEY, QueryBuilder.bindMarker())));
            stmt.setConsistencyLevel(writeConsistencyLevel);
            if (trace) {
                stmt.enableTracing();
            }
            PreparedStatement prevStmt = deleteStmt.getAndSet(stmt);
            if (prevStmt != null) {
                stmt = prevStmt;
            }
        }
        logger.debug(stmt.getQueryString());
        logger.debug("key = {}", key);
        session.execute(stmt.bind(key));
        return Status.OK;
    } catch (Exception e) {
        logger.error(MessageFormatter.format("Error deleting key: {}", key).getMessage(), e);
    }
    return Status.ERROR;
}
Also used : PreparedStatement(com.datastax.driver.core.PreparedStatement) DBException(site.ycsb.DBException)

Aggregations

PreparedStatement (com.datastax.driver.core.PreparedStatement)113 ResultSet (com.datastax.driver.core.ResultSet)60 BoundStatement (com.datastax.driver.core.BoundStatement)59 Session (com.datastax.driver.core.Session)39 Test (org.junit.Test)30 Row (com.datastax.driver.core.Row)27 InvalidQueryException (com.datastax.driver.core.exceptions.InvalidQueryException)27 XMLStreamException (javolution.xml.stream.XMLStreamException)25 PersistenceException (org.mobicents.smsc.cassandra.PersistenceException)15 Cluster (com.datastax.driver.core.Cluster)9 Date (java.util.Date)9 IInvokableInstance (org.apache.cassandra.distributed.api.IInvokableInstance)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 Map (java.util.Map)7 QueryProcessor (org.apache.cassandra.cql3.QueryProcessor)7 GOSSIP (org.apache.cassandra.distributed.api.Feature.GOSSIP)7 NATIVE_PROTOCOL (org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL)7 NETWORK (org.apache.cassandra.distributed.api.Feature.NETWORK)7 ICluster (org.apache.cassandra.distributed.api.ICluster)7