Search in sources :

Example 6 with ClusteringOrder

use of com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder in project jnosql-diana-driver by eclipse.

the class QueryUtils method select.

public static Select select(ColumnQuery query, String keyspace) {
    String columnFamily = query.getColumnFamily();
    final List<String> columns = query.getColumns();
    Select select = null;
    if (columns.isEmpty()) {
        select = QueryBuilder.selectFrom(keyspace, columnFamily).all();
    } else {
        select = QueryBuilder.selectFrom(keyspace, columnFamily).columns(columns);
    }
    select = select.where(Relations.createClause(query.getCondition().orElse(null)));
    final Map<String, ClusteringOrder> sort = query.getSorts().stream().collect(Collectors.toMap(s -> s.getName(), mapSort()));
    select = select.orderBy(sort);
    return select;
}
Also used : QueryBuilder(com.datastax.oss.driver.api.querybuilder.QueryBuilder) SortType(jakarta.nosql.SortType) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) ClusteringOrder(com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder) Insert(com.datastax.oss.driver.api.querybuilder.insert.Insert) HashMap(java.util.HashMap) Function(java.util.function.Function) ValueUtil(org.eclipse.jnosql.communication.driver.ValueUtil) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CqlSession(com.datastax.oss.driver.api.core.CqlSession) Duration(java.time.Duration) Map(java.util.Map) InsertInto(com.datastax.oss.driver.api.querybuilder.insert.InsertInto) Select(com.datastax.oss.driver.api.querybuilder.select.Select) RegularInsert(com.datastax.oss.driver.api.querybuilder.insert.RegularInsert) TableMetadata(com.datastax.oss.driver.api.core.metadata.schema.TableMetadata) ColumnEntity(jakarta.nosql.column.ColumnEntity) CodecRegistry(com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry) Collection(java.util.Collection) DataType(com.datastax.oss.driver.api.core.type.DataType) Collectors(java.util.stream.Collectors) UdtValue(com.datastax.oss.driver.api.core.data.UdtValue) ColumnMetadata(com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata) ProtocolConstants(com.datastax.oss.protocol.internal.ProtocolConstants) UserDefinedType(com.datastax.oss.driver.api.core.type.UserDefinedType) KeyspaceMetadata(com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata) Value(jakarta.nosql.Value) List(java.util.List) Column(jakarta.nosql.column.Column) CodecNotFoundException(com.datastax.oss.driver.api.core.type.codec.CodecNotFoundException) TypeCodec(com.datastax.oss.driver.api.core.type.codec.TypeCodec) Optional(java.util.Optional) SetType(com.datastax.oss.driver.api.core.type.SetType) Term(com.datastax.oss.driver.api.querybuilder.term.Term) ColumnQuery(jakarta.nosql.column.ColumnQuery) Sort(jakarta.nosql.Sort) CommunicationException(jakarta.nosql.CommunicationException) Select(com.datastax.oss.driver.api.querybuilder.select.Select) ClusteringOrder(com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder)

Example 7 with ClusteringOrder

use of com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder in project java-driver by datastax.

the class TableParser method parseTable.

public TableMetadata parseTable(AdminRow tableRow, CqlIdentifier keyspaceId, Map<CqlIdentifier, UserDefinedType> userTypes) {
    // Cassandra <= 2.2:
    // CREATE TABLE system.schema_columnfamilies (
    // keyspace_name text,
    // columnfamily_name text,
    // bloom_filter_fp_chance double,
    // caching text,
    // cf_id uuid,
    // column_aliases text, (2.1 only)
    // comment text,
    // compaction_strategy_class text,
    // compaction_strategy_options text,
    // comparator text,
    // compression_parameters text,
    // default_time_to_live int,
    // default_validator text,
    // dropped_columns map<text, bigint>,
    // gc_grace_seconds int,
    // index_interval int,
    // is_dense boolean, (2.1 only)
    // key_aliases text, (2.1 only)
    // key_validator text,
    // local_read_repair_chance double,
    // max_compaction_threshold int,
    // max_index_interval int,
    // memtable_flush_period_in_ms int,
    // min_compaction_threshold int,
    // min_index_interval int,
    // read_repair_chance double,
    // speculative_retry text,
    // subcomparator text,
    // type text,
    // value_alias text, (2.1 only)
    // PRIMARY KEY (keyspace_name, columnfamily_name)
    // ) WITH CLUSTERING ORDER BY (columnfamily_name ASC)
    // 
    // Cassandra 3.0:
    // CREATE TABLE system_schema.tables (
    // keyspace_name text,
    // table_name text,
    // bloom_filter_fp_chance double,
    // caching frozen<map<text, text>>,
    // cdc boolean,
    // comment text,
    // compaction frozen<map<text, text>>,
    // compression frozen<map<text, text>>,
    // crc_check_chance double,
    // dclocal_read_repair_chance double,
    // default_time_to_live int,
    // extensions frozen<map<text, blob>>,
    // flags frozen<set<text>>,
    // gc_grace_seconds int,
    // id uuid,
    // max_index_interval int,
    // memtable_flush_period_in_ms int,
    // min_index_interval int,
    // read_repair_chance double,
    // speculative_retry text,
    // PRIMARY KEY (keyspace_name, table_name)
    // ) WITH CLUSTERING ORDER BY (table_name ASC)
    CqlIdentifier tableId = CqlIdentifier.fromInternal(tableRow.getString(tableRow.contains("table_name") ? "table_name" : "columnfamily_name"));
    UUID uuid = tableRow.contains("id") ? tableRow.getUuid("id") : tableRow.getUuid("cf_id");
    List<RawColumn> rawColumns = RawColumn.toRawColumns(rows.columns().getOrDefault(keyspaceId, ImmutableMultimap.of()).get(tableId));
    if (rawColumns.isEmpty()) {
        LOG.warn("[{}] Processing TABLE refresh for {}.{} but found no matching rows, skipping", logPrefix, keyspaceId, tableId);
        return null;
    }
    boolean isCompactStorage;
    if (tableRow.contains("flags")) {
        Set<String> flags = tableRow.getSetOfString("flags");
        boolean isDense = flags.contains("dense");
        boolean isSuper = flags.contains("super");
        boolean isCompound = flags.contains("compound");
        isCompactStorage = isSuper || isDense || !isCompound;
        boolean isStaticCompact = !isSuper && !isDense && !isCompound;
        if (isStaticCompact) {
            RawColumn.pruneStaticCompactTableColumns(rawColumns);
        } else if (isDense) {
            RawColumn.pruneDenseTableColumnsV3(rawColumns);
        }
    } else {
        boolean isDense = tableRow.getBoolean("is_dense");
        if (isDense) {
            RawColumn.pruneDenseTableColumnsV2(rawColumns);
        }
        DataTypeClassNameCompositeParser.ParseResult comparator = new DataTypeClassNameCompositeParser().parseWithComposite(tableRow.getString("comparator"), keyspaceId, userTypes, context);
        isCompactStorage = isDense || !comparator.isComposite;
    }
    Collections.sort(rawColumns);
    ImmutableMap.Builder<CqlIdentifier, ColumnMetadata> allColumnsBuilder = ImmutableMap.builder();
    ImmutableList.Builder<ColumnMetadata> partitionKeyBuilder = ImmutableList.builder();
    ImmutableMap.Builder<ColumnMetadata, ClusteringOrder> clusteringColumnsBuilder = ImmutableMap.builder();
    ImmutableMap.Builder<CqlIdentifier, IndexMetadata> indexesBuilder = ImmutableMap.builder();
    for (RawColumn raw : rawColumns) {
        DataType dataType = rows.dataTypeParser().parse(keyspaceId, raw.dataType, userTypes, context);
        ColumnMetadata column = new DefaultColumnMetadata(keyspaceId, tableId, raw.name, dataType, raw.kind.equals(RawColumn.KIND_STATIC));
        switch(raw.kind) {
            case RawColumn.KIND_PARTITION_KEY:
                partitionKeyBuilder.add(column);
                break;
            case RawColumn.KIND_CLUSTERING_COLUMN:
                clusteringColumnsBuilder.put(column, raw.reversed ? ClusteringOrder.DESC : ClusteringOrder.ASC);
                break;
            default:
        }
        allColumnsBuilder.put(column.getName(), column);
        IndexMetadata index = buildLegacyIndex(raw, column);
        if (index != null) {
            indexesBuilder.put(index.getName(), index);
        }
    }
    Map<CqlIdentifier, Object> options;
    try {
        options = parseOptions(tableRow);
    } catch (Exception e) {
        // Options change the most often, so be especially lenient if anything goes wrong.
        Loggers.warnWithException(LOG, "[{}] Error while parsing options for {}.{}, getOptions() will be empty", logPrefix, keyspaceId, tableId, e);
        options = Collections.emptyMap();
    }
    Collection<AdminRow> indexRows = rows.indexes().getOrDefault(keyspaceId, ImmutableMultimap.of()).get(tableId);
    for (AdminRow indexRow : indexRows) {
        IndexMetadata index = buildModernIndex(keyspaceId, tableId, indexRow);
        indexesBuilder.put(index.getName(), index);
    }
    return new DefaultTableMetadata(keyspaceId, tableId, uuid, isCompactStorage, false, partitionKeyBuilder.build(), clusteringColumnsBuilder.build(), allColumnsBuilder.build(), options, indexesBuilder.build());
}
Also used : DefaultColumnMetadata(com.datastax.oss.driver.internal.core.metadata.schema.DefaultColumnMetadata) ColumnMetadata(com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata) ImmutableList(com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList) DataType(com.datastax.oss.driver.api.core.type.DataType) UUID(java.util.UUID) DefaultIndexMetadata(com.datastax.oss.driver.internal.core.metadata.schema.DefaultIndexMetadata) IndexMetadata(com.datastax.oss.driver.api.core.metadata.schema.IndexMetadata) DefaultColumnMetadata(com.datastax.oss.driver.internal.core.metadata.schema.DefaultColumnMetadata) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) ImmutableMap(com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap) DefaultTableMetadata(com.datastax.oss.driver.internal.core.metadata.schema.DefaultTableMetadata) ClusteringOrder(com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder) AdminRow(com.datastax.oss.driver.internal.core.adminrequest.AdminRow)

Example 8 with ClusteringOrder

use of com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder in project java-driver by datastax.

the class DaoSelectMethodGenerator method addOrdering.

private void addOrdering(String orderingSpec, MethodSpec.Builder methodBuilder) {
    List<String> tokens = ON_SPACES.splitToList(orderingSpec);
    ClusteringOrder clusteringOrder;
    if (tokens.size() != 2 || (clusteringOrder = parseClusteringOrder(tokens.get(1))) == null) {
        context.getMessager().error(methodElement, "Can't parse ordering '%s', expected a column name followed by ASC or DESC", orderingSpec);
        return;
    }
    methodBuilder.addCode(".orderBy($S, $T.$L)", tokens.get(0), ClusteringOrder.class, clusteringOrder);
}
Also used : ClusteringOrder(com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder)

Example 9 with ClusteringOrder

use of com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder in project java-driver by datastax.

the class DseViewParser method parseView.

public DseViewMetadata parseView(AdminRow viewRow, CqlIdentifier keyspaceId, Map<CqlIdentifier, UserDefinedType> userTypes) {
    // Cassandra 3.0 (no views in earlier versions):
    // CREATE TABLE system_schema.views (
    // keyspace_name text,
    // view_name text,
    // base_table_id uuid,
    // base_table_name text,
    // bloom_filter_fp_chance double,
    // caching frozen<map<text, text>>,
    // cdc boolean,
    // comment text,
    // compaction frozen<map<text, text>>,
    // compression frozen<map<text, text>>,
    // crc_check_chance double,
    // dclocal_read_repair_chance double,
    // default_time_to_live int,
    // extensions frozen<map<text, blob>>,
    // gc_grace_seconds int,
    // id uuid,
    // include_all_columns boolean,
    // max_index_interval int,
    // memtable_flush_period_in_ms int,
    // min_index_interval int,
    // read_repair_chance double,
    // speculative_retry text,
    // where_clause text,
    // PRIMARY KEY (keyspace_name, view_name)
    // ) WITH CLUSTERING ORDER BY (view_name ASC)
    CqlIdentifier viewId = CqlIdentifier.fromInternal(viewRow.getString("view_name"));
    UUID uuid = viewRow.getUuid("id");
    CqlIdentifier baseTableId = CqlIdentifier.fromInternal(viewRow.getString("base_table_name"));
    boolean includesAllColumns = MoreObjects.firstNonNull(viewRow.getBoolean("include_all_columns"), false);
    String whereClause = viewRow.getString("where_clause");
    List<RawColumn> rawColumns = RawColumn.toRawColumns(rows.columns().getOrDefault(keyspaceId, ImmutableMultimap.of()).get(viewId));
    if (rawColumns.isEmpty()) {
        LOG.warn("[{}] Processing VIEW refresh for {}.{} but found no matching rows, skipping", logPrefix, keyspaceId, viewId);
        return null;
    }
    Collections.sort(rawColumns);
    ImmutableMap.Builder<CqlIdentifier, ColumnMetadata> allColumnsBuilder = ImmutableMap.builder();
    ImmutableList.Builder<ColumnMetadata> partitionKeyBuilder = ImmutableList.builder();
    ImmutableMap.Builder<ColumnMetadata, ClusteringOrder> clusteringColumnsBuilder = ImmutableMap.builder();
    for (RawColumn raw : rawColumns) {
        DataType dataType = rows.dataTypeParser().parse(keyspaceId, raw.dataType, userTypes, context);
        DseColumnMetadata column = new DefaultDseColumnMetadata(keyspaceId, viewId, raw.name, dataType, raw.kind.equals(RawColumn.KIND_STATIC));
        switch(raw.kind) {
            case RawColumn.KIND_PARTITION_KEY:
                partitionKeyBuilder.add(column);
                break;
            case RawColumn.KIND_CLUSTERING_COLUMN:
                clusteringColumnsBuilder.put(column, raw.reversed ? ClusteringOrder.DESC : ClusteringOrder.ASC);
                break;
            default:
        }
        allColumnsBuilder.put(column.getName(), column);
    }
    Map<CqlIdentifier, Object> options;
    try {
        options = parseOptions(viewRow);
    } catch (Exception e) {
        // Options change the most often, so be especially lenient if anything goes wrong.
        Loggers.warnWithException(LOG, "[{}] Error while parsing options for {}.{}, getOptions() will be empty", logPrefix, keyspaceId, viewId, e);
        options = Collections.emptyMap();
    }
    return new DefaultDseViewMetadata(keyspaceId, viewId, baseTableId, includesAllColumns, whereClause, uuid, partitionKeyBuilder.build(), clusteringColumnsBuilder.build(), allColumnsBuilder.build(), options);
}
Also used : DefaultDseColumnMetadata(com.datastax.dse.driver.internal.core.metadata.schema.DefaultDseColumnMetadata) ColumnMetadata(com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata) DseColumnMetadata(com.datastax.dse.driver.api.core.metadata.schema.DseColumnMetadata) DefaultDseColumnMetadata(com.datastax.dse.driver.internal.core.metadata.schema.DefaultDseColumnMetadata) DseColumnMetadata(com.datastax.dse.driver.api.core.metadata.schema.DseColumnMetadata) ImmutableList(com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) ImmutableMap(com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap) DefaultDseColumnMetadata(com.datastax.dse.driver.internal.core.metadata.schema.DefaultDseColumnMetadata) DefaultDseViewMetadata(com.datastax.dse.driver.internal.core.metadata.schema.DefaultDseViewMetadata) RawColumn(com.datastax.oss.driver.internal.core.metadata.schema.parsing.RawColumn) DataType(com.datastax.oss.driver.api.core.type.DataType) UUID(java.util.UUID) ClusteringOrder(com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder)

Example 10 with ClusteringOrder

use of com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder in project java-driver by datastax.

the class DseGraphTableMetadata method describe.

@NonNull
@Override
default String describe(boolean pretty) {
    ScriptBuilder builder = new ScriptBuilder(pretty);
    if (isVirtual()) {
        builder.append("/* VIRTUAL ");
    } else {
        builder.append("CREATE ");
    }
    builder.append("TABLE ").append(getKeyspace()).append(".").append(getName()).append(" (").newLine().increaseIndent();
    for (ColumnMetadata column : getColumns().values()) {
        builder.append(column.getName()).append(" ").append(column.getType().asCql(true, pretty));
        if (column.isStatic()) {
            builder.append(" static");
        }
        builder.append(",").newLine();
    }
    // PK
    builder.append("PRIMARY KEY (");
    if (getPartitionKey().size() == 1) {
        // PRIMARY KEY (k
        builder.append(getPartitionKey().get(0).getName());
    } else {
        // PRIMARY KEY ((k1, k2)
        builder.append("(");
        boolean first = true;
        for (ColumnMetadata pkColumn : getPartitionKey()) {
            if (first) {
                first = false;
            } else {
                builder.append(", ");
            }
            builder.append(pkColumn.getName());
        }
        builder.append(")");
    }
    // PRIMARY KEY (<pk portion>, cc1, cc2, cc3)
    for (ColumnMetadata clusteringColumn : getClusteringColumns().keySet()) {
        builder.append(", ").append(clusteringColumn.getName());
    }
    builder.append(")");
    builder.newLine().decreaseIndent().append(")");
    builder.increaseIndent();
    if (isCompactStorage()) {
        builder.andWith().append("COMPACT STORAGE");
    }
    if (getClusteringColumns().containsValue(ClusteringOrder.DESC)) {
        builder.andWith().append("CLUSTERING ORDER BY (");
        boolean first = true;
        for (Map.Entry<? extends ColumnMetadata, ClusteringOrder> entry : getClusteringColumns().entrySet()) {
            if (first) {
                first = false;
            } else {
                builder.append(", ");
            }
            builder.append(entry.getKey().getName()).append(" ").append(entry.getValue().name());
        }
        builder.append(")");
    }
    getVertex().ifPresent(vertex -> {
        builder.andWith().append("VERTEX LABEL").append(" ").append(vertex.getLabelName());
    });
    getEdge().ifPresent(edge -> {
        builder.andWith().append("EDGE LABEL").append(" ").append(edge.getLabelName());
        ScriptHelper.appendEdgeSide(builder, edge.getFromTable(), edge.getFromLabel(), edge.getFromPartitionKeyColumns(), edge.getFromClusteringColumns(), "FROM");
        ScriptHelper.appendEdgeSide(builder, edge.getToTable(), edge.getToLabel(), edge.getToPartitionKeyColumns(), edge.getToClusteringColumns(), "TO");
    });
    Map<CqlIdentifier, Object> options = getOptions();
    RelationParser.appendOptions(options, builder);
    builder.append(";");
    if (isVirtual()) {
        builder.append(" */");
    }
    return builder.build();
}
Also used : ColumnMetadata(com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata) ScriptBuilder(com.datastax.oss.driver.internal.core.metadata.schema.ScriptBuilder) Map(java.util.Map) ClusteringOrder(com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder) CqlIdentifier(com.datastax.oss.driver.api.core.CqlIdentifier) NonNull(edu.umd.cs.findbugs.annotations.NonNull)

Aggregations

ClusteringOrder (com.datastax.oss.driver.api.core.metadata.schema.ClusteringOrder)10 CqlIdentifier (com.datastax.oss.driver.api.core.CqlIdentifier)8 ColumnMetadata (com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata)8 DataType (com.datastax.oss.driver.api.core.type.DataType)7 ImmutableList (com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList)6 ImmutableMap (com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap)6 UUID (java.util.UUID)4 DseColumnMetadata (com.datastax.dse.driver.api.core.metadata.schema.DseColumnMetadata)3 DefaultDseColumnMetadata (com.datastax.dse.driver.internal.core.metadata.schema.DefaultDseColumnMetadata)3 DefaultColumnMetadata (com.datastax.oss.driver.internal.core.metadata.schema.DefaultColumnMetadata)3 RawColumn (com.datastax.oss.driver.internal.core.metadata.schema.parsing.RawColumn)3 DefaultDseTableMetadata (com.datastax.dse.driver.internal.core.metadata.schema.DefaultDseTableMetadata)2 IndexMetadata (com.datastax.oss.driver.api.core.metadata.schema.IndexMetadata)2 AdminRow (com.datastax.oss.driver.internal.core.adminrequest.AdminRow)2 DefaultTableMetadata (com.datastax.oss.driver.internal.core.metadata.schema.DefaultTableMetadata)2 ArrayList (java.util.ArrayList)2 DseIndexMetadata (com.datastax.dse.driver.api.core.metadata.schema.DseIndexMetadata)1 DefaultDseIndexMetadata (com.datastax.dse.driver.internal.core.metadata.schema.DefaultDseIndexMetadata)1 DefaultDseViewMetadata (com.datastax.dse.driver.internal.core.metadata.schema.DefaultDseViewMetadata)1 CqlSession (com.datastax.oss.driver.api.core.CqlSession)1