org.apache.cassandra.db.marshal.MapType Java Examples

The following examples show how to use org.apache.cassandra.db.marshal.MapType. 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: Sets.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private void validateAssignableTo(String keyspace, ColumnSpecification receiver) throws InvalidRequestException
{
    if (!(receiver.type instanceof SetType))
    {
        // We've parsed empty maps as a set literal to break the ambiguity so
        // handle that case now
        if ((receiver.type instanceof MapType) && elements.isEmpty())
            return;

        throw new InvalidRequestException(String.format("Invalid set literal for %s of type %s", receiver.name, receiver.type.asCQL3Type()));
    }

    ColumnSpecification valueSpec = Sets.valueSpecOf(receiver);
    for (Term.Raw rt : elements)
    {
        if (!rt.isAssignableTo(keyspace, valueSpec))
            throw new InvalidRequestException(String.format("Invalid set literal for %s: value %s is not of type %s", receiver.name, rt, valueSpec.type.asCQL3Type()));
    }
}
 
Example #2
Source File: ColumnMapper.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
/**
 * Returns {@code true} if the specified Cassandra type/marshaller is supported, {@code false} otherwise.
 *
 * @param type A Cassandra type/marshaller.
 * @return {@code true} if the specified Cassandra type/marshaller is supported, {@code false} otherwise.
 */
public boolean supports(final AbstractType<?> type) {
    AbstractType<?> checkedType = type;
    if (type.isCollection()) {
        if (type instanceof MapType<?, ?>) {
            checkedType = ((MapType<?, ?>) type).getValuesType();
        } else if (type instanceof ListType<?>) {
            checkedType = ((ListType<?>) type).getElementsType();
        } else if (type instanceof SetType) {
            checkedType = ((SetType<?>) type).getElementsType();
        }
    }

    if (type instanceof ReversedType) {
        ReversedType reversedType = (ReversedType) type;
        checkedType = reversedType.baseType;
    }

    for (AbstractType<?> n : supportedTypes) {
        if (checkedType.getClass() == n.getClass()) {
            return true;
        }
    }
    return false;
}
 
Example #3
Source File: Maps.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public boolean equals(MapType mt, Value v)
{
    if (map.size() != v.map.size())
        return false;

    // We use the fact that we know the maps iteration will both be in comparator order
    Iterator<Map.Entry<ByteBuffer, ByteBuffer>> thisIter = map.entrySet().iterator();
    Iterator<Map.Entry<ByteBuffer, ByteBuffer>> thatIter = v.map.entrySet().iterator();
    while (thisIter.hasNext())
    {
        Map.Entry<ByteBuffer, ByteBuffer> thisEntry = thisIter.next();
        Map.Entry<ByteBuffer, ByteBuffer> thatEntry = thatIter.next();
        if (mt.getKeysType().compare(thisEntry.getKey(), thatEntry.getKey()) != 0 || mt.getValuesType().compare(thisEntry.getValue(), thatEntry.getValue()) != 0)
            return false;
    }

    return true;
}
 
Example #4
Source File: Maps.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public static Value fromSerialized(ByteBuffer value, MapType type, int version) throws InvalidRequestException
{
    try
    {
        // Collections have this small hack that validate cannot be called on a serialized object,
        // but compose does the validation (so we're fine).
        Map<?, ?> m = (Map<?, ?>)type.getSerializer().deserializeForNativeProtocol(value, version);
        Map<ByteBuffer, ByteBuffer> map = new LinkedHashMap<ByteBuffer, ByteBuffer>(m.size());
        for (Map.Entry<?, ?> entry : m.entrySet())
            map.put(type.getKeysType().decompose(entry.getKey()), type.getValuesType().decompose(entry.getValue()));
        return new Value(map);
    }
    catch (MarshalException e)
    {
        throw new InvalidRequestException(e.getMessage());
    }
}
 
Example #5
Source File: Maps.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public Term prepare(String keyspace, ColumnSpecification receiver) throws InvalidRequestException
{
    validateAssignableTo(keyspace, receiver);

    ColumnSpecification keySpec = Maps.keySpecOf(receiver);
    ColumnSpecification valueSpec = Maps.valueSpecOf(receiver);
    Map<Term, Term> values = new HashMap<Term, Term>(entries.size());
    boolean allTerminal = true;
    for (Pair<Term.Raw, Term.Raw> entry : entries)
    {
        Term k = entry.left.prepare(keyspace, keySpec);
        Term v = entry.right.prepare(keyspace, valueSpec);

        if (k.containsBindMarker() || v.containsBindMarker())
            throw new InvalidRequestException(String.format("Invalid map literal for %s: bind variables are not supported inside collection literals", receiver.name));

        if (k instanceof Term.NonTerminal || v instanceof Term.NonTerminal)
            allTerminal = false;

        values.put(k, v);
    }
    DelayedValue value = new DelayedValue(((MapType)receiver.type).getKeysType(), values);
    return allTerminal ? value.bind(QueryOptions.DEFAULT) : value;
}
 
Example #6
Source File: CellValidatorTest.java    From deep-spark with Apache License 2.0 6 votes vote down vote up
public void testValidatorClassToKind() {
    assertEquals(Kind.validatorClassToKind(null), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(TimeUUIDType.class), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(UTF8Type.class), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(Int32Type.class), Kind.NOT_A_COLLECTION);

    assertEquals(Kind.validatorClassToKind(BooleanType.class), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(TimestampType.class), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(DecimalType.class), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(LongType.class), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(DoubleType.class), Kind.NOT_A_COLLECTION);

    assertEquals(Kind.validatorClassToKind(FloatType.class), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(InetAddressType.class), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(IntegerType.class), Kind.NOT_A_COLLECTION);
    assertEquals(Kind.validatorClassToKind(UUIDType.class), Kind.NOT_A_COLLECTION);

    assertEquals(Kind.validatorClassToKind(SetType.class), Kind.SET);
    assertEquals(Kind.validatorClassToKind(ListType.class), Kind.LIST);
    assertEquals(Kind.validatorClassToKind(MapType.class), Kind.MAP);
}
 
Example #7
Source File: CellValidatorTest.java    From deep-spark with Apache License 2.0 6 votes vote down vote up
public void testDataTypeMapInstantiation() {
    DataType type = DataType.map(DataType.text(), DataType.bigint());

    CellValidator cv = cellValidator(type);
    assertNotNull(cv);
    assertEquals(cv.getValidatorClassName(), MapType.class.getName());
    assertNotNull(cv.getValidatorTypes());
    assertEquals(cv.validatorKind(), Kind.MAP);
    assertEquals(cv.getValidatorTypes().size(), 2);
    Iterator<String> types = cv.getValidatorTypes().iterator();
    assertEquals(types.next(), "text");
    assertEquals(types.next(), "bigint");
    assertEquals(DataType.Name.MAP, cv.getCqlTypeName());

    try {
        Collection<String> ctypes = cv.getValidatorTypes();
        ctypes.add("test");
        fail("Validator types collection must be inmutable");
    } catch (Exception ex) {
        // ok
    }

    //        assertNotNull(cv.getAbstractType());
    //        assertEquals(cv.getAbstractType(), MapType.getInstance(UTF8Type.instance, LongType.instance));
}
 
Example #8
Source File: CassandraTypeDeserializerTest.java    From debezium-incubator with Apache License 2.0 6 votes vote down vote up
@Test
public void testMapTypeNonStringKeys() {
    Map<Integer, Float> sourceMap = new HashMap<>();
    sourceMap.put(1, 1.5F);
    sourceMap.put(2, 3.1414F);

    MapType<Integer, Float> mapType = MapType.getInstance(Int32Type.instance, FloatType.instance, true);
    ByteBuffer serializedMap = mapType.decompose(sourceMap);
    Object deserializedMap = CassandraTypeDeserializer.deserialize(mapType, serializedMap);

    Map<Integer, Float> expectedMap = new HashMap<>();
    expectedMap.put(1, 1.5F);
    expectedMap.put(2, 3.1414F);

    Assert.assertEquals(expectedMap, deserializedMap);
}
 
Example #9
Source File: CassandraTypeDeserializerTest.java    From debezium-incubator with Apache License 2.0 6 votes vote down vote up
@Test
public void testMapType() {
    Map<String, Double> expectedMap = new HashMap<>();
    expectedMap.put("foo", 1D);
    expectedMap.put("bar", 50D);

    // non-frozen
    MapType<String, Double> nonFrozenMapType = MapType.getInstance(AsciiType.instance, DoubleType.instance, true);
    ByteBuffer serializedMap = nonFrozenMapType.decompose(expectedMap);
    Object deserializedMap = CassandraTypeDeserializer.deserialize(nonFrozenMapType, serializedMap);
    Assert.assertEquals(expectedMap, deserializedMap);

    // frozen
    MapType<String, Double> frozenMapType = MapType.getInstance(AsciiType.instance, DoubleType.instance, false);
    serializedMap = frozenMapType.decompose(expectedMap);
    deserializedMap = CassandraTypeDeserializer.deserialize(frozenMapType, serializedMap);
    Assert.assertEquals(expectedMap, deserializedMap);
}
 
Example #10
Source File: CassandraTypeConverterTest.java    From debezium-incubator with Apache License 2.0 6 votes vote down vote up
@Test
public void testMap() {
    // map from ASCII to Double
    // test non-frozen
    DataType mapType = DataType.map(DataType.ascii(), DataType.cdouble());
    AbstractType<?> convertedType = CassandraTypeConverter.convert(mapType);

    MapType<?, ?> expectedType = MapType.getInstance(AsciiType.instance, DoubleType.instance, true);
    Assert.assertEquals(expectedType, convertedType);

    // test frozen
    mapType = DataType.map(DataType.ascii(), DataType.cdouble(), true);
    convertedType = CassandraTypeConverter.convert(mapType);
    expectedType = MapType.getInstance(AsciiType.instance, DoubleType.instance, false);
    Assert.assertEquals(expectedType, convertedType);
    Assert.assertTrue("Expected convertType to be frozen", convertedType.isFrozenCollection());
}
 
Example #11
Source File: CellValidator.java    From deep-spark with Apache License 2.0 5 votes vote down vote up
/**
 * private constructor.
 *
 * @param type a {@link com.datastax.driver.core.DataType} coming from the underlying Java driver.
 */
private CellValidator(DataType type) {
    if (type == null) {
        throw new DeepInstantiationException("input DataType cannot be null");
    }

    cqlTypeName = type.getName();

    if (!type.isCollection()) {
        validatorClassName = MAP_JAVA_TYPE_TO_ABSTRACT_TYPE.get(type.asJavaClass()).getClass()
                .getName();
    } else {
        validatorTypes = new ArrayList<>();

        for (DataType dataType : type.getTypeArguments()) {
            validatorTypes.add(dataType.toString());
        }

        switch (type.getName()) {
        case SET:
            validatorKind = Kind.SET;
            validatorClassName = SetType.class.getName();
            break;
        case LIST:
            validatorKind = Kind.LIST;
            validatorClassName = ListType.class.getName();
            break;
        case MAP:
            validatorKind = Kind.MAP;
            validatorClassName = MapType.class.getName();
            break;
        default:
            throw new DeepGenericException("Cannot determine collection type for " + type.getName());
        }

        validatorTypes = unmodifiableCollection(validatorTypes);
    }
}
 
Example #12
Source File: Sets.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public Term prepare(String keyspace, ColumnSpecification receiver) throws InvalidRequestException
{
    validateAssignableTo(keyspace, receiver);

    // We've parsed empty maps as a set literal to break the ambiguity so
    // handle that case now
    if (receiver.type instanceof MapType && elements.isEmpty())
        return new Maps.Value(Collections.<ByteBuffer, ByteBuffer>emptyMap());

    ColumnSpecification valueSpec = Sets.valueSpecOf(receiver);
    Set<Term> values = new HashSet<Term>(elements.size());
    boolean allTerminal = true;
    for (Term.Raw rt : elements)
    {
        Term t = rt.prepare(keyspace, valueSpec);

        if (t.containsBindMarker())
            throw new InvalidRequestException(String.format("Invalid set literal for %s: bind variables are not supported inside collection literals", receiver.name));

        if (t instanceof Term.NonTerminal)
            allTerminal = false;

        values.add(t);
    }
    DelayedValue value = new DelayedValue(((SetType)receiver.type).getElementsType(), values);
    return allTerminal ? value.bind(QueryOptions.DEFAULT) : value;
}
 
Example #13
Source File: MapTypeConverter.java    From debezium-incubator with Apache License 2.0 5 votes vote down vote up
@Override
public MapType convert(DataType dataType) {
    List<DataType> innerDataTypes = dataType.getTypeArguments();
    return MapType.getInstance(CassandraTypeConverter.convert(innerDataTypes.get(0)),
            CassandraTypeConverter.convert(innerDataTypes.get(1)),
            !dataType.isFrozen());
}
 
Example #14
Source File: Maps.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private void validateAssignableTo(String keyspace, ColumnSpecification receiver) throws InvalidRequestException
{
    if (!(receiver.type instanceof MapType))
        throw new InvalidRequestException(String.format("Invalid map literal for %s of type %s", receiver.name, receiver.type.asCQL3Type()));

    ColumnSpecification keySpec = Maps.keySpecOf(receiver);
    ColumnSpecification valueSpec = Maps.valueSpecOf(receiver);
    for (Pair<Term.Raw, Term.Raw> entry : entries)
    {
        if (!entry.left.isAssignableTo(keyspace, keySpec))
            throw new InvalidRequestException(String.format("Invalid map literal for %s: key %s is not of type %s", receiver.name, entry.left, keySpec.type.asCQL3Type()));
        if (!entry.right.isAssignableTo(keyspace, valueSpec))
            throw new InvalidRequestException(String.format("Invalid map literal for %s: value %s is not of type %s", receiver.name, entry.right, valueSpec.type.asCQL3Type()));
    }
}
 
Example #15
Source File: MapTypeDeserializer.java    From debezium-incubator with Apache License 2.0 5 votes vote down vote up
@Override
public SchemaBuilder getSchemaBuilder(AbstractType<?> abstractType) {
    MapType<?, ?> mapType = (MapType<?, ?>) abstractType;
    AbstractType<?> keysType = mapType.getKeysType();
    AbstractType<?> valuesType = mapType.getValuesType();
    Schema keySchema = CassandraTypeDeserializer.getSchemaBuilder(keysType).build();
    Schema valuesSchema = CassandraTypeDeserializer.getSchemaBuilder(valuesType).build();
    return SchemaBuilder.map(keySchema, valuesSchema);
}
 
Example #16
Source File: FunctionCall.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private static Term.Terminal makeTerminal(Function fun, ByteBuffer result, int version) throws InvalidRequestException
{
    if (!(fun.returnType() instanceof CollectionType))
        return new Constants.Value(result);

    switch (((CollectionType)fun.returnType()).kind)
    {
        case LIST: return Lists.Value.fromSerialized(result, (ListType)fun.returnType(), version);
        case SET:  return Sets.Value.fromSerialized(result, (SetType)fun.returnType(), version);
        case MAP:  return Maps.Value.fromSerialized(result, (MapType)fun.returnType(), version);
    }
    throw new AssertionError();
}
 
Example #17
Source File: CellValidator.java    From deep-spark with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the Kind associated to the provided Cassandra validator class.
 * <p/>
 * <p>
 * To be more specific, returns:
 * <ul>
 * <li>NOT_A_COLLECTION: when the provided type is not a set a list or a map</li>
 * <li>MAP: when the provided validator is MapType.class</li>
 * <li>LIST: when the provided validator is ListType.class</li>
 * <li>SET: when the provided validator is SetType.class</li>
 * </ul>
 * </p>
 *
 * @param type the marshaller Class object.
 * @return the Kind associated to the provided marhaller Class object.
 */
public static Kind validatorClassToKind(Class<? extends AbstractType> type) {
    if (type == null) {
        return NOT_A_COLLECTION;
    }

    if (type.equals(SetType.class)) {
        return SET;
    } else if (type.equals(ListType.class)) {
        return LIST;
    } else if (type.equals(MapType.class)) {
        return MAP;
    } else {
        return NOT_A_COLLECTION;
    }
}
 
Example #18
Source File: CreateIndexStatement.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public void validate(ClientState state) throws RequestValidationException
{
    CFMetaData cfm = ThriftValidation.validateColumnFamily(keyspace(), columnFamily());
    if (cfm.isCounter())
        throw new InvalidRequestException("Secondary indexes are not supported on counter tables");

    IndexTarget target = rawTarget.prepare(cfm);
    ColumnDefinition cd = cfm.getColumnDefinition(target.column);

    if (cd == null)
        throw new InvalidRequestException("No column definition found for column " + target.column);

    boolean isMap = cd.type instanceof MapType;
    boolean isFrozenCollection = cd.type.isCollection() && !cd.type.isMultiCell();
    if (target.isCollectionKeys)
    {
        if (!isMap)
            throw new InvalidRequestException("Cannot create index on keys of column " + target + " with non-map type");
        if (!cd.type.isMultiCell())
            throw new InvalidRequestException("Cannot create index on keys of frozen<map> column " + target);
    }
    else if (target.isFullCollection)
    {
        if (!isFrozenCollection)
            throw new InvalidRequestException("full() indexes can only be created on frozen collections");
    }
    else if (isFrozenCollection)
    {
        throw new InvalidRequestException("Frozen collections currently only support full-collection indexes. " +
                                          "For example, 'CREATE INDEX ON <table>(full(<columnName>))'.");
    }

    if (cd.getIndexType() != null)
    {
        boolean previousIsKeys = cd.hasIndexOption(SecondaryIndex.INDEX_KEYS_OPTION_NAME);
        if (isMap && target.isCollectionKeys != previousIsKeys)
        {
            String msg = "Cannot create index on %s %s, an index on %s %s already exists and indexing "
                    + "a map on both keys and values at the same time is not currently supported";
            throw new InvalidRequestException(String.format(msg,
                                                            target.column, target.isCollectionKeys ? "keys" : "values",
                                                            target.column, previousIsKeys ? "keys" : "values"));
        }

        if (ifNotExists)
            return;
        else
            throw new InvalidRequestException("Index already exists");
    }

    properties.validate(cfm);

    // TODO: we could lift that limitation
    if ((cfm.comparator.isDense() || !cfm.comparator.isCompound()) && cd.kind != ColumnDefinition.Kind.REGULAR)
        throw new InvalidRequestException("Secondary indexes are not supported on PRIMARY KEY columns in COMPACT STORAGE tables");

    // It would be possible to support 2ndary index on static columns (but not without modifications of at least ExtendedFilter and
    // CompositesIndex) and maybe we should, but that means a query like:
    //     SELECT * FROM foo WHERE static_column = 'bar'
    // would pull the full partition every time the static column of partition is 'bar', which sounds like offering a
    // fair potential for foot-shooting, so I prefer leaving that to a follow up ticket once we have identified cases where
    // such indexing is actually useful.
    if (cd.isStatic())
        throw new InvalidRequestException("Secondary indexes are not allowed on static columns");

    if (cd.kind == ColumnDefinition.Kind.PARTITION_KEY && cd.isOnAllComponents())
        throw new InvalidRequestException(String.format("Cannot create secondary index on partition key column %s", target.column));
}
 
Example #19
Source File: Maps.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public static ColumnSpecification keySpecOf(ColumnSpecification column)
{
    return new ColumnSpecification(column.ksName, column.cfName, new ColumnIdentifier("key(" + column.name + ")", true), ((MapType)column.type).getKeysType());
}
 
Example #20
Source File: Maps.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public static ColumnSpecification valueSpecOf(ColumnSpecification column)
{
    return new ColumnSpecification(column.ksName, column.cfName, new ColumnIdentifier("value(" + column.name + ")", true), ((MapType)column.type).getValuesType());
}
 
Example #21
Source File: Maps.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
public Value bind(QueryOptions options) throws InvalidRequestException
{
    ByteBuffer value = options.getValues().get(bindIndex);
    return value == null ? null : Value.fromSerialized(value, (MapType)receiver.type, options.getProtocolVersion());
}
 
Example #22
Source File: MapTypeDeserializer.java    From debezium-incubator with Apache License 2.0 4 votes vote down vote up
@Override
public Object deserialize(AbstractType<?> abstractType, ByteBuffer bb) {
    Map<?, ?> deserializedMap = (Map<?, ?>) super.deserialize(abstractType, bb);
    MapType<?, ?> mapType = (MapType<?, ?>) abstractType;
    return Values.convertToMap(getSchemaBuilder(mapType).build(), deserializedMap);
}