Search in sources :

Example 6 with QueryProcessingException

use of org.teiid.api.exception.query.QueryProcessingException in project teiid by teiid.

the class TempTableStore method getOrCreateTempTable.

TempTable getOrCreateTempTable(String tempTableID, Command command, BufferManager buffer, boolean delegate, boolean forUpdate, CommandContext context, GroupSymbol group) throws TeiidProcessingException, BlockedException, TeiidComponentException {
    if (!(group.getMetadataID() instanceof TempMetadataID)) {
        // TODO: use a proper metadata
        TempTableStore tts = context.getSessionTempTableStore();
        context.setDeterminismLevel(Determinism.SESSION_DETERMINISTIC);
        if (tts.getTempTable(tempTableID) == null) {
            // implicitly create global (session scoped) temp table
            // $NON-NLS-1$
            LogManager.logDetail(LogConstants.CTX_DQP, "binding global temp table to session", group);
            QueryMetadataInterface metadata = context.getMetadata();
            Create create = GlobalTableStoreImpl.getCreateCommand(group, false, metadata);
            tts.addTempTable(tempTableID, create, buffer, true, context);
        }
        return getTempTable(tempTableID, command, buffer, delegate, forUpdate, context);
    }
    TempTable tempTable = getTempTable(tempTableID, command, buffer, delegate, forUpdate, context);
    if (tempTable != null) {
        if (processors != null) {
            TableProcessor withProcessor = processors.get(tempTableID);
            if (withProcessor != null) {
                TempTable tt = withProcessor.process(tempTable);
                if (tt != tempTable) {
                    return tt;
                }
                processors.remove(tempTableID);
            }
        }
        return tempTable;
    }
    // allow implicit temp group definition
    List<ElementSymbol> columns = null;
    if (command instanceof Insert) {
        Insert insert = (Insert) command;
        if (group.isImplicitTempGroupSymbol()) {
            columns = insert.getVariables();
        }
    }
    if (columns == null) {
        if (processors != null) {
            TableProcessor withProcessor = processors.get(tempTableID);
            if (withProcessor != null) {
                // $NON-NLS-1$
                LogManager.logDetail(LogConstants.CTX_DQP, "Creating temporary table for with clause", tempTableID);
                Create create = new Create();
                create.setTable(new GroupSymbol(tempTableID));
                create.setElementSymbolsAsColumns(withProcessor.columns);
                withProcessor.alterCreate(create);
                tempTable = addTempTable(tempTableID, create, buffer, true, context);
                TempTable tt = withProcessor.process(tempTable);
                if (tt != tempTable) {
                    return tt;
                }
                processors.remove(tempTableID);
                return tempTable;
            }
        }
        if (delegate && this.parentTempTableStore != null) {
            // may be a cte from a higher scope that needs to have creation triggered
            return parentTempTableStore.getOrCreateTempTable(tempTableID, command, buffer, delegate, forUpdate, context, group);
        }
        throw new QueryProcessingException(QueryPlugin.Event.TEIID30226, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30226, tempTableID));
    }
    // $NON-NLS-1$
    LogManager.logDetail(LogConstants.CTX_DQP, "Creating temporary table", tempTableID);
    Create create = new Create();
    create.setTable(new GroupSymbol(tempTableID));
    create.setElementSymbolsAsColumns(columns);
    return addTempTable(tempTableID, create, buffer, true, context);
}
Also used : ElementSymbol(org.teiid.query.sql.symbol.ElementSymbol) Create(org.teiid.query.sql.lang.Create) TempMetadataID(org.teiid.query.metadata.TempMetadataID) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) QueryMetadataInterface(org.teiid.query.metadata.QueryMetadataInterface) Insert(org.teiid.query.sql.lang.Insert) QueryProcessingException(org.teiid.api.exception.query.QueryProcessingException)

Example 7 with QueryProcessingException

use of org.teiid.api.exception.query.QueryProcessingException in project teiid by teiid.

the class RowBasedSecurityHelper method evaluateConstraint.

private static void evaluateConstraint(Command atomicCommand, Evaluator eval, Criteria constraint, Map<ElementSymbol, Expression> values) throws BlockedException, TeiidComponentException, QueryProcessingException {
    Criteria clone = (Criteria) constraint.clone();
    ExpressionMappingVisitor.mapExpressions(clone, values);
    try {
        if (!eval.evaluate(clone, null)) {
            throw new QueryProcessingException(QueryPlugin.Event.TEIID31130, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31130, atomicCommand));
        }
    } catch (ExpressionEvaluationException e) {
        throw new QueryProcessingException(QueryPlugin.Event.TEIID31130, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31130, atomicCommand));
    }
}
Also used : ExpressionEvaluationException(org.teiid.api.exception.query.ExpressionEvaluationException) QueryProcessingException(org.teiid.api.exception.query.QueryProcessingException)

Example 8 with QueryProcessingException

use of org.teiid.api.exception.query.QueryProcessingException in project teiid by teiid.

the class ExecDynamicSqlInstruction method process.

/**
 * <p>
 * Processing this instruction executes the ProcessorPlan for the command on
 * the CommandStatement of the update procedure language. Executing this
 * plan does not effect the values of any of the variables defined as part
 * of the update procedure and hence the results of the ProcessPlan
 * execution need not be stored for further processing. The results are
 * removed from the buffer manager immediately after execution. The program
 * counter is incremented after execution of the plan.
 * </p>
 *
 * @throws BlockedException
 *             if this processing the plan throws a currentVarContext
 */
public void process(ProcedurePlan procEnv) throws BlockedException, TeiidComponentException, TeiidProcessingException {
    VariableContext localContext = procEnv.getCurrentVariableContext();
    String query = null;
    try {
        Clob value = (Clob) procEnv.evaluateExpression(dynamicCommand.getSql());
        if (value == null) {
            throw new QueryProcessingException(QueryPlugin.Util.getString(// $NON-NLS-1$
            "ExecDynamicSqlInstruction.0"));
        }
        if (value.length() > MAX_SQL_LENGTH) {
            throw new QueryProcessingException(QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31204, MAX_SQL_LENGTH));
        }
        query = value.getSubString(1, MAX_SQL_LENGTH);
        LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, // $NON-NLS-1$
        new Object[] { "Executing dynamic sql ", query });
        Command command = QueryParser.getQueryParser().parseCommand(query);
        // special handling for dynamic anon blocks
        if (command instanceof CreateProcedureCommand) {
            if (dynamicCommand.getIntoGroup() != null || returnable) {
                // and the creation of an inline view
                throw new QueryProcessingException(QueryPlugin.Event.TEIID31250, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31250));
            }
            ((CreateProcedureCommand) command).setResultSetColumns(Collections.EMPTY_LIST);
        }
        command.setExternalGroupContexts(dynamicCommand.getExternalGroupContexts());
        command.setTemporaryMetadata(dynamicCommand.getTemporaryMetadata().clone());
        updateContextWithUsingValues(procEnv, localContext);
        TempMetadataStore metadataStore = command.getTemporaryMetadata();
        if (dynamicCommand.getUsing() != null && !dynamicCommand.getUsing().isEmpty()) {
            metadataStore.addTempGroup(Reserved.USING, new LinkedList<ElementSymbol>(dynamicCommand.getUsing().getClauseMap().keySet()));
            GroupSymbol using = new GroupSymbol(Reserved.USING);
            using.setMetadataID(metadataStore.getTempGroupID(Reserved.USING));
            command.addExternalGroupToContext(using);
            metadataStore.addTempGroup(ProcedureReservedWords.DVARS, new LinkedList<ElementSymbol>(dynamicCommand.getUsing().getClauseMap().keySet()));
            using = new GroupSymbol(ProcedureReservedWords.DVARS);
            using.setMetadataID(metadataStore.getTempGroupID(ProcedureReservedWords.DVARS));
            command.addExternalGroupToContext(using);
        }
        QueryResolver.resolveCommand(command, metadata.getDesignTimeMetadata());
        validateDynamicCommand(procEnv, command, value.toString());
        // create a new set of variables including vars
        Map<ElementSymbol, Expression> nameValueMap = createVariableValuesMap(localContext);
        ValidationVisitor visitor = new ValidationVisitor();
        Request.validateWithVisitor(visitor, metadata, command);
        boolean insertInto = false;
        boolean updateCommand = false;
        if (!command.returnsResultSet() && !(command instanceof StoredProcedure)) {
            if (dynamicCommand.isAsClauseSet()) {
                if (dynamicCommand.getProjectedSymbols().size() != 1 || ((Expression) dynamicCommand.getProjectedSymbols().get(0)).getType() != DataTypeManager.DefaultDataClasses.INTEGER) {
                    throw new QueryProcessingException(QueryPlugin.Event.TEIID31157, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31157));
                }
            }
            updateCommand = true;
        } else if (dynamicCommand.getAsColumns() != null && !dynamicCommand.getAsColumns().isEmpty()) {
            // $NON-NLS-1$
            command = QueryRewriter.createInlineViewQuery(new GroupSymbol("X"), command, metadata, dynamicCommand.getAsColumns());
            if (dynamicCommand.getIntoGroup() != null) {
                Insert insert = new Insert(dynamicCommand.getIntoGroup(), dynamicCommand.getAsColumns(), Collections.emptyList());
                insert.setQueryExpression((Query) command);
                command = insert;
                insertInto = true;
            }
        }
        // if this is an update procedure, it could reassign variables
        command = QueryRewriter.rewrite(command, metadata, procEnv.getContext(), command instanceof CreateProcedureCommand ? Collections.EMPTY_MAP : nameValueMap);
        ProcessorPlan commandPlan = QueryOptimizer.optimizePlan(command, metadata, idGenerator, capFinder, AnalysisRecord.createNonRecordingRecord(), procEnv.getContext());
        if (command instanceof CreateProcedureCommand && commandPlan instanceof ProcedurePlan) {
            ((ProcedurePlan) commandPlan).setValidateAccess(procEnv.isValidateAccess());
        }
        CreateCursorResultSetInstruction inst = new CreateCursorResultSetInstruction(null, commandPlan, (insertInto || updateCommand) ? Mode.UPDATE : returnable ? Mode.HOLD : Mode.NOHOLD) {

            @Override
            public void process(ProcedurePlan procEnv) throws BlockedException, TeiidComponentException, TeiidProcessingException {
                boolean done = true;
                try {
                    super.process(procEnv);
                } catch (BlockedException e) {
                    done = false;
                    throw e;
                } finally {
                    if (done) {
                        procEnv.getContext().popCall();
                    }
                }
            }
        };
        dynamicProgram = new Program(false);
        dynamicProgram.addInstruction(inst);
        if (dynamicCommand.getIntoGroup() != null) {
            String groupName = dynamicCommand.getIntoGroup().getName();
            if (!procEnv.getTempTableStore().hasTempTable(groupName, true)) {
                // create the temp table in the parent scope
                Create create = new Create();
                create.setTable(new GroupSymbol(groupName));
                for (ElementSymbol es : (List<ElementSymbol>) dynamicCommand.getAsColumns()) {
                    Column c = new Column();
                    c.setName(es.getShortName());
                    c.setRuntimeType(DataTypeManager.getDataTypeName(es.getType()));
                    create.getColumns().add(c);
                }
                procEnv.getDataManager().registerRequest(procEnv.getContext(), create, TempMetadataAdapter.TEMP_MODEL.getName(), new RegisterRequestParameter());
            }
            // backwards compatibility to support into with a rowcount
            if (updateCommand) {
                Insert insert = new Insert();
                insert.setGroup(new GroupSymbol(groupName));
                for (ElementSymbol es : (List<ElementSymbol>) dynamicCommand.getAsColumns()) {
                    ElementSymbol col = new ElementSymbol(es.getShortName(), insert.getGroup());
                    col.setType(es.getType());
                    insert.addVariable(col);
                }
                insert.addValue(new Constant(procEnv.getCurrentVariableContext().getValue(ProcedurePlan.ROWCOUNT)));
                QueryResolver.resolveCommand(insert, metadata.getDesignTimeMetadata());
                TupleSource ts = procEnv.getDataManager().registerRequest(procEnv.getContext(), insert, TempMetadataAdapter.TEMP_MODEL.getName(), new RegisterRequestParameter());
                ts.nextTuple();
                ts.closeSource();
            }
        }
        // Add group to recursion stack
        if (parentProcCommand.getUpdateType() != Command.TYPE_UNKNOWN) {
            // $NON-NLS-1$
            procEnv.getContext().pushCall(Command.getCommandToken(parentProcCommand.getUpdateType()) + " " + parentProcCommand.getVirtualGroup());
        } else {
            if (parentProcCommand.getVirtualGroup() != null) {
                procEnv.getContext().pushCall(parentProcCommand.getVirtualGroup().toString());
            }
        }
        procEnv.push(dynamicProgram);
    } catch (SQLException e) {
        Object[] params = { dynamicCommand, dynamicCommand.getSql(), e.getMessage() };
        throw new QueryProcessingException(QueryPlugin.Event.TEIID30168, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30168, params));
    } catch (TeiidProcessingException e) {
        Object[] params = { dynamicCommand, query == null ? dynamicCommand.getSql() : query, e.getMessage() };
        throw new QueryProcessingException(QueryPlugin.Event.TEIID30168, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30168, params));
    }
}
Also used : ElementSymbol(org.teiid.query.sql.symbol.ElementSymbol) ValidationVisitor(org.teiid.query.validator.ValidationVisitor) CreateProcedureCommand(org.teiid.query.sql.proc.CreateProcedureCommand) Query(org.teiid.query.sql.lang.Query) SQLException(java.sql.SQLException) Constant(org.teiid.query.sql.symbol.Constant) Insert(org.teiid.query.sql.lang.Insert) BlockedException(org.teiid.common.buffer.BlockedException) TeiidProcessingException(org.teiid.core.TeiidProcessingException) Column(org.teiid.metadata.Column) Create(org.teiid.query.sql.lang.Create) List(java.util.List) LinkedList(java.util.LinkedList) VariableContext(org.teiid.query.sql.util.VariableContext) RegisterRequestParameter(org.teiid.query.processor.RegisterRequestParameter) StoredProcedure(org.teiid.query.sql.lang.StoredProcedure) CreateProcedureCommand(org.teiid.query.sql.proc.CreateProcedureCommand) Command(org.teiid.query.sql.lang.Command) DynamicCommand(org.teiid.query.sql.lang.DynamicCommand) Expression(org.teiid.query.sql.symbol.Expression) TupleSource(org.teiid.common.buffer.TupleSource) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) Clob(java.sql.Clob) ProcessorPlan(org.teiid.query.processor.ProcessorPlan) TempMetadataStore(org.teiid.query.metadata.TempMetadataStore) QueryProcessingException(org.teiid.api.exception.query.QueryProcessingException)

Example 9 with QueryProcessingException

use of org.teiid.api.exception.query.QueryProcessingException in project teiid by teiid.

the class ExecDynamicSqlInstruction method validateDynamicCommand.

/**
 * @param procEnv
 * @param command
 * @throws TeiidComponentException
 * @throws QueryProcessingException
 */
private void validateDynamicCommand(ProcedurePlan procEnv, Command command, String commandString) throws TeiidComponentException, QueryProcessingException {
    // validate project symbols
    List dynamicExpectedColumns = dynamicCommand.getAsColumns();
    List<Expression> sourceProjectedSymbolList = command.getProjectedSymbols();
    if (dynamicExpectedColumns != null && !dynamicExpectedColumns.isEmpty()) {
        if (dynamicExpectedColumns.size() != sourceProjectedSymbolList.size()) {
            throw new QueryProcessingException(QueryPlugin.Util.getString(// $NON-NLS-1$
            "ExecDynamicSqlInstruction.4"));
        }
        // If there is only one project symbol, we won't validate the name.
        Iterator dynamicIter = dynamicExpectedColumns.iterator();
        Iterator<Expression> sourceIter = sourceProjectedSymbolList.iterator();
        // the name.
        while (dynamicIter.hasNext()) {
            Expression dynamicSymbol = (Expression) dynamicIter.next();
            Expression sourceExpr = sourceIter.next();
            Class<?> sourceSymbolDatatype = sourceExpr.getType();
            // Check if the the dynamic sql element types are equal or
            // implicitly convertible to the source types
            Class<?> dynamicType = dynamicSymbol.getType();
            String dynamicTypeName = DataTypeManager.getDataTypeName(dynamicType);
            String sourceTypeName = DataTypeManager.getDataTypeName(sourceSymbolDatatype);
            if (!dynamicTypeName.equals(sourceTypeName) && // If the types aren't the same, and...
            !DataTypeManager.isImplicitConversion(sourceTypeName, dynamicTypeName)) {
                // conversion between the two
                throw new QueryProcessingException(QueryPlugin.Util.getString("ExecDynamicSqlInstruction.6", sourceTypeName, sourceExpr, // $NON-NLS-1$
                dynamicTypeName));
            }
        }
    }
    CommandContext context = procEnv.getContext();
    if (procEnv.isValidateAccess() && !context.getDQPWorkContext().isAdmin() && context.getAuthorizationValidator() != null) {
        context.getAuthorizationValidator().validate(new String[] { commandString }, command, metadata, context, CommandType.USER);
    }
}
Also used : CommandContext(org.teiid.query.util.CommandContext) Expression(org.teiid.query.sql.symbol.Expression) Iterator(java.util.Iterator) List(java.util.List) LinkedList(java.util.LinkedList) QueryProcessingException(org.teiid.api.exception.query.QueryProcessingException)

Example 10 with QueryProcessingException

use of org.teiid.api.exception.query.QueryProcessingException in project teiid by teiid.

the class AccessNode method multiSourceModify.

private static RelationalNode multiSourceModify(AccessNode accessNode, Expression ex, QueryMetadataInterface metadata, List<String> sourceNames) throws TeiidComponentException, TeiidProcessingException {
    List<AccessNode> accessNodes = new ArrayList<AccessNode>();
    boolean hasOutParams = RelationalNodeUtil.hasOutputParams(accessNode.getCommand());
    if (!Constant.NULL_CONSTANT.equals(ex)) {
        for (String sourceName : sourceNames) {
            Command command = accessNode.getCommand();
            // Modify the command to pull the instance column and evaluate the criteria
            if (!(command instanceof Insert || command instanceof StoredProcedure)) {
                command = (Command) command.clone();
                MultiSourceElementReplacementVisitor.visit(sourceName, metadata, command);
                if (!RelationalNodeUtil.shouldExecute(command, false, true)) {
                    continue;
                }
            }
            // Create a new cloned version of the access node and set it's model name to be the bindingUUID
            AccessNode instanceNode = (AccessNode) accessNode.clone();
            instanceNode.setMultiSource(false);
            instanceNode.setCommand(command);
            accessNodes.add(instanceNode);
            if (accessNodes.size() > 1 && command instanceof Insert) {
                // $NON-NLS-1$
                throw new AssertionError("Multi-source insert must target a single source.  Should have been caught in validation");
            }
            instanceNode.setConnectorBindingId(sourceName);
        }
    }
    if (hasOutParams && accessNodes.size() != 1) {
        throw new QueryProcessingException(QueryPlugin.Event.TEIID30561, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30561, accessNode.getCommand()));
    }
    switch(accessNodes.size()) {
        case 0:
            {
                if (RelationalNodeUtil.isUpdate(accessNode.getCommand())) {
                    // should return a 0 update count
                    ProjectNode pnode = new ProjectNode(accessNode.getID());
                    pnode.setSelectSymbols(Arrays.asList(new Constant(0)));
                    return pnode;
                }
                // Replace existing access node with a NullNode
                NullNode nullNode = new NullNode(accessNode.getID());
                return nullNode;
            }
        case 1:
            {
                // Replace existing access node with new access node (simplified command)
                return accessNodes.get(0);
            }
        default:
            {
                UnionAllNode unionNode = new UnionAllNode(accessNode.getID());
                unionNode.setElements(accessNode.getElements());
                for (AccessNode newNode : accessNodes) {
                    unionNode.addChild(newNode);
                }
                RelationalNode parent = unionNode;
                // More than 1 access node - replace with a union
                if (RelationalNodeUtil.isUpdate(accessNode.getCommand())) {
                    GroupingNode groupNode = new GroupingNode(accessNode.getID());
                    AggregateSymbol sumCount = new AggregateSymbol(NonReserved.SUM, false, accessNode.getElements().get(0));
                    groupNode.setElements(Arrays.asList(sumCount));
                    groupNode.addChild(unionNode);
                    ProjectNode projectNode = new ProjectNode(accessNode.getID());
                    Expression intSum = ResolverUtil.getConversion(sumCount, DataTypeManager.getDataTypeName(sumCount.getType()), DataTypeManager.DefaultDataTypes.INTEGER, false, metadata.getFunctionLibrary());
                    List<Expression> outputElements = Arrays.asList(intSum);
                    projectNode.setElements(outputElements);
                    projectNode.setSelectSymbols(outputElements);
                    projectNode.addChild(groupNode);
                    parent = projectNode;
                }
                return parent;
            }
    }
}
Also used : AggregateSymbol(org.teiid.query.sql.symbol.AggregateSymbol) Constant(org.teiid.query.sql.symbol.Constant) Insert(org.teiid.query.sql.lang.Insert) StoredProcedure(org.teiid.query.sql.lang.StoredProcedure) QueryCommand(org.teiid.query.sql.lang.QueryCommand) Command(org.teiid.query.sql.lang.Command) WithQueryCommand(org.teiid.query.sql.lang.WithQueryCommand) Expression(org.teiid.query.sql.symbol.Expression) QueryProcessingException(org.teiid.api.exception.query.QueryProcessingException)

Aggregations

QueryProcessingException (org.teiid.api.exception.query.QueryProcessingException)12 List (java.util.List)6 ArrayList (java.util.ArrayList)5 LinkedList (java.util.LinkedList)4 Insert (org.teiid.query.sql.lang.Insert)4 Expression (org.teiid.query.sql.symbol.Expression)4 GroupSymbol (org.teiid.query.sql.symbol.GroupSymbol)4 Test (org.junit.Test)3 TupleSource (org.teiid.common.buffer.TupleSource)3 TransformationMetadata (org.teiid.query.metadata.TransformationMetadata)3 ProcessorPlan (org.teiid.query.processor.ProcessorPlan)3 Command (org.teiid.query.sql.lang.Command)3 Constant (org.teiid.query.sql.symbol.Constant)3 ElementSymbol (org.teiid.query.sql.symbol.ElementSymbol)3 BlockedException (org.teiid.common.buffer.BlockedException)2 Evaluator (org.teiid.query.eval.Evaluator)2 QueryMetadataInterface (org.teiid.query.metadata.QueryMetadataInterface)2 TempMetadataID (org.teiid.query.metadata.TempMetadataID)2 CollectionTupleSource (org.teiid.query.processor.CollectionTupleSource)2 Create (org.teiid.query.sql.lang.Create)2