Search in sources :

Example 16 with Insert

use of org.teiid.language.Insert in project teiid by teiid.

the class TestBulkInsertExecution method testFlowAndInvocationStack.

@Test
public void testFlowAndInvocationStack() throws Exception {
    NamedTable table = new NamedTable("temp", null, Mockito.mock(Table.class));
    ArrayList<ColumnReference> elements = new ArrayList<ColumnReference>();
    elements.add(new ColumnReference(table, "one", Mockito.mock(Column.class), Integer.class));
    elements.add(new ColumnReference(table, "two", Mockito.mock(Column.class), String.class));
    List<Expression> values = new ArrayList<Expression>();
    Parameter param = new Parameter();
    param.setType(DataTypeManager.DefaultDataClasses.INTEGER);
    param.setValueIndex(0);
    values.add(param);
    param = new Parameter();
    param.setType(DataTypeManager.DefaultDataClasses.STRING);
    param.setValueIndex(1);
    values.add(param);
    ExpressionValueSource valueSource = new ExpressionValueSource(values);
    Insert insert = new Insert(table, elements, valueSource);
    insert.setParameterValues(Arrays.asList(Arrays.asList(2, '2'), Arrays.asList(2, '2'), Arrays.asList(3, '3')).iterator());
    Result r1 = Mockito.mock(Result.class);
    Result r2 = Mockito.mock(Result.class);
    Result r3 = Mockito.mock(Result.class);
    Mockito.when(r1.isSuccess()).thenReturn(true);
    Mockito.when(r1.isCreated()).thenReturn(true);
    Mockito.when(r2.isSuccess()).thenReturn(true);
    Mockito.when(r2.isCreated()).thenReturn(true);
    Mockito.when(r3.isSuccess()).thenReturn(true);
    Mockito.when(r3.isCreated()).thenReturn(true);
    BatchResult batchResult = Mockito.mock(BatchResult.class);
    Mockito.when(batchResult.getResult()).thenReturn(new Result[] { r1 }).thenReturn((new Result[] { r2 })).thenReturn(new Result[] { r3 });
    SalesforceConnection connection = Mockito.mock(SalesforceConnection.class);
    JobInfo jobInfo = Mockito.mock(JobInfo.class);
    Mockito.when(connection.createBulkJob(Mockito.anyString(), Mockito.eq(OperationEnum.insert), Mockito.eq(false))).thenReturn(jobInfo);
    Mockito.when(connection.getBulkResults(Mockito.any(JobInfo.class), Mockito.anyList())).thenReturn(new BatchResult[] { batchResult, batchResult, batchResult });
    SalesForceExecutionFactory config = new SalesForceExecutionFactory();
    config.setMaxBulkInsertBatchSize(1);
    InsertExecutionImpl updateExecution = new InsertExecutionImpl(config, insert, connection, Mockito.mock(RuntimeMetadata.class), Mockito.mock(ExecutionContext.class));
    while (true) {
        try {
            updateExecution.execute();
            org.junit.Assert.assertArrayEquals(new int[] { 1, 1, 1 }, updateExecution.getUpdateCounts());
            break;
        } catch (DataNotAvailableException e) {
            continue;
        }
    }
    Mockito.verify(connection, Mockito.times(1)).createBulkJob(Mockito.anyString(), Mockito.eq(OperationEnum.insert), Mockito.eq(false));
    Mockito.verify(connection, Mockito.times(1)).getBulkResults(Mockito.any(JobInfo.class), Mockito.anyList());
}
Also used : NamedTable(org.teiid.language.NamedTable) NamedTable(org.teiid.language.NamedTable) Table(org.teiid.metadata.Table) SalesForceExecutionFactory(org.teiid.translator.salesforce.SalesForceExecutionFactory) ArrayList(java.util.ArrayList) Insert(org.teiid.language.Insert) BatchResult(com.sforce.async.BatchResult) SalesforceConnection(org.teiid.translator.salesforce.SalesforceConnection) RuntimeMetadata(org.teiid.metadata.RuntimeMetadata) Result(com.sforce.async.Result) BatchResult(com.sforce.async.BatchResult) ExecutionContext(org.teiid.translator.ExecutionContext) Expression(org.teiid.language.Expression) JobInfo(com.sforce.async.JobInfo) Parameter(org.teiid.language.Parameter) DataNotAvailableException(org.teiid.translator.DataNotAvailableException) ColumnReference(org.teiid.language.ColumnReference) ExpressionValueSource(org.teiid.language.ExpressionValueSource) Test(org.junit.Test)

Example 17 with Insert

use of org.teiid.language.Insert in project teiid by teiid.

the class TestSingleInsert method testDateTypes.

@Test
public void testDateTypes() throws Exception {
    NamedTable table = new NamedTable("temp", null, Mockito.mock(Table.class));
    ArrayList<ColumnReference> elements = new ArrayList<ColumnReference>();
    elements.add(new ColumnReference(table, "one", Mockito.mock(Column.class), Integer.class));
    elements.add(new ColumnReference(table, "two", Mockito.mock(Column.class), Date.class));
    elements.add(new ColumnReference(table, "three", Mockito.mock(Column.class), Timestamp.class));
    List<Expression> values = new ArrayList<Expression>();
    values.add(new Literal(1, DataTypeManager.DefaultDataClasses.INTEGER));
    values.add(new Literal(TimestampUtil.createDate(100, 01, 1), DataTypeManager.DefaultDataClasses.DATE));
    values.add(new Literal(TimestampUtil.createTimestamp(100, 01, 1, 0, 4, 0, 0), DataTypeManager.DefaultDataClasses.TIMESTAMP));
    ExpressionValueSource valueSource = new ExpressionValueSource(values);
    Insert insert = new Insert(table, elements, valueSource);
    SalesforceConnection connection = Mockito.mock(SalesforceConnection.class);
    Mockito.stub(connection.create(Mockito.any(DataPayload.class))).toAnswer(new Answer<Integer>() {

        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            DataPayload payload = (DataPayload) invocation.getArguments()[0];
            List<DataPayload.Field> fields = payload.getMessageElements();
            assertEquals(3, fields.size());
            assertEquals(1, fields.get(0).value);
            assertEquals(TimestampUtil.createDate(100, 01, 1), fields.get(1).value);
            Calendar cal = (Calendar) fields.get(2).value;
            assertEquals(TimeZone.getTimeZone("GMT-1"), cal.getTimeZone());
            return 1;
        }
    });
    Mockito.stub(connection.upsert(Mockito.any(DataPayload.class))).toReturn(1);
    SalesForceExecutionFactory config = new SalesForceExecutionFactory();
    config.setMaxBulkInsertBatchSize(1);
    InsertExecutionImpl updateExecution = new InsertExecutionImpl(config, insert, connection, Mockito.mock(RuntimeMetadata.class), Mockito.mock(ExecutionContext.class));
    while (true) {
        try {
            updateExecution.execute();
            org.junit.Assert.assertArrayEquals(new int[] { 1 }, updateExecution.getUpdateCounts());
            break;
        } catch (DataNotAvailableException e) {
            continue;
        }
    }
    insert.setUpsert(true);
    updateExecution = new InsertExecutionImpl(config, insert, connection, Mockito.mock(RuntimeMetadata.class), Mockito.mock(ExecutionContext.class));
    while (true) {
        try {
            updateExecution.execute();
            org.junit.Assert.assertArrayEquals(new int[] { 1 }, updateExecution.getUpdateCounts());
            break;
        } catch (DataNotAvailableException e) {
            continue;
        }
    }
    Mockito.verify(connection).upsert(Mockito.any(DataPayload.class));
}
Also used : NamedTable(org.teiid.language.NamedTable) ArrayList(java.util.ArrayList) Insert(org.teiid.language.Insert) RuntimeMetadata(org.teiid.metadata.RuntimeMetadata) Timestamp(java.sql.Timestamp) Literal(org.teiid.language.Literal) ArrayList(java.util.ArrayList) List(java.util.List) DataNotAvailableException(org.teiid.translator.DataNotAvailableException) ExpressionValueSource(org.teiid.language.ExpressionValueSource) NamedTable(org.teiid.language.NamedTable) Table(org.teiid.metadata.Table) Calendar(java.util.Calendar) SalesForceExecutionFactory(org.teiid.translator.salesforce.SalesForceExecutionFactory) SalesforceConnection(org.teiid.translator.salesforce.SalesforceConnection) Date(java.sql.Date) ExecutionContext(org.teiid.translator.ExecutionContext) Expression(org.teiid.language.Expression) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ColumnReference(org.teiid.language.ColumnReference) Test(org.junit.Test)

Example 18 with Insert

use of org.teiid.language.Insert in project teiid by teiid.

the class CoherenceUpdateExecution method executeInsert.

/**
 * Private method to perform the inserting of an object into the cache
 * @throws TranslatorException
 */
private void executeInsert() throws TranslatorException {
    Insert icommand = (Insert) command;
    Table t = metadata.getTable(icommand.getTable().getMetadataObject().getFullName());
    // if the table has a foreign key, its must be a child (contained) object in the root
    if (t.getForeignKeys() != null && t.getForeignKeys().size() > 0) {
        this.addChildObject(t);
        return;
    }
    String pkColName = null;
    // process the top level object
    List<Column> pk = t.getPrimaryKey().getColumns();
    if (pk == null || pk.isEmpty()) {
        // $NON-NLS-1$
        final String msg = CoherencePlugin.Util.getString("CoherenceUpdateExecution.noPrimaryKeyDefinedOnTable", new Object[] { t.getName() });
        throw new TranslatorException(msg);
    }
    pkColName = visitor.getNameFromElement(pk.get(0));
    Object newObject = cacheTranslator.createObject(icommand.getColumns(), ((ExpressionValueSource) icommand.getValueSource()).getValues(), this.visitor, t);
    // get the key value to use to for adding to the cache
    Object keyvalue = ObjectSourceMethodManager.getValue("get" + pkColName, newObject);
    // add to cache
    try {
        this.connection.add(keyvalue, newObject);
    } catch (ResourceException e) {
        throw new TranslatorException(e);
    }
}
Also used : Table(org.teiid.metadata.Table) Column(org.teiid.metadata.Column) TranslatorException(org.teiid.translator.TranslatorException) ResourceException(javax.resource.ResourceException) Insert(org.teiid.language.Insert)

Example 19 with Insert

use of org.teiid.language.Insert in project teiid by teiid.

the class CoherenceUpdateExecution method addChildObject.

private void addChildObject(Table t) throws TranslatorException {
    List<ForeignKey> fks = t.getForeignKeys();
    ForeignKey fk = fks.get(0);
    Table parentTable = fk.getParent();
    // the name of the method to obtain the collection is the nameInSource of the foreginKey
    String parentToChildMethod = fk.getNameInSource();
    if (parentToChildMethod == null) {
        // $NON-NLS-1$
        final String msg = CoherencePlugin.Util.getString("CoherenceUpdateExecution.noNameInSourceForForeingKey", new Object[] { fk.getName() });
        throw new TranslatorException(msg);
    }
    // there must only be 1 column in the primary key
    String parentColName = visitor.getNameFromElement(fk.getPrimaryKey().getColumns().get(0));
    Insert icommand = (Insert) command;
    List<ColumnReference> insertElementList = icommand.getColumns();
    List<Expression> insertValueList = ((ExpressionValueSource) icommand.getValueSource()).getValues();
    if (insertElementList.size() != insertValueList.size()) {
        throw new TranslatorException("Error:  columns.size and values.size are not the same.");
    }
    ColumnReference insertElement;
    String[] nameOfElement = new String[insertElementList.size()];
    int parentValueLoc = -1;
    for (int i = 0; i < insertElementList.size(); i++) {
        insertElement = insertElementList.get(i);
        // // call utility class to get NameInSource/Name of element
        nameOfElement[i] = visitor.getNameFromElement(insertElement.getMetadataObject());
        // match the parent column to the colum in the insert statement
        if (nameOfElement[i].equalsIgnoreCase(parentColName)) {
            parentValueLoc = i;
        }
    }
    if (parentColName != null && parentValueLoc == -1) {
        // $NON-NLS-1$
        final String msg = CoherencePlugin.Util.getString("CoherenceUpdateExecution.noColumnMatchedForeignColumn", new Object[] { t.getName(), parentColName });
        throw new TranslatorException(msg);
    }
    // get the parent key and find the root object
    Object parentValue = insertValueList.get(parentValueLoc);
    Object val;
    if (parentValue instanceof Literal) {
        Literal literalValue = (Literal) parentValue;
        val = literalValue.getValue();
    } else {
        val = parentValue;
    }
    Object parentObject = null;
    // get the parent object from the cache
    try {
        List<Object> result = this.connection.get(CoherenceFilterUtil.createCompareFilter(parentColName, val, Operator.EQ, val.getClass()));
        // visitor.createFilter(parentColName + " = " + val));
        if (result == null || result.isEmpty()) {
            // $NON-NLS-1$
            final String msg = CoherencePlugin.Util.getString("CoherenceUpdateExecution.noobjectfound", new Object[] { parentTable.getName(), parentColName, val });
            throw new TranslatorException(msg);
        }
        parentObject = result.get(0);
    } catch (ResourceException e) {
        throw new TranslatorException(e);
    }
    // create and load the child object data
    Object newChildObject = cacheTranslator.createObject(insertElementList, insertValueList, this.visitor, t);
    // /--- questions
    // / --- how to not process - setvalue for parent column
    // / --- need to get the key value off the object of the parent
    // get the key value to use to for adding to the cache
    Object parentContainer = ObjectSourceMethodManager.getValue("get" + parentToChildMethod, parentObject);
    if (parentContainer == null) {
        // $NON-NLS-1$
        final String msg = CoherencePlugin.Util.getString("CoherenceUpdateExecution.noParentContainerObjectFound", new Object[] { parentTable.getName(), parentToChildMethod });
        throw new TranslatorException(msg);
    }
    if (parentContainer.getClass().isArray()) {
    } else if (parentContainer instanceof Collection) {
        Collection c = (Collection) parentContainer;
        c.add(newChildObject);
    } else if (parentContainer instanceof Map) {
        Map m = (Map) parentContainer;
        m.put(1, newChildObject);
    }
    try {
        this.connection.update(parentValue, parentObject);
    } catch (ResourceException e) {
        throw new TranslatorException(e);
    }
}
Also used : Table(org.teiid.metadata.Table) ForeignKey(org.teiid.metadata.ForeignKey) Insert(org.teiid.language.Insert) Expression(org.teiid.language.Expression) Literal(org.teiid.language.Literal) Collection(java.util.Collection) TranslatorException(org.teiid.translator.TranslatorException) ResourceException(javax.resource.ResourceException) Map(java.util.Map) ColumnReference(org.teiid.language.ColumnReference) ExpressionValueSource(org.teiid.language.ExpressionValueSource)

Example 20 with Insert

use of org.teiid.language.Insert in project teiid by teiid.

the class TestBatchedUpdatesImpl method testGetUpdateCommands.

@Test
public void testGetUpdateCommands() throws Exception {
    List updates = example().getUpdateCommands();
    assertEquals(3, updates.size());
    assertTrue(updates.get(0) instanceof Insert);
    assertTrue(updates.get(1) instanceof Update);
    assertTrue(updates.get(2) instanceof Delete);
}
Also used : Delete(org.teiid.language.Delete) List(java.util.List) ArrayList(java.util.ArrayList) Insert(org.teiid.language.Insert) Update(org.teiid.language.Update) Test(org.junit.Test)

Aggregations

Insert (org.teiid.language.Insert)26 Test (org.junit.Test)15 Expression (org.teiid.language.Expression)11 ExpressionValueSource (org.teiid.language.ExpressionValueSource)11 PreparedStatement (java.sql.PreparedStatement)9 Connection (java.sql.Connection)8 FakeExecutionContextImpl (org.teiid.dqp.internal.datamgr.FakeExecutionContextImpl)8 Parameter (org.teiid.language.Parameter)8 ResultSet (java.sql.ResultSet)7 ArrayList (java.util.ArrayList)7 ResultSetMetaData (java.sql.ResultSetMetaData)6 List (java.util.List)6 TranslatorException (org.teiid.translator.TranslatorException)6 ColumnReference (org.teiid.language.ColumnReference)5 RuntimeMetadata (org.teiid.metadata.RuntimeMetadata)5 Table (org.teiid.metadata.Table)5 ExecutionContext (org.teiid.translator.ExecutionContext)5 NamedTable (org.teiid.language.NamedTable)4 Update (org.teiid.language.Update)4 BatchResult (com.sforce.async.BatchResult)3