Search in sources :

Example 26 with QueryResolverException

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

the class SourceTriggerActionPlanner method optimize.

@Override
public ProcessorPlan optimize(Command command, IDGenerator idGenerator, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord, CommandContext context) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
    SourceEventCommand sec = (SourceEventCommand) command;
    Map<Expression, Integer> lookup = new HashMap<Expression, Integer>();
    Map<ElementSymbol, Expression> params = new HashMap<ElementSymbol, Expression>();
    List<Object> tuple = new ArrayList<Object>();
    Map<String, Integer> map = null;
    if (sec.getColumnNames() != null) {
        map = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
        for (String name : sec.getColumnNames()) {
            map.put(name, map.size());
        }
    }
    GroupSymbol changingGroup = new GroupSymbol(ProcedureReservedWords.CHANGING);
    if (sec.newValues != null) {
        GroupSymbol newGroup = new GroupSymbol(SQLConstants.Reserved.NEW);
        newGroup.setMetadataID(sec.table);
        for (int i = 0; i < sec.getTable().getColumns().size(); i++) {
            Column c = sec.getTable().getColumns().get(i);
            Integer index = null;
            if (map != null) {
                index = map.get(c.getName());
            } else {
                index = i;
            }
            ElementSymbol newElement = new ElementSymbol(c.getName(), newGroup);
            newElement.setMetadataID(c);
            ElementSymbol changingElement = new ElementSymbol(c.getName(), changingGroup);
            lookup.put(newElement, tuple.size());
            lookup.put(changingElement, tuple.size() + 1);
            params.put(newElement, newElement);
            params.put(changingElement, changingElement);
            if (index == null) {
                // not changing
                tuple.add(new Constant(null));
                tuple.add(new Constant(Boolean.FALSE));
            } else {
                // changing
                tuple.add(new Constant(DataTypeManager.convertToRuntimeType(sec.newValues[index], true)));
                tuple.add(new Constant(Boolean.TRUE));
            }
        }
    }
    if (sec.oldValues != null) {
        GroupSymbol oldGroup = new GroupSymbol(SQLConstants.Reserved.OLD);
        oldGroup.setMetadataID(sec.table);
        for (int i = 0; i < sec.getTable().getColumns().size(); i++) {
            Column c = sec.getTable().getColumns().get(i);
            Integer index = null;
            if (map != null) {
                index = map.get(c.getName());
            } else {
                index = i;
            }
            ElementSymbol oldElement = new ElementSymbol(c.getName(), oldGroup);
            oldElement.setMetadataID(c);
            lookup.put(oldElement, tuple.size());
            params.put(oldElement, oldElement);
            if (index != null) {
                tuple.add(new Constant(DataTypeManager.convertToRuntimeType(sec.oldValues[index], true)));
            }
        }
    }
    List<ProcessorPlan> plans = new ArrayList<ProcessorPlan>();
    List<String> names = new ArrayList<String>();
    for (Trigger tr : sec.getTable().getTriggers().values()) {
        int updateType = Command.TYPE_UPDATE;
        switch(tr.getEvent()) {
            case DELETE:
                updateType = Command.TYPE_DELETE;
                if (sec.newValues != null) {
                    continue;
                }
                break;
            case INSERT:
                updateType = Command.TYPE_INSERT;
                if (sec.oldValues != null) {
                    continue;
                }
                break;
            case UPDATE:
                if (sec.oldValues == null || sec.newValues == null) {
                    continue;
                }
                break;
        }
        // create plan
        ForEachRowPlan result = new ForEachRowPlan();
        result.setSingleRow(true);
        result.setParams(params);
        TriggerAction parseProcedure;
        GroupSymbol gs = new GroupSymbol(sec.table.getFullName());
        try {
            parseProcedure = (TriggerAction) QueryParser.getQueryParser().parseProcedure(tr.getPlan(), true);
            QueryResolver.resolveCommand(parseProcedure, gs, updateType, metadata.getDesignTimeMetadata(), false);
        } catch (QueryParserException e) {
            // should have been validated
            throw new TeiidComponentException(e);
        } catch (QueryResolverException e) {
            // should have been validated
            throw new TeiidComponentException(e);
        }
        CreateProcedureCommand cpc = new CreateProcedureCommand(parseProcedure.getBlock());
        gs.setMetadataID(sec.table);
        cpc.setVirtualGroup(gs);
        cpc.setUpdateType(updateType);
        ProcedurePlan rowProcedure = (ProcedurePlan) QueryOptimizer.optimizePlan(cpc, metadata, idGenerator, capFinder, analysisRecord, context);
        rowProcedure.setRunInContext(false);
        result.setRowProcedure(rowProcedure);
        result.setLookupMap(lookup);
        result.setTupleSource(new CollectionTupleSource(Arrays.asList(tuple).iterator()));
        plans.add(result);
        names.add(tr.getName());
    }
    return new CompositeProcessorPlan(plans, names, sec.table);
}
Also used : ElementSymbol(org.teiid.query.sql.symbol.ElementSymbol) QueryParserException(org.teiid.api.exception.query.QueryParserException) TriggerAction(org.teiid.query.sql.proc.TriggerAction) CreateProcedureCommand(org.teiid.query.sql.proc.CreateProcedureCommand) HashMap(java.util.HashMap) Constant(org.teiid.query.sql.symbol.Constant) ArrayList(java.util.ArrayList) CollectionTupleSource(org.teiid.query.processor.CollectionTupleSource) QueryResolverException(org.teiid.api.exception.query.QueryResolverException) Trigger(org.teiid.metadata.Trigger) Column(org.teiid.metadata.Column) ForEachRowPlan(org.teiid.query.processor.proc.ForEachRowPlan) Expression(org.teiid.query.sql.symbol.Expression) ProcedurePlan(org.teiid.query.processor.proc.ProcedurePlan) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) TeiidComponentException(org.teiid.core.TeiidComponentException) ProcessorPlan(org.teiid.query.processor.ProcessorPlan)

Example 27 with QueryResolverException

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

the class MetadataValidator method validate.

private void validate(VDBMetaData vdb, ModelMetaData model, AbstractMetadataRecord record, ValidatorReport report, QueryMetadataInterface metadata, MetadataFactory mf) {
    ValidatorReport resolverReport = null;
    try {
        if (record instanceof Procedure) {
            Procedure p = (Procedure) record;
            Command command = parser.parseProcedure(p.getQueryPlan(), false);
            validateNoReferences(command, report, model);
            QueryResolver.resolveCommand(command, new GroupSymbol(p.getFullName()), Command.TYPE_STORED_PROCEDURE, metadata, false);
            resolverReport = Validator.validate(command, metadata);
            determineDependencies(p, command);
        } else if (record instanceof Table) {
            Table t = (Table) record;
            GroupSymbol symbol = new GroupSymbol(t.getFullName());
            ResolverUtil.resolveGroup(symbol, metadata);
            String selectTransformation = t.getSelectTransformation();
            QueryNode node = null;
            if (t.isVirtual()) {
                QueryCommand command = (QueryCommand) parser.parseCommand(selectTransformation);
                validateNoReferences(command, report, model);
                QueryResolver.resolveCommand(command, metadata);
                resolverReport = Validator.validate(command, metadata);
                if (!resolverReport.hasItems() && (t.getColumns() == null || t.getColumns().isEmpty())) {
                    List<Expression> symbols = command.getProjectedSymbols();
                    for (Expression column : symbols) {
                        try {
                            addColumn(Symbol.getShortName(column), column.getType(), t, mf);
                        } catch (TranslatorException e) {
                            log(report, model, e.getMessage());
                        }
                    }
                }
                node = QueryResolver.resolveView(symbol, new QueryNode(selectTransformation), SQLConstants.Reserved.SELECT, metadata, true);
                if (t.getColumns() != null && !t.getColumns().isEmpty()) {
                    determineDependencies(t, command);
                    if (t.getInsertPlan() != null && t.isInsertPlanEnabled()) {
                        validateUpdatePlan(model, report, metadata, t, t.getInsertPlan(), Command.TYPE_INSERT);
                    }
                    if (t.getUpdatePlan() != null && t.isUpdatePlanEnabled()) {
                        validateUpdatePlan(model, report, metadata, t, t.getUpdatePlan(), Command.TYPE_UPDATE);
                    }
                    if (t.getDeletePlan() != null && t.isDeletePlanEnabled()) {
                        validateUpdatePlan(model, report, metadata, t, t.getDeletePlan(), Command.TYPE_DELETE);
                    }
                }
            }
            boolean addCacheHint = false;
            if (t.isVirtual() && t.isMaterialized() && t.getMaterializedTable() == null) {
                List<KeyRecord> fbis = t.getFunctionBasedIndexes();
                List<GroupSymbol> groups = Arrays.asList(symbol);
                if (fbis != null && !fbis.isEmpty()) {
                    for (KeyRecord fbi : fbis) {
                        for (int j = 0; j < fbi.getColumns().size(); j++) {
                            Column c = fbi.getColumns().get(j);
                            if (c.getParent() != fbi) {
                                continue;
                            }
                            String exprString = c.getNameInSource();
                            try {
                                Expression ex = parser.parseExpression(exprString);
                                validateNoReferences(ex, report, model);
                                ResolverVisitor.resolveLanguageObject(ex, groups, metadata);
                                if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(ex).isEmpty()) {
                                    log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31114, exprString, fbi.getFullName()));
                                }
                                EvaluatableVisitor ev = new EvaluatableVisitor();
                                PreOrPostOrderNavigator.doVisit(ex, ev, PreOrPostOrderNavigator.PRE_ORDER);
                                if (ev.getDeterminismLevel().compareTo(Determinism.VDB_DETERMINISTIC) < 0) {
                                    log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31115, exprString, fbi.getFullName()));
                                }
                            } catch (QueryResolverException e) {
                                log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31116, exprString, fbi.getFullName(), e.getMessage()));
                            }
                        }
                    }
                }
            } else {
                addCacheHint = true;
            }
            if (node != null && addCacheHint && t.isMaterialized()) {
                CacheHint cacheHint = node.getCommand().getCacheHint();
                Long ttl = -1L;
                if (cacheHint != null) {
                    if (cacheHint.getTtl() != null && t.getProperty(MaterializationMetadataRepository.MATVIEW_TTL, false) == null) {
                        ttl = cacheHint.getTtl();
                        t.setProperty(MaterializationMetadataRepository.MATVIEW_TTL, String.valueOf(ttl));
                    }
                    if (cacheHint.getUpdatable() != null && t.getProperty(MaterializationMetadataRepository.MATVIEW_UPDATABLE, false) == null) {
                        t.setProperty(MaterializationMetadataRepository.MATVIEW_UPDATABLE, String.valueOf(cacheHint.getUpdatable()));
                    }
                    if (cacheHint.getPrefersMemory() != null && t.getProperty(MaterializationMetadataRepository.MATVIEW_PREFER_MEMORY, false) == null) {
                        t.setProperty(MaterializationMetadataRepository.MATVIEW_PREFER_MEMORY, String.valueOf(cacheHint.getPrefersMemory()));
                    }
                    if (cacheHint.getScope() != null && t.getProperty(MaterializationMetadataRepository.MATVIEW_SHARE_SCOPE, false) == null) {
                        log(report, model, Severity.WARNING, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31252, t.getName(), cacheHint.getScope().name()));
                        t.setProperty(MaterializationMetadataRepository.MATVIEW_SHARE_SCOPE, MaterializationMetadataRepository.Scope.IMPORTED.name());
                    }
                }
            }
        }
        processReport(model, record, report, resolverReport);
    } catch (TeiidException e) {
        log(report, model, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31080, record.getFullName(), e.getMessage()));
    }
}
Also used : CacheHint(org.teiid.query.sql.lang.CacheHint) ValidatorReport(org.teiid.query.validator.ValidatorReport) QueryResolverException(org.teiid.api.exception.query.QueryResolverException) TeiidException(org.teiid.core.TeiidException) EvaluatableVisitor(org.teiid.query.sql.visitor.EvaluatableVisitor) CreateProcedureCommand(org.teiid.query.sql.proc.CreateProcedureCommand) Command(org.teiid.query.sql.lang.Command) QueryCommand(org.teiid.query.sql.lang.QueryCommand) Expression(org.teiid.query.sql.symbol.Expression) QueryNode(org.teiid.query.mapping.relational.QueryNode) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) QueryCommand(org.teiid.query.sql.lang.QueryCommand) TranslatorException(org.teiid.translator.TranslatorException)

Example 28 with QueryResolverException

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

the class PreparedStatementRequest method resolveParameterValues.

/**
 * @param params
 * @param values
 * @throws QueryResolverException
 * @throws QueryValidatorException
 */
public static void resolveParameterValues(List<Reference> params, List values, CommandContext context, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException, QueryValidatorException {
    VariableContext result = new VariableContext();
    // the size of the values must be the same as that of the parameters
    if (params.size() != values.size()) {
        // $NON-NLS-1$
        String msg = QueryPlugin.Util.getString("QueryUtil.wrong_number_of_values", new Object[] { new Integer(values.size()), new Integer(params.size()) });
        throw new QueryResolverException(QueryPlugin.Event.TEIID30556, msg);
    }
    boolean embedded = context != null && context.getSession() != null && context.getSession().isEmbedded();
    // to that of the reference
    for (int i = 0; i < params.size(); i++) {
        Reference param = params.get(i);
        Object value = values.get(i);
        if (value != null) {
            if (embedded && value instanceof BaseLob) {
                createStreamCopy(context, i, param, value);
            }
            try {
                String targetTypeName = DataTypeManager.getDataTypeName(param.getType());
                Expression expr = ResolverUtil.convertExpression(new Constant(DataTypeManager.convertToRuntimeType(value, param.getType() != DataTypeManager.DefaultDataClasses.OBJECT)), targetTypeName, metadata);
                value = Evaluator.evaluate(expr);
            } catch (ExpressionEvaluationException e) {
                // $NON-NLS-1$
                String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", i + 1, value, value.getClass(), DataTypeManager.getDataTypeName(param.getType()));
                throw new QueryResolverException(QueryPlugin.Event.TEIID30557, e, msg);
            } catch (QueryResolverException e) {
                // $NON-NLS-1$
                String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", i + 1, value, value.getClass(), DataTypeManager.getDataTypeName(param.getType()));
                throw new QueryResolverException(QueryPlugin.Event.TEIID30558, e, msg);
            }
        }
        if (param.getConstraint() != null) {
            param.getConstraint().validate(value);
        }
        // bind variable
        result.setGlobalValue(param.getContextSymbol(), value);
    }
    context.setVariableContext(result);
}
Also used : ExpressionEvaluationException(org.teiid.api.exception.query.ExpressionEvaluationException) Expression(org.teiid.query.sql.symbol.Expression) Reference(org.teiid.query.sql.symbol.Reference) Constant(org.teiid.query.sql.symbol.Constant) BaseLob(org.teiid.core.types.BaseLob) VariableContext(org.teiid.query.sql.util.VariableContext) QueryResolverException(org.teiid.api.exception.query.QueryResolverException)

Example 29 with QueryResolverException

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

the class PreparedStatementRequest method createStreamCopy.

/**
 * embedded lobs can be sent with just a reference to a stream,
 * create a copy instead
 * @param context
 * @param i
 * @param param
 * @param value
 * @throws QueryResolverException
 */
private static void createStreamCopy(CommandContext context, int i, Reference param, Object value) throws QueryResolverException {
    try {
        InputStreamFactory isf = ((BaseLob) value).getStreamFactory();
        InputStream initial = isf.getInputStream();
        InputStream other = isf.getInputStream();
        if (initial == other) {
            // this violates the expectation that the inputstream is a new instance,
            // $NON-NLS-1$
            FileStore fs = context.getBufferManager().createFileStore("bytes");
            FileStoreInputStreamFactory fsisf = new FileStoreInputStreamFactory(fs, Streamable.ENCODING);
            SaveOnReadInputStream is = new SaveOnReadInputStream(initial, fsisf);
            context.addCreatedLob(fsisf);
            ((BaseLob) value).setStreamFactory(is.getInputStreamFactory());
        } else {
            initial.close();
            other.close();
        }
    } catch (SQLException e) {
        // $NON-NLS-1$
        String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", i + 1, value, value.getClass(), DataTypeManager.getDataTypeName(param.getType()));
        throw new QueryResolverException(QueryPlugin.Event.TEIID30557, e, msg);
    } catch (IOException e) {
        // $NON-NLS-1$
        String msg = QueryPlugin.Util.getString("QueryUtil.Error_executing_conversion_function_to_convert_value", i + 1, value, value.getClass(), DataTypeManager.getDataTypeName(param.getType()));
        throw new QueryResolverException(QueryPlugin.Event.TEIID30557, e, msg);
    }
}
Also used : FileStore(org.teiid.common.buffer.FileStore) FileStoreInputStreamFactory(org.teiid.common.buffer.FileStoreInputStreamFactory) SQLException(java.sql.SQLException) InputStream(java.io.InputStream) BaseLob(org.teiid.core.types.BaseLob) IOException(java.io.IOException) InputStreamFactory(org.teiid.core.types.InputStreamFactory) FileStoreInputStreamFactory(org.teiid.common.buffer.FileStoreInputStreamFactory) QueryResolverException(org.teiid.api.exception.query.QueryResolverException)

Example 30 with QueryResolverException

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

the class RulePushAggregates method defineNewGroup.

static List<ElementSymbol> defineNewGroup(GroupSymbol group, List<? extends Expression> virtualElements, QueryMetadataInterface metadata) throws TeiidComponentException, QueryMetadataException {
    TempMetadataStore store = new TempMetadataStore();
    TempMetadataAdapter tma = new TempMetadataAdapter(metadata, store);
    try {
        group.setMetadataID(ResolverUtil.addTempGroup(tma, group, virtualElements, false));
    } catch (QueryResolverException e) {
        throw new TeiidComponentException(QueryPlugin.Event.TEIID30265, e);
    }
    List<ElementSymbol> projectedSymbols = ResolverUtil.resolveElementsInGroup(group, metadata);
    return projectedSymbols;
}
Also used : TempMetadataAdapter(org.teiid.query.metadata.TempMetadataAdapter) TeiidComponentException(org.teiid.core.TeiidComponentException) TempMetadataStore(org.teiid.query.metadata.TempMetadataStore) QueryResolverException(org.teiid.api.exception.query.QueryResolverException)

Aggregations

QueryResolverException (org.teiid.api.exception.query.QueryResolverException)62 GroupSymbol (org.teiid.query.sql.symbol.GroupSymbol)13 TempMetadataID (org.teiid.query.metadata.TempMetadataID)11 ExceptionExpression (org.teiid.query.sql.proc.ExceptionExpression)11 ArrayList (java.util.ArrayList)10 Test (org.junit.Test)10 TeiidComponentException (org.teiid.core.TeiidComponentException)10 Expression (org.teiid.query.sql.symbol.Expression)10 QueryMetadataException (org.teiid.api.exception.query.QueryMetadataException)8 CreateProcedureCommand (org.teiid.query.sql.proc.CreateProcedureCommand)7 Command (org.teiid.query.sql.lang.Command)6 ElementSymbol (org.teiid.query.sql.symbol.ElementSymbol)6 QueryParserException (org.teiid.api.exception.query.QueryParserException)5 TempMetadataStore (org.teiid.query.metadata.TempMetadataStore)5 LanguageObject (org.teiid.query.sql.LanguageObject)5 List (java.util.List)4 UnresolvedSymbolDescription (org.teiid.api.exception.query.UnresolvedSymbolDescription)4 TempMetadataAdapter (org.teiid.query.metadata.TempMetadataAdapter)4 StoredProcedure (org.teiid.query.sql.lang.StoredProcedure)4 HashSet (java.util.HashSet)3