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

The following examples show how to use com.datastax.oss.driver.api.core.cql.PreparedStatement. 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: 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 #2
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 #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: CassandraSupport.java    From jesterj with Apache License 2.0 5 votes vote down vote up
/**
 * Retreive a prepared statement added via {@link #addStatement(String, String)}. This method will block until
 * cassandra has finished booting, a session has been created and the statement has been prepared.
 *
 * @param qName the name of the statement to retrieve
 * @return the prepared statement ready for use.
 */
public PreparedStatement getPreparedQuery(String qName) {
  try {
    return preparedQueries.get(qName).get();
  } catch (InterruptedException | ExecutionException e) {
    throw new RuntimeException(e);
  }
}
 
Example #5
Source File: CassandraManager.java    From dynamo-cassandra-proxy with Apache License 2.0 5 votes vote down vote up
public PreparedStatement getPutStatement(String tableName) {
    TableDef tableDef = tableDefs.get(tableName);
    if (tableDef == null){
        logger.error(String.format("Table %s does not exist", tableName));
        return null;
    }
    return tableDefs.get(tableName).getJsonPutStatement();
}
 
Example #6
Source File: CassandraStatements.java    From dynamo-cassandra-proxy with Apache License 2.0 5 votes vote down vote up
public PreparedStatement prepare(String stmt) {
    String withKeyspace = stmt.replaceAll(KEYSPACE_PATTERN, this.keyspace);
    String withReplication = withKeyspace.replaceAll(REPLICATION_STRATEGY_PATTERN, this.replicationStrategy);
    PreparedStatement prepared = session.prepare(withReplication);

    return prepared;
}
 
Example #7
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public PreparedStatement getLazyJsonQueryPartitionAndClusteringStatement(ComparisonOperator comparisonOperator) {

        PreparedStatement preparedStatment = null;

        if (jsonQueryRangeStatementMap.containsKey(comparisonOperator)){
            preparedStatment = jsonQueryRangeStatementMap.get(comparisonOperator);
        }
        else{
            String clustering = "\"" + clusteringKey.get().getAttributeName() + "\"";
            String partition= "\"" + partitionKey.getAttributeName() + "\"";
            Select select = selectFrom(keyspaceName, tableName).all().whereColumn(partition).isEqualTo(bindMarker());
            switch (comparisonOperator) {
                case EQ:
                    preparedStatment = session.prepare(select.whereColumn(clustering).isEqualTo(bindMarker()).build());
                    break;
                case NE:
                    preparedStatment = session.prepare(select.whereColumn(clustering).isNotEqualTo(bindMarker()).build());
                    break;
                case IN:
                    preparedStatment = session.prepare(select.whereColumn(clustering).in(bindMarker()).build());
                    break;
                case LE:
                    preparedStatment = session.prepare(select.whereColumn(clustering).isLessThanOrEqualTo(bindMarker()).build());
                    break;
                case LT:
                    preparedStatment = session.prepare(select.whereColumn(clustering).isLessThan(bindMarker()).build());
                    break;
                case GE:
                    preparedStatment = session.prepare(select.whereColumn(clustering).isGreaterThanOrEqualTo(bindMarker()).build());
                    break;
                case GT:
                    preparedStatment = session.prepare(select.whereColumn(clustering).isGreaterThan(bindMarker()).build());
                    break;
                case BETWEEN:
                    preparedStatment = session.prepare(select
                            .whereColumn(clustering).isGreaterThanOrEqualTo(bindMarker())
                            .whereColumn(clustering).isLessThanOrEqualTo(bindMarker())
                            .build()
                    );
                    break;
                case NOT_NULL:
                    preparedStatment = session.prepare(select
                            .whereColumn(clustering).isNotNull()
                            .build()
                    );
                    break;
                case NULL:
                    throw new UnsupportedOperationException("CQL does not support null clustering columns");
                case CONTAINS:
                    throw new UnsupportedOperationException("Contains - feature unsupported");
                case NOT_CONTAINS:
                    throw new UnsupportedOperationException("Not Contains - feature unsupported");
                case BEGINS_WITH:
                    throw new UnsupportedOperationException("Begins With - feature unsupported");
            }
        }
        return preparedStatment;
    }
 
Example #8
Source File: ScannerImpl.java    From jesterj with Apache License 2.0 4 votes vote down vote up
/**
 * What to do when a document has been recognized as required for indexing.
 *
 * @param doc The document to be processed
 */
public void docFound(Document doc) {
  log.trace("{} found doc: {}", getName(), doc.getId());
  String id = doc.getId();
  Function<String, String> idFunction = getIdFunction();
  String result = idFunction.apply(id);
  String idField = doc.getIdField();
  doc.removeAll(idField);
  doc.put(idField, result);

  id = doc.getId();
  String status = null;
  String md5 = null;
  if (isRemembering()) {
    PreparedStatement preparedQuery = getCassandra().getPreparedQuery(FTI_CHECK_Q);
    CqlSession session = getCassandra().getSession();
    ResultSet statusRs = session.execute(preparedQuery.bind(id, getName()));
    if (statusRs.getAvailableWithoutFetching() > 0) {
      if (statusRs.getAvailableWithoutFetching() > 1 || !statusRs.isFullyFetched()) {
        log.error("FATAL: duplicate primary keys in cassandra table??");
        throw new RuntimeException("VERY BAD: duplicate primary keys in FTI table?");
      } else {
        Row next = statusRs.all().iterator().next();
        status = next.getString(0);
        log.trace("Found '{}' with status {}", id, status);
        if (isHashing()) {
          md5 = next.getString(1);
        }
      }
    }
  }
  // written with negated and's so I can defer doc.getHash() until we are sure we
  // need to check the hash.
  if (isRemembering() &&                                         // easier to read, let jvm optimize this check out
      status != null &&                                          // A status was found so we have seen this before
      Status.valueOf(status) != Status.DIRTY &&                  // not marked dirty
      !heuristicDirty(doc)                                       // not dirty by subclass logic
      ) {
    if (!isHashing()) {
      log.trace("{} ignoring previously seen document {}", getName(), id);
      return;
    }
    if (md5 != null) {
      String hash = doc.getHash();
      if (md5.equals(hash)) {
        log.trace("{} ignoring document with previously seen content {}", getName(), id);
        return;
      }
    }
  }
  sendToNext(doc);
}
 
Example #9
Source File: CassandraClientImpl.java    From vertx-cassandra-client with Apache License 2.0 4 votes vote down vote up
@Override
public Future<PreparedStatement> prepare(String query) {
  return getSession(vertx.getOrCreateContext())
    .flatMap(session -> Future.fromCompletionStage(session.prepareAsync(query), vertx.getContext()));
}
 
Example #10
Source File: CassandraClientImpl.java    From vertx-cassandra-client with Apache License 2.0 4 votes vote down vote up
@Override
public CassandraClient prepare(String query, Handler<AsyncResult<PreparedStatement>> resultHandler) {
  Future<PreparedStatement> future = prepare(query);
  setHandler(future, resultHandler);
  return this;
}
 
Example #11
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 #12
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 #13
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public void setQueryRowStatement(PreparedStatement queryRowStatement) {
    this.queryRowStatement = queryRowStatement;
}
 
Example #14
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public void setDeleteStatement(PreparedStatement deleteStatement) {
    this.deleteStatement = deleteStatement;
}
 
Example #15
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public PreparedStatement getDeleteStatement() {
    return deleteStatement;
}
 
Example #16
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public void setJsonQueryPartitionStatement(PreparedStatement jsonQueryPartitionStatement) {
    this.jsonQueryPartitionStatement = jsonQueryPartitionStatement;
}
 
Example #17
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public PreparedStatement getJsonQueryPartitionStatement() {
    return jsonQueryPartitionStatement;
}
 
Example #18
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public void setJsonPutStatement(PreparedStatement jsonPutStatement) {
    this.jsonPutStatement = jsonPutStatement;
}
 
Example #19
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public PreparedStatement getJsonPutStatement() {
    return jsonPutStatement;
}
 
Example #20
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public void setJsonQueryRowStatement(PreparedStatement jsonQueryRowStatement) {
    this.jsonQueryRowStatement = jsonQueryRowStatement;
}
 
Example #21
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public PreparedStatement getJsonQueryRowStatement() {
    return jsonQueryRowStatement;
}
 
Example #22
Source File: TableDef.java    From dynamo-cassandra-proxy with Apache License 2.0 4 votes vote down vote up
public PreparedStatement getQueryRowStatement() {
    return queryRowStatement;
}
 
Example #23
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 #24
Source File: CassandraClient.java    From vertx-cassandra-client with Apache License 2.0 2 votes vote down vote up
/**
 * Prepares the provided query string.
 *
 * @param resultHandler handler called when result of query preparation is present
 * @param query the query to prepare
 *
 * @return current Cassandra client instance
 */
@GenIgnore(GenIgnore.PERMITTED_TYPE)
@Fluent
CassandraClient prepare(String query, Handler<AsyncResult<PreparedStatement>> resultHandler);
 
Example #25
Source File: CassandraClient.java    From vertx-cassandra-client with Apache License 2.0 2 votes vote down vote up
/**
 * Like {@link #prepare(String, Handler)} but returns a {@code Future} of the asynchronous result.
 */
@GenIgnore(GenIgnore.PERMITTED_TYPE)
Future<PreparedStatement> prepare(String query);