Search in sources :

Example 11 with TempMetadataID

use of org.teiid.query.metadata.TempMetadataID in project teiid by teiid.

the class TestTempTables method testInherentUpdateUsingTemp.

@Test
public void testInherentUpdateUsingTemp() throws Exception {
    TransformationMetadata metadata = RealMetadataFactory.fromDDL("create foreign table g1 (e1 string primary key, e2 integer, e3 boolean, e4 double, FOREIGN KEY (e1) REFERENCES G2 (e1)) options (updatable true);" + " create foreign table g2 (e1 string primary key, e2 integer, e3 boolean, e4 double) options (updatable true);" + " create view v options (updatable true) as select g2.e1, g1.e2 from g1 inner join g2 on g1.e1 = g2.e1;", "x", "pm1");
    HardcodedDataManager hdm = new HardcodedDataManager(metadata);
    setUp(metadata, hdm);
    BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();
    SessionAwareCache<CachedResults> cache = new SessionAwareCache<CachedResults>("resultset", DefaultCacheFactory.INSTANCE, SessionAwareCache.Type.RESULTSET, 0);
    cache.setTupleBufferCache(bm);
    dataManager = new TempTableDataManager(hdm, bm, cache);
    // $NON-NLS-1$
    execute("create temporary table x (e1 string, e2 integer, e3 string, primary key (e1))", new List[] { Arrays.asList(0) });
    execute("insert into x values ('a', 1, 'b')", new List[] { Arrays.asList(1) });
    TempMetadataID id = this.tempStore.getMetadataStore().getData().get("x");
    // ensure that we're using the actual metadata
    assertNotNull(id);
    assertNotNull(this.metadata.getPrimaryKey(id));
    hdm.addData("SELECT g_0.e1 FROM g1 AS g_0 WHERE g_0.e2 = 1", new List[] { Arrays.asList("a") });
    hdm.addData("DELETE FROM g1 WHERE g1.e1 = 'a'", new List[] { Arrays.asList(1) });
    // $NON-NLS-1$
    execute("delete from v where e2 = (select max(e2) from x as z where e3 = z.e3)", new List[] { Arrays.asList(1) }, TestOptimizer.getGenericFinder());
}
Also used : TransformationMetadata(org.teiid.query.metadata.TransformationMetadata) SessionAwareCache(org.teiid.dqp.internal.process.SessionAwareCache) TempTableDataManager(org.teiid.query.tempdata.TempTableDataManager) TempMetadataID(org.teiid.query.metadata.TempMetadataID) BufferManager(org.teiid.common.buffer.BufferManager) CachedResults(org.teiid.dqp.internal.process.CachedResults) Test(org.junit.Test)

Example 12 with TempMetadataID

use of org.teiid.query.metadata.TempMetadataID in project teiid by teiid.

the class TestProcedureResolving method testDefect13029_CorrectlySetUpdateProcedureTempGroupIDs.

@Test
public void testDefect13029_CorrectlySetUpdateProcedureTempGroupIDs() throws Exception {
    StringBuffer proc = // $NON-NLS-1$
    new StringBuffer("FOR EACH ROW").append(// $NON-NLS-1$
    "\nBEGIN").append(// $NON-NLS-1$
    "\nDECLARE string var1;").append(// $NON-NLS-1$
    "\nvar1 = '';").append(// $NON-NLS-1$
    "\n  LOOP ON (SELECT pm1.g1.e1 FROM pm1.g1) AS loopCursor").append(// $NON-NLS-1$
    "\n  BEGIN").append(// $NON-NLS-1$
    "\n    LOOP ON (SELECT pm1.g2.e1 FROM pm1.g2 WHERE loopCursor.e1 = pm1.g2.e1) AS loopCursor2").append(// $NON-NLS-1$
    "\n    BEGIN").append(// $NON-NLS-1$
    "\n      var1 = CONCAT(var1, CONCAT(' ', loopCursor2.e1));").append(// $NON-NLS-1$
    "\n    END").append(// $NON-NLS-1$
    "\n  END").append(// $NON-NLS-1$
    "\nEND");
    // $NON-NLS-1$
    String userUpdateStr = "UPDATE vm1.g1 SET e1='x'";
    Command command = helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE);
    Map<String, TempMetadataID> tempIDs = command.getTemporaryMetadata().getData();
    assertNotNull(tempIDs);
    // $NON-NLS-1$
    assertNull(tempIDs.get("LOOPCURSOR"));
    // $NON-NLS-1$
    assertNull(tempIDs.get("LOOPCURSOR2"));
    Command subCommand = CommandCollectorVisitor.getCommands(command).get(0);
    tempIDs = subCommand.getTemporaryMetadata().getData();
    assertNotNull(tempIDs);
    // $NON-NLS-1$
    assertNull(tempIDs.get("LOOPCURSOR"));
    // $NON-NLS-1$
    assertNull(tempIDs.get("LOOPCURSOR2"));
    subCommand = CommandCollectorVisitor.getCommands(command).get(1);
    tempIDs = subCommand.getTemporaryMetadata().getData();
    assertNotNull(tempIDs);
    // $NON-NLS-1$
    assertNotNull(tempIDs.get("LOOPCURSOR"));
    // $NON-NLS-1$
    assertNull(tempIDs.get("LOOPCURSOR2"));
}
Also used : CreateProcedureCommand(org.teiid.query.sql.proc.CreateProcedureCommand) Command(org.teiid.query.sql.lang.Command) TempMetadataID(org.teiid.query.metadata.TempMetadataID) Test(org.junit.Test)

Example 13 with TempMetadataID

use of org.teiid.query.metadata.TempMetadataID in project teiid by teiid.

the class TestResolver method testInsertWithNullLiteral.

@Test
public void testInsertWithNullLiteral() {
    // $NON-NLS-1$
    String sql = "insert into #temp (x) values (null)";
    Insert insert = (Insert) helpResolve(sql);
    TempMetadataStore store = insert.getTemporaryMetadata();
    // $NON-NLS-1$
    TempMetadataID id = store.getTempElementID("#temp.x");
    assertEquals(DataTypeManager.DefaultDataClasses.STRING, id.getType());
}
Also used : TempMetadataID(org.teiid.query.metadata.TempMetadataID) TempMetadataStore(org.teiid.query.metadata.TempMetadataStore) Test(org.junit.Test)

Example 14 with TempMetadataID

use of org.teiid.query.metadata.TempMetadataID in project teiid by teiid.

the class ResolverUtil method resolveOrderBy.

/**
 * Attempt to resolve the order by throws QueryResolverException if the
 * symbol is not of SingleElementSymbol type
 *
 * @param orderBy
 * @param fromClauseGroups
 *            groups of the FROM clause of the query (for resolving
 *            ambiguous unqualified element names), or empty List if a Set
 *            Query Order By is being resolved
 * @param knownElements
 *            resolved elements from SELECT clause, which are only ones
 *            allowed to be in ORDER BY
 * @param metadata
 *            QueryMetadataInterface
 */
public static void resolveOrderBy(OrderBy orderBy, QueryCommand command, TempMetadataAdapter metadata) throws QueryResolverException, QueryMetadataException, TeiidComponentException {
    List<Expression> knownElements = command.getProjectedQuery().getSelect().getProjectedSymbols();
    boolean isSimpleQuery = false;
    List<GroupSymbol> fromClauseGroups = Collections.emptyList();
    GroupBy groupBy = null;
    if (command instanceof Query) {
        Query query = (Query) command;
        isSimpleQuery = !query.getSelect().isDistinct() && !query.hasAggregates();
        if (query.getFrom() != null) {
            fromClauseGroups = query.getFrom().getGroups();
        }
        if (!query.getSelect().isDistinct()) {
            groupBy = query.getGroupBy();
        }
    }
    // Cached state, if needed
    String[] knownShortNames = new String[knownElements.size()];
    List<Expression> expressions = new ArrayList<Expression>(knownElements.size());
    for (int i = 0; i < knownElements.size(); i++) {
        Expression knownSymbol = knownElements.get(i);
        expressions.add(SymbolMap.getExpression(knownSymbol));
        if (knownSymbol instanceof ElementSymbol || knownSymbol instanceof AliasSymbol) {
            String name = ((Symbol) knownSymbol).getShortName();
            knownShortNames[i] = name;
        }
    }
    for (int i = 0; i < orderBy.getVariableCount(); i++) {
        Expression sortKey = orderBy.getVariable(i);
        if (sortKey instanceof ElementSymbol) {
            ElementSymbol symbol = (ElementSymbol) sortKey;
            String groupPart = null;
            if (symbol.getGroupSymbol() != null) {
                groupPart = symbol.getGroupSymbol().getName();
            }
            String symbolName = symbol.getName();
            String shortName = symbol.getShortName();
            if (groupPart == null) {
                int position = -1;
                Expression matchedSymbol = null;
                // walk the SELECT col short names, looking for a match on the current ORDER BY 'short name'
                for (int j = 0; j < knownShortNames.length; j++) {
                    if (!shortName.equalsIgnoreCase(knownShortNames[j])) {
                        continue;
                    }
                    // if we already have a matched symbol, matching again here means it is duplicate/ambiguous
                    if (matchedSymbol != null) {
                        if (!matchedSymbol.equals(knownElements.get(j))) {
                            throw new QueryResolverException(QueryPlugin.Event.TEIID30084, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30084, symbolName));
                        }
                        continue;
                    }
                    matchedSymbol = knownElements.get(j);
                    position = j;
                }
                if (matchedSymbol != null) {
                    TempMetadataID tempMetadataID = new TempMetadataID(symbol.getName(), matchedSymbol.getType());
                    symbol.setMetadataID(tempMetadataID);
                    symbol.setType(matchedSymbol.getType());
                }
                if (position != -1) {
                    orderBy.setExpressionPosition(i, position);
                    continue;
                }
            }
        } else if (sortKey instanceof Constant) {
            // check for legacy positional
            Constant c = (Constant) sortKey;
            int elementOrder = Integer.valueOf(c.getValue().toString()).intValue();
            // adjust for the 1 based index.
            if (elementOrder > knownElements.size() || elementOrder < 1) {
                throw new QueryResolverException(QueryPlugin.Event.TEIID30085, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30085, c));
            }
            orderBy.setExpressionPosition(i, elementOrder - 1);
            continue;
        }
        // handle order by expressions
        if (command instanceof SetQuery) {
            throw new QueryResolverException(QueryPlugin.Event.TEIID30086, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30086, sortKey));
        }
        // resolve subqueries
        for (SubqueryContainer container : ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(sortKey)) {
            Command c = container.getCommand();
            QueryResolver.setChildMetadata(c, command);
            c.pushNewResolvingContext(fromClauseGroups);
            QueryResolver.resolveCommand(c, metadata.getMetadata(), false);
        }
        for (ElementSymbol symbol : ElementCollectorVisitor.getElements(sortKey, false)) {
            try {
                ResolverVisitor.resolveLanguageObject(symbol, fromClauseGroups, command.getExternalGroupContexts(), metadata);
            } catch (QueryResolverException e) {
                throw new QueryResolverException(QueryPlugin.Event.TEIID30087, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30087, symbol.getName()));
            }
        }
        ResolverVisitor.resolveLanguageObject(sortKey, metadata);
        int index = expressions.indexOf(SymbolMap.getExpression(sortKey));
        // if unrelated and not a simple query - that is more than just a grouping, throw an exception
        if (index == -1 && !isSimpleQuery && groupBy == null) {
            throw new QueryResolverException(QueryPlugin.Event.TEIID30088, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30088, sortKey));
        }
        orderBy.setExpressionPosition(i, index);
    }
}
Also used : TempMetadataID(org.teiid.query.metadata.TempMetadataID) QueryResolverException(org.teiid.api.exception.query.QueryResolverException)

Example 15 with TempMetadataID

use of org.teiid.query.metadata.TempMetadataID in project teiid by teiid.

the class ResolverUtil method resolveLookup.

public static ResolvedLookup resolveLookup(Function lookup, QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
    Expression[] args = lookup.getArgs();
    ResolvedLookup result = new ResolvedLookup();
    // Special code to handle setting return type of the lookup function to match the type of the return element
    if (!(args[0] instanceof Constant) || !(args[1] instanceof Constant) || !(args[2] instanceof Constant)) {
        throw new QueryResolverException(QueryPlugin.Event.TEIID30095, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30095));
    }
    // If code table name in lookup function refers to temp group throw exception
    GroupSymbol groupSym = new GroupSymbol((String) ((Constant) args[0]).getValue());
    try {
        groupSym.setMetadataID(metadata.getGroupID((String) ((Constant) args[0]).getValue()));
        if (groupSym.getMetadataID() instanceof TempMetadataID) {
            throw new QueryResolverException(QueryPlugin.Event.TEIID30096, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30096, ((Constant) args[0]).getValue()));
        }
    } catch (QueryMetadataException e) {
        throw new QueryResolverException(QueryPlugin.Event.TEIID30097, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30097, ((Constant) args[0]).getValue()));
    }
    result.setGroup(groupSym);
    List<GroupSymbol> groups = Arrays.asList(groupSym);
    // $NON-NLS-1$
    String returnElementName = (String) ((Constant) args[0]).getValue() + "." + (String) ((Constant) args[1]).getValue();
    ElementSymbol returnElement = new ElementSymbol(returnElementName);
    try {
        ResolverVisitor.resolveLanguageObject(returnElement, groups, metadata);
    } catch (QueryMetadataException e) {
        throw new QueryResolverException(QueryPlugin.Event.TEIID30098, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30098, returnElementName));
    }
    result.setReturnElement(returnElement);
    // $NON-NLS-1$
    String keyElementName = (String) ((Constant) args[0]).getValue() + "." + (String) ((Constant) args[2]).getValue();
    ElementSymbol keyElement = new ElementSymbol(keyElementName);
    try {
        ResolverVisitor.resolveLanguageObject(keyElement, groups, metadata);
    } catch (QueryMetadataException e) {
        throw new QueryResolverException(QueryPlugin.Event.TEIID30099, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30099, keyElementName));
    }
    result.setKeyElement(keyElement);
    args[3] = convertExpression(args[3], DataTypeManager.getDataTypeName(keyElement.getType()), metadata);
    return result;
}
Also used : TempMetadataID(org.teiid.query.metadata.TempMetadataID) QueryMetadataException(org.teiid.api.exception.query.QueryMetadataException) QueryResolverException(org.teiid.api.exception.query.QueryResolverException)

Aggregations

TempMetadataID (org.teiid.query.metadata.TempMetadataID)48 GroupSymbol (org.teiid.query.sql.symbol.GroupSymbol)21 ElementSymbol (org.teiid.query.sql.symbol.ElementSymbol)16 QueryResolverException (org.teiid.api.exception.query.QueryResolverException)12 QueryMetadataException (org.teiid.api.exception.query.QueryMetadataException)9 ArrayList (java.util.ArrayList)8 List (java.util.List)8 Test (org.junit.Test)7 TempMetadataStore (org.teiid.query.metadata.TempMetadataStore)6 CreateProcedureCommand (org.teiid.query.sql.proc.CreateProcedureCommand)6 HashSet (java.util.HashSet)5 QueryPlannerException (org.teiid.api.exception.query.QueryPlannerException)5 TeiidComponentException (org.teiid.core.TeiidComponentException)5 TeiidProcessingException (org.teiid.core.TeiidProcessingException)5 QueryMetadataInterface (org.teiid.query.metadata.QueryMetadataInterface)5 LanguageObject (org.teiid.query.sql.LanguageObject)4 CacheHint (org.teiid.query.sql.lang.CacheHint)4 Expression (org.teiid.query.sql.symbol.Expression)4 QueryProcessingException (org.teiid.api.exception.query.QueryProcessingException)3 QueryValidatorException (org.teiid.api.exception.query.QueryValidatorException)3