Search in sources :

Example 11 with KeyRecord

use of org.teiid.metadata.KeyRecord in project teiid by teiid.

the class PhoenixSQLConversionVisitor method visit.

@Override
public void visit(Update update) {
    // use an upsert
    List<ColumnReference> cols = new ArrayList<ColumnReference>();
    List<Expression> vals = new ArrayList<Expression>();
    for (SetClause set : update.getChanges()) {
        cols.add(set.getSymbol());
        vals.add(set.getValue());
    }
    Insert insert = null;
    if (update.getWhere() == null) {
        insert = new Insert(update.getTable(), cols, new ExpressionValueSource(vals));
    } else {
        List<DerivedColumn> select = new ArrayList<DerivedColumn>();
        Set<Column> columns = new HashSet<Column>();
        for (ColumnReference col : cols) {
            columns.add(col.getMetadataObject());
        }
        for (Expression val : vals) {
            select.add(new DerivedColumn(null, val));
        }
        KeyRecord pk = update.getTable().getMetadataObject().getPrimaryKey();
        if (pk != null) {
            for (Column c : pk.getColumns()) {
                if (!columns.contains(c)) {
                    ColumnReference cr = new ColumnReference(update.getTable(), c.getName(), c, c.getJavaType());
                    select.add(new DerivedColumn(null, cr));
                    cols.add(cr);
                }
            }
        }
        Select query = new Select(select, false, Arrays.asList((TableReference) update.getTable()), update.getWhere(), null, null, null);
        insert = new Insert(update.getTable(), cols, query);
    }
    append(insert);
}
Also used : ArrayList(java.util.ArrayList) KeyRecord(org.teiid.metadata.KeyRecord) Column(org.teiid.metadata.Column) HashSet(java.util.HashSet)

Example 12 with KeyRecord

use of org.teiid.metadata.KeyRecord in project teiid by teiid.

the class JPAMetadataProcessor method addSingularAttributes.

private void addSingularAttributes(MetadataFactory mf, Metamodel model, ManagedType<?> entity, Table entityTable) throws TranslatorException {
    for (Attribute<?, ?> attr : entity.getAttributes()) {
        if (!attr.isCollection()) {
            boolean simpleType = isSimpleType(attr.getJavaType());
            if (simpleType) {
                Column column = addColumn(mf, attr.getName(), TypeFacility.getDataTypeName(getJavaDataType(attr.getJavaType())), entityTable);
                if (((SingularAttribute) attr).isOptional()) {
                    column.setDefaultValue(null);
                }
            } else {
                boolean classFound = false;
                // this tables columns
                for (EmbeddableType<?> embeddable : model.getEmbeddables()) {
                    if (embeddable.getJavaType().equals(attr.getJavaType())) {
                        addSingularAttributes(mf, model, embeddable, entityTable);
                        classFound = true;
                        break;
                    }
                }
                if (!classFound) {
                    // table, then add that column as FK
                    for (EntityType et : model.getEntities()) {
                        if (et.getJavaType().equals(attr.getJavaType())) {
                            Table attributeTable = addEntity(mf, model, et);
                            KeyRecord pk = attributeTable.getPrimaryKey();
                            if (pk != null) {
                                // TODO: entities must have PK, so this check is not needed.
                                ArrayList<String> keys = new ArrayList<String>();
                                for (Column column : pk.getColumns()) {
                                    addColumn(mf, column.getName(), column.getDatatype().getRuntimeTypeName(), entityTable);
                                    keys.add(column.getName());
                                }
                                if (!foreignKeyExists(keys, entityTable)) {
                                    addForeignKey(mf, attr.getName(), keys, attributeTable.getName(), entityTable);
                                }
                            } else {
                                throw new TranslatorException(JPAPlugin.Util.gs(JPAPlugin.Event.TEIID14001, attributeTable.getName()));
                            }
                            classFound = true;
                            break;
                        }
                    }
                }
                if (!classFound) {
                    throw new TranslatorException(JPAPlugin.Util.gs(JPAPlugin.Event.TEIID14002, attr.getName()));
                }
            }
        }
    }
}
Also used : EntityType(javax.persistence.metamodel.EntityType) KeyRecord(org.teiid.metadata.KeyRecord) SingularAttribute(javax.persistence.metamodel.SingularAttribute) Table(org.teiid.metadata.Table) Column(org.teiid.metadata.Column) ArrayList(java.util.ArrayList) TranslatorException(org.teiid.translator.TranslatorException)

Example 13 with KeyRecord

use of org.teiid.metadata.KeyRecord in project teiid by teiid.

the class SolrUpdateExecution method performUpdate.

private void performUpdate(Delete obj) throws TranslatorException {
    Table table = obj.getTable().getMetadataObject();
    KeyRecord pk = table.getPrimaryKey();
    final String id = getRecordName(pk.getColumns().get(0));
    if (obj.getParameterValues() != null) {
        throw new TranslatorException(SolrPlugin.Event.TEIID20008, SolrPlugin.Util.gs(SolrPlugin.Event.TEIID20008));
    }
    SolrQueryExecution query = new SolrQueryExecution(ef, obj, this.executionContext, this.metadata, this.connection);
    query.execute();
    final UpdateRequest request = new UpdateRequest();
    query.walkDocuments(new SolrDocumentCallback() {

        @Override
        public void walk(SolrDocument doc) {
            SolrUpdateExecution.this.updateCount++;
            request.deleteById(doc.getFieldValue(id).toString());
        }
    });
    UpdateResponse response = this.connection.update(request);
    if (response.getStatus() != 0) {
        throw new TranslatorException(SolrPlugin.Event.TEIID20005, SolrPlugin.Util.gs(SolrPlugin.Event.TEIID20005, response.getStatus()));
    }
}
Also used : KeyRecord(org.teiid.metadata.KeyRecord) UpdateResponse(org.apache.solr.client.solrj.response.UpdateResponse) Table(org.teiid.metadata.Table) SolrDocument(org.apache.solr.common.SolrDocument) UpdateRequest(org.apache.solr.client.solrj.request.UpdateRequest) SolrDocumentCallback(org.teiid.translator.solr.SolrQueryExecution.SolrDocumentCallback) TranslatorException(org.teiid.translator.TranslatorException)

Example 14 with KeyRecord

use of org.teiid.metadata.KeyRecord in project teiid by teiid.

the class GlobalTableStoreImpl method getGlobalTempTableMetadataId.

@Override
public TempMetadataID getGlobalTempTableMetadataId(Object viewId) throws TeiidProcessingException, TeiidComponentException {
    String matViewName = metadata.getFullName(viewId);
    String matTableName = RelationalPlanner.MAT_PREFIX + matViewName.toUpperCase();
    GroupSymbol group = new GroupSymbol(matViewName);
    group.setMetadataID(viewId);
    TempMetadataID id = tableStore.getMetadataStore().getTempGroupID(matTableName);
    // define the table preserving the key/index information and ensure that only a single instance exists
    if (id == null) {
        synchronized (viewId) {
            id = tableStore.getMetadataStore().getTempGroupID(matTableName);
            LinkedHashMap<Expression, Integer> newExprs = null;
            if (id == null) {
                List<ElementSymbol> allCols = ResolverUtil.resolveElementsInGroup(group, metadata);
                QueryNode qnode = metadata.getVirtualPlan(viewId);
                if (viewId instanceof Table) {
                    Table t = (Table) viewId;
                    List<KeyRecord> fbis = t.getFunctionBasedIndexes();
                    if (!fbis.isEmpty()) {
                        List<GroupSymbol> groups = Arrays.asList(group);
                        int i = 0;
                        newExprs = new LinkedHashMap<Expression, Integer>();
                        for (KeyRecord keyRecord : fbis) {
                            for (int j = 0; j < keyRecord.getColumns().size(); j++) {
                                Column c = keyRecord.getColumns().get(j);
                                if (c.getParent() != keyRecord) {
                                    continue;
                                }
                                String exprString = c.getNameInSource();
                                Expression ex = QueryParser.getQueryParser().parseExpression(exprString);
                                Integer index = newExprs.get(ex);
                                if (index == null) {
                                    ResolverVisitor.resolveLanguageObject(ex, groups, metadata);
                                    ex = QueryRewriter.rewriteExpression(ex, null, metadata);
                                    String colName = TEIID_FBI + i;
                                    while (t.getColumnByName(colName) != null) {
                                        colName = TEIID_FBI + (++i);
                                    }
                                    ElementSymbol es = new ElementSymbol(colName);
                                    es.setType(ex.getType());
                                    allCols.add(es);
                                    c.setPosition(allCols.size());
                                    newExprs.put(ex, allCols.size());
                                    ex = (Expression) ex.clone();
                                } else {
                                    c.setPosition(index);
                                }
                            }
                        }
                        ResolverUtil.clearGroupInfo(group, metadata);
                        // $NON-NLS-1$
                        StringBuilder query = new StringBuilder("SELECT ");
                        // $NON-NLS-1$
                        query.append(group).append(".*, ");
                        for (Iterator<Expression> iter = newExprs.keySet().iterator(); iter.hasNext(); ) {
                            query.append(iter.next());
                            if (iter.hasNext()) {
                                // $NON-NLS-1$
                                query.append(", ");
                            }
                        }
                        // $NON-NLS-1$ //$NON-NLS-2$
                        query.append(" FROM ").append(group).append(" option nocache ").append(group);
                        qnode = new QueryNode(query.toString());
                    }
                }
                id = tableStore.getMetadataStore().addTempGroup(matTableName, allCols, false, true);
                id.setQueryNode(qnode);
                id.setCardinality((int) metadata.getCardinality(viewId));
                id.setOriginalMetadataID(viewId);
                Object pk = metadata.getPrimaryKey(viewId);
                if (pk != null) {
                    ArrayList<TempMetadataID> primaryKey = resolveIndex(metadata, id, pk);
                    id.setPrimaryKey(primaryKey);
                }
                Collection keys = metadata.getUniqueKeysInGroup(viewId);
                for (Object key : keys) {
                    id.addUniqueKey(resolveIndex(metadata, id, key));
                }
                Collection indexes = metadata.getIndexesInGroup(viewId);
                for (Object index : indexes) {
                    id.addIndex(index, resolveIndex(metadata, id, index));
                }
                if (newExprs != null) {
                    Table table = (Table) viewId;
                    List<KeyRecord> fbis = table.getFunctionBasedIndexes();
                    for (KeyRecord keyRecord : fbis) {
                        id.addIndex(keyRecord, resolveIndex(metadata, id, keyRecord));
                    }
                    GroupSymbol gs = new GroupSymbol(matTableName);
                    gs.setMetadataID(id);
                    SymbolMap map = SymbolMap.createSymbolMap(group, ResolverUtil.resolveElementsInGroup(gs, metadata).subList(0, allCols.size() - newExprs.size()), metadata);
                    LinkedHashMap<Expression, Integer> mappedExprs = new LinkedHashMap<Expression, Integer>();
                    for (Map.Entry<Expression, Integer> entry : newExprs.entrySet()) {
                        Expression ex = (Expression) entry.getKey().clone();
                        ExpressionMappingVisitor.mapExpressions(ex, map.asMap());
                        mappedExprs.put(ex, entry.getValue());
                    }
                    id.getTableData().setFunctionBasedExpressions(mappedExprs);
                }
            }
        }
    }
    updateCacheHint(viewId, group, id);
    return id;
}
Also used : ElementSymbol(org.teiid.query.sql.symbol.ElementSymbol) Table(org.teiid.metadata.Table) TempMetadataID(org.teiid.query.metadata.TempMetadataID) SymbolMap(org.teiid.query.sql.util.SymbolMap) CacheHint(org.teiid.query.sql.lang.CacheHint) LinkedHashMap(java.util.LinkedHashMap) KeyRecord(org.teiid.metadata.KeyRecord) Expression(org.teiid.query.sql.symbol.Expression) Column(org.teiid.metadata.Column) QueryNode(org.teiid.query.mapping.relational.QueryNode) GroupSymbol(org.teiid.query.sql.symbol.GroupSymbol) Collection(java.util.Collection) ReplicatedObject(org.teiid.query.ReplicatedObject) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SymbolMap(org.teiid.query.sql.util.SymbolMap)

Example 15 with KeyRecord

use of org.teiid.metadata.KeyRecord in project teiid by teiid.

the class JPAMetadataProcessor method addForeignKeys.

private void addForeignKeys(MetadataFactory mf, Metamodel model, ManagedType<?> entity, Table entityTable) throws TranslatorException {
    for (Attribute<?, ?> attr : entity.getAttributes()) {
        if (attr.isCollection()) {
            PluralAttribute pa = (PluralAttribute) attr;
            Table forignTable = null;
            for (EntityType et : model.getEntities()) {
                if (et.getJavaType().equals(pa.getElementType().getJavaType())) {
                    forignTable = mf.getSchema().getTable(et.getName());
                    break;
                }
            }
            if (forignTable == null) {
                continue;
            }
            // add foreign keys as columns in table first; check if they exist first
            ArrayList<String> keys = new ArrayList<String>();
            KeyRecord pk = entityTable.getPrimaryKey();
            for (Column entityColumn : pk.getColumns()) {
                addColumn(mf, entityColumn.getName(), entityColumn.getDatatype().getRuntimeTypeName(), forignTable);
                keys.add(entityColumn.getName());
            }
            if (!foreignKeyExists(keys, forignTable)) {
                addForeignKey(mf, attr.getName(), keys, entityTable.getName(), forignTable);
            }
        }
    }
}
Also used : EntityType(javax.persistence.metamodel.EntityType) KeyRecord(org.teiid.metadata.KeyRecord) Table(org.teiid.metadata.Table) PluralAttribute(javax.persistence.metamodel.PluralAttribute) Column(org.teiid.metadata.Column) ArrayList(java.util.ArrayList)

Aggregations

KeyRecord (org.teiid.metadata.KeyRecord)22 Column (org.teiid.metadata.Column)18 Table (org.teiid.metadata.Table)14 ArrayList (java.util.ArrayList)11 LinkedHashMap (java.util.LinkedHashMap)3 Test (org.junit.Test)3 ForeignKey (org.teiid.metadata.ForeignKey)3 MetadataStore (org.teiid.metadata.MetadataStore)3 Schema (org.teiid.metadata.Schema)3 QueryNode (org.teiid.query.mapping.relational.QueryNode)3 ElementSymbol (org.teiid.query.sql.symbol.ElementSymbol)3 TranslatorException (org.teiid.translator.TranslatorException)3 HashSet (java.util.HashSet)2 List (java.util.List)2 Map (java.util.Map)2 Properties (java.util.Properties)2 EntityType (javax.persistence.metamodel.EntityType)2 GroupSymbol (org.teiid.query.sql.symbol.GroupSymbol)2 ChildRelationship (com.sforce.soap.partner.ChildRelationship)1 BatchUpdateException (java.sql.BatchUpdateException)1