Search in sources :

Example 1 with QueryOptions

use of org.apache.cassandra.cql3.QueryOptions in project cassandra by apache.

the class CassandraAuthorizer method addPermissionsForRole.

// Add every permission on the resource granted to the role
private void addPermissionsForRole(Set<Permission> permissions, IResource resource, RoleResource role) throws RequestExecutionException, RequestValidationException {
    QueryOptions options = QueryOptions.forInternalCalls(ConsistencyLevel.LOCAL_ONE, Lists.newArrayList(ByteBufferUtil.bytes(role.getRoleName()), ByteBufferUtil.bytes(resource.getName())));
    SelectStatement statement;
    // is being upgraded and so is running with mixed versions of the authz schema
    if (Schema.instance.getTableMetadata(SchemaConstants.AUTH_KEYSPACE_NAME, USER_PERMISSIONS) == null)
        statement = authorizeRoleStatement;
    else {
        // If the permissions table was initialised only after the statement got prepared, re-prepare (CASSANDRA-12813)
        if (legacyAuthorizeRoleStatement == null)
            legacyAuthorizeRoleStatement = prepare(USERNAME, USER_PERMISSIONS);
        statement = legacyAuthorizeRoleStatement;
    }
    ResultMessage.Rows rows = statement.execute(QueryState.forInternalCalls(), options, System.nanoTime());
    UntypedResultSet result = UntypedResultSet.create(rows.result);
    if (!result.isEmpty() && result.one().has(PERMISSIONS)) {
        for (String perm : result.one().getSet(PERMISSIONS, UTF8Type.instance)) {
            permissions.add(Permission.valueOf(perm));
        }
    }
}
Also used : UntypedResultSet(org.apache.cassandra.cql3.UntypedResultSet) SelectStatement(org.apache.cassandra.cql3.statements.SelectStatement) ResultMessage(org.apache.cassandra.transport.messages.ResultMessage) QueryOptions(org.apache.cassandra.cql3.QueryOptions)

Example 2 with QueryOptions

use of org.apache.cassandra.cql3.QueryOptions 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 3 with QueryOptions

use of org.apache.cassandra.cql3.QueryOptions in project cassandra by apache.

the class SelectStatement method process.

private ResultSet process(PartitionIterator partitions, QueryOptions options, int nowInSec, int userLimit) throws InvalidRequestException {
    Selection.ResultSetBuilder result = selection.resultSetBuilder(options, parameters.isJson, aggregationSpec);
    while (partitions.hasNext()) {
        try (RowIterator partition = partitions.next()) {
            processPartition(partition, options, result, nowInSec);
        }
    }
    ResultSet cqlRows = result.build();
    orderResults(cqlRows);
    cqlRows.trim(userLimit);
    return cqlRows;
}
Also used : Selection(org.apache.cassandra.cql3.selection.Selection) RowIterator(org.apache.cassandra.db.rows.RowIterator)

Example 4 with QueryOptions

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

use of org.apache.cassandra.cql3.QueryOptions in project cassandra by apache.

the class ExecuteMessage method execute.

public Message.Response execute(QueryState state, long queryStartNanoTime) {
    try {
        QueryHandler handler = ClientState.getCQLQueryHandler();
        ParsedStatement.Prepared prepared = handler.getPrepared(statementId);
        if (prepared == null)
            throw new PreparedQueryNotFoundException(statementId);
        options.prepare(prepared.boundNames);
        CQLStatement statement = prepared.statement;
        if (options.getPageSize() == 0)
            throw new ProtocolException("The page size cannot be 0");
        UUID tracingId = null;
        if (isTracingRequested()) {
            tracingId = UUIDGen.getTimeUUID();
            state.prepareTracingSession(tracingId);
        }
        if (state.traceNextQuery()) {
            state.createTracingSession(getCustomPayload());
            ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
            if (options.getPageSize() > 0)
                builder.put("page_size", Integer.toString(options.getPageSize()));
            if (options.getConsistency() != null)
                builder.put("consistency_level", options.getConsistency().name());
            if (options.getSerialConsistency() != null)
                builder.put("serial_consistency_level", options.getSerialConsistency().name());
            builder.put("query", prepared.rawCQLStatement);
            for (int i = 0; i < prepared.boundNames.size(); i++) {
                ColumnSpecification cs = prepared.boundNames.get(i);
                String boundName = cs.name.toString();
                String boundValue = cs.type.asCQL3Type().toCQLLiteral(options.getValues().get(i), options.getProtocolVersion());
                if (boundValue.length() > 1000) {
                    boundValue = boundValue.substring(0, 1000) + "...'";
                }
                //Here we prefix boundName with the index to avoid possible collission in builder keys due to
                //having multiple boundValues for the same variable
                builder.put("bound_var_" + Integer.toString(i) + "_" + boundName, boundValue);
            }
            Tracing.instance.begin("Execute CQL3 prepared query", state.getClientAddress(), builder.build());
        }
        // Some custom QueryHandlers are interested by the bound names. We provide them this information
        // by wrapping the QueryOptions.
        QueryOptions queryOptions = QueryOptions.addColumnSpecifications(options, prepared.boundNames);
        Message.Response response = handler.processPrepared(statement, state, queryOptions, getCustomPayload(), queryStartNanoTime);
        if (options.skipMetadata() && response instanceof ResultMessage.Rows)
            ((ResultMessage.Rows) response).result.metadata.setSkipMetadata();
        if (tracingId != null)
            response.setTracingId(tracingId);
        return response;
    } catch (Exception e) {
        JVMStabilityInspector.inspectThrowable(e);
        return ErrorMessage.fromException(e);
    } finally {
        Tracing.instance.stopSession();
    }
}
Also used : CQLStatement(org.apache.cassandra.cql3.CQLStatement) QueryHandler(org.apache.cassandra.cql3.QueryHandler) ColumnSpecification(org.apache.cassandra.cql3.ColumnSpecification) ParsedStatement(org.apache.cassandra.cql3.statements.ParsedStatement) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) QueryOptions(org.apache.cassandra.cql3.QueryOptions) ImmutableMap(com.google.common.collect.ImmutableMap) PreparedQueryNotFoundException(org.apache.cassandra.exceptions.PreparedQueryNotFoundException) UUID(java.util.UUID)

Aggregations

QueryOptions (org.apache.cassandra.cql3.QueryOptions)5 ByteBuffer (java.nio.ByteBuffer)3 InvalidRequestException (org.apache.cassandra.exceptions.InvalidRequestException)3 ColumnSpecification (org.apache.cassandra.cql3.ColumnSpecification)2 UpdateParameters (org.apache.cassandra.cql3.UpdateParameters)2 Selection (org.apache.cassandra.cql3.selection.Selection)2 ParsedStatement (org.apache.cassandra.cql3.statements.ParsedStatement)2 ColumnMetadata (org.apache.cassandra.schema.ColumnMetadata)2 ImmutableMap (com.google.common.collect.ImmutableMap)1 IOException (java.io.IOException)1 java.util (java.util)1 List (java.util.List)1 UUID (java.util.UUID)1 ExecutionException (java.util.concurrent.ExecutionException)1 CQLStatement (org.apache.cassandra.cql3.CQLStatement)1 QueryHandler (org.apache.cassandra.cql3.QueryHandler)1 MultiItemTerminal (org.apache.cassandra.cql3.Term.MultiItemTerminal)1 Terminal (org.apache.cassandra.cql3.Term.Terminal)1 UntypedResultSet (org.apache.cassandra.cql3.UntypedResultSet)1 Function (org.apache.cassandra.cql3.functions.Function)1