Search in sources :

Example 6 with Statement

use of com.datastax.driver.core.Statement 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 {
        Statement stmt;
        stmt = QueryBuilder.delete().from(table).where(QueryBuilder.eq(YCSB_KEY, key));
        stmt.setConsistencyLevel(writeConsistencyLevel);
        if (debug) {
            System.out.println(stmt.toString());
        }
        if (trace) {
            stmt.enableTracing();
        }
        session.execute(stmt);
        return Status.OK;
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error deleting key: " + key);
    }
    return Status.ERROR;
}
Also used : SimpleStatement(com.datastax.driver.core.SimpleStatement) Statement(com.datastax.driver.core.Statement) DBException(com.yahoo.ycsb.DBException)

Example 7 with Statement

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

the class CassandraSessionImpl method execute.

/** {@inheritDoc} */
@Override
public void execute(BatchLoaderAssistant assistant) {
    int attempt = 0;
    String errorMsg = "Failed to execute Cassandra " + assistant.operationName() + " operation";
    Throwable error = new IgniteException(errorMsg);
    RandomSleeper sleeper = newSleeper();
    incrementSessionRefs();
    try {
        while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) {
            if (attempt != 0)
                log.warning("Trying " + (attempt + 1) + " attempt to load Ignite cache");
            Statement statement = tuneStatementExecutionOptions(assistant.getStatement());
            try {
                ResultSetFuture fut = session().executeAsync(statement);
                ResultSet resSet = fut.getUninterruptibly();
                if (resSet == null || !resSet.iterator().hasNext())
                    return;
                for (Row row : resSet) assistant.process(row);
                return;
            } catch (Throwable e) {
                error = e;
                if (CassandraHelper.isTableAbsenceError(e))
                    return;
                else if (CassandraHelper.isHostsAvailabilityError(e))
                    handleHostsAvailabilityError(e, attempt, errorMsg);
                else if (CassandraHelper.isPreparedStatementClusterError(e))
                    handlePreparedStatementClusterError(e);
                else
                    // For an error which we don't know how to handle, we will not try next attempts and terminate.
                    throw new IgniteException(errorMsg, e);
            }
            sleeper.sleep();
            attempt++;
        }
    } catch (Throwable e) {
        error = e;
    } finally {
        decrementSessionRefs();
    }
    log.error(errorMsg, error);
    throw new IgniteException(errorMsg, error);
}
Also used : ResultSetFuture(com.datastax.driver.core.ResultSetFuture) IgniteException(org.apache.ignite.IgniteException) PreparedStatement(com.datastax.driver.core.PreparedStatement) BoundStatement(com.datastax.driver.core.BoundStatement) BatchStatement(com.datastax.driver.core.BatchStatement) Statement(com.datastax.driver.core.Statement) ResultSet(com.datastax.driver.core.ResultSet) RandomSleeper(org.apache.ignite.cache.store.cassandra.common.RandomSleeper) Row(com.datastax.driver.core.Row)

Example 8 with Statement

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

the class CassandraSessionImpl method execute.

/** {@inheritDoc} */
@Override
public <R, V> R execute(BatchExecutionAssistant<R, V> assistant, Iterable<? extends V> data) {
    if (data == null || !data.iterator().hasNext())
        return assistant.processedData();
    int attempt = 0;
    String errorMsg = "Failed to execute Cassandra " + assistant.operationName() + " operation";
    Throwable error = new IgniteException(errorMsg);
    RandomSleeper sleeper = newSleeper();
    int dataSize = 0;
    incrementSessionRefs();
    try {
        while (attempt < CQL_EXECUTION_ATTEMPTS_COUNT) {
            if (attempt != 0) {
                log.warning("Trying " + (attempt + 1) + " attempt to execute Cassandra batch " + assistant.operationName() + " operation to process rest " + (dataSize - assistant.processedCount()) + " of " + dataSize + " elements");
            }
            //clean errors info before next communication with Cassandra
            Throwable unknownEx = null;
            Throwable tblAbsenceEx = null;
            Throwable hostsAvailEx = null;
            Throwable prepStatEx = null;
            List<Cache.Entry<Integer, ResultSetFuture>> futResults = new LinkedList<>();
            PreparedStatement preparedSt = prepareStatement(assistant.getTable(), assistant.getStatement(), assistant.getPersistenceSettings(), assistant.tableExistenceRequired());
            if (preparedSt == null)
                return null;
            int seqNum = 0;
            for (V obj : data) {
                if (!assistant.alreadyProcessed(seqNum)) {
                    try {
                        Statement statement = tuneStatementExecutionOptions(assistant.bindStatement(preparedSt, obj));
                        ResultSetFuture fut = session().executeAsync(statement);
                        futResults.add(new CacheEntryImpl<>(seqNum, fut));
                    } catch (Throwable e) {
                        if (CassandraHelper.isTableAbsenceError(e)) {
                            // If there are table absence error and it is not required for the operation we can return.
                            if (!assistant.tableExistenceRequired())
                                return assistant.processedData();
                            tblAbsenceEx = e;
                            handleTableAbsenceError(assistant.getTable(), assistant.getPersistenceSettings());
                        } else if (CassandraHelper.isHostsAvailabilityError(e)) {
                            hostsAvailEx = e;
                            // Handle host availability only once.
                            if (hostsAvailEx == null)
                                handleHostsAvailabilityError(e, attempt, errorMsg);
                        } else if (CassandraHelper.isPreparedStatementClusterError(e)) {
                            prepStatEx = e;
                            handlePreparedStatementClusterError(e);
                        } else
                            unknownEx = e;
                    }
                }
                seqNum++;
            }
            dataSize = seqNum;
            // For an error which we don't know how to handle, we will not try next attempts and terminate.
            if (unknownEx != null)
                throw new IgniteException(errorMsg, unknownEx);
            // Remembering any of last errors.
            if (tblAbsenceEx != null)
                error = tblAbsenceEx;
            else if (hostsAvailEx != null)
                error = hostsAvailEx;
            else if (prepStatEx != null)
                error = prepStatEx;
            // Clean errors info before next communication with Cassandra.
            unknownEx = null;
            tblAbsenceEx = null;
            hostsAvailEx = null;
            prepStatEx = null;
            for (Cache.Entry<Integer, ResultSetFuture> futureResult : futResults) {
                try {
                    ResultSet resSet = futureResult.getValue().getUninterruptibly();
                    Row row = resSet != null && resSet.iterator().hasNext() ? resSet.iterator().next() : null;
                    if (row != null)
                        assistant.process(row, futureResult.getKey());
                } catch (Throwable e) {
                    if (CassandraHelper.isTableAbsenceError(e))
                        tblAbsenceEx = e;
                    else if (CassandraHelper.isHostsAvailabilityError(e))
                        hostsAvailEx = e;
                    else if (CassandraHelper.isPreparedStatementClusterError(e))
                        prepStatEx = e;
                    else
                        unknownEx = e;
                }
            }
            // For an error which we don't know how to handle, we will not try next attempts and terminate.
            if (unknownEx != null)
                throw new IgniteException(errorMsg, unknownEx);
            // If there are no errors occurred it means that operation successfully completed and we can return.
            if (tblAbsenceEx == null && hostsAvailEx == null && prepStatEx == null)
                return assistant.processedData();
            if (tblAbsenceEx != null) {
                // If there are table absence error and it is not required for the operation we can return.
                if (!assistant.tableExistenceRequired())
                    return assistant.processedData();
                error = tblAbsenceEx;
                handleTableAbsenceError(assistant.getTable(), assistant.getPersistenceSettings());
            }
            if (hostsAvailEx != null) {
                error = hostsAvailEx;
                handleHostsAvailabilityError(hostsAvailEx, attempt, errorMsg);
            }
            if (prepStatEx != null) {
                error = prepStatEx;
                handlePreparedStatementClusterError(prepStatEx);
            }
            if (!CassandraHelper.isTableAbsenceError(error))
                sleeper.sleep();
            attempt++;
        }
    } catch (Throwable e) {
        error = e;
    } finally {
        decrementSessionRefs();
    }
    errorMsg = "Failed to process " + (dataSize - assistant.processedCount()) + " of " + dataSize + " elements, during " + assistant.operationName() + " operation with Cassandra";
    log.error(errorMsg, error);
    throw new IgniteException(errorMsg, error);
}
Also used : ResultSetFuture(com.datastax.driver.core.ResultSetFuture) PreparedStatement(com.datastax.driver.core.PreparedStatement) BoundStatement(com.datastax.driver.core.BoundStatement) BatchStatement(com.datastax.driver.core.BatchStatement) Statement(com.datastax.driver.core.Statement) PreparedStatement(com.datastax.driver.core.PreparedStatement) LinkedList(java.util.LinkedList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgniteException(org.apache.ignite.IgniteException) ResultSet(com.datastax.driver.core.ResultSet) RandomSleeper(org.apache.ignite.cache.store.cassandra.common.RandomSleeper) Row(com.datastax.driver.core.Row) Cache(javax.cache.Cache)

Example 9 with Statement

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

the class CassandraCacheStore method loadCache.

/** {@inheritDoc} */
@Override
public void loadCache(IgniteBiInClosure<K, V> clo, Object... args) throws CacheLoaderException {
    if (clo == null)
        return;
    if (args == null || args.length == 0)
        args = new String[] { "select * from " + controller.getPersistenceSettings().getKeyspace() + "." + cassandraTable() + ";" };
    ExecutorService pool = null;
    Collection<Future<?>> futs = new ArrayList<>(args.length);
    try {
        pool = Executors.newFixedThreadPool(maxPoolSize, new IgniteThreadFactory(ignite.name(), CACHE_LOADER_THREAD_NAME));
        CassandraSession ses = getCassandraSession();
        for (Object obj : args) {
            LoadCacheCustomQueryWorker<K, V> task = null;
            if (obj instanceof Statement)
                task = new LoadCacheCustomQueryWorker<>(ses, (Statement) obj, controller, log, clo);
            else if (obj instanceof String) {
                String qry = ((String) obj).trim();
                if (qry.toLowerCase().startsWith("select"))
                    task = new LoadCacheCustomQueryWorker<>(ses, (String) obj, controller, log, clo);
            }
            if (task != null)
                futs.add(pool.submit(task));
        }
        for (Future<?> fut : futs) U.get(fut);
        if (log != null && log.isDebugEnabled() && storeSes != null)
            log.debug("Cache loaded from db: " + storeSes.cacheName());
    } catch (IgniteCheckedException e) {
        if (storeSes != null)
            throw new CacheLoaderException("Failed to load Ignite cache: " + storeSes.cacheName(), e.getCause());
        else
            throw new CacheLoaderException("Failed to load cache", e.getCause());
    } finally {
        U.shutdownNow(getClass(), pool, log);
    }
}
Also used : PreparedStatement(com.datastax.driver.core.PreparedStatement) BoundStatement(com.datastax.driver.core.BoundStatement) Statement(com.datastax.driver.core.Statement) ArrayList(java.util.ArrayList) CassandraSession(org.apache.ignite.cache.store.cassandra.session.CassandraSession) IgniteThreadFactory(org.apache.ignite.thread.IgniteThreadFactory) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) LoadCacheCustomQueryWorker(org.apache.ignite.cache.store.cassandra.session.LoadCacheCustomQueryWorker) CacheLoaderException(javax.cache.integration.CacheLoaderException) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future)

Example 10 with Statement

use of com.datastax.driver.core.Statement in project cassandra-driver-mapping by valchkou.

the class MappingSession method save.

/**
     * Save Entity. If Entity has @Version field, in attempt to save not the
     * latest version null is returned.
     * 
     * @param entity
     * @param options WriteOptions
     * @return ResultSetFuture.
     */
public <E> E save(E entity, WriteOptions options) {
    maybeSync(entity.getClass());
    Statement stmt = MappingBuilder.prepareSave(entity, options, keyspace);
    ResultSet rs = session.execute(stmt);
    EntityTypeMetadata entityMetadata = EntityTypeParser.getEntityMetadata(entity.getClass());
    if (entityMetadata.hasVersion()) {
        Row row = rs.one();
        if (!(row != null && rs.wasApplied())) {
            return null;
        }
    }
    return entity;
}
Also used : EntityTypeMetadata(com.datastax.driver.mapping.meta.EntityTypeMetadata) RegularStatement(com.datastax.driver.core.RegularStatement) PreparedStatement(com.datastax.driver.core.PreparedStatement) BoundStatement(com.datastax.driver.core.BoundStatement) BuiltStatement(com.datastax.driver.core.querybuilder.BuiltStatement) Statement(com.datastax.driver.core.Statement) ResultSet(com.datastax.driver.core.ResultSet) Row(com.datastax.driver.core.Row)

Aggregations

Statement (com.datastax.driver.core.Statement)19 BoundStatement (com.datastax.driver.core.BoundStatement)9 PreparedStatement (com.datastax.driver.core.PreparedStatement)9 ResultSet (com.datastax.driver.core.ResultSet)7 Row (com.datastax.driver.core.Row)7 BatchStatement (com.datastax.driver.core.BatchStatement)6 RegularStatement (com.datastax.driver.core.RegularStatement)6 SimpleStatement (com.datastax.driver.core.SimpleStatement)5 ArrayList (java.util.ArrayList)5 ResultSetFuture (com.datastax.driver.core.ResultSetFuture)4 List (java.util.List)4 DBException (com.yahoo.ycsb.DBException)3 IgniteException (org.apache.ignite.IgniteException)3 RandomSleeper (org.apache.ignite.cache.store.cassandra.common.RandomSleeper)3 ColumnDefinitions (com.datastax.driver.core.ColumnDefinitions)2 BuiltStatement (com.datastax.driver.core.querybuilder.BuiltStatement)2 Select (com.datastax.driver.core.querybuilder.Select)2 ByteArrayByteIterator (com.yahoo.ycsb.ByteArrayByteIterator)2 ByteBuffer (java.nio.ByteBuffer)2 FailedException (org.apache.storm.topology.FailedException)2