Search in sources :

Example 1 with NamedRelation

use of org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation in project legend-pure by finos.

the class DatabaseProcessor method processTable.

static void processTable(CoreInstance table, Matcher matcher, ProcessorState processorState, ProcessorSupport processorSupport) {
    MapIterable<String, Column> columnsByName = processColumnsForTableOrView(table);
    if (table instanceof Table) {
        MutableList<Column> primaryKey = (MutableList<Column>) ((Table) table)._primaryKey().toList();
        for (int i = 0; i < primaryKey.size(); i++) {
            CoreInstance key = primaryKey.get(i);
            if (processorSupport.instance_instanceOf(key, M3Paths.String)) {
                String columnName = key.getName();
                Column column = columnsByName.get(columnName);
                if (column == null) {
                    throw new PureCompilationException(table.getSourceInformation(), "Could not find column " + columnName + " in table " + ((NamedRelation) table)._name());
                }
                primaryKey.set(i, column);
            }
        }
        ((Table) table)._primaryKey(primaryKey);
    }
    if (table instanceof Relation) {
        Relation relation = (Relation) table;
        relation._setColumnsCoreInstance(relation._columns().collect(relationalOperationElement -> (Column) relationalOperationElement));
    }
    processTableMilestoning(table, columnsByName, matcher, processorState, processorSupport);
}
Also used : Maps(org.eclipse.collections.impl.factory.Maps) Join(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.join.Join) BusinessMilestoning(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.BusinessMilestoning) Predicate2(org.eclipse.collections.api.block.predicate.Predicate2) MutableList(org.eclipse.collections.api.list.MutableList) ProcessorState(org.finos.legend.pure.m3.compiler.postprocessing.ProcessorState) ProcessorSupport(org.finos.legend.pure.m3.navigation.ProcessorSupport) MutableSet(org.eclipse.collections.api.set.MutableSet) Pair(org.finos.legend.pure.m3.coreinstance.meta.pure.functions.collection.Pair) Filter(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Filter) RichIterable(org.eclipse.collections.api.RichIterable) Relation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Relation) PostProcessor(org.finos.legend.pure.m3.compiler.postprocessing.PostProcessor) PureCompilationException(org.finos.legend.pure.m4.exception.PureCompilationException) UnifiedMap(org.eclipse.collections.impl.map.mutable.UnifiedMap) Schema(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Schema) ModelRepository(org.finos.legend.pure.m4.ModelRepository) Class(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Class) Iterate(org.eclipse.collections.impl.utility.Iterate) Matcher(org.finos.legend.pure.m3.tools.matcher.Matcher) Milestoning(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Milestoning) NamedRelationAccessor(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelationAccessor) UnaryOperation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.operation.UnaryOperation) GenericType(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.generics.GenericType) Lists(org.eclipse.collections.impl.factory.Lists) ImportStub(org.finos.legend.pure.m3.navigation.importstub.ImportStub) TableAliasColumn(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAliasColumn) ListIterable(org.eclipse.collections.api.list.ListIterable) Processor(org.finos.legend.pure.m3.compiler.postprocessing.processor.Processor) Queue(java.util.Queue) ReferenceUsage(org.finos.legend.pure.m3.compiler.ReferenceUsage) ProcessingMilestoning(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.ProcessingMilestoning) Function(org.eclipse.collections.api.block.function.Function) BinaryOperation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.operation.BinaryOperation) Database(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Database) FastList(org.eclipse.collections.impl.list.mutable.FastList) M3Paths(org.finos.legend.pure.m3.navigation.M3Paths) Context(org.finos.legend.pure.m3.compiler.Context) IndexSpecification(org.finos.legend.pure.m4.coreinstance.indexing.IndexSpecification) MutableMap(org.eclipse.collections.api.map.MutableMap) Column(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Column) BusinessSnapshotMilestoning(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.BusinessSnapshotMilestoning) M2RelationalProperties(org.finos.legend.pure.m2.relational.M2RelationalProperties) Date(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.datatype.Date) DynaFunction(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.DynaFunction) Predicates2(org.eclipse.collections.impl.block.factory.Predicates2) PackageableElement(org.finos.legend.pure.m3.navigation.PackageableElement.PackageableElement) M2RelationalPaths(org.finos.legend.pure.m2.relational.M2RelationalPaths) SourceInformation(org.finos.legend.pure.m4.coreinstance.SourceInformation) CoreInstance(org.finos.legend.pure.m4.coreinstance.CoreInstance) IndexSpecifications(org.finos.legend.pure.m4.coreinstance.indexing.IndexSpecifications) Functions0(org.eclipse.collections.impl.block.factory.Functions0) LazyIterate(org.eclipse.collections.impl.utility.LazyIterate) RelationalOperationElement(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.RelationalOperationElement) Table(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Table) Sets(org.eclipse.collections.impl.factory.Sets) MapIterable(org.eclipse.collections.api.map.MapIterable) TableAlias(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAlias) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) Operation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.operation.Operation) M3Properties(org.finos.legend.pure.m3.navigation.M3Properties) ArrayDeque(java.util.ArrayDeque) Relation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Relation) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) Table(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Table) MutableList(org.eclipse.collections.api.list.MutableList) TableAliasColumn(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAliasColumn) Column(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Column) CoreInstance(org.finos.legend.pure.m4.coreinstance.CoreInstance) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) PureCompilationException(org.finos.legend.pure.m4.exception.PureCompilationException)

Example 2 with NamedRelation

use of org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation in project legend-pure by finos.

the class DatabaseProcessor method processJoin.

private static void processJoin(Join join, Database defaultDb, ModelRepository repository, ProcessorSupport processorSupport) {
    MutableMap<String, MutableMap<String, CoreInstance>> tableByAliasBySchema = Maps.mutable.empty();
    Operation operation = join._operation();
    MutableList<TableAliasColumn> selfJoinTargets = Lists.mutable.empty();
    scanOperation(operation, tableByAliasBySchema, selfJoinTargets, defaultDb, repository, processorSupport, true);
    Class<?> tableAliasClass = (Class<?>) processorSupport.package_getByUserPath(M2RelationalPaths.TableAlias);
    MutableList<TableAlias> tableAliases = Lists.mutable.empty();
    for (MutableMap<String, CoreInstance> schemaTableByAlias : tableByAliasBySchema) {
        schemaTableByAlias.forEachKeyValue((alias, table) -> {
            TableAlias tableAlias = (TableAlias) repository.newAnonymousCoreInstance(join.getSourceInformation(), tableAliasClass);
            tableAlias._name(repository.newStringCoreInstance_cached(alias).getName());
            tableAlias._relationalElement((RelationalOperationElement) table);
            tableAliases.add(tableAlias);
        });
    }
    if (tableAliases.size() > 2) {
        throw new PureCompilationException(join.getSourceInformation(), "A join can only contain 2 tables. Please use Join chains (using '>') in your mapping in order to compose many of them.");
    }
    if (tableAliases.size() == 1) {
        // Self Join
        if (selfJoinTargets.isEmpty()) {
            throw new PureCompilationException(join.getSourceInformation(), "The system can only find one table in the join. Please use the '{target}' notation in order to define a directed self join.");
        }
        TableAlias existingAlias = tableAliases.get(0);
        String existingAliasName = existingAlias._name();
        RelationalOperationElement existingRelationalElement = existingAlias._relationalElement();
        TableAlias tableAlias = (TableAlias) repository.newAnonymousCoreInstance(existingAlias.getSourceInformation(), tableAliasClass);
        tableAlias._name(repository.newStringCoreInstance_cached("t_" + existingAliasName).getName());
        tableAlias._relationalElement(existingRelationalElement);
        tableAliases.add(tableAlias);
        join._target(tableAlias);
        for (TableAliasColumn selfJoinTarget : selfJoinTargets) {
            selfJoinTarget._alias(tableAlias);
            String columnName = selfJoinTarget._columnName();
            Column col = null;
            if (existingRelationalElement instanceof Relation) {
                col = (Column) ((Relation) existingRelationalElement)._columns().selectWith(COLUMN_NAME_PREDICATE, columnName).toList().getFirst();
            }
            if (col == null) {
                throw new PureCompilationException(selfJoinTarget.getSourceInformation(), "The column '" + columnName + "' can't be found in the table '" + ((NamedRelation) existingRelationalElement)._name() + "'");
            }
            selfJoinTarget._column(col);
        }
    } else if (selfJoinTargets.notEmpty()) {
        throw new PureCompilationException(join.getSourceInformation(), "A self join can only contain 1 table, found " + selfJoinTargets.size());
    }
    // All Joins
    Pair<TableAlias, TableAlias> pair1 = newPair(tableAliasClass, tableAliasClass, repository, processorSupport);
    pair1._first(tableAliases.get(0));
    pair1._second(tableAliases.get(1));
    Pair<TableAlias, TableAlias> pair2 = newPair(tableAliasClass, tableAliasClass, repository, processorSupport);
    pair2._first(tableAliases.get(1));
    pair2._second(tableAliases.get(0));
    join._aliases(Lists.immutable.with(pair1, pair2));
}
Also used : RelationalOperationElement(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.RelationalOperationElement) MutableMap(org.eclipse.collections.api.map.MutableMap) UnaryOperation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.operation.UnaryOperation) BinaryOperation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.operation.BinaryOperation) Operation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.operation.Operation) Relation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Relation) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) TableAliasColumn(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAliasColumn) Column(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Column) CoreInstance(org.finos.legend.pure.m4.coreinstance.CoreInstance) TableAlias(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAlias) Class(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Class) TableAliasColumn(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAliasColumn) PureCompilationException(org.finos.legend.pure.m4.exception.PureCompilationException)

Example 3 with NamedRelation

use of org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation in project legend-pure by finos.

the class DatabaseProcessor method processColumnsForTableOrView.

public static MapIterable<String, Column> processColumnsForTableOrView(CoreInstance tableOrView) {
    ListIterable<? extends RelationalOperationElement> columns = FastList.newList();
    if (tableOrView instanceof Relation) {
        columns = ((Relation) tableOrView)._columns().toList();
    }
    MutableMap<String, Column> columnsByName = UnifiedMap.newMap(columns.size());
    for (RelationalOperationElement column : columns) {
        if (!(column instanceof Column)) {
            throw new PureCompilationException(column.getSourceInformation(), "Expected an instance of " + M2RelationalPaths.Column + ", found " + PackageableElement.getUserPathForPackageableElement(column.getClassifier()));
        }
        String columnName = ((Column) column)._name();
        RelationalOperationElement old = columnsByName.put(columnName, (Column) column);
        if (old != null) {
            throw new PureCompilationException(column.getSourceInformation(), "Multiple columns named '" + columnName + "' found in " + tableOrView.getClassifier().getName().toLowerCase() + " " + ((NamedRelation) tableOrView)._name());
        }
        ((Column) column)._owner((Relation) tableOrView);
    }
    return columnsByName;
}
Also used : Relation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Relation) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) TableAliasColumn(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAliasColumn) Column(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Column) RelationalOperationElement(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.RelationalOperationElement) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) PureCompilationException(org.finos.legend.pure.m4.exception.PureCompilationException)

Example 4 with NamedRelation

use of org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation in project legend-engine by finos.

the class RelationalCompilerExtension method getExtraExecutionContextProcessors.

@Override
public List<Function2<ExecutionContext, CompileContext, org.finos.legend.pure.m3.coreinstance.meta.pure.runtime.ExecutionContext>> getExtraExecutionContextProcessors() {
    return Collections.singletonList((executionContext, context) -> {
        if (executionContext instanceof RelationalExecutionContext) {
            RelationalExecutionContext relationalContext = (RelationalExecutionContext) executionContext;
            MutableMap<Relation, org.finos.legend.pure.m3.coreinstance.meta.pure.functions.collection.List<Column>> fksByTable = Maps.mutable.empty();
            ListIterate.forEach(relationalContext.importDataFlowFkCols, fks -> {
                org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Schema schema = ((org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Database) context.pureModel.getStore(fks.table.getDb()))._schemas().detect(s -> s._name().equals(fks.table.schema));
                RichIterable<? extends NamedRelation> relations = fks.table._type.equals("Table") ? schema._tables() : fks.table._type.equals("View") ? schema._views() : null;
                Relation table = relations != null ? relations.detect(a -> a._name().equals(fks.table.table)) : null;
                RichIterable<Column> columns = ListIterate.collect(fks.columns, col -> table != null ? table._columns().select(c -> c instanceof Column).collect(c -> (Column) c).detect(c -> c._name().equals(col)) : null).select(Objects::nonNull);
                fksByTable.put(table, new Root_meta_pure_functions_collection_List_Impl("")._values(columns));
            });
            return new Root_meta_relational_runtime_RelationalExecutionContext_Impl("")._queryTimeOutInSeconds(relationalContext.queryTimeOutInSeconds)._enableConstraints(relationalContext.enableConstraints)._addDriverTablePkForProject(relationalContext.addDriverTablePkForProject)._insertDriverTablePkInTempTable(relationalContext.insertDriverTablePkInTempTable)._useTempTableAsDriver(relationalContext.useTempTableAsDriver)._preserveJoinOrder(relationalContext.preserveJoinOrder)._importDataFlow(relationalContext.importDataFlow)._importDataFlowAddFks(relationalContext.importDataFlowAddFks)._importDataFlowFksByTable(relationalContext.importDataFlowAddFks != null && relationalContext.importDataFlowAddFks ? new PureMap(fksByTable) : null)._importDataFlowImplementationCount(relationalContext.importDataFlowImplementationCount);
        }
        return null;
    });
}
Also used : PostProcessorWithParameter(org.finos.legend.pure.m3.coreinstance.meta.relational.runtime.PostProcessorWithParameter) RootRelationalInstanceSetImplementation(org.finos.legend.pure.m3.coreinstance.meta.relational.mapping.RootRelationalInstanceSetImplementation) Multimap(org.eclipse.collections.api.multimap.Multimap) Schema(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.model.Schema) RelationalAssociationImplementation(org.finos.legend.pure.m3.coreinstance.meta.relational.mapping.RelationalAssociationImplementation) MutableList(org.eclipse.collections.api.list.MutableList) AggregationAwareClassMapping(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.mapping.aggregationAware.AggregationAwareClassMapping) Maps(org.eclipse.collections.api.factory.Maps) RootRelationalClassMapping(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.mapping.RootRelationalClassMapping) MutableSet(org.eclipse.collections.api.set.MutableSet) Handlers(org.finos.legend.engine.language.pure.compiler.toPureGraph.handlers.Handlers) RichIterable(org.eclipse.collections.api.RichIterable) Store(org.finos.legend.pure.m3.coreinstance.meta.pure.store.Store) Relation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Relation) Processor(org.finos.legend.engine.language.pure.compiler.toPureGraph.extension.Processor) Tuples(org.eclipse.collections.impl.tuple.Tuples) RelationalInputData(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.mapping.mappingTest.RelationalInputData) org.finos.legend.pure.m3.coreinstance.meta.pure.mapping(org.finos.legend.pure.m3.coreinstance.meta.pure.mapping) Function4(org.finos.legend.engine.shared.core.function.Function4) IntObjectToIntFunction(org.eclipse.collections.api.block.function.primitive.IntObjectToIntFunction) PostProcessor(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.connection.postprocessor.PostProcessor) PureClientVersions(org.finos.legend.engine.protocol.pure.PureClientVersions) Objects(java.util.Objects) Procedure3(org.finos.legend.engine.shared.core.function.Procedure3) RelationalDatabaseConnection(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.connection.RelationalDatabaseConnection) org.finos.legend.pure.generated(org.finos.legend.pure.generated) List(java.util.List) ClassMapping(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.mapping.ClassMapping) Procedure2(org.eclipse.collections.api.block.procedure.Procedure2) DatabaseInstance(org.finos.legend.engine.protocol.pure.v1.model.valueSpecification.DatabaseInstance) EngineException(org.finos.legend.engine.shared.core.operational.errorManagement.EngineException) org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel) InputData(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.mapping.mappingTest.InputData) PackageableElement(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.PackageableElement) Function(org.eclipse.collections.api.block.function.Function) AuthenticationStrategy(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.connection.authentication.AuthenticationStrategy) Lists(org.eclipse.collections.api.factory.Lists) AssociationMapping(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.mapping.AssociationMapping) Procedure(org.eclipse.collections.api.block.procedure.Procedure) FastList(org.eclipse.collections.impl.list.mutable.FastList) DatasourceSpecification(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.connection.specification.DatasourceSpecification) Function3(org.eclipse.collections.api.block.function.Function3) MutableMap(org.eclipse.collections.api.map.MutableMap) HelperModelBuilder.getElementFullPath(org.finos.legend.engine.language.pure.compiler.toPureGraph.HelperModelBuilder.getElementFullPath) Function2(org.eclipse.collections.api.block.function.Function2) FunctionHandlerRegistrationInfo(org.finos.legend.engine.language.pure.compiler.toPureGraph.handlers.FunctionHandlerRegistrationInfo) RelationalAssociationMapping(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.mapping.RelationalAssociationMapping) Database(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.model.Database) RelationalExecutionContext(org.finos.legend.engine.protocol.pure.v1.model.valueSpecification.executionContext.RelationalExecutionContext) PureMap(org.finos.legend.pure.runtime.java.compiled.generation.processors.support.map.PureMap) Pair(org.eclipse.collections.api.tuple.Pair) FunctionHandlerDispatchBuilderInfo(org.finos.legend.engine.language.pure.compiler.toPureGraph.handlers.FunctionHandlerDispatchBuilderInfo) ListIterate(org.eclipse.collections.impl.utility.ListIterate) AggregationAwareSetImplementation(org.finos.legend.pure.m3.coreinstance.meta.pure.mapping.aggregationAware.AggregationAwareSetImplementation) ValueSpecification(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.valuespecification.ValueSpecification) EmbeddedRelationalInstanceSetImplementation(org.finos.legend.pure.m3.coreinstance.meta.relational.mapping.EmbeddedRelationalInstanceSetImplementation) Connection(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.connection.Connection) ImmutableList(org.eclipse.collections.api.list.ImmutableList) ExecutionContext(org.finos.legend.engine.protocol.pure.v1.model.valueSpecification.raw.executionContext.ExecutionContext) AggregateSetImplementationContainer(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.mapping.aggregationAware.AggregateSetImplementationContainer) MapperPostProcessor(org.finos.legend.engine.protocol.pure.v1.model.packageableElement.store.relational.connection.postprocessor.MapperPostProcessor) FunctionExpressionBuilderRegistrationInfo(org.finos.legend.engine.language.pure.compiler.toPureGraph.handlers.FunctionExpressionBuilderRegistrationInfo) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) Collections(java.util.Collections) org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel) PureMap(org.finos.legend.pure.runtime.java.compiled.generation.processors.support.map.PureMap) Relation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Relation) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) RelationalExecutionContext(org.finos.legend.engine.protocol.pure.v1.model.valueSpecification.executionContext.RelationalExecutionContext) Objects(java.util.Objects) MutableList(org.eclipse.collections.api.list.MutableList) List(java.util.List) FastList(org.eclipse.collections.impl.list.mutable.FastList) ImmutableList(org.eclipse.collections.api.list.ImmutableList)

Example 5 with NamedRelation

use of org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation in project legend-pure by finos.

the class RelationalInstanceSetImplementationProcessor method process.

@Override
public void process(RootRelationalInstanceSetImplementation implementation, ProcessorState state, Matcher matcher, final ModelRepository repository, final Context context, final ProcessorSupport processorSupport) {
    // No need to cross reference... ClassMapping is responsible for that
    ModelElement cls = (ModelElement) ImportStub.withImportStubByPass(implementation._classCoreInstance(), processorSupport);
    GenericType instanceGenericType = cls._classifierGenericType() == null ? (GenericType) Type.wrapGenericType(processorSupport.getClassifier(cls), processorSupport) : cls._classifierGenericType();
    CoreInstance propertyReturnGenericType = org.finos.legend.pure.m3.navigation.generictype.GenericType.resolvePropertyReturnType((implementation._classifierGenericType() == null ? (GenericType) Type.wrapGenericType(processorSupport.getClassifier(implementation), processorSupport) : implementation._classifierGenericType()), implementation.getKeyByName(M3Properties._class), processorSupport);
    if (!org.finos.legend.pure.m3.navigation.generictype.GenericType.subTypeOf(instanceGenericType, propertyReturnGenericType, processorSupport)) {
        throw new PureCompilationException(implementation.getSourceInformation(), "Trying to map an unsupported type in Relational: Type Error: '" + org.finos.legend.pure.m3.navigation.generictype.GenericType.print(instanceGenericType, processorSupport) + "' not a subtype of '" + org.finos.legend.pure.m3.navigation.generictype.GenericType.print(propertyReturnGenericType, processorSupport) + "'");
    }
    RichIterable<? extends PropertyMapping> propertyMappings = implementation._propertyMappings();
    MutableSet<TableAlias> tableAliases = RelationalPropertyMappingProcessor.processRelationalPropertyMappings(propertyMappings, implementation, implementation, implementation._id(), matcher, state, repository, processorSupport);
    if (implementation._id().equals(implementation._superSetImplementationId())) {
        throw new PureCompilationException(implementation.getSourceInformation(), "Extend mapping id cannot reference self \'" + implementation._id() + "\'");
    }
    TableAlias mainTableAlias;
    TableAlias userDefinedMainTable = implementation._mainTableAlias();
    if (userDefinedMainTable == null) {
        MutableSet<RelationalOperationElement> tables = tableAliases.collect(TABLE_ALIAS_TO_RELATIONAL_OPERATION_ELEMENT_FN);
        MutableSet<Database> databases = tableAliases.collectWith(TABLE_ALIAS_TO_DATABASE_FN, processorSupport);
        if (implementation._superSetImplementationId() != null) {
            RootRelationalInstanceSetImplementation superImplementation = getSuperMapping(implementation, processorSupport);
            PostProcessor.processElement(matcher, superImplementation, state, processorSupport);
            collectTableAndDatabaseFromSuperImplementation(superImplementation, implementation, tables, databases, processorSupport);
        }
        if (tables.size() != 1) {
            throw new PureCompilationException(implementation.getSourceInformation(), "Can't find the main table for class '" + cls._name() + "'. Please specify a main table using the ~mainTable directive.");
        }
        if (databases.size() != 1) {
            throw new PureCompilationException(implementation.getSourceInformation(), "Can't find the main table for class '" + cls._name() + "'. Inconsistent database definitions for the mapping");
        }
        mainTableAlias = (TableAlias) processorSupport.newAnonymousCoreInstance(null, M2RelationalPaths.TableAlias);
        mainTableAlias._name(repository.newStringCoreInstance_cached("").getName());
        mainTableAlias._relationalElement(tables.toList().getFirst());
        mainTableAlias._databaseCoreInstance(databases.toList().getFirst());
        implementation._mainTableAlias(mainTableAlias);
    } else {
        if (implementation._superSetImplementationId() == null) {
            mainTableAlias = userDefinedMainTable;
            Database database = (Database) ImportStub.withImportStubByPass(mainTableAlias._databaseCoreInstance(), processorSupport);
            NamedRelation table = (NamedRelation) DatabaseProcessor.findTableForAlias(database, mainTableAlias, processorSupport);
            mainTableAlias._relationalElement(table);
            mainTableAlias._setMappingOwner(implementation);
        } else {
            throw new PureCompilationException(implementation.getSourceInformation(), "Cannot specify main table explicitly for extended mapping [" + implementation._id() + "]");
        }
    }
    RelationalOperationElement mainTable = mainTableAlias._relationalElement();
    for (JoinTreeNode joinTreeNode : RelationalPropertyMappingProcessor.collectJoinTreeNodes(propertyMappings)) {
        RelationalOperationElementProcessor.processAliasForJoinTreeNode(joinTreeNode, mainTable, processorSupport);
    }
    RelationalMappingSpecificationProcessing.processFilterMapping(implementation, implementation, mainTable, matcher, state, repository, processorSupport);
    GroupByMapping groupByMapping = RelationalMappingSpecificationProcessing.processGroupByMapping(implementation, implementation, state, matcher, repository, processorSupport).getOne();
    Boolean distinct = implementation._distinct();
    if (groupByMapping != null) {
        implementation._primaryKey(groupByMapping._columns());
    } else if (distinct) {
        RichIterable<RelationalOperationElement> pks = propertyMappings.flatCollect(PROPERTY_MAPPING_TO_RELATIONAL_OPERATION_ELEMENT_FN);
        RichIterable<RelationalOperationElement> pksWithDistinctColumns = pks.groupBy(TAC_TO_COLUMN).keyMultiValuePairsView().collect(Functions.<RichIterable<RelationalOperationElement>>secondOfPair()).collect(new Function<RichIterable<RelationalOperationElement>, RelationalOperationElement>() {

            @Override
            public RelationalOperationElement valueOf(RichIterable<RelationalOperationElement> roes) {
                return roes.getFirst();
            }
        });
        implementation._primaryKey(pksWithDistinctColumns.select(RELATIONAL_OPERATION_ELEMENT_PK_PREDICATE));
    } else if (implementation._primaryKey().isEmpty()) {
        Relation relation = (Relation) mainTableAlias._relationalElement();
        final TableAlias finalMainTable = mainTableAlias;
        DatabaseProcessor.processTable(relation, matcher, state, processorSupport);
        RichIterable<? extends Column> columns = FastList.newList();
        if (relation instanceof Table) {
            columns = ((Table) relation)._primaryKey();
        } else if (relation instanceof View) {
            columns = ((View) relation)._primaryKey();
        }
        RichIterable<TableAliasColumn> primaryKey = columns.collect(new Function<Column, TableAliasColumn>() {

            @Override
            public TableAliasColumn valueOf(Column column) {
                TableAliasColumn tableAliasColumn = (TableAliasColumn) repository.newEphemeralAnonymousCoreInstance(null, processorSupport.package_getByUserPath(M2RelationalPaths.TableAliasColumn));
                tableAliasColumn._column(column);
                tableAliasColumn._alias(finalMainTable);
                return tableAliasColumn;
            }
        });
        implementation._primaryKey(primaryKey);
    } else // else if (Instance.getValueForMetaPropertyToManyResolved(implementation, M2RelationalProperties.primaryKey, context, processorSupport).isEmpty())
    // {
    // //            throw new PureCompilationException(implementation.getSourceInformation(), "Please provide a primaryKey");
    // }
    {
        processUserDefinedPrimaryKey(implementation, implementation, matcher, state, repository, processorSupport);
    }
    implementation._stores(implementation._propertyMappings().collect(STORE).toSet().with(implementation._mainTableAlias()._database()).without(null));
    MilestoningPropertyMappingProcessor.processMilestoningPropertyMapping(implementation, implementation, processorSupport);
}
Also used : RelationalOperationElement(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.RelationalOperationElement) ModelElement(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.ModelElement) Function(org.eclipse.collections.api.block.function.Function) Relation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Relation) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) Column(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Column) TableAliasColumn(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAliasColumn) Database(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Database) GroupByMapping(org.finos.legend.pure.m3.coreinstance.meta.relational.mapping.GroupByMapping) PureCompilationException(org.finos.legend.pure.m4.exception.PureCompilationException) GenericType(org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.generics.GenericType) Table(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Table) NamedRelation(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation) JoinTreeNode(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.join.JoinTreeNode) View(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.View) RichIterable(org.eclipse.collections.api.RichIterable) RootRelationalInstanceSetImplementation(org.finos.legend.pure.m3.coreinstance.meta.relational.mapping.RootRelationalInstanceSetImplementation) CoreInstance(org.finos.legend.pure.m4.coreinstance.CoreInstance) TableAlias(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAlias) TableAliasColumn(org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAliasColumn)

Aggregations

NamedRelation (org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.NamedRelation)8 Relation (org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.relation.Relation)7 Column (org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Column)6 TableAliasColumn (org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAliasColumn)6 RelationalOperationElement (org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.RelationalOperationElement)5 TableAlias (org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.TableAlias)5 CoreInstance (org.finos.legend.pure.m4.coreinstance.CoreInstance)5 PureCompilationException (org.finos.legend.pure.m4.exception.PureCompilationException)5 RichIterable (org.eclipse.collections.api.RichIterable)4 Function (org.eclipse.collections.api.block.function.Function)3 MutableMap (org.eclipse.collections.api.map.MutableMap)3 Database (org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.Database)3 Operation (org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.operation.Operation)3 ListIterable (org.eclipse.collections.api.list.ListIterable)2 MutableList (org.eclipse.collections.api.list.MutableList)2 MapIterable (org.eclipse.collections.api.map.MapIterable)2 MutableSet (org.eclipse.collections.api.set.MutableSet)2 FastList (org.eclipse.collections.impl.list.mutable.FastList)2 Class (org.finos.legend.pure.m3.coreinstance.meta.pure.metamodel.type.Class)2 Join (org.finos.legend.pure.m3.coreinstance.meta.relational.metamodel.join.Join)2