Search in sources :

Example 16 with TupleValue

use of com.datastax.oss.driver.api.core.data.TupleValue in project java-driver by datastax.

the class CachingCodecRegistry method inferCqlTypeFromValue.

@Nullable
protected DataType inferCqlTypeFromValue(@NonNull Object value) {
    if (value instanceof List) {
        List<?> list = (List<?>) value;
        if (list.isEmpty()) {
            return CQL_TYPE_FOR_EMPTY_LISTS;
        }
        Object firstElement = list.get(0);
        if (firstElement == null) {
            throw new IllegalArgumentException("Can't infer list codec because the first element is null " + "(note that CQL does not allow null values in collections)");
        }
        DataType elementType = inferCqlTypeFromValue(firstElement);
        if (elementType == null) {
            return null;
        }
        return DataTypes.listOf(elementType);
    } else if (value instanceof Set) {
        Set<?> set = (Set<?>) value;
        if (set.isEmpty()) {
            return CQL_TYPE_FOR_EMPTY_SETS;
        }
        Object firstElement = set.iterator().next();
        if (firstElement == null) {
            throw new IllegalArgumentException("Can't infer set codec because the first element is null " + "(note that CQL does not allow null values in collections)");
        }
        DataType elementType = inferCqlTypeFromValue(firstElement);
        if (elementType == null) {
            return null;
        }
        return DataTypes.setOf(elementType);
    } else if (value instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) value;
        if (map.isEmpty()) {
            return CQL_TYPE_FOR_EMPTY_MAPS;
        }
        Entry<?, ?> firstEntry = map.entrySet().iterator().next();
        Object firstKey = firstEntry.getKey();
        Object firstValue = firstEntry.getValue();
        if (firstKey == null || firstValue == null) {
            throw new IllegalArgumentException("Can't infer map codec because the first key and/or value is null " + "(note that CQL does not allow null values in collections)");
        }
        DataType keyType = inferCqlTypeFromValue(firstKey);
        DataType valueType = inferCqlTypeFromValue(firstValue);
        if (keyType == null || valueType == null) {
            return null;
        }
        return DataTypes.mapOf(keyType, valueType);
    }
    Class<?> javaClass = value.getClass();
    if (ByteBuffer.class.isAssignableFrom(javaClass)) {
        return DataTypes.BLOB;
    } else if (String.class.equals(javaClass)) {
        return DataTypes.TEXT;
    } else if (Long.class.equals(javaClass)) {
        return DataTypes.BIGINT;
    } else if (Boolean.class.equals(javaClass)) {
        return DataTypes.BOOLEAN;
    } else if (BigDecimal.class.equals(javaClass)) {
        return DataTypes.DECIMAL;
    } else if (Double.class.equals(javaClass)) {
        return DataTypes.DOUBLE;
    } else if (Float.class.equals(javaClass)) {
        return DataTypes.FLOAT;
    } else if (Integer.class.equals(javaClass)) {
        return DataTypes.INT;
    } else if (Instant.class.equals(javaClass)) {
        return DataTypes.TIMESTAMP;
    } else if (UUID.class.equals(javaClass)) {
        return DataTypes.UUID;
    } else if (BigInteger.class.equals(javaClass)) {
        return DataTypes.VARINT;
    } else if (InetAddress.class.isAssignableFrom(javaClass)) {
        return DataTypes.INET;
    } else if (LocalDate.class.equals(javaClass)) {
        return DataTypes.DATE;
    } else if (LocalTime.class.equals(javaClass)) {
        return DataTypes.TIME;
    } else if (Short.class.equals(javaClass)) {
        return DataTypes.SMALLINT;
    } else if (Byte.class.equals(javaClass)) {
        return DataTypes.TINYINT;
    } else if (CqlDuration.class.equals(javaClass)) {
        return DataTypes.DURATION;
    } else if (UdtValue.class.isAssignableFrom(javaClass)) {
        return ((UdtValue) value).getType();
    } else if (TupleValue.class.isAssignableFrom(javaClass)) {
        return ((TupleValue) value).getType();
    }
    // so don't throw CodecNotFoundException just yet.
    return null;
}
Also used : UdtValue(com.datastax.oss.driver.api.core.data.UdtValue) Set(java.util.Set) LocalTime(java.time.LocalTime) TupleValue(com.datastax.oss.driver.api.core.data.TupleValue) BigInteger(java.math.BigInteger) DataType(com.datastax.oss.driver.api.core.type.DataType) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) UUID(java.util.UUID) Map(java.util.Map) IntMap(com.datastax.oss.protocol.internal.util.IntMap) InetAddress(java.net.InetAddress) Nullable(edu.umd.cs.findbugs.annotations.Nullable)

Example 17 with TupleValue

use of com.datastax.oss.driver.api.core.data.TupleValue in project java-driver by datastax.

the class TupleCodec method parse.

@Nullable
@Override
public TupleValue parse(@Nullable String value) {
    if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) {
        return null;
    }
    TupleValue tuple = cqlType.newValue();
    int length = value.length();
    int position = ParseUtils.skipSpaces(value, 0);
    if (value.charAt(position) != '(') {
        throw new IllegalArgumentException(String.format("Cannot parse tuple value from \"%s\", at character %d expecting '(' but got '%c'", value, position, value.charAt(position)));
    }
    position++;
    position = ParseUtils.skipSpaces(value, position);
    CodecRegistry registry = cqlType.getAttachmentPoint().getCodecRegistry();
    int field = 0;
    while (position < length) {
        if (value.charAt(position) == ')') {
            position = ParseUtils.skipSpaces(value, position + 1);
            if (position == length) {
                return tuple;
            }
            throw new IllegalArgumentException(String.format("Cannot parse tuple value from \"%s\", at character %d expecting EOF or blank, but got \"%s\"", value, position, value.substring(position)));
        }
        int n;
        try {
            n = ParseUtils.skipCQLValue(value, position);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(String.format("Cannot parse tuple value from \"%s\", invalid CQL value at field %d (character %d)", value, field, position), e);
        }
        String fieldValue = value.substring(position, n);
        DataType elementType = cqlType.getComponentTypes().get(field);
        TypeCodec<Object> codec = registry.codecFor(elementType);
        Object parsed;
        try {
            parsed = codec.parse(fieldValue);
        } catch (Exception e) {
            throw new IllegalArgumentException(String.format("Cannot parse tuple value from \"%s\", invalid CQL value at field %d (character %d): %s", value, field, position, e.getMessage()), e);
        }
        tuple = tuple.set(field, parsed, codec);
        position = n;
        position = ParseUtils.skipSpaces(value, position);
        if (position == length) {
            throw new IllegalArgumentException(String.format("Cannot parse tuple value from \"%s\", at field %d (character %d) expecting ',' or ')', but got EOF", value, field, position));
        }
        if (value.charAt(position) == ')') {
            continue;
        }
        if (value.charAt(position) != ',') {
            throw new IllegalArgumentException(String.format("Cannot parse tuple value from \"%s\", at field %d (character %d) expecting ',' but got '%c'", value, field, position, value.charAt(position)));
        }
        // skip ','
        ++position;
        position = ParseUtils.skipSpaces(value, position);
        field += 1;
    }
    throw new IllegalArgumentException(String.format("Cannot parse tuple value from \"%s\", at field %d (character %d) expecting CQL value or ')', got EOF", value, field, position));
}
Also used : DataType(com.datastax.oss.driver.api.core.type.DataType) CodecRegistry(com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry) TupleValue(com.datastax.oss.driver.api.core.data.TupleValue) BufferUnderflowException(java.nio.BufferUnderflowException) Nullable(edu.umd.cs.findbugs.annotations.Nullable)

Example 18 with TupleValue

use of com.datastax.oss.driver.api.core.data.TupleValue in project java-driver by datastax.

the class TuplesMapped method registerCoordinatesCodec.

private static void registerCoordinatesCodec(CqlSession session) {
    // retrieve the codec registry
    MutableCodecRegistry codecRegistry = (MutableCodecRegistry) session.getContext().getCodecRegistry();
    // create the tuple metadata
    TupleType coordinatesType = DataTypes.tupleOf(DataTypes.INT, DataTypes.INT);
    // retrieve the driver built-in codec for the tuple "coordinates"
    TypeCodec<TupleValue> innerCodec = codecRegistry.codecFor(coordinatesType);
    // create a custom codec to map the "coordinates" tuple to the Coordinates class
    CoordinatesCodec coordinatesCodec = new CoordinatesCodec(innerCodec);
    // register the new codec
    codecRegistry.register(coordinatesCodec);
}
Also used : MutableCodecRegistry(com.datastax.oss.driver.api.core.type.codec.registry.MutableCodecRegistry) TupleType(com.datastax.oss.driver.api.core.type.TupleType) TupleValue(com.datastax.oss.driver.api.core.data.TupleValue)

Example 19 with TupleValue

use of com.datastax.oss.driver.api.core.data.TupleValue in project java-driver by datastax.

the class CustomCodecs method retrieveData.

private static void retrieveData(CqlSession session) {
    // Execute the SELECT query and retrieve the single row in the result set
    SimpleStatement statement = SimpleStatement.newInstance("SELECT pk, contents, uploaded, tags, week_day, ip FROM examples.videos WHERE pk = ?", // If this is an issue, use prepared statements.
    1);
    Row row = session.execute(statement).one();
    assert row != null;
    {
        // Retrieve values from row using custom codecs
        // will use CqlIntToStringCodec
        String pk = row.getString("pk");
        // will use TypeCodecs.BLOB_SIMPLE
        byte[] contents = row.get("contents", byte[].class);
        ZonedDateTime uploaded = // will use TypeCodecs.ZONED_TIMESTAMP_PERSISTED
        row.get("uploaded", ZonedDateTime.class);
        String[] tags = // will use  TypeCodecs.arrayOf(TypeCodecs.TEXT)
        row.get("tags", String[].class);
        WeekDay weekDay = // will use TypeCodecs.enumNamesOf(WeekDay.class)
        row.get("week_day", WeekDay.class);
        Optional<InetAddress> maybeIp = // will use TypeCodecs.optionalOf(TypeCodecs.INET)
        row.get("ip", OPTIONAL_OF_INET);
        System.out.println("pk: " + pk);
        System.out.println("contents: " + Arrays.toString(contents));
        System.out.println("uploaded: " + uploaded);
        System.out.println("tags: " + Arrays.toString(tags));
        System.out.println("week day: " + weekDay);
        System.out.println("ip: " + maybeIp);
    }
    System.out.println("------------------");
    {
        // It is still possible to retrieve the same values from row using driver built-in codecs
        int pk = row.getInt("pk");
        ByteBuffer contents = row.getByteBuffer("contents");
        TupleValue uploaded = row.getTupleValue("uploaded");
        List<String> tags = row.getList("tags", String.class);
        String weekDay = row.getString("week_day");
        InetAddress ip = row.getInetAddress("ip");
        System.out.println("pk: " + pk);
        System.out.println("contents: " + ByteUtils.toHexString(contents));
        System.out.println("uploaded: " + (uploaded == null ? null : uploaded.getFormattedContents()));
        System.out.println("tags: " + tags);
        System.out.println("week day: " + weekDay);
        System.out.println("ip: " + ip);
    }
}
Also used : Optional(java.util.Optional) ZonedDateTime(java.time.ZonedDateTime) SimpleStatement(com.datastax.oss.driver.api.core.cql.SimpleStatement) List(java.util.List) Row(com.datastax.oss.driver.api.core.cql.Row) ByteBuffer(java.nio.ByteBuffer) InetAddress(java.net.InetAddress) TupleValue(com.datastax.oss.driver.api.core.data.TupleValue)

Example 20 with TupleValue

use of com.datastax.oss.driver.api.core.data.TupleValue in project java-driver by datastax.

the class TuplesSimple method insertData.

private static void insertData(CqlSession session) {
    // prepare the INSERT statement
    PreparedStatement prepared = session.prepare("INSERT INTO examples.tuples (k, c) VALUES (?, ?)");
    // create the tuple metadata
    TupleType coordinatesType = DataTypes.tupleOf(DataTypes.INT, DataTypes.INT);
    // bind the parameters in one pass
    TupleValue coordinates1 = coordinatesType.newValue(12, 34);
    BoundStatement boundStatement1 = prepared.bind(1, coordinates1);
    // execute the insertion
    session.execute(boundStatement1);
    // alternate method: bind the parameters one by one
    TupleValue coordinates2 = coordinatesType.newValue(56, 78);
    BoundStatement boundStatement2 = prepared.bind().setInt("k", 2).setTupleValue("c", coordinates2);
    // execute the insertion
    session.execute(boundStatement2);
}
Also used : TupleType(com.datastax.oss.driver.api.core.type.TupleType) PreparedStatement(com.datastax.oss.driver.api.core.cql.PreparedStatement) BoundStatement(com.datastax.oss.driver.api.core.cql.BoundStatement) TupleValue(com.datastax.oss.driver.api.core.data.TupleValue)

Aggregations

TupleValue (com.datastax.oss.driver.api.core.data.TupleValue)31 Test (org.junit.Test)18 DefaultTupleValue (com.datastax.oss.driver.internal.core.data.DefaultTupleValue)12 TupleType (com.datastax.oss.driver.api.core.type.TupleType)10 Row (com.datastax.oss.driver.api.core.cql.Row)6 UdtValue (com.datastax.oss.driver.api.core.data.UdtValue)5 DefaultTupleType (com.datastax.oss.driver.internal.core.type.DefaultTupleType)5 DataType (com.datastax.oss.driver.api.core.type.DataType)4 ByteBuffer (java.nio.ByteBuffer)4 ResultSet (com.datastax.oss.driver.api.core.cql.ResultSet)3 Nullable (edu.umd.cs.findbugs.annotations.Nullable)3 InetAddress (java.net.InetAddress)3 List (java.util.List)3 BoundStatement (com.datastax.oss.driver.api.core.cql.BoundStatement)2 PreparedStatement (com.datastax.oss.driver.api.core.cql.PreparedStatement)2 SimpleStatement (com.datastax.oss.driver.api.core.cql.SimpleStatement)2 UserDefinedType (com.datastax.oss.driver.api.core.type.UserDefinedType)2 CodecRegistry (com.datastax.oss.driver.api.core.type.codec.registry.CodecRegistry)2 UserDefinedTypeBuilder (com.datastax.oss.driver.internal.core.type.UserDefinedTypeBuilder)2 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)2