Search in sources :

Example 1 with TupleType

use of com.datastax.driver.core.TupleType in project cassandra by apache.

the class TraceCqlTest method testCqlStatementTracing.

@Test
public void testCqlStatementTracing() throws Throwable {
    requireNetwork();
    createTable("CREATE TABLE %s (id int primary key, v1 text, v2 text)");
    execute("INSERT INTO %s (id, v1, v2) VALUES (?, ?, ?)", 1, "Apache", "Cassandra");
    execute("INSERT INTO %s (id, v1, v2) VALUES (?, ?, ?)", 2, "trace", "test");
    try (Session session = sessionNet()) {
        String cql = "SELECT id, v1, v2 FROM " + KEYSPACE + '.' + currentTable() + " WHERE id = ?";
        PreparedStatement pstmt = session.prepare(cql).enableTracing();
        QueryTrace trace = session.execute(pstmt.bind(1)).getExecutionInfo().getQueryTrace();
        assertEquals(cql, trace.getParameters().get("query"));
        assertEquals("1", trace.getParameters().get("bound_var_0_id"));
        String cql2 = "SELECT id, v1, v2 FROM " + KEYSPACE + '.' + currentTable() + " WHERE id IN (?, ?, ?)";
        pstmt = session.prepare(cql2).enableTracing();
        trace = session.execute(pstmt.bind(19, 15, 16)).getExecutionInfo().getQueryTrace();
        assertEquals(cql2, trace.getParameters().get("query"));
        assertEquals("19", trace.getParameters().get("bound_var_0_id"));
        assertEquals("15", trace.getParameters().get("bound_var_1_id"));
        assertEquals("16", trace.getParameters().get("bound_var_2_id"));
        // some more complex tests for tables with map and tuple data types and long bound values
        createTable("CREATE TABLE %s (id int primary key, v1 text, v2 tuple<int, text, float>, v3 map<int, text>)");
        execute("INSERT INTO %s (id, v1, v2, v3) values (?, ?, ?, ?)", 12, "mahdix", tuple(3, "bar", 2.1f), map(1290, "birthday", 39, "anniversary"));
        execute("INSERT INTO %s (id, v1, v2, v3) values (?, ?, ?, ?)", 274, "CassandraRocks", tuple(9, "foo", 3.14f), map(9181, "statement", 716, "public speech"));
        cql = "SELECT id, v1, v2, v3 FROM " + KEYSPACE + '.' + currentTable() + " WHERE v2 = ? ALLOW FILTERING";
        pstmt = session.prepare(cql).enableTracing();
        TupleType tt = TupleType.of(ProtocolVersion.NEWEST_SUPPORTED, CodecRegistry.DEFAULT_INSTANCE, DataType.cint(), DataType.text(), DataType.cfloat());
        TupleValue value = tt.newValue();
        value.setInt(0, 3);
        value.setString(1, "bar");
        value.setFloat(2, 2.1f);
        trace = session.execute(pstmt.bind(value)).getExecutionInfo().getQueryTrace();
        assertEquals(cql, trace.getParameters().get("query"));
        assertEquals("(3, 'bar', 2.1)", trace.getParameters().get("bound_var_0_v2"));
        cql2 = "SELECT id, v1, v2, v3 FROM " + KEYSPACE + '.' + currentTable() + " WHERE v3 CONTAINS KEY ? ALLOW FILTERING";
        pstmt = session.prepare(cql2).enableTracing();
        trace = session.execute(pstmt.bind(9181)).getExecutionInfo().getQueryTrace();
        assertEquals(cql2, trace.getParameters().get("query"));
        assertEquals("9181", trace.getParameters().get("bound_var_0_key(v3)"));
        String boundValue = "Indulgence announcing uncommonly met she continuing two unpleasing terminated. Now " + "busy say down the shed eyes roof paid her. Of shameless collected suspicion existence " + "in. Share walls stuff think but the arise guest. Course suffer to do he sussex it " + "window advice. Yet matter enable misery end extent common men should. Her indulgence " + "but assistance favourable cultivated everything collecting." + "On projection apartments unsatiable so if he entreaties appearance. Rose you wife " + "how set lady half wish. Hard sing an in true felt. Welcomed stronger if steepest " + "ecstatic an suitable finished of oh. Entered at excited at forming between so " + "produce. Chicken unknown besides attacks gay compact out you. Continuing no " + "simplicity no favourable on reasonably melancholy estimating. Own hence views two " + "ask right whole ten seems. What near kept met call old west dine. Our announcing " + "sufficient why pianoforte. Full age foo set feel her told. Tastes giving in passed" + "direct me valley as supply. End great stood boy noisy often way taken short. Rent the " + "size our more door. Years no place abode in \uFEFFno child my. Man pianoforte too " + "solicitude friendship devonshire ten ask. Course sooner its silent but formal she " + "led. Extensive he assurance extremity at breakfast. Dear sure ye sold fine sell on. " + "Projection at up connection literature insensible motionless projecting." + "Nor hence hoped her after other known defer his. For county now sister engage had " + "season better had waited. Occasional mrs interested far expression acceptance. Day " + "either mrs talent pulled men rather regret admire but. Life ye sake it shed. Five " + "lady he cold in meet up. Service get met adapted matters offence for. Principles man " + "any insipidity age you simplicity understood. Do offering pleasure no ecstatic " + "whatever on mr directly. ";
        String cql3 = "SELECT id, v1, v2, v3 FROM " + KEYSPACE + '.' + currentTable() + " WHERE v3 CONTAINS ? ALLOW FILTERING";
        pstmt = session.prepare(cql3).enableTracing();
        trace = session.execute(pstmt.bind(boundValue)).getExecutionInfo().getQueryTrace();
        assertEquals(cql3, trace.getParameters().get("query"));
        // when tracing is done, this boundValue will be surrounded by single quote, and first 1000 characters
        // will be filtered. Here we take into account single quotes by adding them to the expected output
        assertEquals("'" + boundValue.substring(0, 999) + "...'", trace.getParameters().get("bound_var_0_value(v3)"));
    }
}
Also used : TupleType(com.datastax.driver.core.TupleType) PreparedStatement(com.datastax.driver.core.PreparedStatement) QueryTrace(com.datastax.driver.core.QueryTrace) TupleValue(com.datastax.driver.core.TupleValue) Session(com.datastax.driver.core.Session) Test(org.junit.Test)

Example 2 with TupleType

use of com.datastax.driver.core.TupleType in project cassandra by apache.

the class UFJavaTest method testJavaTupleTypeCollection.

@Test
public void testJavaTupleTypeCollection() throws Throwable {
    String tupleTypeDef = "tuple<double, list<double>, set<text>, map<int, boolean>>";
    createTable("CREATE TABLE %s (key int primary key, tup frozen<" + tupleTypeDef + ">)");
    String fTup0 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "CALLED ON NULL INPUT " + "RETURNS " + tupleTypeDef + ' ' + "LANGUAGE java\n" + "AS $$return " + "       tup;$$;");
    String fTup1 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "CALLED ON NULL INPUT " + "RETURNS double " + "LANGUAGE java\n" + "AS $$return " + "       Double.valueOf(tup.getDouble(0));$$;");
    String fTup2 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "RETURNS NULL ON NULL INPUT " + "RETURNS list<double> " + "LANGUAGE java\n" + "AS $$return " + "       tup.getList(1, Double.class);$$;");
    String fTup3 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "RETURNS NULL ON NULL INPUT " + "RETURNS set<text> " + "LANGUAGE java\n" + "AS $$return " + "       tup.getSet(2, String.class);$$;");
    String fTup4 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "RETURNS NULL ON NULL INPUT " + "RETURNS map<int, boolean> " + "LANGUAGE java\n" + "AS $$return " + "       tup.getMap(3, Integer.class, Boolean.class);$$;");
    List<Double> list = Arrays.asList(1d, 2d, 3d);
    Set<String> set = new TreeSet<>(Arrays.asList("one", "three", "two"));
    Map<Integer, Boolean> map = new TreeMap<>();
    map.put(1, true);
    map.put(2, false);
    map.put(3, true);
    Object t = tuple(1d, list, set, map);
    execute("INSERT INTO %s (key, tup) VALUES (1, ?)", t);
    assertRows(execute("SELECT " + fTup0 + "(tup) FROM %s WHERE key = 1"), row(t));
    assertRows(execute("SELECT " + fTup1 + "(tup) FROM %s WHERE key = 1"), row(1d));
    assertRows(execute("SELECT " + fTup2 + "(tup) FROM %s WHERE key = 1"), row(list));
    assertRows(execute("SELECT " + fTup3 + "(tup) FROM %s WHERE key = 1"), row(set));
    assertRows(execute("SELECT " + fTup4 + "(tup) FROM %s WHERE key = 1"), row(map));
    // same test - but via native protocol
    // we use protocol V3 here to encode the expected version because the server
    // always serializes Collections using V3 - see CollectionSerializer's
    // serialize and deserialize methods.
    TupleType tType = tupleTypeOf(ProtocolVersion.V3, DataType.cdouble(), DataType.list(DataType.cdouble()), DataType.set(DataType.text()), DataType.map(DataType.cint(), DataType.cboolean()));
    TupleValue tup = tType.newValue(1d, list, set, map);
    for (ProtocolVersion version : PROTOCOL_VERSIONS) {
        assertRowsNet(version, executeNet(version, "SELECT " + fTup0 + "(tup) FROM %s WHERE key = 1"), row(tup));
        assertRowsNet(version, executeNet(version, "SELECT " + fTup1 + "(tup) FROM %s WHERE key = 1"), row(1d));
        assertRowsNet(version, executeNet(version, "SELECT " + fTup2 + "(tup) FROM %s WHERE key = 1"), row(list));
        assertRowsNet(version, executeNet(version, "SELECT " + fTup3 + "(tup) FROM %s WHERE key = 1"), row(set));
        assertRowsNet(version, executeNet(version, "SELECT " + fTup4 + "(tup) FROM %s WHERE key = 1"), row(map));
    }
}
Also used : TreeMap(java.util.TreeMap) ProtocolVersion(org.apache.cassandra.transport.ProtocolVersion) TupleValue(com.datastax.driver.core.TupleValue) TreeSet(java.util.TreeSet) TupleType(com.datastax.driver.core.TupleType) Test(org.junit.Test)

Example 3 with TupleType

use of com.datastax.driver.core.TupleType in project cassandra by apache.

the class UFPureScriptTupleCollectionTest method testJavascriptTupleTypeCollection.

// Just JavaScript UDFs to check how UDF - especially security/class-loading/sandboxing stuff -
// behaves, if no Java UDF has been executed before.
// Do not add any other test here!
// See CASSANDRA-10141
@Test
public void testJavascriptTupleTypeCollection() throws Throwable {
    String tupleTypeDef = "tuple<double, list<double>, set<text>, map<int, boolean>>";
    createTable("CREATE TABLE %s (key int primary key, tup frozen<" + tupleTypeDef + ">)");
    String fTup1 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "RETURNS NULL ON NULL INPUT " + "RETURNS tuple<double, list<double>, set<text>, map<int, boolean>> " + "LANGUAGE javascript\n" + "AS $$" + "       tup;$$;");
    String fTup2 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "RETURNS NULL ON NULL INPUT " + "RETURNS double " + "LANGUAGE javascript\n" + "AS $$" + "       tup.getDouble(0);$$;");
    String fTup3 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "RETURNS NULL ON NULL INPUT " + "RETURNS list<double> " + "LANGUAGE javascript\n" + "AS $$" + "       tup.getList(1, java.lang.Double.class);$$;");
    String fTup4 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "RETURNS NULL ON NULL INPUT " + "RETURNS set<text> " + "LANGUAGE javascript\n" + "AS $$" + "       tup.getSet(2, java.lang.String.class);$$;");
    String fTup5 = createFunction(KEYSPACE_PER_TEST, tupleTypeDef, "CREATE FUNCTION %s( tup " + tupleTypeDef + " ) " + "RETURNS NULL ON NULL INPUT " + "RETURNS map<int, boolean> " + "LANGUAGE javascript\n" + "AS $$" + "       tup.getMap(3, java.lang.Integer.class, java.lang.Boolean.class);$$;");
    List<Double> list = Arrays.asList(1d, 2d, 3d);
    Set<String> set = new TreeSet<>(Arrays.asList("one", "three", "two"));
    Map<Integer, Boolean> map = new TreeMap<>();
    map.put(1, true);
    map.put(2, false);
    map.put(3, true);
    Object t = tuple(1d, list, set, map);
    execute("INSERT INTO %s (key, tup) VALUES (1, ?)", t);
    assertRows(execute("SELECT " + fTup1 + "(tup) FROM %s WHERE key = 1"), row(t));
    assertRows(execute("SELECT " + fTup2 + "(tup) FROM %s WHERE key = 1"), row(1d));
    assertRows(execute("SELECT " + fTup3 + "(tup) FROM %s WHERE key = 1"), row(list));
    assertRows(execute("SELECT " + fTup4 + "(tup) FROM %s WHERE key = 1"), row(set));
    assertRows(execute("SELECT " + fTup5 + "(tup) FROM %s WHERE key = 1"), row(map));
    // same test - but via native protocol
    // we use protocol V3 here to encode the expected version because the server
    // always serializes Collections using V3 - see CollectionSerializer's
    // serialize and deserialize methods.
    TupleType tType = tupleTypeOf(ProtocolVersion.V3, DataType.cdouble(), DataType.list(DataType.cdouble()), DataType.set(DataType.text()), DataType.map(DataType.cint(), DataType.cboolean()));
    TupleValue tup = tType.newValue(1d, list, set, map);
    for (ProtocolVersion version : PROTOCOL_VERSIONS) {
        assertRowsNet(version, executeNet(version, "SELECT " + fTup1 + "(tup) FROM %s WHERE key = 1"), row(tup));
        assertRowsNet(version, executeNet(version, "SELECT " + fTup2 + "(tup) FROM %s WHERE key = 1"), row(1d));
        assertRowsNet(version, executeNet(version, "SELECT " + fTup3 + "(tup) FROM %s WHERE key = 1"), row(list));
        assertRowsNet(version, executeNet(version, "SELECT " + fTup4 + "(tup) FROM %s WHERE key = 1"), row(set));
        assertRowsNet(version, executeNet(version, "SELECT " + fTup5 + "(tup) FROM %s WHERE key = 1"), row(map));
    }
}
Also used : TreeMap(java.util.TreeMap) ProtocolVersion(org.apache.cassandra.transport.ProtocolVersion) TupleValue(com.datastax.driver.core.TupleValue) TreeSet(java.util.TreeSet) TupleType(com.datastax.driver.core.TupleType) Test(org.junit.Test)

Example 4 with TupleType

use of com.datastax.driver.core.TupleType in project jhipster-sample-app-cassandra by jhipster.

the class CassandraConfiguration method cluster.

@Bean
public Cluster cluster(CassandraProperties properties) {
    Cluster.Builder builder = Cluster.builder().withClusterName(properties.getClusterName()).withProtocolVersion(protocolVersion).withPort(getPort(properties));
    if (properties.getUsername() != null) {
        builder.withCredentials(properties.getUsername(), properties.getPassword());
    }
    if (properties.getCompression() != null) {
        builder.withCompression(properties.getCompression());
    }
    if (properties.getLoadBalancingPolicy() != null) {
        LoadBalancingPolicy policy = instantiate(properties.getLoadBalancingPolicy());
        builder.withLoadBalancingPolicy(policy);
    }
    builder.withQueryOptions(getQueryOptions(properties));
    if (properties.getReconnectionPolicy() != null) {
        ReconnectionPolicy policy = instantiate(properties.getReconnectionPolicy());
        builder.withReconnectionPolicy(policy);
    }
    if (properties.getRetryPolicy() != null) {
        RetryPolicy policy = instantiate(properties.getRetryPolicy());
        builder.withRetryPolicy(policy);
    }
    builder.withSocketOptions(getSocketOptions(properties));
    if (properties.isSsl()) {
        builder.withSSL();
    }
    builder.addContactPoints(StringUtils.toStringArray(properties.getContactPoints()));
    Cluster cluster = builder.build();
    TupleType tupleType = cluster.getMetadata().newTupleType(DataType.timestamp(), DataType.varchar());
    cluster.getConfiguration().getCodecRegistry().register(LocalDateCodec.instance).register(InstantCodec.instance).register(new ZonedDateTimeCodec(tupleType));
    if (metricRegistry != null) {
        cluster.init();
        metricRegistry.registerAll(cluster.getMetrics().getRegistry());
    }
    return cluster;
}
Also used : LoadBalancingPolicy(com.datastax.driver.core.policies.LoadBalancingPolicy) ReconnectionPolicy(com.datastax.driver.core.policies.ReconnectionPolicy) TupleType(com.datastax.driver.core.TupleType) Cluster(com.datastax.driver.core.Cluster) RetryPolicy(com.datastax.driver.core.policies.RetryPolicy) ZonedDateTimeCodec(com.datastax.driver.extras.codecs.jdk8.ZonedDateTimeCodec) Bean(org.springframework.context.annotation.Bean)

Example 5 with TupleType

use of com.datastax.driver.core.TupleType in project DataX by alibaba.

the class CassandraReaderHelper method transferObjectForJson.

static Object transferObjectForJson(Object o, DataType type) throws TypeNotSupported {
    if (o == null)
        return o;
    switch(type.getName()) {
        case ASCII:
        case TEXT:
        case VARCHAR:
        case BOOLEAN:
        case SMALLINT:
        case TINYINT:
        case INT:
        case BIGINT:
        case VARINT:
        case FLOAT:
        case DOUBLE:
        case DECIMAL:
        case UUID:
        case TIMEUUID:
        case TIME:
            return o;
        case BLOB:
            ByteBuffer byteBuffer = (ByteBuffer) o;
            String s = Base64.encodeBase64String(Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()));
            return s;
        case DATE:
            return ((LocalDate) o).getMillisSinceEpoch();
        case TIMESTAMP:
            return ((Date) o).getTime();
        case DURATION:
            return o.toString();
        case INET:
            return ((InetAddress) o).getHostAddress();
        case LIST:
            {
                return transferListForJson((List) o, type.getTypeArguments().get(0));
            }
        case MAP:
            {
                DataType keyType = type.getTypeArguments().get(0);
                DataType valType = type.getTypeArguments().get(1);
                return transferMapForJson((Map) o, keyType, valType);
            }
        case SET:
            {
                return transferSetForJson((Set) o, type.getTypeArguments().get(0));
            }
        case TUPLE:
            {
                return transferTupleForJson((TupleValue) o, ((TupleType) type).getComponentTypes());
            }
        case UDT:
            {
                return transferUDTForJson((UDTValue) o);
            }
        default:
            throw new TypeNotSupported();
    }
}
Also used : UDTValue(com.datastax.driver.core.UDTValue) HashSet(java.util.HashSet) Set(java.util.Set) ByteBuffer(java.nio.ByteBuffer) LocalDate(com.datastax.driver.core.LocalDate) Date(java.util.Date) LocalDate(com.datastax.driver.core.LocalDate) TupleValue(com.datastax.driver.core.TupleValue) TupleType(com.datastax.driver.core.TupleType) DataType(com.datastax.driver.core.DataType) ArrayList(java.util.ArrayList) List(java.util.List) InetAddress(java.net.InetAddress) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

TupleType (com.datastax.driver.core.TupleType)7 TupleValue (com.datastax.driver.core.TupleValue)5 Test (org.junit.Test)3 TreeMap (java.util.TreeMap)2 TreeSet (java.util.TreeSet)2 ProtocolVersion (org.apache.cassandra.transport.ProtocolVersion)2 Test (org.testng.annotations.Test)2 Cluster (com.datastax.driver.core.Cluster)1 DataType (com.datastax.driver.core.DataType)1 LocalDate (com.datastax.driver.core.LocalDate)1 PreparedStatement (com.datastax.driver.core.PreparedStatement)1 QueryTrace (com.datastax.driver.core.QueryTrace)1 Session (com.datastax.driver.core.Session)1 UDTValue (com.datastax.driver.core.UDTValue)1 LoadBalancingPolicy (com.datastax.driver.core.policies.LoadBalancingPolicy)1 ReconnectionPolicy (com.datastax.driver.core.policies.ReconnectionPolicy)1 RetryPolicy (com.datastax.driver.core.policies.RetryPolicy)1 ZonedDateTimeCodec (com.datastax.driver.extras.codecs.jdk8.ZonedDateTimeCodec)1 InetAddress (java.net.InetAddress)1 ByteBuffer (java.nio.ByteBuffer)1