Search in sources :

Example 1 with NamedTable

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

the class CassandraSQLVisitor method visit.

@Override
public void visit(Select obj) {
    boolean allowFiltering = false;
    buffer.append(SELECT).append(Tokens.SPACE);
    if (obj.getFrom() != null && !obj.getFrom().isEmpty()) {
        NamedTable table = (NamedTable) obj.getFrom().get(0);
        allowFiltering = Boolean.parseBoolean(table.getMetadataObject().getProperties().get(CassandraMetadataProcessor.ALLOWFILTERING));
        if (table.getMetadataObject().getColumns() != null) {
            append(obj.getDerivedColumns());
        }
        buffer.append(Tokens.SPACE).append(FROM).append(Tokens.SPACE);
        append(obj.getFrom());
    }
    if (obj.getWhere() != null) {
        buffer.append(Tokens.SPACE).append(WHERE).append(Tokens.SPACE);
        append(obj.getWhere());
    }
    if (obj.getOrderBy() != null) {
        buffer.append(Tokens.SPACE);
        append(obj.getOrderBy());
    }
    if (obj.getLimit() != null) {
        buffer.append(Tokens.SPACE);
        append(obj.getLimit());
    }
    if (allowFiltering) {
        buffer.append(Tokens.SPACE);
        buffer.append(ALLOW_FILTERING);
    }
}
Also used : NamedTable(org.teiid.language.NamedTable)

Example 2 with NamedTable

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

the class TestMongoDBQueryExecution method testGeoFunctionInWhereWithGeometry.

@Test
public void testGeoFunctionInWhereWithGeometry() throws Exception {
    Table table = this.utility.createRuntimeMetadata().getTable("northwind.Categories");
    NamedTable namedTable = new NamedTable("Categories", "g0", table);
    ColumnReference colRef = new ColumnReference(namedTable, "CategoryName", table.getColumnByName("CategoryName"), String.class);
    DerivedColumn col = new DerivedColumn("CategoryName", colRef);
    Select select = new Select();
    select.setDerivedColumns(Arrays.asList(col));
    List<TableReference> tables = new ArrayList<TableReference>();
    tables.add(namedTable);
    select.setFrom(tables);
    final GeometryType geo = GeometryUtils.geometryFromClob(new ClobType(new ClobImpl("POLYGON ((1.0 2.0,3.0 4.0,5.0 6.0,1.0 2.0))")));
    Function function = new // $NON-NLS-1$
    Function(// $NON-NLS-1$
    "mongo.geoWithin", // $NON-NLS-1$
    Arrays.asList(colRef, new Literal(geo, GeometryType.class)), // $NON-NLS-2$
    Boolean.class);
    function.setMetadataObject(getFunctionMethod("mongo.geoWithin"));
    Comparison c = new Comparison(function, new Literal(true, Boolean.class), Comparison.Operator.EQ);
    select.setWhere(c);
    DBCollection dbCollection = helpExecute(select, new String[] { "Categories" }, 2);
    BasicDBObjectBuilder builder = new BasicDBObjectBuilder();
    builder.push("CategoryName");
    // $NON-NLS-1$
    builder.push("$geoWithin");
    // $NON-NLS-1$
    builder.add("$geometry", "{\"type\":\"Polygon\",\"coordinates\":[[[1.0,2.0],[3.0,4.0],[5.0,6.0],[1.0,2.0]]]}");
    BasicDBObject result = new BasicDBObject();
    result.append("CategoryName", "$CategoryName");
    List<DBObject> pipeline = buildArray(new BasicDBObject("$match", builder.get()), new BasicDBObject("$project", result));
    Mockito.verify(dbCollection).aggregate(Mockito.eq(pipeline), Mockito.any(AggregationOptions.class));
}
Also used : NamedTable(org.teiid.language.NamedTable) NamedTable(org.teiid.language.NamedTable) Table(org.teiid.metadata.Table) ArrayList(java.util.ArrayList) ClobType(org.teiid.core.types.ClobType) GeometryType(org.teiid.core.types.GeometryType) Function(org.teiid.language.Function) TableReference(org.teiid.language.TableReference) Comparison(org.teiid.language.Comparison) Literal(org.teiid.language.Literal) Select(org.teiid.language.Select) DerivedColumn(org.teiid.language.DerivedColumn) ClobImpl(org.teiid.core.types.ClobImpl) ColumnReference(org.teiid.language.ColumnReference) Test(org.junit.Test)

Example 3 with NamedTable

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

the class InfinispanUpdateExecution method execute.

@Override
public void execute() throws TranslatorException {
    if (useAliasCache) {
        if (useAliasCache) {
            InfinispanQueryExecution.useModifiedGroups(this.connection, this.executionContext, this.metadata, this.command);
        }
    }
    final InfinispanUpdateVisitor visitor = new InfinispanUpdateVisitor(this.metadata);
    visitor.append(this.command);
    if (!visitor.exceptions.isEmpty()) {
        throw visitor.exceptions.get(0);
    }
    TeiidTableMarsheller marshaller = null;
    try {
        Table table = visitor.getParentTable();
        Column pkColumn = visitor.getPrimaryKey();
        if (pkColumn == null) {
            throw new TranslatorException(InfinispanPlugin.Util.gs(InfinispanPlugin.Event.TEIID25013, table.getName()));
        }
        final String PK = MarshallerBuilder.getDocumentAttributeName(pkColumn, false, this.metadata);
        DocumentFilter docFilter = null;
        if (visitor.isNestedOperation() && visitor.getWhereClause() != null) {
            Action action = Action.ALWAYSADD;
            if (command instanceof Delete) {
                action = Action.REMOVE;
            }
            SQLStringVisitor ssv = new SQLStringVisitor() {

                @Override
                public void visit(ColumnReference obj) {
                    String groupName = null;
                    NamedTable group = obj.getTable();
                    if (group.getCorrelationName() != null) {
                        groupName = group.getCorrelationName();
                    } else {
                        Table groupID = group.getMetadataObject();
                        if (groupID.getFullName().equals(visitor.getParentTable().getFullName())) {
                            groupName = visitor.getParentNamedTable().getCorrelationName();
                        } else {
                            groupName = visitor.getQueryNamedTable().getCorrelationName();
                        }
                    }
                    buffer.append(groupName).append(Tokens.DOT).append(getName(obj.getMetadataObject()));
                }

                @Override
                public String getName(AbstractMetadataRecord object) {
                    return object.getName();
                }
            };
            ssv.append(visitor.getWhereClause());
            docFilter = new ComplexDocumentFilter(visitor.getParentNamedTable(), visitor.getQueryNamedTable(), this.metadata, ssv.toString(), action);
        }
        marshaller = MarshallerBuilder.getMarshaller(table, this.metadata, docFilter);
        this.connection.registerMarshaller(marshaller);
        // if the message in defined in different cache than the default, switch it out now.
        final RemoteCache<Object, Object> cache = InfinispanQueryExecution.getCache(table, connection);
        if (visitor.getOperationType() == OperationType.DELETE) {
            paginateDeleteResults(cache, visitor.getDeleteQuery(), new Task() {

                @Override
                public void run(Object row) throws TranslatorException {
                    if (visitor.isNestedOperation()) {
                        String childName = ProtobufMetadataProcessor.getMessageName(visitor.getQueryTable());
                        InfinispanDocument document = (InfinispanDocument) row;
                        cache.replace(document.getProperties().get(PK), document);
                        // false below means count that not matched, i.e. deleted count
                        updateCount = updateCount + document.getUpdateCount(childName, false);
                    } else {
                        Object key = ((Object[]) row)[0];
                        cache.remove(key);
                        updateCount++;
                    }
                }
            }, this.executionContext.getBatchSize());
        } else if (visitor.getOperationType() == OperationType.UPDATE) {
            paginateUpdateResults(cache, visitor.getUpdateQuery(), new Task() {

                @Override
                public void run(Object row) throws TranslatorException {
                    InfinispanDocument previous = (InfinispanDocument) row;
                    Object key = previous.getProperties().get(PK);
                    int count = previous.merge(visitor.getInsertPayload());
                    cache.replace(key, previous);
                    updateCount = updateCount + count;
                }
            }, this.executionContext.getBatchSize());
        } else if (visitor.getOperationType() == OperationType.INSERT) {
            performInsert(visitor, table, cache, false, marshaller);
        } else if (visitor.getOperationType() == OperationType.UPSERT) {
            performInsert(visitor, table, cache, true, marshaller);
        }
    } finally {
        if (marshaller != null) {
            this.connection.unRegisterMarshaller(marshaller);
        }
    }
}
Also used : Delete(org.teiid.language.Delete) NamedTable(org.teiid.language.NamedTable) Action(org.teiid.infinispan.api.DocumentFilter.Action) NamedTable(org.teiid.language.NamedTable) Table(org.teiid.metadata.Table) SQLStringVisitor(org.teiid.language.visitor.SQLStringVisitor) TeiidTableMarsheller(org.teiid.infinispan.api.TeiidTableMarsheller) InfinispanDocument(org.teiid.infinispan.api.InfinispanDocument) DocumentFilter(org.teiid.infinispan.api.DocumentFilter) AbstractMetadataRecord(org.teiid.metadata.AbstractMetadataRecord) Column(org.teiid.metadata.Column) TranslatorException(org.teiid.translator.TranslatorException) ColumnReference(org.teiid.language.ColumnReference)

Example 4 with NamedTable

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

the class JDBCUpdateExecution method executeTranslatedCommand.

/**
 * @param translatedComm
 * @throws TranslatorException
 * @since 4.3
 */
private void executeTranslatedCommand(TranslatedCommand translatedComm) throws TranslatorException {
    // create statement or PreparedStatement and execute
    String sql = translatedComm.getSql();
    boolean commitType = false;
    boolean succeeded = false;
    try {
        int updateCount = 0;
        Class<?>[] keyColumnDataTypes = null;
        String[] keyColumnNames = null;
        if (command instanceof Insert && context.getCommandContext().isReturnAutoGeneratedKeys() && executionFactory.supportsGeneratedKeys(context, command)) {
            Insert insert = (Insert) command;
            NamedTable nt = insert.getTable();
            if (nt.getMetadataObject() != null) {
                KeyRecord key = nt.getMetadataObject().getPrimaryKey();
                if (key != null) {
                    List<Column> cols = key.getColumns();
                    keyColumnDataTypes = new Class<?>[cols.size()];
                    keyColumnNames = new String[cols.size()];
                    for (int i = 0; i < cols.size(); i++) {
                        Column c = cols.get(i);
                        keyColumnDataTypes[i] = c.getJavaType();
                        // won't work in scenarios where the teiid name is changed or contains a .
                        keyColumnNames[i] = c.getName();
                    }
                }
            }
        }
        if (!translatedComm.isPrepared()) {
            statement = getStatement();
            // handle autoGeneratedKeys
            if (keyColumnDataTypes != null) {
                if (executionFactory.useColumnNamesForGeneratedKeys()) {
                    updateCount = statement.executeUpdate(sql, keyColumnNames);
                } else {
                    updateCount = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
                }
            } else {
                updateCount = statement.executeUpdate(sql);
            }
            result = new int[] { updateCount };
            addStatementWarnings();
        } else {
            PreparedStatement pstatement = null;
            if (statement != null) {
                statement.close();
            }
            if (keyColumnDataTypes != null) {
                if (executionFactory.useColumnNamesForGeneratedKeys()) {
                    pstatement = connection.prepareStatement(sql, keyColumnNames);
                } else {
                    pstatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                }
            } else {
                pstatement = getPreparedStatement(sql);
            }
            statement = pstatement;
            Iterator<? extends List<?>> vi = null;
            if (command instanceof BulkCommand) {
                BulkCommand batchCommand = (BulkCommand) command;
                vi = batchCommand.getParameterValues();
            }
            int k = 0;
            int batchStart = 0;
            if (vi != null) {
                try {
                    commitType = getAutoCommit(translatedComm);
                    if (commitType) {
                        connection.setAutoCommit(false);
                    }
                    int maxBatchSize = (command instanceof Insert) ? maxPreparedInsertBatchSize : Integer.MAX_VALUE;
                    boolean done = false;
                    outer: while (!done) {
                        for (int i = 0; i < maxBatchSize; i++) {
                            if (vi.hasNext()) {
                                List<?> values = vi.next();
                                bind(pstatement, translatedComm.getPreparedValues(), values);
                                k++;
                            } else {
                                if (i == 0) {
                                    break outer;
                                }
                                done = true;
                                break;
                            }
                        }
                        int[] results = pstatement.executeBatch();
                        batchStart = k;
                        if (result == null) {
                            result = results;
                        } else {
                            int len = result.length;
                            result = Arrays.copyOf(result, len + results.length);
                            System.arraycopy(results, 0, result, len, results.length);
                        }
                    }
                } catch (SQLException e) {
                    int size = k + 1;
                    if (result == null) {
                        result = new int[size];
                    } else {
                        result = Arrays.copyOf(result, size);
                    }
                    // if there is a BatchUpdateException, there are more update counts to accumulate
                    if (e instanceof BatchUpdateException) {
                        BatchUpdateException bue = (BatchUpdateException) e;
                        int[] batchResults = bue.getUpdateCounts();
                        for (int j = 0; j < batchResults.length; j++) {
                            result[batchStart + j] = batchResults[j];
                        }
                        size = batchStart + batchResults.length;
                    } else {
                        size = batchStart;
                    }
                    // resize the result and throw exception
                    throw new TranslatorBatchException(e, Arrays.copyOf(result, size));
                }
            } else {
                bind(pstatement, translatedComm.getPreparedValues(), null);
                updateCount = pstatement.executeUpdate();
                result = new int[] { updateCount };
            }
            addStatementWarnings();
            succeeded = true;
        }
        if (keyColumnDataTypes != null) {
            try {
                ResultSet keys = statement.getGeneratedKeys();
                GeneratedKeys generatedKeys = context.getCommandContext().returnGeneratedKeys(keyColumnNames, keyColumnDataTypes);
                // many databases only support returning a single generated value, but we'll still attempt to gather all
                outer: while (keys.next()) {
                    List<Object> vals = new ArrayList<Object>(keyColumnDataTypes.length);
                    for (int i = 0; i < keyColumnDataTypes.length; i++) {
                        Object value = this.executionFactory.retrieveValue(keys, i + 1, keyColumnDataTypes[i]);
                        if (value != null && TypeFacility.getRuntimeType(value.getClass()) != keyColumnDataTypes[i]) {
                            // TODO we may need to let the engine to the final conversion
                            LogManager.logDetail(LogConstants.CTX_CONNECTOR, JDBCPlugin.Util.gs(JDBCPlugin.Event.TEIID11023, keyColumnDataTypes[i], keyColumnNames[i], value.getClass()));
                            continue outer;
                        }
                        vals.add(value);
                    }
                    generatedKeys.addKey(vals);
                }
            } catch (SQLException e) {
                context.addWarning(e);
                // $NON-NLS-1$
                LogManager.logDetail(LogConstants.CTX_CONNECTOR, e, "Exception determining generated keys, no keys will be returned");
            }
        }
    } catch (SQLException err) {
        throw new JDBCExecutionException(JDBCPlugin.Event.TEIID11013, err, translatedComm);
    } finally {
        if (commitType) {
            restoreAutoCommit(!succeeded, translatedComm);
        }
    }
}
Also used : NamedTable(org.teiid.language.NamedTable) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) GeneratedKeys(org.teiid.GeneratedKeys) Insert(org.teiid.language.Insert) TranslatorBatchException(org.teiid.translator.TranslatorBatchException) KeyRecord(org.teiid.metadata.KeyRecord) Column(org.teiid.metadata.Column) BulkCommand(org.teiid.language.BulkCommand) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) BatchUpdateException(java.sql.BatchUpdateException)

Example 5 with NamedTable

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

the class TestTranslationUtility method testGetRMD.

public void testGetRMD() throws Exception {
    TranslationUtility util = new TranslationUtility(getTestVDB());
    // Translate command to get some ids
    // $NON-NLS-1$
    Select query = (Select) util.parseCommand("select * from partssupplier.parts");
    NamedTable group = (NamedTable) query.getFrom().get(0);
    AbstractMetadataRecord mid = group.getMetadataObject();
    // $NON-NLS-1$
    assertEquals("PartsSupplier.PARTSSUPPLIER.PARTS", mid.getFullName());
    // Use RMD to get stuff
    // $NON-NLS-1$
    assertEquals("PARTS", mid.getNameInSource());
}
Also used : NamedTable(org.teiid.language.NamedTable) Select(org.teiid.language.Select) AbstractMetadataRecord(org.teiid.metadata.AbstractMetadataRecord)

Aggregations

NamedTable (org.teiid.language.NamedTable)23 ColumnReference (org.teiid.language.ColumnReference)13 ArrayList (java.util.ArrayList)8 Test (org.junit.Test)6 Select (org.teiid.language.Select)6 Table (org.teiid.metadata.Table)6 Column (org.teiid.metadata.Column)5 List (java.util.List)4 DerivedColumn (org.teiid.language.DerivedColumn)4 Expression (org.teiid.language.Expression)4 Insert (org.teiid.language.Insert)4 ExpressionValueSource (org.teiid.language.ExpressionValueSource)3 TableReference (org.teiid.language.TableReference)3 AbstractMetadataRecord (org.teiid.metadata.AbstractMetadataRecord)3 RuntimeMetadata (org.teiid.metadata.RuntimeMetadata)3 DataNotAvailableException (org.teiid.translator.DataNotAvailableException)3 ExecutionContext (org.teiid.translator.ExecutionContext)3 TranslatorException (org.teiid.translator.TranslatorException)3 SalesForceExecutionFactory (org.teiid.translator.salesforce.SalesForceExecutionFactory)3 SalesforceConnection (org.teiid.translator.salesforce.SalesforceConnection)3