Search in sources :

Example 6 with Type

use of org.apache.cassandra.cql3.statements.schema.IndexTarget.Type in project cassandra by apache.

the class ElementsSelector method newSliceFactory.

/**
 * Creates a {@code Selector.Factory} for the selection of a slice of a collection.
 *
 * @param name a string representing the selection the factory is for. Something like "c[x..y]".
 * @param factory the {@code Selector.Factory} corresponding to the collection on which a slice
 * is selected.
 * @param type the type of the collection.
 * @param from the starting bound of the selected slice. This cannot be {@code null} but can be
 * {@code Constants.UNSET_VALUE} if the slice doesn't have a start.
 * @param to the ending bound of the selected slice. This cannot be {@code null} but can be
 * {@code Constants.UNSET_VALUE} if the slice doesn't have an end.
 * @return the created factory.
 */
public static Factory newSliceFactory(String name, Selector.Factory factory, CollectionType<?> type, final Term from, final Term to) {
    return new AbstractFactory(name, factory, type) {

        protected AbstractType<?> getReturnType() {
            return type;
        }

        public Selector newInstance(QueryOptions options) throws InvalidRequestException {
            ByteBuffer fromValue = from.bindAndGet(options);
            ByteBuffer toValue = to.bindAndGet(options);
            // Note that we use UNSET values to represent no bound, so null is truly invalid
            if (fromValue == null || toValue == null)
                throw new InvalidRequestException("Invalid null value for slice selection on " + factory.getColumnName());
            return new SliceSelector(factory.newInstance(options), from.bindAndGet(options), to.bindAndGet(options));
        }

        public boolean areAllFetchedColumnsKnown() {
            // 3) the bound of the selected slice are terminal.
            return factory.areAllFetchedColumnsKnown() && (!type.isMultiCell() || !factory.isSimpleSelectorFactory() || (from.isTerminal() && to.isTerminal()));
        }

        public void addFetchedColumns(ColumnFilter.Builder builder) {
            if (!type.isMultiCell() || !factory.isSimpleSelectorFactory()) {
                factory.addFetchedColumns(builder);
                return;
            }
            ColumnMetadata column = ((SimpleSelectorFactory) factory).getColumn();
            ByteBuffer fromBB = ((Term.Terminal) from).get(ProtocolVersion.V3);
            ByteBuffer toBB = ((Term.Terminal) to).get(ProtocolVersion.V3);
            builder.slice(column, isUnset(fromBB) ? CellPath.BOTTOM : CellPath.create(fromBB), isUnset(toBB) ? CellPath.TOP : CellPath.create(toBB));
        }
    };
}
Also used : ColumnMetadata(org.apache.cassandra.schema.ColumnMetadata) SimpleSelectorFactory(org.apache.cassandra.cql3.selection.SimpleSelector.SimpleSelectorFactory) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException) QueryOptions(org.apache.cassandra.cql3.QueryOptions) ByteBuffer(java.nio.ByteBuffer)

Example 7 with Type

use of org.apache.cassandra.cql3.statements.schema.IndexTarget.Type in project cassandra by apache.

the class Terms method ofListMarker.

/**
 * Creates a {@code Terms} for the specified list marker.
 *
 * @param marker the list  marker
 * @param type the element type
 * @return a {@code Terms} for the specified list marker
 */
public static Terms ofListMarker(final Lists.Marker marker, final AbstractType<?> type) {
    return new Terms() {

        @Override
        public void addFunctionsTo(List<Function> functions) {
        }

        @Override
        public void collectMarkerSpecification(VariableSpecifications boundNames) {
            marker.collectMarkerSpecification(boundNames);
        }

        @Override
        public List<ByteBuffer> bindAndGet(QueryOptions options) {
            Terminal terminal = marker.bind(options);
            if (terminal == null)
                return null;
            if (terminal == Constants.UNSET_VALUE)
                return UNSET_LIST;
            return ((MultiItemTerminal) terminal).getElements();
        }

        @Override
        public List<Terminal> bind(QueryOptions options) {
            Terminal terminal = marker.bind(options);
            if (terminal == null)
                return null;
            if (terminal == Constants.UNSET_VALUE)
                return UNSET_LIST;
            java.util.function.Function<ByteBuffer, Term.Terminal> deserializer = deserializer(options.getProtocolVersion());
            List<ByteBuffer> boundValues = ((MultiItemTerminal) terminal).getElements();
            List<Term.Terminal> values = new ArrayList<>(boundValues.size());
            for (int i = 0, m = boundValues.size(); i < m; i++) {
                ByteBuffer buffer = boundValues.get(i);
                Term.Terminal value = buffer == null ? null : deserializer.apply(buffer);
                values.add(value);
            }
            return values;
        }

        public java.util.function.Function<ByteBuffer, Term.Terminal> deserializer(ProtocolVersion version) {
            if (type.isCollection()) {
                switch(((CollectionType<?>) type).kind) {
                    case LIST:
                        return e -> Lists.Value.fromSerialized(e, (ListType<?>) type, version);
                    case SET:
                        return e -> Sets.Value.fromSerialized(e, (SetType<?>) type, version);
                    case MAP:
                        return e -> Maps.Value.fromSerialized(e, (MapType<?, ?>) type, version);
                }
                throw new AssertionError();
            }
            return e -> new Constants.Value(e);
        }
    };
}
Also used : MultiItemTerminal(org.apache.cassandra.cql3.Term.MultiItemTerminal) Terminal(org.apache.cassandra.cql3.Term.Terminal) java.util(java.util) Function(org.apache.cassandra.cql3.functions.Function) org.apache.cassandra.db.marshal(org.apache.cassandra.db.marshal) MultiItemTerminal(org.apache.cassandra.cql3.Term.MultiItemTerminal) ProtocolVersion(org.apache.cassandra.transport.ProtocolVersion) ByteBuffer(java.nio.ByteBuffer) ProtocolVersion(org.apache.cassandra.transport.ProtocolVersion) ByteBuffer(java.nio.ByteBuffer) Terminal(org.apache.cassandra.cql3.Term.Terminal) MultiItemTerminal(org.apache.cassandra.cql3.Term.MultiItemTerminal) Terminal(org.apache.cassandra.cql3.Term.Terminal)

Example 8 with Type

use of org.apache.cassandra.cql3.statements.schema.IndexTarget.Type in project cassandra by apache.

the class AggregateFcts method all.

public static Collection<AggregateFunction> all() {
    Collection<AggregateFunction> functions = new ArrayList<>();
    functions.add(countRowsFunction);
    // sum for primitives
    functions.add(sumFunctionForByte);
    functions.add(sumFunctionForShort);
    functions.add(sumFunctionForInt32);
    functions.add(sumFunctionForLong);
    functions.add(sumFunctionForFloat);
    functions.add(sumFunctionForDouble);
    functions.add(sumFunctionForDecimal);
    functions.add(sumFunctionForVarint);
    functions.add(sumFunctionForCounter);
    // avg for primitives
    functions.add(avgFunctionForByte);
    functions.add(avgFunctionForShort);
    functions.add(avgFunctionForInt32);
    functions.add(avgFunctionForLong);
    functions.add(avgFunctionForFloat);
    functions.add(avgFunctionForDouble);
    functions.add(avgFunctionForDecimal);
    functions.add(avgFunctionForVarint);
    functions.add(avgFunctionForCounter);
    // count, max, and min for all standard types
    for (CQL3Type type : CQL3Type.Native.values()) {
        if (// varchar and text both mapping to UTF8Type
        type != CQL3Type.Native.VARCHAR) {
            functions.add(AggregateFcts.makeCountFunction(type.getType()));
            if (type != CQL3Type.Native.COUNTER) {
                functions.add(AggregateFcts.makeMaxFunction(type.getType()));
                functions.add(AggregateFcts.makeMinFunction(type.getType()));
            } else {
                functions.add(AggregateFcts.maxFunctionForCounter);
                functions.add(AggregateFcts.minFunctionForCounter);
            }
        }
    }
    return functions;
}
Also used : CQL3Type(org.apache.cassandra.cql3.CQL3Type) ArrayList(java.util.ArrayList)

Example 9 with Type

use of org.apache.cassandra.cql3.statements.schema.IndexTarget.Type in project cassandra by apache.

the class UFJavaTest method testJavaKeyspaceFunction.

@Test
public void testJavaKeyspaceFunction() throws Throwable {
    createTable("CREATE TABLE %s (key int primary key, val double)");
    String functionBody = '\n' + "  // parameter val is of type java.lang.Double\n" + "  /* return type is of type java.lang.Double */\n" + "  if (val == null) {\n" + "    return null;\n" + "  }\n" + "  return Math.sin( val );\n";
    String fName = createFunction(KEYSPACE_PER_TEST, "double", "CREATE OR REPLACE FUNCTION %s(val double) " + "CALLED ON NULL INPUT " + "RETURNS double " + "LANGUAGE JAVA " + "AS '" + functionBody + "';");
    FunctionName fNameName = parseFunctionName(fName);
    assertRows(execute("SELECT language, body FROM system_schema.functions WHERE keyspace_name=? AND function_name=?", fNameName.keyspace, fNameName.name), row("java", functionBody));
    execute("INSERT INTO %s (key, val) VALUES (?, ?)", 1, 1d);
    execute("INSERT INTO %s (key, val) VALUES (?, ?)", 2, 2d);
    execute("INSERT INTO %s (key, val) VALUES (?, ?)", 3, 3d);
    assertRows(execute("SELECT key, val, " + fName + "(val) FROM %s"), row(1, 1d, Math.sin(1d)), row(2, 2d, Math.sin(2d)), row(3, 3d, Math.sin(3d)));
}
Also used : FunctionName(org.apache.cassandra.cql3.functions.FunctionName) Test(org.junit.Test)

Example 10 with Type

use of org.apache.cassandra.cql3.statements.schema.IndexTarget.Type in project cassandra by apache.

the class UFJavaTest method testJavaUserType.

@Test
public void testJavaUserType() throws Throwable {
    String type = KEYSPACE + '.' + createType("CREATE TYPE %s (txt text, i int)");
    createTable("CREATE TABLE %s (key int primary key, udt frozen<" + type + ">)");
    String fUdt0 = createFunction(KEYSPACE, type, "CREATE FUNCTION %s( udt " + type + " ) " + "RETURNS NULL ON NULL INPUT " + "RETURNS " + type + " " + "LANGUAGE java " + "AS $$return " + "     udt;$$;");
    String fUdt1 = createFunction(KEYSPACE, type, "CREATE FUNCTION %s( udt " + type + ") " + "RETURNS NULL ON NULL INPUT " + "RETURNS text " + "LANGUAGE java " + "AS $$return " + "     udt.getString(\"txt\");$$;");
    String fUdt2 = createFunction(KEYSPACE, type, "CREATE FUNCTION %s( udt " + type + ") " + "CALLED ON NULL INPUT " + "RETURNS int " + "LANGUAGE java " + "AS $$return " + "     Integer.valueOf(udt.getInt(\"i\"));$$;");
    execute("INSERT INTO %s (key, udt) VALUES (1, {txt: 'one', i:1})");
    UntypedResultSet rows = execute("SELECT " + fUdt0 + "(udt) FROM %s WHERE key = 1");
    Assert.assertEquals(1, rows.size());
    assertRows(execute("SELECT " + fUdt1 + "(udt) FROM %s WHERE key = 1"), row("one"));
    assertRows(execute("SELECT " + fUdt2 + "(udt) FROM %s WHERE key = 1"), row(1));
    for (ProtocolVersion version : PROTOCOL_VERSIONS) {
        List<Row> rowsNet = executeNet(version, "SELECT " + fUdt0 + "(udt) FROM %s WHERE key = 1").all();
        Assert.assertEquals(1, rowsNet.size());
        UDTValue udtVal = rowsNet.get(0).getUDTValue(0);
        Assert.assertEquals("one", udtVal.getString("txt"));
        Assert.assertEquals(1, udtVal.getInt("i"));
        assertRowsNet(version, executeNet(version, "SELECT " + fUdt1 + "(udt) FROM %s WHERE key = 1"), row("one"));
        assertRowsNet(version, executeNet(version, "SELECT " + fUdt2 + "(udt) FROM %s WHERE key = 1"), row(1));
    }
}
Also used : UntypedResultSet(org.apache.cassandra.cql3.UntypedResultSet) UDTValue(com.datastax.driver.core.UDTValue) Row(com.datastax.driver.core.Row) ProtocolVersion(org.apache.cassandra.transport.ProtocolVersion) Test(org.junit.Test)

Aggregations

CQL3Type (org.apache.cassandra.cql3.CQL3Type)14 ByteBuffer (java.nio.ByteBuffer)12 Test (org.junit.Test)12 AbstractType (org.apache.cassandra.db.marshal.AbstractType)11 ColumnMetadata (org.apache.cassandra.schema.ColumnMetadata)10 ArrayList (java.util.ArrayList)9 List (java.util.List)8 ClientState (org.apache.cassandra.service.ClientState)8 ColumnIdentifier (org.apache.cassandra.cql3.ColumnIdentifier)7 ProtocolVersion (org.apache.cassandra.transport.ProtocolVersion)7 FunctionName (org.apache.cassandra.cql3.functions.FunctionName)6 InvalidRequestException (org.apache.cassandra.exceptions.InvalidRequestException)6 java.util (java.util)4 Collections (java.util.Collections)4 ChronicleQueue (net.openhft.chronicle.queue.ChronicleQueue)4 ExcerptTailer (net.openhft.chronicle.queue.ExcerptTailer)4 RollCycles (net.openhft.chronicle.queue.RollCycles)4 QueryOptions (org.apache.cassandra.cql3.QueryOptions)4 TableMetadata (org.apache.cassandra.schema.TableMetadata)4 Set (java.util.Set)3