Search in sources :

Example 6 with SchemaStatement

use of com.datastax.driver.core.schemabuilder.SchemaStatement in project scalardb by scalar-labs.

the class CassandraAdminTest method createSecondaryIndex_WithTwoIndexesNames_ShouldCreateBothIndexes.

@Test
public void createSecondaryIndex_WithTwoIndexesNames_ShouldCreateBothIndexes() throws ExecutionException {
    // Arrange
    String namespace = "sample_ns";
    String table = "sample_table";
    Set<String> indexes = new HashSet<>();
    indexes.add("c1");
    indexes.add("c5");
    // Act
    cassandraAdmin.createSecondaryIndexes(namespace, table, indexes, Collections.emptyMap());
    // Assert
    SchemaStatement c1IndexStatement = SchemaBuilder.createIndex(table + "_" + CassandraAdmin.INDEX_NAME_PREFIX + "_c1").onTable(namespace, table).andColumn("c1");
    SchemaStatement c5IndexStatement = SchemaBuilder.createIndex(table + "_" + CassandraAdmin.INDEX_NAME_PREFIX + "_c5").onTable(namespace, table).andColumn("c5");
    verify(cassandraSession).execute(c1IndexStatement.getQueryString());
    verify(cassandraSession).execute(c5IndexStatement.getQueryString());
}
Also used : SchemaStatement(com.datastax.driver.core.schemabuilder.SchemaStatement) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Example 7 with SchemaStatement

use of com.datastax.driver.core.schemabuilder.SchemaStatement in project sdc by onap.

the class SdcSchemaBuilder method createTables.

/**
 * the method creats all the tables and indexes thet do not already exist
 *
 * @param iTableDescriptions:    a list of table description we want to create
 * @param keyspaceMetadata:      the current tables that exist in the cassandra under this keyspace
 * @param session:               the session object used for the execution of the query.
 * @param existingTablesMetadata the current tables columns that exist in the cassandra under this keyspace
 */
private static void createTables(List<ITableDescription> iTableDescriptions, Map<String, List<String>> keyspaceMetadata, Session session, Map<String, List<String>> existingTablesMetadata) {
    for (ITableDescription tableDescription : iTableDescriptions) {
        String tableName = tableDescription.getTableName().toLowerCase();
        Map<String, ImmutablePair<DataType, Boolean>> columnDescription = tableDescription.getColumnDescription();
        log.info("creating tables:{}.", tableName);
        if (keyspaceMetadata == null || !keyspaceMetadata.containsKey(tableName)) {
            Create create = SchemaBuilder.createTable(tableDescription.getKeyspace(), tableDescription.getTableName());
            for (ImmutablePair<String, DataType> key : tableDescription.primaryKeys()) {
                create.addPartitionKey(key.getLeft(), key.getRight());
            }
            if (tableDescription.clusteringKeys() != null) {
                for (ImmutablePair<String, DataType> key : tableDescription.clusteringKeys()) {
                    create.addClusteringColumn(key.getLeft(), key.getRight());
                }
            }
            final Function<Entry<String, ?>, Boolean> notPrimaryKeyFilter = (Entry<String, ?> entry) -> {
                if (entry == null) {
                    return true;
                }
                return tableDescription.primaryKeys().stream().noneMatch(primaryKeyPair -> primaryKeyPair.getLeft().equals(entry.getKey()));
            };
            columnDescription.entrySet().stream().filter(notPrimaryKeyFilter::apply).forEach(entry -> create.addColumn(entry.getKey(), entry.getValue().getLeft()));
            log.trace("exacuting :{}", create);
            session.execute(create);
            log.info("table:{} created successfully.", tableName);
        } else {
            log.info("table:{} already exists, skipping.", tableName);
            alterTable(session, existingTablesMetadata, tableDescription, tableName, columnDescription);
        }
        log.info("keyspacemetadata:{}", keyspaceMetadata);
        List<String> indexNames = (keyspaceMetadata != null && keyspaceMetadata.get(tableName) != null ? keyspaceMetadata.get(tableName) : new ArrayList<>());
        log.info("table:{} creating indexes.", tableName);
        for (Map.Entry<String, ImmutablePair<DataType, Boolean>> description : columnDescription.entrySet()) {
            String indexName = createIndexName(tableName, description.getKey()).toLowerCase();
            if (description.getValue().getRight()) {
                if (!indexNames.contains(indexName)) {
                    SchemaStatement creatIndex = SchemaBuilder.createIndex(indexName).onTable(tableDescription.getKeyspace(), tableName).andColumn(description.getKey());
                    log.info("executing :{}", creatIndex);
                    session.execute(creatIndex);
                    log.info("index:{} created successfully.", indexName);
                } else {
                    log.info("index:{} already exists, skipping.", indexName);
                }
            }
        }
    }
}
Also used : Function(com.datastax.oss.driver.shaded.guava.common.base.Function) Getter(lombok.Getter) HashMap(java.util.HashMap) Supplier(java.util.function.Supplier) AuditingTypesConstants(org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants) EcompLoggerErrorCode(org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode) ArrayList(java.util.ArrayList) AbstractTableMetadata(com.datastax.driver.core.AbstractTableMetadata) SchemaStatement(com.datastax.driver.core.schemabuilder.SchemaStatement) Session(com.datastax.driver.core.Session) Map(java.util.Map) Alter(com.datastax.driver.core.schemabuilder.Alter) Create(com.datastax.driver.core.schemabuilder.Create) OldExternalApiEventTableDesc(org.openecomp.sdc.be.dao.cassandra.schema.tables.OldExternalApiEventTableDesc) Logger(org.openecomp.sdc.common.log.wrappers.Logger) SchemaBuilder(com.datastax.driver.core.schemabuilder.SchemaBuilder) Configuration(org.openecomp.sdc.be.config.Configuration) IndexMetadata(com.datastax.driver.core.IndexMetadata) Collectors(java.util.stream.Collectors) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) List(java.util.List) KeyspaceMetadata(com.datastax.driver.core.KeyspaceMetadata) Cluster(com.datastax.driver.core.Cluster) DataType(com.datastax.driver.core.DataType) Entry(java.util.Map.Entry) Optional(java.util.Optional) AllArgsConstructor(lombok.AllArgsConstructor) ArrayList(java.util.ArrayList) Entry(java.util.Map.Entry) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Create(com.datastax.driver.core.schemabuilder.Create) SchemaStatement(com.datastax.driver.core.schemabuilder.SchemaStatement) DataType(com.datastax.driver.core.DataType) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with SchemaStatement

use of com.datastax.driver.core.schemabuilder.SchemaStatement in project scalardb by scalar-labs.

the class CassandraAdmin method createSecondaryIndex.

@VisibleForTesting
void createSecondaryIndex(String fullKeyspace, String table, Set<String> secondaryIndexNames) throws ExecutionException {
    for (String index : secondaryIndexNames) {
        String indexName = String.format("%s_%s_%s", table, INDEX_NAME_PREFIX, index);
        SchemaStatement createIndex = SchemaBuilder.createIndex(indexName).onTable(quoteIfNecessary(fullKeyspace), quoteIfNecessary(table)).andColumn(quoteIfNecessary(index));
        try {
            clusterManager.getSession().execute(createIndex.getQueryString());
        } catch (RuntimeException e) {
            throw new ExecutionException(String.format("creating the secondary index for %s.%s.%s failed", fullKeyspace, table, index), e);
        }
    }
}
Also used : SchemaStatement(com.datastax.driver.core.schemabuilder.SchemaStatement) ExecutionException(com.scalar.db.exception.storage.ExecutionException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

SchemaStatement (com.datastax.driver.core.schemabuilder.SchemaStatement)8 ExecutionException (com.scalar.db.exception.storage.ExecutionException)3 Alter (com.datastax.driver.core.schemabuilder.Alter)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)2 Test (org.junit.jupiter.api.Test)2 AbstractTableMetadata (com.datastax.driver.core.AbstractTableMetadata)1 Cluster (com.datastax.driver.core.Cluster)1 DataType (com.datastax.driver.core.DataType)1 IndexMetadata (com.datastax.driver.core.IndexMetadata)1 KeyspaceMetadata (com.datastax.driver.core.KeyspaceMetadata)1 Session (com.datastax.driver.core.Session)1 Create (com.datastax.driver.core.schemabuilder.Create)1 SchemaBuilder (com.datastax.driver.core.schemabuilder.SchemaBuilder)1 Function (com.datastax.oss.driver.shaded.guava.common.base.Function)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1