Search in sources :

Example 1 with Selection

use of org.apache.cassandra.cql3.selection.Selection in project cassandra by apache.

the class ModificationStatement method buildCasFailureResultSet.

private static ResultSet buildCasFailureResultSet(RowIterator partition, Iterable<ColumnMetadata> columnsWithConditions, boolean isBatch, QueryOptions options) throws InvalidRequestException {
    TableMetadata metadata = partition.metadata();
    Selection selection;
    if (columnsWithConditions == null) {
        selection = Selection.wildcard(metadata);
    } else {
        // We can have multiple conditions on the same columns (for collections) so use a set
        // to avoid duplicate, but preserve the order just to it follows the order of IF in the query in general
        Set<ColumnMetadata> defs = new LinkedHashSet<>();
        // of batches for compatibility sakes).
        if (isBatch)
            Iterables.addAll(defs, metadata.primaryKeyColumns());
        Iterables.addAll(defs, columnsWithConditions);
        selection = Selection.forColumns(metadata, new ArrayList<>(defs));
    }
    Selection.ResultSetBuilder builder = selection.resultSetBuilder(options, false);
    SelectStatement.forSelection(metadata, selection).processPartition(partition, options, builder, FBUtilities.nowInSeconds());
    return builder.build();
}
Also used : TableMetadata(org.apache.cassandra.schema.TableMetadata) ColumnMetadata(org.apache.cassandra.schema.ColumnMetadata) Selection(org.apache.cassandra.cql3.selection.Selection)

Example 2 with Selection

use of org.apache.cassandra.cql3.selection.Selection in project cassandra by apache.

the class FunctionResolver method get.

/**
     * @param keyspace the current keyspace
     * @param name the name of the function
     * @param providedArgs the arguments provided for the function call
     * @param receiverKs the receiver's keyspace
     * @param receiverCf the receiver's table
     * @param receiverType if the receiver type is known (during inserts, for example), this should be the type of
     *                     the receiver
     * @throws InvalidRequestException
     */
public static Function get(String keyspace, FunctionName name, List<? extends AssignmentTestable> providedArgs, String receiverKs, String receiverCf, AbstractType<?> receiverType) throws InvalidRequestException {
    if (name.equalsNativeFunction(TOKEN_FUNCTION_NAME))
        return new TokenFct(Schema.instance.getTableMetadata(receiverKs, receiverCf));
    // due to needing to know the argument types in advance).
    if (name.equalsNativeFunction(ToJsonFct.NAME))
        throw new InvalidRequestException("toJson() may only be used within the selection clause of SELECT statements");
    // Similarly, we can only use fromJson when we know the receiver type (such as inserts)
    if (name.equalsNativeFunction(FromJsonFct.NAME)) {
        if (receiverType == null)
            throw new InvalidRequestException("fromJson() cannot be used in the selection clause of a SELECT statement");
        return FromJsonFct.getInstance(receiverType);
    }
    Collection<Function> candidates;
    if (!name.hasKeyspace()) {
        // function name not fully qualified
        candidates = new ArrayList<>();
        // add 'SYSTEM' (native) candidates
        candidates.addAll(Schema.instance.getFunctions(name.asNativeFunction()));
        // add 'current keyspace' candidates
        candidates.addAll(Schema.instance.getFunctions(new FunctionName(keyspace, name.name)));
    } else {
        // function name is fully qualified (keyspace + name)
        candidates = Schema.instance.getFunctions(name);
    }
    if (candidates.isEmpty())
        return null;
    // Fast path if there is only one choice
    if (candidates.size() == 1) {
        Function fun = candidates.iterator().next();
        validateTypes(keyspace, fun, providedArgs, receiverKs, receiverCf);
        return fun;
    }
    List<Function> compatibles = null;
    for (Function toTest : candidates) {
        if (matchReturnType(toTest, receiverType)) {
            AssignmentTestable.TestResult r = matchAguments(keyspace, toTest, providedArgs, receiverKs, receiverCf);
            switch(r) {
                case EXACT_MATCH:
                    // We always favor exact matches
                    return toTest;
                case WEAKLY_ASSIGNABLE:
                    if (compatibles == null)
                        compatibles = new ArrayList<>();
                    compatibles.add(toTest);
                    break;
            }
        }
    }
    if (compatibles == null) {
        if (OperationFcts.isOperation(name))
            throw invalidRequest("the '%s' operation is not supported between %s and %s", OperationFcts.getOperator(name), providedArgs.get(0), providedArgs.get(1));
        throw invalidRequest("Invalid call to function %s, none of its type signatures match (known type signatures: %s)", name, format(candidates));
    }
    if (compatibles.size() > 1) {
        if (OperationFcts.isOperation(name)) {
            if (receiverType != null && !containsMarkers(providedArgs)) {
                for (Function toTest : compatibles) {
                    List<AbstractType<?>> argTypes = toTest.argTypes();
                    if (receiverType.equals(argTypes.get(0)) && receiverType.equals(argTypes.get(1)))
                        return toTest;
                }
            }
            throw invalidRequest("Ambiguous '%s' operation: use type casts to disambiguate", OperationFcts.getOperator(name), providedArgs.get(0), providedArgs.get(1));
        }
        if (OperationFcts.isNegation(name))
            throw invalidRequest("Ambiguous negation: use type casts to disambiguate");
        throw invalidRequest("Ambiguous call to function %s (can be matched by following signatures: %s): use type casts to disambiguate", name, format(compatibles));
    }
    return compatibles.get(0);
}
Also used : AssignmentTestable(org.apache.cassandra.cql3.AssignmentTestable) ArrayList(java.util.ArrayList) AbstractType(org.apache.cassandra.db.marshal.AbstractType) InvalidRequestException(org.apache.cassandra.exceptions.InvalidRequestException)

Example 3 with Selection

use of org.apache.cassandra.cql3.selection.Selection in project cassandra by apache.

the class ModificationStatement method buildCasFailureResultSet.

private static ResultSet buildCasFailureResultSet(RowIterator partition, Iterable<ColumnMetadata> columnsWithConditions, boolean isBatch, QueryOptions options, int nowInSeconds) {
    TableMetadata metadata = partition.metadata();
    Selection selection;
    if (columnsWithConditions == null) {
        selection = Selection.wildcard(metadata, false, false);
    } else {
        // We can have multiple conditions on the same columns (for collections) so use a set
        // to avoid duplicate, but preserve the order just to it follows the order of IF in the query in general
        Set<ColumnMetadata> defs = new LinkedHashSet<>();
        // of batches for compatibility sakes).
        if (isBatch)
            Iterables.addAll(defs, metadata.primaryKeyColumns());
        Iterables.addAll(defs, columnsWithConditions);
        selection = Selection.forColumns(metadata, new ArrayList<>(defs), false);
    }
    Selectors selectors = selection.newSelectors(options);
    ResultSetBuilder builder = new ResultSetBuilder(selection.getResultMetadata(), selectors);
    SelectStatement.forSelection(metadata, selection).processPartition(partition, options, builder, nowInSeconds);
    return builder.build();
}
Also used : TableMetadata(org.apache.cassandra.schema.TableMetadata) ColumnMetadata(org.apache.cassandra.schema.ColumnMetadata) ResultSetBuilder(org.apache.cassandra.cql3.selection.ResultSetBuilder) Selection(org.apache.cassandra.cql3.selection.Selection) Selectors(org.apache.cassandra.cql3.selection.Selection.Selectors)

Example 4 with Selection

use of org.apache.cassandra.cql3.selection.Selection 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 5 with Selection

use of org.apache.cassandra.cql3.selection.Selection in project cassandra by apache.

the class CollectionsTest method testCollectionOperationResultSetMetadata.

@Test
public void testCollectionOperationResultSetMetadata() throws Throwable {
    createTable("CREATE TABLE %s (k int PRIMARY KEY," + "m map<text, text>," + "fm frozen<map<text, text>>," + "s set<text>," + "fs frozen<set<text>>)");
    execute("INSERT INTO %s (k, m, fm, s, fs) VALUES (?, ?, ?, ?, ?)", 0, map("1", "one", "2", "two"), map("1", "one", "2", "two"), set("1", "2", "3"), set("1", "2", "3"));
    String cql = "SELECT k, " + "m, m['2'], m['2'..'3'], m[..'2'], m['3'..], " + "fm, fm['2'], fm['2'..'3'], fm[..'2'], fm['3'..], " + "s, s['2'], s['2'..'3'], s[..'2'], s['3'..], " + "fs, fs['2'], fs['2'..'3'], fs[..'2'], fs['3'..] " + "FROM " + KEYSPACE + '.' + currentTable() + " WHERE k = 0";
    UntypedResultSet result = execute(cql);
    Iterator<ColumnSpecification> meta = result.metadata().iterator();
    meta.next();
    for (int i = 0; i < 4; i++) {
        // take the "full" collection selection
        ColumnSpecification ref = meta.next();
        ColumnSpecification selSingle = meta.next();
        assertEquals(ref.toString(), UTF8Type.instance, selSingle.type);
        for (int selOrSlice = 0; selOrSlice < 3; selOrSlice++) {
            ColumnSpecification selSlice = meta.next();
            assertEquals(ref.toString(), ref.type, selSlice.type);
        }
    }
    assertRows(result, row(0, map("1", "one", "2", "two"), "two", map("2", "two"), map("1", "one", "2", "two"), null, map("1", "one", "2", "two"), "two", map("2", "two"), map("1", "one", "2", "two"), map(), set("1", "2", "3"), "2", set("2", "3"), set("1", "2"), set("3"), set("1", "2", "3"), "2", set("2", "3"), set("1", "2"), set("3")));
    Session session = sessionNet();
    ResultSet rset = session.execute(cql);
    ColumnDefinitions colDefs = rset.getColumnDefinitions();
    Iterator<ColumnDefinitions.Definition> colDefIter = colDefs.asList().iterator();
    colDefIter.next();
    for (int i = 0; i < 4; i++) {
        // take the "full" collection selection
        ColumnDefinitions.Definition ref = colDefIter.next();
        ColumnDefinitions.Definition selSingle = colDefIter.next();
        assertEquals(ref.getName(), DataType.NativeType.text(), selSingle.getType());
        for (int selOrSlice = 0; selOrSlice < 3; selOrSlice++) {
            ColumnDefinitions.Definition selSlice = colDefIter.next();
            assertEquals(ref.getName() + ' ' + ref.getType(), ref.getType(), selSlice.getType());
        }
    }
}
Also used : UntypedResultSet(org.apache.cassandra.cql3.UntypedResultSet) ColumnSpecification(org.apache.cassandra.cql3.ColumnSpecification) ColumnDefinitions(com.datastax.driver.core.ColumnDefinitions) ResultSet(com.datastax.driver.core.ResultSet) UntypedResultSet(org.apache.cassandra.cql3.UntypedResultSet) Session(com.datastax.driver.core.Session) Test(org.junit.Test)

Aggregations

ColumnMetadata (org.apache.cassandra.schema.ColumnMetadata)5 InvalidRequestException (org.apache.cassandra.exceptions.InvalidRequestException)4 TableMetadata (org.apache.cassandra.schema.TableMetadata)3 ByteBuffer (java.nio.ByteBuffer)2 QueryOptions (org.apache.cassandra.cql3.QueryOptions)2 Selection (org.apache.cassandra.cql3.selection.Selection)2 SimpleSelectorFactory (org.apache.cassandra.cql3.selection.SimpleSelector.SimpleSelectorFactory)2 ColumnDefinitions (com.datastax.driver.core.ColumnDefinitions)1 ResultSet (com.datastax.driver.core.ResultSet)1 Session (com.datastax.driver.core.Session)1 ArrayList (java.util.ArrayList)1 AssignmentTestable (org.apache.cassandra.cql3.AssignmentTestable)1 ColumnSpecification (org.apache.cassandra.cql3.ColumnSpecification)1 UntypedResultSet (org.apache.cassandra.cql3.UntypedResultSet)1 StatementRestrictions (org.apache.cassandra.cql3.restrictions.StatementRestrictions)1 RawSelector (org.apache.cassandra.cql3.selection.RawSelector)1 ResultSetBuilder (org.apache.cassandra.cql3.selection.ResultSetBuilder)1 Selectable (org.apache.cassandra.cql3.selection.Selectable)1 Selectors (org.apache.cassandra.cql3.selection.Selection.Selectors)1 AbstractType (org.apache.cassandra.db.marshal.AbstractType)1