com.datastax.driver.core.schemabuilder.SchemaBuilder Java Examples

The following examples show how to use com.datastax.driver.core.schemabuilder.SchemaBuilder. 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: SessionWithInitializedTablesFactoryTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void createSessionShouldKeepTheSetSchemaVersionWhenTypesAndTablesHavePartiallyChanged() {
    Session session = testee.get();
    assertThat(versionManager(session).computeVersion().block())
            .isEqualTo(MAX_VERSION);

    new CassandraTableManager(MODULE, session).clearAllTables();
    versionManagerDAO(session).updateVersion(MIN_VERSION);
    assertThat(versionManager(session).computeVersion().block())
            .isEqualTo(MIN_VERSION);
    session.execute(SchemaBuilder.dropTable(TABLE_NAME));
    session.execute(SchemaBuilder.dropType(TYPE_NAME));

    assertThat(versionManager(testee.get()).computeVersion().block())
            .isEqualTo(MIN_VERSION);
}
 
Example #2
Source File: CQLStashTableDAO.java    From emodb with Apache License 2.0 5 votes vote down vote up
private void ensureStashTokenRangeTableExists() {
    if (!_verifiedStashTokenRangeTableExists) {
        synchronized(this) {
            if (!_verifiedStashTokenRangeTableExists) {
                // Primary key is ((stash_id, data_center), placement, range_token, is_start_token).
                // Note that Cassandra performs unsigned byte comparison for "range_token" and sorts False before
                // True for "is_start_token".  The latter is necessary because it sorts two tables with
                // adjacent UUIDs correctly, returning the exclusive "to" token for the previous table before the
                // inclusive "from" token for the next table.
                _placementCache.get(_systemTablePlacement)
                        .getKeyspace()
                        .getCqlSession()
                        .execute(SchemaBuilder.createTable(STASH_TOKEN_RANGE_TABLE)
                                .ifNotExists()
                                .addPartitionKey(STASH_ID_COLUMN, DataType.text())
                                .addPartitionKey(DATA_CENTER_COLUMN, DataType.text())
                                .addClusteringColumn(PLACEMENT_COLUMN, DataType.text())
                                .addClusteringColumn(RANGE_TOKEN_COLUMN, DataType.blob())
                                .addClusteringColumn(IS_START_TOKEN_COLUMN, DataType.cboolean())
                                .addColumn(TABLE_JSON_COLUMN, DataType.text())
                                .withOptions()
                                // The following cluster orders should be the defaults but for clarity let's be explicit
                                .clusteringOrder(PLACEMENT_COLUMN, SchemaBuilder.Direction.ASC)
                                .clusteringOrder(RANGE_TOKEN_COLUMN, SchemaBuilder.Direction.ASC)
                                .clusteringOrder(IS_START_TOKEN_COLUMN, SchemaBuilder.Direction.ASC)
                                .compactStorage()
                                .defaultTimeToLive(TTL));

                _verifiedStashTokenRangeTableExists = true;
            }
        }
    }
}
 
Example #3
Source File: CassandraOperations.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteAll() throws Exception {
  state.tableExistsCache.clear();
  state.preparedRangeReadsPerTable.clear();
  state.preparedRowReadPerTable.clear();
  state.preparedWritesPerTable.clear();
  session.execute(SchemaBuilder.dropKeyspace(gwNamespace).ifExists());
}
 
Example #4
Source File: CassandraOperations.java    From geowave with Apache License 2.0 5 votes vote down vote up
public void initKeyspace() {
  // TODO consider exposing important keyspace options through commandline
  // such as understanding how to properly enable cassandra in production
  // - with data centers and snitch, for now because this is only creating
  // a keyspace "if not exists" a user can create a keyspace matching
  // their geowave namespace with any settings they want manually
  session.execute(
      SchemaBuilder.createKeyspace(gwNamespace).ifNotExists().with().replication(
          ImmutableMap.of(
              "class",
              "SimpleStrategy",
              "replication_factor",
              options.getReplicationFactor())).durableWrites(options.isDurableWrites()));
}
 
Example #5
Source File: CassandraPersistWriter.java    From streams with Apache License 2.0 5 votes vote down vote up
private void createKeyspaceAndTable() {
  Metadata metadata = client.cluster().getMetadata();
  if (Objects.isNull(metadata.getKeyspace(config.getKeyspace()))) {
    LOGGER.info("Keyspace {} does not exist. Creating Keyspace", config.getKeyspace());
    Map<String, Object> replication = new HashMap<>();
    replication.put("class", "SimpleStrategy");
    replication.put("replication_factor", 1);

    String createKeyspaceStmt = SchemaBuilder.createKeyspace(config.getKeyspace()).with()
        .replication(replication).getQueryString();
    client.cluster().connect().execute(createKeyspaceStmt);
  }

  session = client.cluster().connect(config.getKeyspace());

  KeyspaceMetadata ks = metadata.getKeyspace(config.getKeyspace());
  TableMetadata tableMetadata = ks.getTable(config.getTable());

  if (Objects.isNull(tableMetadata)) {
    LOGGER.info("Table {} does not exist in Keyspace {}. Creating Table", config.getTable(), config.getKeyspace());
    String createTableStmt = SchemaBuilder.createTable(config.getTable())
                              .addPartitionKey(config.getPartitionKeyColumn(), DataType.varchar())
                              .addColumn(config.getColumn(), DataType.blob()).getQueryString();

    session.execute(createTableStmt);
  }
}
 
Example #6
Source File: CassandraTypeProviderTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void initializeTypesShouldCreateTheTypes() {
    cassandra.getConf().execute(SchemaBuilder.dropType(TYPE_NAME));

    assertThat(new CassandraTypesCreator(MODULE, cassandra.getConf()).initializeTypes())
        .isEqualByComparingTo(CassandraType.InitializationStatus.FULL);

    CassandraTypesProvider cassandraTypesProviderTest = new CassandraTypesProvider(MODULE, cassandra.getConf());
    assertThat(cassandraTypesProviderTest.getDefinedUserType(TYPE_NAME))
        .isNotNull();
}
 
Example #7
Source File: CassandraTypesCreatorTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void initializeTypesShouldCreateTheMissingType() {
    cassandra.getConf().execute(SchemaBuilder.dropType(TYPE_NAME_1));

    assertThat(new CassandraTypesCreator(MODULE, cassandra.getConf()).initializeTypes())
            .isEqualByComparingTo(CassandraType.InitializationStatus.PARTIAL);

    CassandraTypesProvider cassandraTypesProviderTest = new CassandraTypesProvider(MODULE, cassandra.getConf());
    assertThat(cassandraTypesProviderTest.getDefinedUserType(TYPE_NAME_1))
            .isNotNull();
}
 
Example #8
Source File: CassandraTypesCreatorTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void initializeTypesShouldCreateTheAllTypes() {
    cassandra.getConf().execute(SchemaBuilder.dropType(TYPE_NAME_1));
    cassandra.getConf().execute(SchemaBuilder.dropType(TYPE_NAME_2));

    assertThat(new CassandraTypesCreator(MODULE, cassandra.getConf()).initializeTypes())
            .isEqualByComparingTo(CassandraType.InitializationStatus.FULL);

    CassandraTypesProvider cassandraTypesProviderTest = new CassandraTypesProvider(MODULE, cassandra.getConf());
    assertThat(cassandraTypesProviderTest.getDefinedUserType(TYPE_NAME_1))
            .isNotNull();
    assertThat(cassandraTypesProviderTest.getDefinedUserType(TYPE_NAME_2))
            .isNotNull();
}
 
Example #9
Source File: CassandraTableManagerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void initializeTableShouldCreateAllTheMissingTable() {
    cassandra.getConf().execute(SchemaBuilder.dropTable(TABLE_NAME));

    assertThat(new CassandraTableManager(MODULE, cassandra.getConf()).initializeTables())
            .isEqualByComparingTo(CassandraTable.InitializationStatus.PARTIAL);

    ensureTableExistence(TABLE_NAME);
}
 
Example #10
Source File: CassandraTableManagerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void initializeTableShouldCreateAllTheTables() {
    cassandra.getConf().execute(SchemaBuilder.dropTable(TABLE_NAME));
    cassandra.getConf().execute(SchemaBuilder.dropTable(CassandraSchemaVersionTable.TABLE_NAME));

    assertThat(new CassandraTableManager(MODULE, cassandra.getConf()).initializeTables())
            .isEqualByComparingTo(CassandraTable.InitializationStatus.FULL);

    ensureTableExistence(TABLE_NAME);
}
 
Example #11
Source File: DockerCassandra.java    From james-project with Apache License 2.0 5 votes vote down vote up
public void dropKeyspace(String keyspace) {
    try (Cluster cluster = ClusterFactory.create(cassandra.superUserConfigurationBuilder().build())) {
        try (Session cassandraSession = cluster.newSession()) {
            boolean applied = cassandraSession.execute(
                SchemaBuilder.dropKeyspace(keyspace)
                    .ifExists())
                .wasApplied();

            if (!applied) {
                throw new IllegalStateException("cannot drop keyspace '" + keyspace + "'");
            }
        }
    }
}
 
Example #12
Source File: CassandraModule.java    From james-project with Apache License 2.0 5 votes vote down vote up
public Builder statement(Function<Create, Create> toCreateStatement) {
    Preconditions.checkState(comment.isPresent(), "`comment` is compulsory");

    Create createStatement = toCreateStatement.apply(
        SchemaBuilder.createTable(tableName)
            .ifNotExists());

    return originalBuilderReference.addTable(
        new CassandraTable(tableName,
            options.orElse(Function.identity())
                .apply(createStatement.withOptions().comment(comment.get()))));
}
 
Example #13
Source File: KeyspaceFactory.java    From james-project with Apache License 2.0 5 votes vote down vote up
public static void createKeyspace(KeyspaceConfiguration configuration, Cluster cluster) {
    try (Session session = cluster.connect()) {
        if (!keyspaceExist(cluster, configuration.getKeyspace())) {
            session.execute(SchemaBuilder.createKeyspace(configuration.getKeyspace())
                .with()
                .replication(ImmutableMap.<String, Object>builder()
                    .put("class", "SimpleStrategy")
                    .put("replication_factor", configuration.getReplicationFactor())
                    .build())
                .durableWrites(configuration.isDurableWrites()));
        }
    }
}
 
Example #14
Source File: CassandraDatabase.java    From modernmt with Apache License 2.0 5 votes vote down vote up
/**
 * This method establishes a new connection to the DB
 * and drops the current keyspace (with all its tables).
 * If the keyspace has already been dropped, the method does nothing.
 *
 * @throws PersistenceException
 */
public void drop() throws PersistenceException {
    CassandraConnection connection = null;

    try {
        connection = new CassandraConnection(this.cluster, null);
        DropKeyspace dropKeyspace = SchemaBuilder.dropKeyspace('"' + this.keyspace + '"').ifExists();
        CassandraUtils.checkedExecute(connection, dropKeyspace);

    } catch (KeyspaceNotFoundException e) {
        /*ignore*/
    } finally {
        IOUtils.closeQuietly(connection);
    }
}
 
Example #15
Source File: TestDataDao.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
public void createKeySpace() {
    Map<String, Object> replication = new HashMap<>();

    replication.put("class", "SimpleStrategy");
    replication.put("replication_factor", 3);

    String statement = SchemaBuilder.createKeyspace(KEY_SPACE)
            .ifNotExists()
            .with()
            .replication(replication).getQueryString();

    LOG.info("Executing {}", statement);

    session.execute(statement);
}
 
Example #16
Source File: AdaptiveResultSetTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@AfterClass
public void tearDown() {
    if (!_runTests) {
        return;
    }
    _session.execute(SchemaBuilder.dropKeyspace(_keyspaceName));
    _session.close();
    _cluster.close();
}
 
Example #17
Source File: CassandraBaseDAO.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getCreateKeyspaceStatement() {
    return SchemaBuilder.createKeyspace(config.getCassandraKeyspace())
        .ifNotExists()
        .with()
        .replication(ImmutableMap.of("class", config.getReplicationStrategy(), config.getReplicationFactorKey(),
            config.getReplicationFactorValue()))
        .durableWrites(true)
        .getQueryString();
}
 
Example #18
Source File: TestDataDao.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
public void createTable() {
    String statement = SchemaBuilder.createTable(TABLE_NAME)
            .addPartitionKey("id", DataType.timeuuid())
            .addClusteringColumn("text", DataType.text())
            .getQueryString();

    LOG.info("Executing create table {}", statement);

    session.execute(statement);
}
 
Example #19
Source File: TestDataDao.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
public void dropTable() {
    String statement = SchemaBuilder.dropTable(TABLE_NAME)
            .getQueryString();

    LOG.info("Executing drop table {}", statement);

    session.execute(statement);
}
 
Example #20
Source File: CassandraTable.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
protected void createIndex(CassandraSessionPool.Session session,
                           String indexLabel, HugeKeys column) {
    String indexName = joinTableName(this.table(), indexLabel);
    SchemaStatement index = SchemaBuilder.createIndex(indexName)
                                         .ifNotExists()
                                         .onTable(this.table())
                                         .andColumn(formatKey(column));
    LOG.debug("Create index: {}", index);
    session.execute(index);
}
 
Example #21
Source File: CassandraStore.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
protected void initKeyspace() {
    Statement stmt = SchemaBuilder.createKeyspace(this.keyspace)
                                  .ifNotExists().with()
                                  .replication(parseReplica(this.conf));
    // Create keyspace with non-keyspace-session
    LOG.debug("Create keyspace: {}", stmt);
    Session session = this.cluster().connect();
    try {
        session.execute(stmt);
    } finally {
        if (!session.isClosed()) {
            session.close();
        }
    }
}
 
Example #22
Source File: CassandraStore.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
protected void clearKeyspace() {
    // Drop keyspace with non-keyspace-session
    Statement stmt = SchemaBuilder.dropKeyspace(this.keyspace).ifExists();
    LOG.debug("Drop keyspace: {}", stmt);

    Session session = this.cluster().connect();
    try {
        session.execute(stmt);
    } finally {
        if (!session.isClosed()) {
            session.close();
        }
    }
}
 
Example #23
Source File: CassandraBaseDAO.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getCreateEventExecutionsTableStatement() {
    return SchemaBuilder.createTable(config.getCassandraKeyspace(), TABLE_EVENT_EXECUTIONS)
        .ifNotExists()
        .addPartitionKey(MESSAGE_ID_KEY, DataType.text())
        .addPartitionKey(EVENT_HANDLER_NAME_KEY, DataType.text())
        .addClusteringColumn(EVENT_EXECUTION_ID_KEY, DataType.text())
        .addColumn(PAYLOAD_KEY, DataType.text())
        .getQueryString();
}
 
Example #24
Source File: CassandraBaseDAO.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getCreateWorkflowsTableStatement() {
    return SchemaBuilder.createTable(config.getCassandraKeyspace(), TABLE_WORKFLOWS)
        .ifNotExists()
        .addPartitionKey(WORKFLOW_ID_KEY, DataType.uuid())
        .addPartitionKey(SHARD_ID_KEY, DataType.cint())
        .addClusteringColumn(ENTITY_KEY, DataType.text())
        .addClusteringColumn(TASK_ID_KEY, DataType.text())
        .addColumn(PAYLOAD_KEY, DataType.text())
        .addStaticColumn(TOTAL_TASKS_KEY, DataType.cint())
        .addStaticColumn(TOTAL_PARTITIONS_KEY, DataType.cint())
        .getQueryString();
}
 
Example #25
Source File: CassandraBaseDAO.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getCreateTaskLookupTableStatement() {
    return SchemaBuilder.createTable(config.getCassandraKeyspace(), TABLE_TASK_LOOKUP)
        .ifNotExists()
        .addPartitionKey(TASK_ID_KEY, DataType.uuid())
        .addColumn(WORKFLOW_ID_KEY, DataType.uuid())
        .getQueryString();
}
 
Example #26
Source File: CassandraBaseDAO.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getCreateTaskDefLimitTableStatement() {
    return SchemaBuilder.createTable(config.getCassandraKeyspace(), TABLE_TASK_DEF_LIMIT)
        .ifNotExists()
        .addPartitionKey(TASK_DEF_NAME_KEY, DataType.text())
        .addClusteringColumn(TASK_ID_KEY, DataType.uuid())
        .addColumn(WORKFLOW_ID_KEY, DataType.uuid())
        .getQueryString();
}
 
Example #27
Source File: CassandraBaseDAO.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getCreateWorkflowDefsTableStatement() {
    return SchemaBuilder.createTable(config.getCassandraKeyspace(), TABLE_WORKFLOW_DEFS)
        .ifNotExists()
        .addPartitionKey(WORKFLOW_DEF_NAME_KEY, DataType.text())
        .addClusteringColumn(WORKFLOW_VERSION_KEY, DataType.cint())
        .addColumn(WORKFLOW_DEFINITION_KEY, DataType.text())
        .getQueryString();
}
 
Example #28
Source File: CassandraBaseDAO.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getCreateWorkflowDefsIndexTableStatement() {
    return SchemaBuilder.createTable(config.getCassandraKeyspace(), TABLE_WORKFLOW_DEFS_INDEX)
        .ifNotExists()
        .addPartitionKey(WORKFLOW_DEF_INDEX_KEY, DataType.text())
        .addClusteringColumn(WORKFLOW_DEF_NAME_VERSION_KEY, DataType.text())
        .addColumn(WORKFLOW_DEF_INDEX_VALUE, DataType.text())
        .getQueryString();
}
 
Example #29
Source File: CassandraBaseDAO.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getCreateTaskDefsTableStatement() {
    return SchemaBuilder.createTable(config.getCassandraKeyspace(), TABLE_TASK_DEFS)
        .ifNotExists()
        .addPartitionKey(TASK_DEFS_KEY, DataType.text())
        .addClusteringColumn(TASK_DEF_NAME_KEY, DataType.text())
        .addColumn(TASK_DEFINITION_KEY, DataType.text())
        .getQueryString();
}
 
Example #30
Source File: CassandraBaseDAO.java    From conductor with Apache License 2.0 5 votes vote down vote up
private String getCreateEventHandlersTableStatement() {
    return SchemaBuilder.createTable(config.getCassandraKeyspace(), TABLE_EVENT_HANDLERS)
        .ifNotExists()
        .addPartitionKey(HANDLERS_KEY, DataType.text())
        .addClusteringColumn(EVENT_HANDLER_NAME_KEY, DataType.text())
        .addColumn(EVENT_HANDLER_KEY, DataType.text())
        .getQueryString();
}