Search in sources :

Example 11 with Command

use of org.teiid.query.sql.lang.Command in project teiid by teiid.

the class TestODataIntegration method testCheckGeneratedColumns.

@Test
public void testCheckGeneratedColumns() throws Exception {
    HardCodedExecutionFactory hc = new HardCodedExecutionFactory() {

        @Override
        public UpdateExecution createUpdateExecution(org.teiid.language.Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection) throws TranslatorException {
            GeneratedKeys keys = executionContext.getCommandContext().returnGeneratedKeys(new String[] { "a" }, new Class[] { String.class });
            keys.addKey(Arrays.asList("ax"));
            return super.createUpdateExecution(command, executionContext, metadata, connection);
        }

        @Override
        public boolean supportsCompareCriteriaEquals() {
            return true;
        }
    };
    hc.addUpdate("INSERT INTO x (b, c) VALUES ('b', 5)", new int[] { 1 });
    // this gets called right after insert.
    hc.addData("SELECT x.a, x.b, x.c FROM x WHERE x.a = 'ax'", Arrays.asList(Arrays.asList("a", "b", 2)));
    teiid.addTranslator("x", hc);
    try {
        ModelMetaData mmd = new ModelMetaData();
        mmd.setName("m");
        mmd.addSourceMetadata("ddl", "create foreign table x (a string, b string, c integer, " + "primary key (a)) options (updatable true);");
        mmd.addSourceMapping("x", "x", null);
        teiid.deployVDB("northwind", mmd);
        localClient = getClient(teiid.getDriver(), "northwind", new Properties());
        ContentResponse response = http.newRequest(baseURL + "/northwind/m/x").method("POST").content(new StringContentProvider("{\"b\":\"b\", \"c\":5}"), "application/json").send();
        assertEquals(201, response.getStatus());
    } finally {
        localClient = null;
        teiid.undeployVDB("northwind");
    }
}
Also used : ExecutionContext(org.teiid.translator.ExecutionContext) Command(org.teiid.query.sql.lang.Command) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) HardCodedExecutionFactory(org.teiid.runtime.HardCodedExecutionFactory) GeneratedKeys(org.teiid.GeneratedKeys) RuntimeMetadata(org.teiid.metadata.RuntimeMetadata) Properties(java.util.Properties) ModelMetaData(org.teiid.adminapi.impl.ModelMetaData) Test(org.junit.Test)

Example 12 with Command

use of org.teiid.query.sql.lang.Command in project teiid by teiid.

the class TestOptimizer method helpGetCommand.

public static Command helpGetCommand(String sql, QueryMetadataInterface md, List<String> bindings) throws TeiidComponentException, TeiidProcessingException {
    // $NON-NLS-1$
    if (DEBUG)
        System.out.println("\n####################################\n" + sql);
    Command command = null;
    if (bindings != null && !bindings.isEmpty()) {
        command = TestResolver.helpResolveWithBindings(sql, md, bindings);
    } else {
        command = QueryParser.getQueryParser().parseCommand(sql);
        QueryResolver.resolveCommand(command, md);
    }
    ValidatorReport repo = Validator.validate(command, md);
    Collection<LanguageObject> failures = new ArrayList<LanguageObject>();
    repo.collectInvalidObjects(failures);
    if (failures.size() > 0) {
        // $NON-NLS-1$
        fail("Exception during validation (" + repo);
    }
    // rewrite
    command = QueryRewriter.rewrite(command, md, new CommandContext());
    return command;
}
Also used : CommandContext(org.teiid.query.util.CommandContext) Command(org.teiid.query.sql.lang.Command) ArrayList(java.util.ArrayList) ValidatorReport(org.teiid.query.validator.ValidatorReport) LanguageObject(org.teiid.query.sql.LanguageObject)

Example 13 with Command

use of org.teiid.query.sql.lang.Command in project teiid by teiid.

the class TestSubqueryPushdown method testSubqueryProducingBuffer.

@Test
public void testSubqueryProducingBuffer() throws Exception {
    TransformationMetadata tm = RealMetadataFactory.example1Cached();
    String sql = "SELECT e1, (select e2 from pm2.g1 where e1 = pm1.g1.e1 order by e2 limit 1) from pm1.g1 limit 1";
    BasicSourceCapabilities bsc = getTypicalCapabilities();
    bsc.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
    ProcessorPlan plan = // $NON-NLS-1$
    TestOptimizer.helpPlan(// $NON-NLS-1$
    sql, tm, null, new DefaultCapabilitiesFinder(bsc), new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, // $NON-NLS-1$
    ComparisonMode.EXACT_COMMAND_STRING);
    HardcodedDataManager hdm = new HardcodedDataManager(tm) {

        @Override
        public TupleSource registerRequest(CommandContext context, Command command, String modelName, RegisterRequestParameter parameterObject) throws TeiidComponentException {
            if (command.toString().equals("SELECT g_0.e2 FROM pm2.g1 AS g_0 WHERE g_0.e1 = 'a'")) {
                return new TupleSource() {

                    @Override
                    public List<?> nextTuple() throws TeiidComponentException, TeiidProcessingException {
                        throw new TeiidProcessingException("something's wrong");
                    }

                    @Override
                    public void closeSource() {
                    }
                };
            }
            return super.registerRequest(context, command, modelName, parameterObject);
        }
    };
    hdm.addData("SELECT g_0.e1 FROM g1 AS g_0", Arrays.asList("a"));
    hdm.setBlockOnce(true);
    CommandContext cc = TestProcessor.createCommandContext();
    cc.setMetadata(tm);
    try {
        TestProcessor.helpProcess(plan, cc, hdm, new List[] { Arrays.asList(2) });
        fail();
    } catch (TeiidProcessingException e) {
        assert (e.getMessage().contains("something's wrong"));
    }
}
Also used : TransformationMetadata(org.teiid.query.metadata.TransformationMetadata) CommandContext(org.teiid.query.util.CommandContext) BasicSourceCapabilities(org.teiid.query.optimizer.capabilities.BasicSourceCapabilities) HardcodedDataManager(org.teiid.query.processor.HardcodedDataManager) Command(org.teiid.query.sql.lang.Command) TupleSource(org.teiid.common.buffer.TupleSource) ProcessorPlan(org.teiid.query.processor.ProcessorPlan) DefaultCapabilitiesFinder(org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder) RegisterRequestParameter(org.teiid.query.processor.RegisterRequestParameter) TeiidProcessingException(org.teiid.core.TeiidProcessingException) Test(org.junit.Test)

Example 14 with Command

use of org.teiid.query.sql.lang.Command in project teiid by teiid.

the class QueryResolver method resolveView.

public static QueryNode resolveView(GroupSymbol virtualGroup, QueryNode qnode, String cacheString, QueryMetadataInterface qmi, boolean logValidation) throws TeiidComponentException, QueryMetadataException, QueryResolverException, QueryValidatorException {
    qmi = qmi.getDesignTimeMetadata();
    // $NON-NLS-1$
    cacheString = "transformation/" + cacheString;
    QueryNode cachedNode = (QueryNode) qmi.getFromMetadataCache(virtualGroup.getMetadataID(), cacheString);
    if (cachedNode == null) {
        Command result = qnode.getCommand();
        List<String> bindings = null;
        if (result == null) {
            try {
                result = QueryParser.getQueryParser().parseCommand(qnode.getQuery());
            } catch (QueryParserException e) {
                throw new QueryResolverException(QueryPlugin.Event.TEIID30065, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30065, virtualGroup));
            }
            bindings = qnode.getBindings();
        } else {
            result = (Command) result.clone();
        }
        if (bindings != null && !bindings.isEmpty()) {
            QueryResolver.resolveWithBindingMetadata(result, qmi, qnode, true);
        } else {
            QueryResolver.resolveCommand(result, qmi, false);
        }
        Request.validateWithVisitor(new ValidationVisitor(), qmi, result);
        validateProjectedSymbols(virtualGroup, qmi, result);
        cachedNode = new QueryNode(qnode.getQuery());
        cachedNode.setCommand(result);
        if (isView(virtualGroup, qmi)) {
            String updatePlan = qmi.getUpdatePlan(virtualGroup.getMetadataID());
            String deletePlan = qmi.getDeletePlan(virtualGroup.getMetadataID());
            String insertPlan = qmi.getInsertPlan(virtualGroup.getMetadataID());
            // the elements must be against the view and not the alias
            if (virtualGroup.getDefinition() != null) {
                GroupSymbol group = new GroupSymbol(virtualGroup.getNonCorrelationName());
                group.setMetadataID(virtualGroup.getMetadataID());
                virtualGroup = group;
            }
            List<ElementSymbol> elements = ResolverUtil.resolveElementsInGroup(virtualGroup, qmi);
            UpdateValidator validator = new UpdateValidator(qmi, determineType(insertPlan), determineType(updatePlan), determineType(deletePlan));
            validator.validate(result, elements);
            UpdateInfo info = validator.getUpdateInfo();
            if (logValidation && qmi.groupSupports(virtualGroup.getMetadataID(), SupportConstants.Group.UPDATE)) {
                if (info.isInherentInsert() && validator.getInsertReport().hasItems()) {
                    LogManager.logDetail(LogConstants.CTX_QUERY_RESOLVER, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31173, validator.getInsertReport().getFailureMessage(), SQLConstants.Reserved.INSERT, qmi.getFullName(virtualGroup.getMetadataID())));
                }
                if (info.isInherentUpdate() && validator.getUpdateReport().hasItems()) {
                    LogManager.logDetail(LogConstants.CTX_QUERY_RESOLVER, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31173, validator.getUpdateReport().getFailureMessage(), SQLConstants.Reserved.UPDATE, qmi.getFullName(virtualGroup.getMetadataID())));
                }
                if (info.isInherentDelete() && validator.getDeleteReport().hasItems()) {
                    LogManager.logDetail(LogConstants.CTX_QUERY_RESOLVER, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31173, validator.getDeleteReport().getFailureMessage(), SQLConstants.Reserved.DELETE, qmi.getFullName(virtualGroup.getMetadataID())));
                }
            }
            cachedNode.setUpdateInfo(info);
        }
        qmi.addToMetadataCache(virtualGroup.getMetadataID(), cacheString, cachedNode);
    }
    return cachedNode;
}
Also used : ElementSymbol(org.teiid.query.sql.symbol.ElementSymbol) ValidationVisitor(org.teiid.query.validator.ValidationVisitor) QueryParserException(org.teiid.api.exception.query.QueryParserException) Command(org.teiid.query.sql.lang.Command) QueryNode(org.teiid.query.mapping.relational.QueryNode) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) QueryResolverException(org.teiid.api.exception.query.QueryResolverException) UpdateValidator(org.teiid.query.validator.UpdateValidator) UpdateInfo(org.teiid.query.validator.UpdateValidator.UpdateInfo)

Example 15 with Command

use of org.teiid.query.sql.lang.Command in project teiid by teiid.

the class AccessNode method openInternal.

private void openInternal() throws TeiidComponentException, TeiidProcessingException {
    // TODO: support a partitioning concept with multi-source and full dependent join pushdown
    if (subPlans != null) {
        if (this.evaluatedPlans == null) {
            this.evaluatedPlans = new HashMap<GroupSymbol, SubqueryState>();
            for (Map.Entry<GroupSymbol, RelationalPlan> entry : subPlans.entrySet()) {
                SubqueryState state = new SubqueryState();
                RelationalPlan value = entry.getValue();
                value.reset();
                state.processor = new QueryProcessor(value, getContext().clone(), getBufferManager(), getDataManager());
                state.collector = state.processor.createBatchCollector();
                this.evaluatedPlans.put(entry.getKey(), state);
            }
        }
        BlockedException be = null;
        for (SubqueryState state : evaluatedPlans.values()) {
            try {
                state.collector.collectTuples();
            } catch (BlockedException e) {
                be = e;
            }
        }
        if (be != null) {
            throw be;
        }
    }
    /*
		 * Check to see if we need a multi-source expansion.  If the connectorBindingExpression != null, then 
		 * the logic below will handle that case
		 */
    if (multiSource && connectorBindingExpression == null) {
        synchronized (this) {
            // the description can be obtained asynchly, so we need to synchronize
            VDBMetaData vdb = getContext().getVdb();
            ModelMetaData model = vdb.getModel(getModelName());
            List<String> sources = model.getSourceNames();
            // make sure that we have the right nodes
            if (this.getChildCount() != 0 && (this.sourceNames == null || !this.sourceNames.equals(sources))) {
                this.childCount--;
                this.getChildren()[0] = null;
            }
            if (this.getChildCount() == 0) {
                sourceNames = sources;
                RelationalNode node = multiSourceModify(this, connectorBindingExpression, getContext().getMetadata(), sourceNames);
                RelationalPlan.connectExternal(node, getContext(), getDataManager(), getBufferManager());
                this.addChild(node);
            }
        }
        this.getChildren()[0].open();
        return;
    }
    // Copy command and resolve references if necessary
    if (processingCommand == null) {
        processingCommand = command;
        isUpdate = RelationalNodeUtil.isUpdate(command);
    }
    boolean needProcessing = true;
    if (this.connectorBindingExpression != null && connectorBindingId == null) {
        this.connectorBindingId = (String) getEvaluator(Collections.emptyMap()).evaluate(this.connectorBindingExpression, null);
        VDBMetaData vdb = getContext().getVdb();
        ModelMetaData model = vdb.getModel(getModelName());
        List<String> sources = model.getSourceNames();
        String replacement = this.connectorBindingId;
        if (!sources.contains(this.connectorBindingId)) {
            shouldExecute = false;
            if (command instanceof StoredProcedure) {
                StoredProcedure sp = (StoredProcedure) command;
                if (sp.returnParameters() && sp.getProjectedSymbols().size() > sp.getResultSetColumns().size()) {
                    throw new TeiidProcessingException(QueryPlugin.Event.TEIID30561, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30561, command));
                }
            }
            return;
        }
        if (!(command instanceof StoredProcedure || command instanceof Insert)) {
            processingCommand = (Command) command.clone();
            MultiSourceElementReplacementVisitor.visit(replacement, getContext().getMetadata(), processingCommand);
        }
    }
    do {
        Command atomicCommand = nextCommand();
        if (shouldEvaluate) {
            needProcessing = prepareNextCommand(atomicCommand);
            nextCommand = null;
        } else {
            needProcessing = RelationalNodeUtil.shouldExecute(atomicCommand, true);
        }
        if (needProcessing) {
            registerRequest(atomicCommand);
        }
    // We use an upper limit here to the currency because these commands have potentially large in-memory value sets
    } while (!processCommandsIndividually() && hasNextCommand() && this.tupleSources.size() < Math.max(Math.min(MAX_CONCURRENT, this.getContext().getUserRequestSourceConcurrency()), this.getContext().getUserRequestSourceConcurrency() / 2));
}
Also used : SubqueryState(org.teiid.query.processor.relational.SubqueryAwareEvaluator.SubqueryState) Insert(org.teiid.query.sql.lang.Insert) BlockedException(org.teiid.common.buffer.BlockedException) QueryProcessor(org.teiid.query.processor.QueryProcessor) ModelMetaData(org.teiid.adminapi.impl.ModelMetaData) TeiidProcessingException(org.teiid.core.TeiidProcessingException) 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) VDBMetaData(org.teiid.adminapi.impl.VDBMetaData) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) SymbolMap(org.teiid.query.sql.util.SymbolMap)

Aggregations

Command (org.teiid.query.sql.lang.Command)232 Test (org.junit.Test)142 QueryMetadataInterface (org.teiid.query.metadata.QueryMetadataInterface)90 BasicSourceCapabilities (org.teiid.query.optimizer.capabilities.BasicSourceCapabilities)73 FakeCapabilitiesFinder (org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder)66 List (java.util.List)64 CommandContext (org.teiid.query.util.CommandContext)38 ArrayList (java.util.ArrayList)37 BatchedUpdateCommand (org.teiid.query.sql.lang.BatchedUpdateCommand)36 BigInteger (java.math.BigInteger)29 DefaultCapabilitiesFinder (org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder)25 AnalysisRecord (org.teiid.query.analysis.AnalysisRecord)21 GroupSymbol (org.teiid.query.sql.symbol.GroupSymbol)20 ProcessorPlan (org.teiid.query.processor.ProcessorPlan)19 TransformationMetadata (org.teiid.query.metadata.TransformationMetadata)16 LinkedList (java.util.LinkedList)10 QueryParser (org.teiid.query.parser.QueryParser)10 RelationalPlan (org.teiid.query.processor.relational.RelationalPlan)10 QueryCommand (org.teiid.query.sql.lang.QueryCommand)10 StoredProcedure (org.teiid.query.sql.lang.StoredProcedure)10