Search in sources :

Example 16 with Evaluator

use of org.teiid.query.eval.Evaluator in project teiid by teiid.

the class TempTableDataManager method registerRequest.

TupleSource registerRequest(final CommandContext context, String modelName, final Command command) throws TeiidComponentException, TeiidProcessingException {
    final TempTableStore contextStore = context.getTempTableStore();
    if (command instanceof Query) {
        Query query = (Query) command;
        if (modelName != null && !modelName.equals(TempMetadataAdapter.TEMP_MODEL.getID())) {
            return null;
        }
        return registerQuery(context, contextStore, query);
    }
    if (command instanceof ProcedureContainer) {
        if (command instanceof StoredProcedure) {
            StoredProcedure proc = (StoredProcedure) command;
            if (CoreConstants.SYSTEM_ADMIN_MODEL.equals(modelName)) {
                TupleSource result = handleSystemProcedures(context, proc);
                if (result != null) {
                    return result;
                }
            } else if (proc.getGroup().isGlobalTable()) {
                return handleCachedProcedure(context, proc);
            }
            // it's not a stored procedure we want to handle
            return null;
        }
        final GroupSymbol group = ((ProcedureContainer) command).getGroup();
        if (!modelName.equals(TempMetadataAdapter.TEMP_MODEL.getID()) || !group.isTempGroupSymbol()) {
            return null;
        }
        return new ProxyTupleSource() {

            @Override
            protected TupleSource createTupleSource() throws TeiidComponentException, TeiidProcessingException {
                final String groupKey = group.getNonCorrelationName();
                final TempTable table = contextStore.getOrCreateTempTable(groupKey, command, bufferManager, true, true, context, group);
                if (command instanceof Insert) {
                    Insert insert = (Insert) command;
                    TupleSource ts = insert.getTupleSource();
                    if (ts == null) {
                        Evaluator eval = new Evaluator(Collections.emptyMap(), TempTableDataManager.this, context);
                        List<Object> values = new ArrayList<Object>(insert.getValues().size());
                        for (Expression expr : (List<Expression>) insert.getValues()) {
                            values.add(eval.evaluate(expr, null));
                        }
                        ts = new CollectionTupleSource(Arrays.asList(values).iterator());
                    }
                    return table.insert(ts, insert.getVariables(), true, insert.isUpsert(), context);
                }
                if (command instanceof Update) {
                    final Update update = (Update) command;
                    final Criteria crit = update.getCriteria();
                    return table.update(crit, update.getChangeList());
                }
                if (command instanceof Delete) {
                    final Delete delete = (Delete) command;
                    final Criteria crit = delete.getCriteria();
                    if (crit == null) {
                        // TODO: we'll add a real truncate later
                        long rows = table.truncate(false);
                        return CollectionTupleSource.createUpdateCountTupleSource((int) Math.min(Integer.MAX_VALUE, rows));
                    }
                    return table.delete(crit);
                }
                // $NON-NLS-1$
                throw new AssertionError("unknown command " + command);
            }
        };
    }
    if (command instanceof Create) {
        Create create = (Create) command;
        String tempTableName = create.getTable().getName();
        if (contextStore.hasTempTable(tempTableName, true)) {
            throw new QueryProcessingException(QueryPlugin.Event.TEIID30229, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30229, tempTableName));
        }
        if (create.getTableMetadata() != null) {
            contextStore.addForeignTempTable(tempTableName, create);
        } else {
            contextStore.addTempTable(tempTableName, create, bufferManager, true, context);
        }
        return CollectionTupleSource.createUpdateCountTupleSource(0);
    }
    if (command instanceof Drop) {
        String tempTableName = ((Drop) command).getTable().getName();
        contextStore.removeTempTableByName(tempTableName, context);
        return CollectionTupleSource.createUpdateCountTupleSource(0);
    }
    if (command instanceof AlterTempTable) {
        // non longer used, was part of xml logic
        AlterTempTable att = (AlterTempTable) command;
        TempTable tt = contextStore.getTempTable(att.getTempTable());
        // $NON-NLS-1$
        Assertion.isNotNull(tt, "Table doesn't exist");
        tt.setUpdatable(false);
        if (att.getIndexColumns() != null && tt.getRowCount() > 2 * tt.getTree().getPageSize(true)) {
            for (List<ElementSymbol> cols : att.getIndexColumns()) {
                tt.addIndex(cols, false);
            }
        }
        return CollectionTupleSource.createUpdateCountTupleSource(0);
    }
    return null;
}
Also used : ElementSymbol(org.teiid.query.sql.symbol.ElementSymbol) ArrayList(java.util.ArrayList) CollectionTupleSource(org.teiid.query.processor.CollectionTupleSource) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Evaluator(org.teiid.query.eval.Evaluator) Expression(org.teiid.query.sql.symbol.Expression) CollectionTupleSource(org.teiid.query.processor.CollectionTupleSource) TupleSource(org.teiid.common.buffer.TupleSource) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) QueryProcessingException(org.teiid.api.exception.query.QueryProcessingException)

Example 17 with Evaluator

use of org.teiid.query.eval.Evaluator in project teiid by teiid.

the class FakeDataManager method registerRequest.

public TupleSource registerRequest(CommandContext context, Command command, String modelName, RegisterRequestParameter parameterObject) throws TeiidComponentException {
    // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
    LogManager.logTrace(LOG_CONTEXT, new Object[] { "Register Request:", command, ",processorID:", context.getRequestId(), ",model name:", modelName, ",TupleSourceID nodeID:", new Integer(parameterObject.nodeID) });
    if (this.recordingCommands) {
        if (!(command instanceof BatchedUpdateCommand)) {
            this.queries.add(command.toString());
        }
    }
    if (ReferenceCollectorVisitor.getReferences(command).size() > 0) {
        // $NON-NLS-1$
        throw new IllegalArgumentException("Found references in the command registered with the DataManager.");
    }
    // Get group ID from atomic command
    GroupSymbol group = null;
    if (command instanceof Query) {
        group = getQueryGroup((Query) command);
    } else if (command instanceof SetQuery) {
        SetQuery union = (SetQuery) command;
        group = getQueryGroup(union.getProjectedQuery());
    } else if (command instanceof StoredProcedure) {
        Object id = ((StoredProcedure) command).getProcedureID();
        List<List<?>>[] data = procTuples.get(id);
        if (data == null) {
            // $NON-NLS-1$
            throw new AssertionError("Undefined results for " + command);
        }
        FakeTupleSource ts = new FakeTupleSource(command.getProjectedSymbols(), data);
        if (this.blockOnce) {
            ts.setBlockOnce();
        }
        return ts;
    } else if (command instanceof ProcedureContainer) {
        group = ((ProcedureContainer) command).getGroup();
    } else if (command instanceof BatchedUpdateCommand) {
        BatchedUpdateCommand buc = (BatchedUpdateCommand) command;
        if (buc.getUpdateCommands().get(0) instanceof Update) {
            group = ((Update) buc.getUpdateCommands().get(0)).getGroup();
        }
        if (this.recordingCommands) {
            for (Iterator<Command> it = ((BatchedUpdateCommand) command).getUpdateCommands().iterator(); it.hasNext(); ) {
                this.queries.add(it.next().toString());
            }
        }
    }
    TupleInfo tupleInfo = tuples.get(group.getNonCorrelationName().toUpperCase());
    List<? extends Expression> elements = tupleInfo.elements;
    List<?>[] data = tupleInfo.data;
    List<Expression> projectedSymbols = command.getProjectedSymbols();
    int[] columnMap = getColumnMap(tupleInfo.elements, projectedSymbols);
    /* 
		*  updateCommands is used to hold a list of commands that 
		*  either came from a BatchedUpdateCommand or a signle 
		*  command from an Update command.
		*/
    List<Command> updateCommands = new ArrayList<Command>();
    // Apply query criteria to tuples
    if (command instanceof Query) {
        Query query = (Query) command;
        if (query.getCriteria() != null) {
            // Build lookupMap from BOTH all the elements and the projected symbols - both may be needed here
            Map lookupMap = new HashMap();
            for (int i = 0; i < elements.size(); i++) {
                Expression element = elements.get(i);
                mapElementToIndex(lookupMap, element, i, group);
            }
            for (int i = 0; i < projectedSymbols.size(); i++) {
                Expression element = projectedSymbols.get(i);
                mapElementToIndex(lookupMap, element, columnMap[i], group);
            }
            List filteredTuples = new ArrayList();
            for (int i = 0; i < data.length; i++) {
                try {
                    if (new Evaluator(lookupMap, null, null).evaluate(query.getCriteria(), data[i])) {
                        filteredTuples.add(data[i]);
                    }
                } catch (ExpressionEvaluationException e) {
                    throw new TeiidComponentException(e, e.getMessage());
                }
            }
            data = new List[filteredTuples.size()];
            filteredTuples.toArray(data);
        }
    } else if (command instanceof Insert || command instanceof Update || command instanceof Delete) {
        // add single update command to a list to be executed
        updateCommands.add(command);
    } else if (command instanceof BatchedUpdateCommand) {
        // add all update commands to a list to be executed
        updateCommands.addAll(((BatchedUpdateCommand) command).getUpdateCommands());
    }
    // if we had update commands added to the list, execute them now
    if (updateCommands.size() > 0) {
        List<List<Integer>> filteredTuples = new ArrayList<List<Integer>>();
        for (int c = 0; c < updateCommands.size(); c++) {
            Command cmd = updateCommands.get(c);
            if (cmd instanceof FilteredCommand) {
                FilteredCommand update = (FilteredCommand) cmd;
                if (update.getCriteria() != null) {
                    // Build lookupMap from BOTH all the elements and the projected symbols - both may be needed here
                    Map<Object, Integer> lookupMap = new HashMap<Object, Integer>();
                    for (int i = 0; i < elements.size(); i++) {
                        Expression element = elements.get(i);
                        mapElementToIndex(lookupMap, element, new Integer(i), group);
                    }
                    for (int i = 0; i < projectedSymbols.size(); i++) {
                        Expression element = projectedSymbols.get(i);
                        mapElementToIndex(lookupMap, element, new Integer(columnMap[i]), group);
                    }
                    int updated = 0;
                    for (int i = 0; i < data.length; i++) {
                        try {
                            if (new Evaluator(lookupMap, null, null).evaluate(update.getCriteria(), data[i])) {
                                updated++;
                            }
                        } catch (ExpressionEvaluationException e) {
                            throw new TeiidComponentException(e, e.getMessage());
                        }
                    }
                    List<Integer> updateTuple = new ArrayList<Integer>(1);
                    updateTuple.add(new Integer(updated));
                    filteredTuples.add(updateTuple);
                }
            } else {
                // TODO: check for bulk
                filteredTuples.add(Arrays.asList(1));
            }
        }
        data = new List[filteredTuples.size()];
        filteredTuples.toArray(data);
        elements = Command.getUpdateCommandSymbol();
        columnMap[0] = 0;
    }
    FakeTupleSource ts = new FakeTupleSource(elements, data, projectedSymbols, columnMap);
    if (this.blockOnce) {
        ts.setBlockOnce();
    }
    return ts;
}
Also used : ExpressionEvaluationException(org.teiid.api.exception.query.ExpressionEvaluationException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Evaluator(org.teiid.query.eval.Evaluator) Expression(org.teiid.query.sql.symbol.Expression) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) TeiidComponentException(org.teiid.core.TeiidComponentException) HashMap(java.util.HashMap) SymbolMap(org.teiid.query.sql.util.SymbolMap) Map(java.util.Map)

Example 18 with Evaluator

use of org.teiid.query.eval.Evaluator in project teiid by teiid.

the class TestCriteriaEvaluator method helpTestCompareSubqueryCriteria.

private void helpTestCompareSubqueryCriteria(Criteria crit, Boolean expectedResult, final Collection<Object> values) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
    Map elementMap = new HashMap();
    // $NON-NLS-1$
    ElementSymbol e1 = new ElementSymbol("e1");
    elementMap.put(e1, new Integer(0));
    // $NON-NLS-1$
    List tuple = Arrays.asList(new String[] { "a" });
    CommandContext cc = new CommandContext();
    assertEquals(expectedResult, new Evaluator(elementMap, null, cc) {

        @Override
        protected ValueIterator evaluateSubquery(SubqueryContainer container, List tuple) throws TeiidProcessingException, BlockedException, TeiidComponentException {
            return new CollectionValueIterator(values);
        }
    }.evaluateTVL(crit, tuple));
}
Also used : ElementSymbol(org.teiid.query.sql.symbol.ElementSymbol) CommandContext(org.teiid.query.util.CommandContext) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) Evaluator(org.teiid.query.eval.Evaluator) HashMap(java.util.HashMap) Map(java.util.Map)

Example 19 with Evaluator

use of org.teiid.query.eval.Evaluator in project teiid by teiid.

the class TestExpressionEvaluator method testUser.

@Test
public void testUser() throws Exception {
    // $NON-NLS-1$
    Function func = new Function("user", new Expression[] {});
    // $NON-NLS-1$
    FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("user", new Class[] {});
    func.setFunctionDescriptor(desc);
    FakeDataManager dataMgr = new FakeDataManager();
    CommandContext context = new CommandContext(new Long(1), null, null, null, 0);
    // $NON-NLS-1$
    context.setUserName("logon");
    assertEquals(context.getUserName(), new Evaluator(Collections.emptyMap(), dataMgr, context).evaluate(func, Collections.emptyList()));
}
Also used : CommandContext(org.teiid.query.util.CommandContext) FakeDataManager(org.teiid.query.processor.FakeDataManager) FunctionDescriptor(org.teiid.query.function.FunctionDescriptor) Evaluator(org.teiid.query.eval.Evaluator) Test(org.junit.Test)

Example 20 with Evaluator

use of org.teiid.query.eval.Evaluator in project teiid by teiid.

the class TestProcedureResolving method testVarArgs1.

@Test
public void testVarArgs1() throws Exception {
    String ddl = "create foreign procedure proc (VARIADIC z integer) returns (x string);\n";
    TransformationMetadata tm = createMetadata(ddl);
    // $NON-NLS-1$
    String sql = "call proc ()";
    StoredProcedure sp = (StoredProcedure) TestResolver.helpResolve(sql, tm);
    assertEquals("EXEC proc()", sp.toString());
    assertEquals(new Array(DataTypeManager.DefaultDataClasses.INTEGER, new ArrayList<Expression>(0)), sp.getParameter(1).getExpression());
    sp = (StoredProcedure) QueryRewriter.evaluateAndRewrite(sp, new Evaluator(null, null, null), null, tm);
    LanguageBridgeFactory lbf = new LanguageBridgeFactory(tm);
    Call call = (Call) lbf.translate(sp);
    assertEquals("EXEC proc()", call.toString());
    // we pass to the translator level flattened, so no argument
    assertEquals(0, call.getArguments().size());
}
Also used : Array(org.teiid.query.sql.symbol.Array) Call(org.teiid.language.Call) TransformationMetadata(org.teiid.query.metadata.TransformationMetadata) StoredProcedure(org.teiid.query.sql.lang.StoredProcedure) ArrayList(java.util.ArrayList) Evaluator(org.teiid.query.eval.Evaluator) LanguageBridgeFactory(org.teiid.dqp.internal.datamgr.LanguageBridgeFactory) Test(org.junit.Test)

Aggregations

Evaluator (org.teiid.query.eval.Evaluator)20 ArrayList (java.util.ArrayList)12 List (java.util.List)7 CommandContext (org.teiid.query.util.CommandContext)7 TeiidComponentException (org.teiid.core.TeiidComponentException)6 ElementSymbol (org.teiid.query.sql.symbol.ElementSymbol)6 HashMap (java.util.HashMap)5 Map (java.util.Map)4 Test (org.junit.Test)4 Expression (org.teiid.query.sql.symbol.Expression)4 ExpressionEvaluationException (org.teiid.api.exception.query.ExpressionEvaluationException)3 BlockedException (org.teiid.common.buffer.BlockedException)3 TransformationMetadata (org.teiid.query.metadata.TransformationMetadata)3 QueryProcessingException (org.teiid.api.exception.query.QueryProcessingException)2 TeiidProcessingException (org.teiid.core.TeiidProcessingException)2 TeiidRuntimeException (org.teiid.core.TeiidRuntimeException)2 LanguageBridgeFactory (org.teiid.dqp.internal.datamgr.LanguageBridgeFactory)2 Call (org.teiid.language.Call)2 FunctionDescriptor (org.teiid.query.function.FunctionDescriptor)2 FakeDataManager (org.teiid.query.processor.FakeDataManager)2