com.datastax.oss.driver.api.core.cql.BoundStatement Java Examples

The following examples show how to use com.datastax.oss.driver.api.core.cql.BoundStatement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CQLKeyColumnValueStore.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
BatchableStatement<BoundStatement> insertColumn(StaticBuffer key, Entry entry, long timestamp) {
    Integer ttl = (Integer) entry.getMetaData().get(EntryMetaData.TTL);
    if (ttl != null) {
        return this.insertColumnWithTTL.bind()
                .setByteBuffer(KEY_BINDING, key.asByteBuffer())
                .setByteBuffer(COLUMN_BINDING, entry.getColumn().asByteBuffer())
                .setByteBuffer(VALUE_BINDING, entry.getValue().asByteBuffer())
                .setLong(TIMESTAMP_BINDING, timestamp)
                .setInt(TTL_BINDING, ttl);
    }
    return this.insertColumn.bind()
            .setByteBuffer(KEY_BINDING, key.asByteBuffer())
            .setByteBuffer(COLUMN_BINDING, entry.getColumn().asByteBuffer())
            .setByteBuffer(VALUE_BINDING, entry.getValue().asByteBuffer())
            .setLong(TIMESTAMP_BINDING, timestamp);
}
 
Example #2
Source File: AbstractStatementFactory.java    From casquatch with Apache License 2.0 5 votes vote down vote up
/**
 * Produce a bound statement while applying object and query options
 * @param buildableQuery buildable query
 * @param obj populated object
 * @param queryOptions query options to apply
 * @param bindToSession override session
 * @return bound statement
 */
protected BoundStatement buildBoundStatement(BuildableQuery buildableQuery, Object obj, QueryOptions queryOptions, CqlSession bindToSession) {
    if(buildableQuery instanceof Select) {
        if(queryOptions!=null) {
            if(queryOptions.getLimit()!=null) {
                buildableQuery = ((Select) buildableQuery).limit(queryOptions.getLimit());
            }
        }
    }
    else if (buildableQuery instanceof RegularInsert) {
        if(queryOptions.getTtl()!=null) {
            buildableQuery = ((RegularInsert) buildableQuery).usingTtl(queryOptions.getTtl());
        }
    }
    SimpleStatement simpleStatement = buildableQuery.build();

    if(log.isTraceEnabled()) log.trace("Preparing Statement {}",simpleStatement.getQuery());
    BoundStatementBuilder boundStatementBuilder = bindToSession.prepare(simpleStatement).boundStatementBuilder();
    if(obj.getClass().equals(this.entityClass)) {
        //noinspection unchecked
        boundStatementBuilder=bindObject(boundStatementBuilder,(E) obj,queryOptions);
    }
    else if (obj.getClass().equals(SolrQueryEntity.class)) {
        //noinspection unchecked
        boundStatementBuilder=bindObject(boundStatementBuilder,(SolrQueryEntity) obj,queryOptions);
    }
    else {
        throw new DriverException(DriverException.CATEGORIES.CASQUATCH_MISSING_GENERATED_CLASS, "Unknown class");
    }
    if(queryOptions!=null) {
        if (queryOptions.getConsistencyLevel() != null) {
            boundStatementBuilder = boundStatementBuilder.setConsistencyLevel(queryOptions.getConsistencyLevel());
        }
        if (queryOptions.getProfile() != null) {
            boundStatementBuilder = boundStatementBuilder.setExecutionProfileName(queryOptions.getProfile());
        }
    }
    return boundStatementBuilder.build();
}
 
Example #3
Source File: ScannerImpl.java    From jesterj with Apache License 2.0 5 votes vote down vote up
@Override
public void activate() {
  super.activate();
  if (isRemembering() || isHashing()) {
    CqlSession session = getCassandra().getSession();
    List<DocKey> strandedDocs = new ArrayList<>();
    PreparedStatement preparedQuery = getCassandra().getPreparedQuery(RESET_PROCESSING_Q);
    BoundStatement statement =  preparedQuery.bind(getName());
    ResultSet procRs = session.execute(statement);
    strandedDocs.addAll(procRs.all().stream()
        .map((row) -> new DocKey(row.getString(0), row.getString(1))).collect(Collectors.toList()));
    preparedQuery = getCassandra().getPreparedQuery(RESET_ERROR_Q);
    statement = preparedQuery.bind(getName());
    ResultSet errorRs = session.execute(statement);
    strandedDocs.addAll(errorRs.all().stream()
        .map((row) -> new DocKey(row.getString(0), row.getString(1))).collect(Collectors.toList()));
    preparedQuery = getCassandra().getPreparedQuery(RESET_BATCHED_Q);
    statement = preparedQuery.bind(getName());
    ResultSet batchedRs = session.execute(statement);
    strandedDocs.addAll(batchedRs.all().stream()
        .map((row) -> new DocKey(row.getString(0), row.getString(1))).collect(Collectors.toList()));

    preparedQuery = getCassandra().getPreparedQuery(RESET_DOCS_U);
    // todo: batch
    for (DocKey docId : strandedDocs) {
      statement = preparedQuery.bind(docId.docid, docId.scanner);
      session.execute(statement);
    }

  }
}
 
Example #4
Source File: ScannerImpl.java    From jesterj with Apache License 2.0 5 votes vote down vote up
@Override
public void sendToNext(Document doc) {
  if (isRemembering()) {
    CqlSession session = getCassandra().getSession();
    PreparedStatement preparedQuery = getCassandra().getPreparedQuery(UPDATE_HASH_U);
    BoundStatement bind = preparedQuery.bind(doc.getHash(), doc.getId(), doc.getSourceScannerName());
    session.execute(bind);
  }
  superSendToNext(doc);
}
 
Example #5
Source File: VideoRepository.java    From tutorials with MIT License 5 votes vote down vote up
public UUID insertVideo(Video video, String keyspace) {
    UUID videoId = UUID.randomUUID();

    video.setId(videoId);

    RegularInsert insertInto = QueryBuilder.insertInto(TABLE_NAME)
      .value("video_id", QueryBuilder.bindMarker())
      .value("title", QueryBuilder.bindMarker())
      .value("creation_date", QueryBuilder.bindMarker());

    SimpleStatement insertStatement = insertInto.build();

    if (keyspace != null) {
        insertStatement = insertStatement.setKeyspace(keyspace);
    }

    PreparedStatement preparedStatement = session.prepare(insertStatement);

    BoundStatement statement = preparedStatement.bind()
      .setUuid(0, video.getId())
      .setString(1, video.getTitle())
      .setInstant(2, video.getCreationDate());

    session.execute(statement);

    return videoId;
}
 
Example #6
Source File: DynamoDSETranslatorJSONBlob.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
private boolean matchesFilterExpression(Map<String, AttributeValue> itemSet, QueryRequest payload) {

        String filterExpression = payload.getFilterExpression();
        Matcher matcher = queryPattern.matcher(filterExpression);
                if (matcher.find())
        {
            BoundStatement boundStatement = null;

            for (int i =0; i < matcher.groupCount();i = i+2) {
                Map<String, AttributeValue> expressionAtributeValues = payload.getExpressionAttributeValues();

                String attributeName = matcher.group(i + 1);
                AttributeValue itemAttributeValue = itemSet.get(attributeName);

                JsonNode valueJson = awsRequestMapper.valueToTree(itemAttributeValue);
                Comparable<Object> itemValue = (Comparable<Object>) getObjectFromJsonLeaf(valueJson.fields().next());

                AttributeValue expressionAttributeValue = expressionAtributeValues.get(attributeName);

                valueJson = awsRequestMapper.valueToTree(expressionAttributeValue);
                Comparable<Object> expressionValue = (Comparable<Object>) getObjectFromJsonLeaf(valueJson.fields().next());

                String operator = matcher.group(i + 2);

                switch (operator) {
                    case "=":
                        return itemValue.equals(expressionValue);
                    case "!=":
                        return !itemValue.equals(expressionValue);
                    case "<=":
                        return itemValue.compareTo(expressionValue) <= 0;
                    case "<":
                        return itemValue.compareTo(expressionValue) < 0;
                    case ">=":
                        return itemValue.compareTo(expressionValue) >= 0;
                    case ">":
                        return itemValue.compareTo(expressionValue) > 0;
                }
            }
        }
        throw new UnsupportedOperationException("Error parsing filter expression: " + filterExpression);

    }
 
Example #7
Source File: DynamoDSETranslatorJSONBlob.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
@Override
public DynamoDBResponse deleteItem(DeleteItemRequest dir) {
    logger.debug("delete item into JSON table");
    String tableName = dir.getTableName();
    TableDef tableDef = cassandraManager.getTableDef(tableName);

    PreparedStatement deleteStatement = tableDef.getDeleteStatement();

    AttributeDefinition partitionKeyAttr = tableDef.getPartitionKey();
    Optional<AttributeDefinition> maybeCusteringKeyAttr = tableDef.getClusteringKey();

    Map<String, AttributeValue> keys = dir.getKey();

    Object partitionKeyValue = getAttributeObject(
            ScalarAttributeType.fromValue(partitionKeyAttr.getAttributeType()),
            keys.get(partitionKeyAttr.getAttributeName())
    );

    BoundStatement boundStatement;

    if (maybeCusteringKeyAttr.isPresent())
    {
        Object clusteringKeyValue = getAttributeObject(
                ScalarAttributeType.fromValue(maybeCusteringKeyAttr.get().getAttributeType()),
                keys.get(maybeCusteringKeyAttr.get().getAttributeName())
        );

        boundStatement = deleteStatement.bind(partitionKeyValue, clusteringKeyValue);
    }
    else
    {
        boundStatement = deleteStatement.bind(partitionKeyValue);
    }

    ResultSet result = session().execute(boundStatement);

    if (result.wasApplied()){
        DeleteItemResult dres = new DeleteItemResult();
        return new DynamoDBResponse(dres, 200);
    }
    else return null;

}
 
Example #8
Source File: DynamoDSETranslatorJSONBlob.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
@Override
public DynamoDBResponse getItem(GetItemRequest getItemRequest) {
    logger.debug("get item from JSON table");

    String tableName = getItemRequest.getTableName();
    TableDef tableDef = cassandraManager.getTableDef(tableName);
    PreparedStatement selectStatement = tableDef.getQueryRowStatement();

    AttributeDefinition partitionKeyDef = tableDef.getPartitionKey();
    Optional<AttributeDefinition> clusteringKeyDef = tableDef.getClusteringKey();

    Map<String, AttributeValue> keys = getItemRequest.getKey();

    AttributeValue partitionKey = keys.get(partitionKeyDef.getAttributeName());
    AttributeValue clusteringKey = clusteringKeyDef.isPresent() ?
            keys.get(clusteringKeyDef.get().getAttributeName()) : null;

    ScalarAttributeType partitionKeyType = ScalarAttributeType.valueOf(partitionKeyDef.getAttributeType());
    ScalarAttributeType clusteringKeyType = clusteringKeyDef.isPresent() ?
            ScalarAttributeType.valueOf(clusteringKeyDef.get().getAttributeType()) : null;

    BoundStatement boundStatement = clusteringKey == null ?
            selectStatement.bind(getAttributeObject(partitionKeyType, partitionKey)) :
            selectStatement.bind(getAttributeObject(partitionKeyType, partitionKey),
                    getAttributeObject(clusteringKeyType, clusteringKey));

    ResultSet result = session().execute(boundStatement);

    GetItemResult gir = new GetItemResult();
    Map<String, AttributeValue> item = new HashMap<>();
    ColumnDefinitions colDefs = result.getColumnDefinitions();

    Row row = result.one();

    //Case that nothing is found
    if (row == null)
        return new DynamoDBResponse(null, 200);

    Map<String, AttributeValue> keysSet = new HashMap<>();
    for (ColumnDefinition colDef : colDefs)
    {
        if (colDef.getName().asInternal().equals("json_blob"))
            continue;

        keysSet.put(colDef.getName().asInternal(), rowToAV(colDef, row));
    }

    try
    {
        item = blobToItemSet(row.getString("json_blob"));
        item.putAll(keysSet);

        gir.withItem(item);
        return new DynamoDBResponse(gir, 200);
    } catch (IOException e) {
        DynamoDBResponse ddbResponse = new DynamoDBResponse(gir, 500);
        String msg = String.format("GetItem failed", getItemRequest.getTableName());
        ddbResponse.setError(msg);
        return ddbResponse;
    }
}
 
Example #9
Source File: Cassandra4Test.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
private static void createKeyspace(final CqlSession session) {
  final PreparedStatement prepared = session.prepare("CREATE keyspace test WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1};");
  final BoundStatement bound = prepared.bind();
  session.execute(bound);
}
 
Example #10
Source File: CQLKeyColumnValueStore.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
BatchableStatement<BoundStatement> deleteColumn(StaticBuffer key, StaticBuffer column, long timestamp) {
    return this.deleteColumn.bind()
            .setByteBuffer(KEY_BINDING, key.asByteBuffer())
            .setByteBuffer(COLUMN_BINDING, column.asByteBuffer())
            .setLong(TIMESTAMP_BINDING, timestamp);
}
 
Example #11
Source File: AbstractStatementFactory.java    From casquatch with Apache License 2.0 2 votes vote down vote up
/**
 * Create a count statement for an object
 *
 * Example: select count(*) from TABLE where KEY=?
 *
 * @param obj partially populated object
 * @param queryOptions query options to apply
 * @return bound statement for the query
 */
public BoundStatement count(E obj, QueryOptions queryOptions) {
    return buildBoundStatement(selectWhereObject(selectCountStart, obj, queryOptions),obj, queryOptions, this.session);
}
 
Example #12
Source File: AbstractStatementFactory.java    From casquatch with Apache License 2.0 2 votes vote down vote up
/**
 * Create a count statement for a solr query
 *
 * Example: select count(*) from TABLE where solr_query=?
 *
 * @param solrQuery solrQuery to search
 * @param queryOptions query options to apply
 * @return bound statement for the query
 */
public BoundStatement countSolr(String solrQuery, QueryOptions queryOptions) {
    return buildBoundStatement(selectSolrCountStart,new SolrQueryEntity(solrQuery), queryOptions, this.session);
}
 
Example #13
Source File: AbstractStatementFactory.java    From casquatch with Apache License 2.0 2 votes vote down vote up
/**
 * Create a delete statement for an object
 *
 * Example: delete from TABLE where KEY=?
 *
 * @param obj partially populated object
 * @param queryOptions query options to apply
 * @return bound statement for the query
 */
public BoundStatement delete(E obj, QueryOptions queryOptions) {
    return buildBoundStatement(deleteObject(obj, queryOptions), obj,queryOptions,this.session);
}
 
Example #14
Source File: AbstractStatementFactory.java    From casquatch with Apache License 2.0 2 votes vote down vote up
/**
 * Create a get statement for an object
 *
 * Example: select [COL1...COLN] from TABLE where KEY=?
 *
 * @param obj partially populated object
 * @param queryOptions query options to apply
 * @return bound statement for the query
 */
public BoundStatement get(E obj, QueryOptions queryOptions) {
    return buildBoundStatement(selectWhereObject(selectAllStart, obj, queryOptions), obj,queryOptions,this.session);
}
 
Example #15
Source File: AbstractStatementFactory.java    From casquatch with Apache License 2.0 2 votes vote down vote up
/**
 * Create a get statement for a solr query
 *
 * Example: select [COL1...COLN] from TABLE where solr_query=?
 *
 * @param solrQuery solr query
 * @param queryOptions query options to apply
 * @return bound statement for the query
 */
public BoundStatement getSolr(String solrQuery, QueryOptions queryOptions) {
    return buildBoundStatement(selectSolrStart,new SolrQueryEntity(solrQuery),queryOptions,this.session);
}
 
Example #16
Source File: AbstractStatementFactory.java    From casquatch with Apache License 2.0 2 votes vote down vote up
/**
 * Create a save statement for an object
 *
 * Example: INSERE INTO TABLE ([COL1..COLN]) VALUES([?..?])
 *
 * @param obj partially populated object
 * @param queryOptions query options to apply
 * @return simple statement for the query
 */
public BoundStatement save(E obj, QueryOptions queryOptions) {
    return buildBoundStatement(insertObject(obj,queryOptions),obj, queryOptions,this.session);
}