protected static Object getCassandraObject(Row row, int i, DataType dataType) { if (dataType.equals(DataType.blob())) { return row.getBytes(i); } else if (dataType.equals(DataType.varint()) || dataType.equals(DataType.decimal())) { } else if (dataType.equals(DataType.cboolean())) { return row.getBool(i); } else if (dataType.equals(DataType.cint())) { return row.getInt(i); } else if (dataType.equals(DataType.bigint()) || dataType.equals(DataType.counter())) { return row.getLong(i); } else if (dataType.equals(DataType.ascii()) || dataType.equals(DataType.text()) || dataType.equals(DataType.varchar())) { return row.getString(i); } else if (dataType.equals(DataType.cfloat())) { return row.getFloat(i); } else if (dataType.equals(DataType.cdouble())) { return row.getDouble(i); } else if (dataType.equals(DataType.timestamp())) { return row.getTimestamp(i);
private String getCreateWorkflowsTableStatement() { return SchemaBuilder.createTable(config.getCassandraKeyspace(), TABLE_WORKFLOWS) .ifNotExists() .addPartitionKey(WORKFLOW_ID_KEY, DataType.uuid()) .addPartitionKey(SHARD_ID_KEY, DataType.cint()) .addClusteringColumn(ENTITY_KEY, DataType.text()) .addClusteringColumn(TASK_ID_KEY, DataType.text()) .addColumn(PAYLOAD_KEY, DataType.text()) .addStaticColumn(TOTAL_TASKS_KEY, DataType.cint()) .addStaticColumn(TOTAL_PARTITIONS_KEY, DataType.cint()) .getQueryString(); }
private Object deserializeColumnValue(final String name, final ByteBuffer bb){ switch (name) { case TOKEN_TYPE: case TOKEN_PRINCIPAL_TYPE: return DataType.text().deserialize(bb, ProtocolVersion.NEWEST_SUPPORTED); case TOKEN_CREATED: case TOKEN_ACCESSED: case TOKEN_INACTIVE: case TOKEN_DURATION: return DataType.bigint().deserialize(bb, ProtocolVersion.NEWEST_SUPPORTED); case TOKEN_ENTITY: case TOKEN_APPLICATION: case TOKEN_WORKFLOW_ORG_ID: case TOKEN_UUID: return DataType.uuid().deserialize(bb, ProtocolVersion.NEWEST_SUPPORTED); case TOKEN_STATE: return fromByteBuffer(bb, Object.class); } return null; }
private static Object deserializeMapEntryKey(ByteBuffer bb){ List<Object> stuff = new ArrayList<>(); while(bb.hasRemaining()){ ByteBuffer data = CQLUtils.getWithShortLength(bb); if(stuff.size() == 0){ stuff.add(DataType.uuid().deserialize(data.slice(), ProtocolVersion.NEWEST_SUPPORTED)); }else{ stuff.add(DataType.text().deserialize(data.slice(), ProtocolVersion.NEWEST_SUPPORTED)); } byte equality = bb.get(); // we don't use this but take the equality byte off the buffer } return stuff; }
@Test(groups = "unit") public void should_create_UDT() throws Exception { // When SchemaStatement statement = createType("ks", "myType") .addColumn("col1", DataType.text()) .addColumn("col2", DataType.bigint()); // Then assertThat(statement.getQueryString()) .isEqualTo("\n\tCREATE TYPE ks.myType(\n\t\t" + "col1 text,\n\t\t" + "col2 bigint)"); }
@Test(groups = "unit") public void should_create_simple_table_with_set() throws Exception { // When SchemaStatement statement = createTable("test") .addPartitionKey("id", DataType.bigint()) .addColumn("friends", DataType.set(DataType.text())); // Then assertThat(statement.getQueryString()) .isEqualTo( "\n\tCREATE TABLE test(\n\t\t" + "id bigint,\n\t\t" + "friends set<text>,\n\t\t" + "PRIMARY KEY(id))"); }
@Test(groups = "short") public void should_parse_and_format_aggregate_with_initcond_and_no_finalfunc() { "CREATE AGGREGATE %s.cat_tos(int) SFUNC cat STYPE text INITCOND '0';", keyspace); session().execute(cqlFunction); session().execute(cqlAggregate); KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace); FunctionMetadata stateFunc = keyspace.getFunction("cat", text(), cint()); AggregateMetadata aggregate = keyspace.getAggregate("cat_tos", cint()); assertThat(aggregate).isNotNull(); assertThat(aggregate.getSignature()).isEqualTo("cat_tos(int)"); assertThat(aggregate.getSimpleName()).isEqualTo("cat_tos"); assertThat(aggregate.getArgumentTypes()).containsExactly(cint()); assertThat(aggregate.getFinalFunc()).isNull(); assertThat(aggregate.getInitCond()).isEqualTo("0"); assertThat(aggregate.getReturnType()).isEqualTo(text()); assertThat(aggregate.getStateFunc()).isEqualTo(stateFunc); assertThat(aggregate.getStateType()).isEqualTo(text()); assertThat(aggregate.toString()).isEqualTo(cqlAggregate); assertThat(aggregate.exportAsString()) .isEqualTo(
/** * Validates that tuple values generated from an attached type (cluster-provided TupleType) and a * detached type (using TupleType.of) are the same. * * @since 2.2.0 */ @Test(groups = "short") public void detachedTupleTypeTest() { TupleType detachedType = TupleType.of( protocolVersion, CodecRegistry.DEFAULT_INSTANCE, DataType.cint(), DataType.text(), DataType.cfloat()); TupleValue detachedValue = detachedType.newValue(1, "hello", 2.0f); TupleType attachedType = cluster().getMetadata().newTupleType(DataType.cint(), DataType.text(), DataType.cfloat()); TupleValue attachedValue = attachedType.newValue(1, "hello", 2.0f); assertThat(detachedValue).isEqualTo(attachedValue); }
@SuppressWarnings("deprecation") @Test(groups = "short") public void should_handle_collections_of_tuples() { String query; BuiltStatement statement; query = "UPDATE foo SET l=[(1,2)] WHERE k=1;"; TupleType tupleType = cluster().getMetadata().newTupleType(cint(), cint()); List<TupleValue> list = ImmutableList.of(tupleType.newValue(1, 2)); statement = update("foo").with(set("l", list)).where(eq("k", 1)); assertThat(statement.toString()).isEqualTo(query); } }
@Test(groups = "unit") public void should_create_simple_table_with_map() throws Exception { // When SchemaStatement statement = createTable("test") .addPartitionKey("id", DataType.bigint()) .addColumn("friends", DataType.map(DataType.cint(), DataType.text())); // Then assertThat(statement.getQueryString()) .isEqualTo( "\n\tCREATE TABLE test(\n\t\t" + "id bigint,\n\t\t" + "friends map<int, text>,\n\t\t" + "PRIMARY KEY(id))"); }
@Test(groups = "short") @CassandraVersion("2.0.0") public void should_log_all_parameter_types_simple_statements() throws Exception { // given normal.setLevel(TRACE); queryLogger = QueryLogger.builder().withMaxParameterValueLength(Integer.MAX_VALUE).build(); cluster().register(queryLogger); // when String query = "UPDATE test SET " + assignments + " WHERE pk = 42"; SimpleStatement ss = new SimpleStatement(query, values.toArray()); session().execute(ss); // then String line = normalAppender.waitAndGet(10000); assertThat(line).contains("Query completed normally").contains(ipOfNode(1)).contains(query); CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry(); for (DataType type : dataTypes) { TypeCodec<Object> codec; if (type.equals(DataType.time())) { codec = codecRegistry.codecFor(DataType.bigint()); } else { codec = codecRegistry.codecFor(type); } assertThat(line).contains(codec.format(getFixedValue(type))); } }
@DataProvider public static Object[][] cql() { return new Object[][] { {DataType.blob(), TypeCodec.blob()}, {DataType.cboolean(), TypeCodec.cboolean()}, {DataType.smallint(), TypeCodec.smallInt()}, {DataType.tinyint(), TypeCodec.tinyInt()}, {DataType.cint(), TypeCodec.cint()}, {DataType.bigint(), TypeCodec.bigint()}, {DataType.counter(), TypeCodec.counter()}, {DataType.cdouble(), TypeCodec.cdouble()}, {DataType.cfloat(), TypeCodec.cfloat()}, {DataType.varint(), TypeCodec.varint()}, {DataType.decimal(), TypeCodec.decimal()}, {DataType.varchar(), TypeCodec.varchar()}, {DataType.ascii(), TypeCodec.ascii()}, {DataType.timestamp(), TypeCodec.timestamp()}, {DataType.date(), TypeCodec.date()}, {DataType.time(), TypeCodec.time()}, {DataType.uuid(), TypeCodec.uuid()}, {DataType.timeuuid(), TypeCodec.timeUUID()}, {DataType.inet(), TypeCodec.inet()}, {DataType.duration(), TypeCodec.duration()} }; }
@Test(groups = "short") public void should_drop_an_index() { // Create a table session() .execute( SchemaBuilder.createTable("ks", "DropIndex") .addPartitionKey("a", DataType.cint()) .addClusteringColumn("b", DataType.cint())); // Create an index // Note: we have to pick a lower-case name because Cassandra uses the CamelCase index name at // creation // but a lowercase index name at deletion // See : https://issues.apache.org/jira/browse/CASSANDRA-8365 session() .execute(SchemaBuilder.createIndex("ks_index").onTable("ks", "DropIndex").andColumn("b")); // Verify that the PK index and the secondary indexes both exist assertThat(numberOfIndexedColumns()).isEqualTo(1); // Delete the index session().execute(SchemaBuilder.dropIndex("ks", "ks_index")); // Verify that only the PK index exists assertThat(numberOfIndexedColumns()).isEqualTo(0); }
@Test( groups = "unit", expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "The column name 'ADD' is not allowed because it is a reserved keyword") public void should_fail_if_simple_column_is_a_reserved_keyword() throws Exception { createTable("test") .addPartitionKey("pk", DataType.bigint()) .addClusteringColumn("cluster", DataType.uuid()) .addColumn("ADD", DataType.text()) .getQueryString(); }
@Test(groups = "unit", expectedExceptions = IllegalArgumentException.class) public void should_fail_when_read_repair_chance_out_of_bound() throws Exception { createTable("test") .addPartitionKey("id", DataType.bigint()) .addColumn("name", DataType.text()) .withOptions() .readRepairChance(1.3); }
@Test(groups = "short") public void should_parse_and_format_function_with_udts() { keyspace); session().execute(cqlFunction); KeyspaceMetadata keyspace = cluster().getMetadata().getKeyspace(this.keyspace); UserType addressType = keyspace.getUserType("\"Address\""); FunctionMetadata function = keyspace.getFunction("\"NUM_PHONES_ACCU\"", cint(), addressType); assertThat(function).isNotNull(); assertThat(function.getKeyspace()).isEqualTo(keyspace); assertThat(function.getSignature()).isEqualTo("\"NUM_PHONES_ACCU\"(int,\"Address\")"); assertThat(function.getSimpleName()).isEqualTo("NUM_PHONES_ACCU"); assertThat(function.getReturnType()).isEqualTo(cint()); assertThat(function.getArguments()) .containsExactly(entry("previous_total", cint()), entry("ADDRESS", addressType)); assertThat(function.getLanguage()).isEqualTo("java"); assertThat(function.getBody()).isEqualTo(body); assertThat(function.isCalledOnNullInput()).isTrue();
@Test(groups = "unit") public void parseTupleTest() { String s = "org.apache.cassandra.db.marshal.TupleType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FloatType)"; TupleType type = (TupleType) DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry); assertNotNull(type); assertEquals(type.getComponentTypes().get(0), DataType.cint()); assertEquals(type.getComponentTypes().get(1), DataType.text()); assertEquals(type.getComponentTypes().get(2), DataType.cfloat()); }
@Test(groups = "short", dataProvider = "existingKeyspaceName") @CassandraVersion("2.2.0") public void should_notify_of_function_drop(String keyspace) { session1.execute( String.format( "CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace)); session1.execute(String.format("DROP FUNCTION %s.\"ID\"", keyspace)); for (SchemaChangeListener listener : listeners) { ArgumentCaptor<FunctionMetadata> removed = ArgumentCaptor.forClass(FunctionMetadata.class); verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionRemoved(removed.capture()); assertThat(removed.getValue()).isInKeyspace(handleId(keyspace)).hasSignature("\"ID\"(int)"); } for (Metadata m : metadatas()) assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint())).isNull(); }
@Test(groups = "short", dataProvider = "existingKeyspaceName") @CassandraVersion("2.2.0") public void should_notify_of_aggregate_drop(String keyspace) { session1.execute( String.format( "CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java" + " AS 'return s+v;'", keyspace)); session1.execute( String.format( "CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace)); session1.execute(String.format("DROP AGGREGATE %s.\"SUM\"", keyspace)); for (SchemaChangeListener listener : listeners) { ArgumentCaptor<AggregateMetadata> removed = ArgumentCaptor.forClass(AggregateMetadata.class); verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateRemoved(removed.capture()); assertThat(removed.getValue()).isInKeyspace(handleId(keyspace)).hasSignature("\"SUM\"(int)"); } for (Metadata m : metadatas()) assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint())).isNull(); }
@Test(groups = "unit") public void parseNestedCollectionTest() { // map<text, frozen<map<int,int>>> String s = "org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.Int32Type,org.apache.cassandra.db.marshal.Int32Type)))"; DataType parentMap = DataTypeClassNameParser.parseOne(s, protocolVersion, codecRegistry); assertThat(parentMap) .hasName(DataType.Name.MAP) .isNotFrozen() .hasTypeArgument(0, DataType.text()); DataType childMap = parentMap.getTypeArguments().get(1); assertThat(childMap) .hasName(DataType.Name.MAP) .isFrozen() .hasTypeArguments(DataType.cint(), DataType.cint()); } }