Search in sources :

Example 21 with ColumnReference

use of org.teiid.language.ColumnReference 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 22 with ColumnReference

use of org.teiid.language.ColumnReference 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 23 with ColumnReference

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

the class CoherenceVisitor method getExpressionString.

// GHH 20080326 - found that code to fall back on Name if NameInSource
// was null wasn't working properly, so replaced with tried and true
// code from another custom connector.
private String getExpressionString(Expression e) throws TranslatorException {
    String expressionName = null;
    // - the rest of this method is unchanged
    if (e instanceof ColumnReference) {
        Column mdIDElement = ((ColumnReference) e).getMetadataObject();
        expressionName = mdIDElement.getNameInSource();
        if (expressionName == null || expressionName.equals("")) {
            // $NON-NLS-1$
            expressionName = mdIDElement.getName();
        }
    } else if (e instanceof Literal) {
        // try {
        // if(((Literal)e).getType().equals(Class.forName(Timestamp.class.getName()))) {
        // LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Found an expression that uses timestamp; converting to LDAP string format."); //$NON-NLS-1$
        // Timestamp ts = (Timestamp)((Literal)e).getValue();
        // Date dt = new Date(ts.getTime());
        // //TODO: Fetch format if provided.
        // SimpleDateFormat sdf = new SimpleDateFormat(LDAPConnectorConstants.ldapTimestampFormat);
        // expressionName = sdf.format(dt);
        // LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Timestamp to stsring is: " + expressionName); //$NON-NLS-1$
        // }
        // else {
        // expressionName = ((Literal)e).getValue().toString();
        // }
        expressionName = ((Literal) e).getValue().toString();
    // } catch (ClassNotFoundException cce) {
    // final String msg = LDAPPlugin.Util.getString("IQueryToLdapSearchParser.timestampClassNotFoundError"); //$NON-NLS-1$
    // throw new TranslatorException(cce, msg);
    // }
    // 
    } else {
        if (e instanceof AggregateFunction) {
            // $NON-NLS-1$
            LogManager.logError(LogConstants.CTX_CONNECTOR, "Received IAggregate, but it is not supported. Check capabilities.");
        } else if (e instanceof Function) {
            // $NON-NLS-1$
            LogManager.logError(LogConstants.CTX_CONNECTOR, "Received IFunction, but it is not supported. Check capabilties.");
        } else if (e instanceof ScalarSubquery) {
            // $NON-NLS-1$
            LogManager.logError(LogConstants.CTX_CONNECTOR, "Received IScalarSubquery, but it is not supported. Check capabilties.");
        } else if (e instanceof SearchedCase) {
            // $NON-NLS-1$
            LogManager.logError(LogConstants.CTX_CONNECTOR, "Received ISearchedCaseExpression, but it is not supported. Check capabilties.");
        }
        // $NON-NLS-1$
        final String msg = CoherencePlugin.Util.getString("CoherenceVisitory.unsupportedElementError", e.toString());
        throw new TranslatorException(msg);
    }
    expressionName = escapeReservedChars(expressionName);
    return expressionName;
}
Also used : SearchedCase(org.teiid.language.SearchedCase) Function(org.teiid.language.Function) AggregateFunction(org.teiid.language.AggregateFunction) ScalarSubquery(org.teiid.language.ScalarSubquery) Column(org.teiid.metadata.Column) DerivedColumn(org.teiid.language.DerivedColumn) Literal(org.teiid.language.Literal) AggregateFunction(org.teiid.language.AggregateFunction) TranslatorException(org.teiid.translator.TranslatorException) ColumnReference(org.teiid.language.ColumnReference)

Example 24 with ColumnReference

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

the class UpdateExecutionImpl method processIds.

@Override
protected int processIds(String[] ids, IQueryProvidingVisitor visitor) throws ResourceException {
    List<DataPayload> updateDataList = new ArrayList<DataPayload>();
    for (int i = 0; i < ids.length; i++) {
        DataPayload data = new DataPayload();
        for (SetClause clause : ((Update) command).getChanges()) {
            ColumnReference element = clause.getSymbol();
            Column column = element.getMetadataObject();
            String val = ((Literal) clause.getValue()).toString();
            data.addField(column.getSourceName(), Util.stripQutes(val));
        }
        data.setType(visitor.getTableName());
        data.setID(ids[i]);
        updateDataList.add(data);
    }
    return getConnection().update(updateDataList);
}
Also used : Column(org.teiid.metadata.Column) Literal(org.teiid.language.Literal) ArrayList(java.util.ArrayList) Update(org.teiid.language.Update) SetClause(org.teiid.language.SetClause) ColumnReference(org.teiid.language.ColumnReference)

Example 25 with ColumnReference

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

the class YahooExecution method getNeededColumns.

/**
 * @param select
 * @return
 * @throws TranslatorException
 */
static int[] getNeededColumns(List<DerivedColumn> select) throws TranslatorException {
    int[] cols = new int[select.size()];
    Iterator<DerivedColumn> iter = select.iterator();
    for (int i = 0; iter.hasNext(); i++) {
        DerivedColumn symbol = iter.next();
        Expression expr = symbol.getExpression();
        if (expr instanceof ColumnReference) {
            Column element = ((ColumnReference) expr).getMetadataObject();
            cols[i] = element.getPosition();
        } else {
            // $NON-NLS-1$
            throw new TranslatorException(YahooPlugin.Util.getString("YahooExecution.Invalid_select_symbol", expr));
        }
    }
    return cols;
}
Also used : Expression(org.teiid.language.Expression) Column(org.teiid.metadata.Column) DerivedColumn(org.teiid.language.DerivedColumn) TranslatorException(org.teiid.translator.TranslatorException) DerivedColumn(org.teiid.language.DerivedColumn) ColumnReference(org.teiid.language.ColumnReference)

Aggregations

ColumnReference (org.teiid.language.ColumnReference)35 Expression (org.teiid.language.Expression)14 NamedTable (org.teiid.language.NamedTable)13 Column (org.teiid.metadata.Column)12 ArrayList (java.util.ArrayList)11 TranslatorException (org.teiid.translator.TranslatorException)11 ExpressionValueSource (org.teiid.language.ExpressionValueSource)10 Literal (org.teiid.language.Literal)10 Table (org.teiid.metadata.Table)10 DerivedColumn (org.teiid.language.DerivedColumn)8 Test (org.junit.Test)7 Select (org.teiid.language.Select)6 Insert (org.teiid.language.Insert)5 List (java.util.List)4 Iterator (java.util.Iterator)3 Function (org.teiid.language.Function)3 Parameter (org.teiid.language.Parameter)3 SetQuery (org.teiid.language.SetQuery)3 RuntimeMetadata (org.teiid.metadata.RuntimeMetadata)3 DataNotAvailableException (org.teiid.translator.DataNotAvailableException)3