Search in sources :

Example 11 with Insert

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

the class TestProcedureResolving method testDefect23257.

/**
 *  Constants will now auto resolve if they are consistently representable in the target type
 */
@Test
public void testDefect23257() throws Exception {
    // $NON-NLS-1$
    CreateProcedureCommand command = (CreateProcedureCommand) helpResolve("EXEC pm6.vsp59()", RealMetadataFactory.example1Cached());
    CommandStatement cs = (CommandStatement) command.getBlock().getStatements().get(1);
    Insert insert = (Insert) cs.getCommand();
    assertEquals(DataTypeManager.DefaultDataClasses.SHORT, ((Expression) insert.getValues().get(1)).getType());
}
Also used : CommandStatement(org.teiid.query.sql.proc.CommandStatement) CreateProcedureCommand(org.teiid.query.sql.proc.CreateProcedureCommand) Insert(org.teiid.query.sql.lang.Insert) Test(org.junit.Test)

Example 12 with Insert

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

the class TestInsertProcessing method testInsertTriggerWithTypeChanges.

@Test
public void testInsertTriggerWithTypeChanges() throws Exception {
    TransformationMetadata tm = RealMetadataFactory.fromDDL("CREATE FOREIGN TABLE SmallA (IntKey integer PRIMARY KEY,         StringKey string,         IntNum integer,         StringNum string,         FloatNum float,         LongNum bigint,         DoubleNum double,         ByteNum smallint,         DateValue date,         TimeValue time,         TimestampValue timestamp,         BooleanValue boolean,         CharValue char(1),         ShortValue smallint,         BigIntegerValue decimal,         BigDecimalValue decimal,         ObjectValue blob)     OPTIONS (UPDATABLE 'TRUE'); " + " CREATE VIEW SmallAV (IntKey integer PRIMARY KEY,     StringKey string,     IntNum integer,     StringNum string,     FloatNum float,     LongNum long,     DoubleNum double,     ByteNum byte,     DateValue date,     TimeValue time,     TimestampValue timestamp,     BooleanValue boolean,     CharValue char,     ShortValue short,     BigIntegerValue biginteger,     BigDecimalValue bigdecimal,     ObjectValue object) OPTIONS (UPDATABLE 'TRUE') AS SELECT IntKey, StringKey, IntNum,     StringNum, FloatNum, LongNum, DoubleNum,     convert(ByteNum, byte) AS ByteNum, DateValue, TimeValue, TimestampValue,     BooleanValue, CharValue, ShortValue,     convert(BigIntegerValue, biginteger) AS BigIntegerValue, BigDecimalValue,     convert(ObjectValue, object) AS ObjectValue FROM SmallA; " + " CREATE TRIGGER ON SmallAV INSTEAD OF INSERT AS FOR EACH ROW BEGIN ATOMIC     INSERT INTO smalla (IntKey, StringKey, IntNum, StringNum, FloatNum, LongNum, DoubleNum, ByteNum, DateValue, TimeValue, TimestampValue, BooleanValue, CharValue, ShortValue, BigIntegerValue, BigDecimalValue, ObjectValue) VALUES         (NEW.IntKey, NEW.StringKey, NEW.IntNum, NEW.StringNum, NEW.FloatNum, NEW.LongNum, NEW.DoubleNum, NEW.ByteNum, NEW.DateValue, NEW.TimeValue, NEW.TimestampValue,         NEW.BooleanValue, NEW.CharValue, NEW.ShortValue, NEW.BigIntegerValue, NEW.BigDecimalValue, to_bytes(convert(NEW.ObjectValue, string), 'UTF-8')); END;", "x", "y");
    // $NON-NLS-1$
    String sql = "INSERT INTO smallav (IntKey, IntNum) VALUES (1, null), (2, 2)";
    List<?>[] expected = new List[] { Arrays.asList(1) };
    final List[] secondResult = new List[] { Arrays.asList(2, null, 2, null, null, null, null, null, null, null, null, null, null, null, null, null, null) };
    HardcodedDataManager dataManager = new HardcodedDataManager() {

        @Override
        public TupleSource registerRequest(CommandContext context, Command command, String modelName, RegisterRequestParameter parameterObject) throws TeiidComponentException {
            TupleSource ts = ((Insert) command).getTupleSource();
            try {
                List<?> tuple = ts.nextTuple();
                assertEquals(Arrays.asList(1, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null), tuple);
                tuple = ts.nextTuple();
                assertEquals(secondResult[0], tuple);
                assertNull(ts.nextTuple());
            } catch (TeiidProcessingException e) {
                throw new TeiidRuntimeException(e);
            }
            return super.registerRequest(context, command, modelName, parameterObject);
        }
    };
    dataManager.addData("INSERT INTO smalla (IntKey, StringKey, IntNum, StringNum, FloatNum, LongNum, DoubleNum, ByteNum, DateValue, TimeValue, TimestampValue, BooleanValue, CharValue, ShortValue, BigIntegerValue, BigDecimalValue, ObjectValue) VALUES (...)", Arrays.asList(2));
    BasicSourceCapabilities bsc = new BasicSourceCapabilities();
    bsc.setCapabilitySupport(Capability.INSERT_WITH_ITERATOR, true);
    ProcessorPlan plan = helpGetPlan(sql, tm, new DefaultCapabilitiesFinder(bsc));
    helpProcess(plan, dataManager, expected);
    sql = "INSERT INTO smallav (IntKey, CharValue) VALUES (1, null), (2, convert('+', char))";
    plan = helpGetPlan(sql, tm, new DefaultCapabilitiesFinder(bsc));
    secondResult[0] = Arrays.asList(2, null, null, null, null, null, null, null, null, null, null, null, '+', null, null, null, null);
    helpProcess(plan, dataManager, expected);
}
Also used : TransformationMetadata(org.teiid.query.metadata.TransformationMetadata) CommandContext(org.teiid.query.util.CommandContext) BasicSourceCapabilities(org.teiid.query.optimizer.capabilities.BasicSourceCapabilities) TeiidRuntimeException(org.teiid.core.TeiidRuntimeException) Insert(org.teiid.query.sql.lang.Insert) DefaultCapabilitiesFinder(org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder) TeiidProcessingException(org.teiid.core.TeiidProcessingException) Command(org.teiid.query.sql.lang.Command) BatchedUpdateCommand(org.teiid.query.sql.lang.BatchedUpdateCommand) TupleSource(org.teiid.common.buffer.TupleSource) List(java.util.List) Test(org.junit.Test)

Example 13 with Insert

use of org.teiid.query.sql.lang.Insert 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 14 with Insert

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

the class RulePlaceAccess method addAccessNode.

/**
 * Adds a access node if the node is a source leaf node.
 *
 * @param metadata
 * @param sourceNode
 * @return true if the source node has an access pattern
 * @throws QueryMetadataException
 * @throws TeiidComponentException
 */
private void addAccessNode(QueryMetadataInterface metadata, PlanNode sourceNode, CapabilitiesFinder finder, boolean[] additionalRules) throws QueryMetadataException, TeiidComponentException {
    boolean isInsert = false;
    Object req = sourceNode.getProperty(NodeConstants.Info.ATOMIC_REQUEST);
    if (req == null) {
        req = sourceNode.getProperty(NodeConstants.Info.NESTED_COMMAND);
    }
    if (sourceNode.getProperty(NodeConstants.Info.TABLE_FUNCTION) != null) {
        return;
    }
    if (req instanceof Insert) {
        isInsert = true;
    } else {
        PlanNode parent = sourceNode.getParent();
        if (parent.getType() == NodeConstants.Types.PROJECT && parent.getProperty(NodeConstants.Info.INTO_GROUP) != null) {
            isInsert = true;
        }
    }
    PlanNode apNode = sourceNode;
    if (sourceNode.getChildCount() == 0) {
        // Create the access node and insert
        PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
        accessNode.addGroups(sourceNode.getGroups());
        copyProperties(sourceNode, accessNode);
        SourceHint sourceHint = (SourceHint) sourceNode.removeProperty(Info.SOURCE_HINT);
        // TODO: trim the hint to only the sources possible under this model (typically 1, but could be more in
        // multi-source
        accessNode.setProperty(Info.SOURCE_HINT, sourceHint);
        Object hint = sourceNode.removeProperty(NodeConstants.Info.IS_OPTIONAL);
        if (hint != null) {
            accessNode.setProperty(NodeConstants.Info.IS_OPTIONAL, hint);
        }
        Object modelId = null;
        if (sourceNode.getGroups().size() == 1) {
            GroupSymbol gs = sourceNode.getGroups().iterator().next();
            modelId = gs.getModelMetadataId();
            if (modelId != null) {
                accessNode.setProperty(NodeConstants.Info.MODEL_ID, modelId);
            }
        }
        if (req instanceof Create || req instanceof Drop) {
            modelId = TempMetadataAdapter.TEMP_MODEL;
        } else {
            modelId = RuleRaiseAccess.getModelIDFromAccess(accessNode, metadata);
        }
        if (modelId != null) {
            boolean multiSource = metadata.isMultiSource(modelId);
            if (multiSource) {
                accessNode.setProperty(Info.IS_MULTI_SOURCE, multiSource);
            }
            accessNode.setProperty(NodeConstants.Info.MODEL_ID, modelId);
        }
        if (req == null && modelId != null) {
            // add "conformed" sources if they exist
            GroupSymbol group = sourceNode.getGroups().iterator().next();
            Object gid = group.getMetadataID();
            String sources = metadata.getExtensionProperty(gid, CONFORMED_SOURCES, false);
            if (sources != null) {
                Set<Object> conformed = new LinkedHashSet<Object>();
                conformed.add(modelId);
                for (String source : StringUtil.split(sources, ",")) {
                    // $NON-NLS-1$
                    Object mid = metadata.getModelID(source.trim());
                    if (metadata.isVirtualModel(mid)) {
                        // TODO: could validate this up-front
                        throw new QueryMetadataException(QueryPlugin.Util.gs(QueryPlugin.Event.TEIID31148, metadata.getName(mid), group));
                    }
                    conformed.add(mid);
                }
                accessNode.setProperty(Info.CONFORMED_SOURCES, conformed);
            }
        }
        // Insert
        sourceNode.addAsParent(accessNode);
        apNode = accessNode;
        // set additional information
        for (GroupSymbol group : accessNode.getGroups()) {
            if (group.getCheckMatViewStatus() != null) {
                LinkedHashSet<Object> viewsToCheck = new LinkedHashSet<Object>();
                viewsToCheck.add(group.getCheckMatViewStatus());
                accessNode.setProperty(Info.CHECK_MAT_VIEW, viewsToCheck);
            }
            Object modelID = metadata.getModelID(group.getMetadataID());
            if (CapabilitiesUtil.requiresCriteria(modelID, metadata, finder)) {
                additionalRules[1] = true;
            }
        }
    }
    // Add access pattern(s), if any, as property of access node
    if (!isInsert && addAccessPatternsProperty(apNode, metadata)) {
        additionalRules[0] = true;
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Insert(org.teiid.query.sql.lang.Insert) QueryMetadataException(org.teiid.api.exception.query.QueryMetadataException) SourceHint(org.teiid.query.sql.lang.SourceHint) Drop(org.teiid.query.sql.lang.Drop) PlanNode(org.teiid.query.optimizer.relational.plantree.PlanNode) Create(org.teiid.query.sql.lang.Create) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol)

Example 15 with Insert

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

the class LanguageBridgeFactory method translate.

/* Insert */
org.teiid.language.Insert translate(Insert insert) {
    List<ElementSymbol> elements = insert.getVariables();
    List<ColumnReference> translatedElements = new ArrayList<ColumnReference>();
    for (ElementSymbol elementSymbol : elements) {
        translatedElements.add(translate(elementSymbol));
    }
    Iterator<List<?>> parameterValues = null;
    InsertValueSource valueSource = null;
    if (insert.getQueryExpression() != null) {
        valueSource = translate(insert.getQueryExpression());
    } else if (insert.getTupleSource() != null) {
        final TupleSource ts = insert.getTupleSource();
        parameterValues = new TupleSourceIterator(ts);
        List<org.teiid.language.Expression> translatedValues = new ArrayList<org.teiid.language.Expression>();
        for (int i = 0; i < insert.getVariables().size(); i++) {
            ElementSymbol es = insert.getVariables().get(i);
            Parameter param = new Parameter();
            param.setType(es.getType());
            param.setValueIndex(i);
            translatedValues.add(param);
        }
        valueSource = new ExpressionValueSource(translatedValues);
    } else {
        // This is for the simple one row insert.
        List values = insert.getValues();
        List<org.teiid.language.Expression> translatedValues = new ArrayList<org.teiid.language.Expression>();
        for (Iterator i = values.iterator(); i.hasNext(); ) {
            translatedValues.add(translate((Expression) i.next()));
        }
        valueSource = new ExpressionValueSource(translatedValues);
    }
    org.teiid.language.Insert result = new org.teiid.language.Insert(translate(insert.getGroup()), translatedElements, valueSource);
    result.setParameterValues(parameterValues);
    setBatchValues(result);
    result.setUpsert(insert.isUpsert());
    return result;
}
Also used : ElementSymbol(org.teiid.query.sql.symbol.ElementSymbol) org.teiid.language(org.teiid.language) Insert(org.teiid.query.sql.lang.Insert) SearchedCaseExpression(org.teiid.query.sql.symbol.SearchedCaseExpression) Expression(org.teiid.query.sql.symbol.Expression) TupleSource(org.teiid.common.buffer.TupleSource) ProcedureParameter(org.teiid.metadata.ProcedureParameter)

Aggregations

Insert (org.teiid.query.sql.lang.Insert)29 List (java.util.List)13 Command (org.teiid.query.sql.lang.Command)9 ElementSymbol (org.teiid.query.sql.symbol.ElementSymbol)8 GroupSymbol (org.teiid.query.sql.symbol.GroupSymbol)8 ArrayList (java.util.ArrayList)7 Test (org.junit.Test)7 Constant (org.teiid.query.sql.symbol.Constant)7 BasicSourceCapabilities (org.teiid.query.optimizer.capabilities.BasicSourceCapabilities)6 BatchedUpdateCommand (org.teiid.query.sql.lang.BatchedUpdateCommand)6 TeiidProcessingException (org.teiid.core.TeiidProcessingException)5 FakeCapabilitiesFinder (org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder)5 QueryProcessingException (org.teiid.api.exception.query.QueryProcessingException)4 TupleSource (org.teiid.common.buffer.TupleSource)4 QueryMetadataInterface (org.teiid.query.metadata.QueryMetadataInterface)4 Delete (org.teiid.query.sql.lang.Delete)4 StoredProcedure (org.teiid.query.sql.lang.StoredProcedure)4 Update (org.teiid.query.sql.lang.Update)4 Expression (org.teiid.query.sql.symbol.Expression)4 CommandContext (org.teiid.query.util.CommandContext)4