コード例 #1
0
        private ErrorLog GenerateQueryViewForExtentAndType(StorageEntityContainerMapping entityContainerMapping, CqlIdentifiers identifiers, ViewSet views, EntitySetBase entity, EntityTypeBase type, ViewGenMode mode)
        {
            Debug.Assert(mode != ViewGenMode.GenerateAllViews);

            // Keep track of the mapping exceptions that we have generated
            ErrorLog errorLog = new ErrorLog();

            if (m_config.IsViewTracing)
            {
                Helpers.StringTraceLine(String.Empty);
                Helpers.StringTraceLine(String.Empty);
                Helpers.FormatTraceLine("================= Generating {0} Query View for: {1} ===========================",
                                        (mode == ViewGenMode.OfTypeViews) ? "OfType" : "OfTypeOnly",
                                        entity.Name);
                Helpers.StringTraceLine(String.Empty);
                Helpers.StringTraceLine(String.Empty);
            }

            try
            {
                // (1) view generation (checks that extents are fully mapped)
                ViewgenContext context       = CreateViewgenContext(entity, ViewTarget.QueryView, identifiers);
                QueryRewriter  queryRewriter = GenerateViewsForExtentAndType(type, context, identifiers, views, mode);
            }
            catch (InternalMappingException exception)
            {
                // All exceptions have mapping errors in them
                Debug.Assert(exception.ErrorLog.Count > 0, "Incorrectly created mapping exception");
                errorLog.Merge(exception.ErrorLog);
            }

            return(errorLog);
        }
コード例 #2
0
        // internal for testing
        internal void WriteEntityContainerMappingElement(StorageEntityContainerMapping containerMapping)
        {
            DebugCheck.NotNull(containerMapping);

            _xmlWriter.WriteStartElement(StorageMslConstructs.EntityContainerMappingElement);
            _xmlWriter.WriteAttributeString(StorageMslConstructs.StorageEntityContainerAttribute, _dbSchemaName);
            _xmlWriter.WriteAttributeString(
                StorageMslConstructs.CdmEntityContainerAttribute, containerMapping.EdmEntityContainer.Name);

            foreach (var set in containerMapping.EntitySetMappings)
            {
                WriteEntitySetMappingElement(set);
            }

            foreach (var set in containerMapping.AssociationSetMappings)
            {
                WriteAssociationSetMappingElement(set);
            }

            foreach (var functionMapping in containerMapping.FunctionImportMappings.OfType <FunctionImportMappingComposable>())
            {
                WriteFunctionImportMappingElement(functionMapping);
            }

            _xmlWriter.WriteEndElement();
        }
コード例 #3
0
        // internal for testing
        internal void WriteEntityContainerMappingElement(StorageEntityContainerMapping containerMapping)
        {
            DebugCheck.NotNull(containerMapping);

            _xmlWriter.WriteStartElement(StorageMslConstructs.EntityContainerMappingElement);
            _xmlWriter.WriteAttributeString(StorageMslConstructs.StorageEntityContainerAttribute, _dbSchemaName);
            _xmlWriter.WriteAttributeString(
                StorageMslConstructs.CdmEntityContainerAttribute, containerMapping.EdmEntityContainer.Name);

            foreach (var set in containerMapping.EntitySetMappings)
            {
                WriteEntitySetMappingElement(set);
            }

            foreach (var set in containerMapping.AssociationSetMappings)
            {
                WriteAssociationSetMappingElement(set);
            }

            foreach (var functionMapping in containerMapping.FunctionImportMappings.OfType<FunctionImportMappingComposable>())
            {
                WriteFunctionImportMappingElement(functionMapping);
            }

            _xmlWriter.WriteEndElement();
        }
コード例 #4
0
        public void Can_get_entity_set()
        {
            var entityContainerMapping = new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace));
            var entitySet = new EntitySet();
            var entitySetMapping = new StorageEntitySetMapping(entitySet, entityContainerMapping);

            Assert.Same(entitySet, entitySetMapping.EntitySet);
        }
コード例 #5
0
        /// <summary>
        ///     Construct a EntitySet mapping object
        /// </summary>
        /// <param name="extent"> EntitySet metadata object </param>
        /// <param name="entityContainerMapping"> The entity Container Mapping that contains this Set mapping </param>
        public StorageEntitySetMapping(EntitySet extent, StorageEntityContainerMapping entityContainerMapping)
            : base(extent, entityContainerMapping)
        {
            Check.NotNull(extent, "extent");

            m_modificationFunctionMappings = new List<StorageEntityTypeModificationFunctionMapping>();
            m_implicitlyMappedAssociationSetEnds = new List<AssociationSetEnd>();
        }
コード例 #6
0
 protected virtual void Visit(StorageEntityContainerMapping storageEntityContainerMapping)
 {
     Visit(storageEntityContainerMapping.EdmEntityContainer);
     Visit(storageEntityContainerMapping.StorageEntityContainer);
     foreach (var mapping in storageEntityContainerMapping.EntitySetMaps)
     {
         Visit(mapping);
     }
 }
        public DynamicToFunctionModificationCommandConverter(
            StorageAssociationSetModificationFunctionMapping associationSetModificationFunctionMapping,
            StorageEntityContainerMapping entityContainerMapping)
        {
            DebugCheck.NotNull(associationSetModificationFunctionMapping);
            DebugCheck.NotNull(entityContainerMapping);

            _associationSetModificationFunctionMapping = associationSetModificationFunctionMapping;
            _entityContainerMapping = entityContainerMapping;
        }
コード例 #8
0
        public void Can_get_container_mapping()
        {
            var containerMapping = new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace));
            var storageSetMapping
                = new StorageEntitySetMapping(
                    new EntitySet(),
                    containerMapping);

            Assert.Same(containerMapping, storageSetMapping.EntityContainerMapping);
        }
        public void Can_get_store_and_entity_containers()
        {
            var entityContainer = new EntityContainer("C", DataSpace.CSpace);
            var storeContainer = new EntityContainer("S", DataSpace.CSpace);
            var entityContainerMapping = 
                new StorageEntityContainerMapping(entityContainer, storeContainer, null, false, false);

            Assert.Same(entityContainer, entityContainerMapping.EdmEntityContainer);
            Assert.Same(storeContainer, entityContainerMapping.StorageEntityContainer);
        }
コード例 #10
0
 private static bool HasQueryView(StorageEntityContainerMapping storageEntityContainerMapping)
 {
     foreach (EntitySetBase extent in storageEntityContainerMapping.EdmEntityContainer.BaseEntitySets)
     {
         if (storageEntityContainerMapping.HasQueryViewForSetMap(extent.Name))
         {
             return(true);
         }
     }
     return(false);
 }
コード例 #11
0
        public void Can_add_container_mappings()
        {
            var mapping = new DbDatabaseMapping();

            Assert.Empty(mapping.EntityContainerMappings);

            var containerMapping = new StorageEntityContainerMapping(new EntityContainer());
            mapping.AddEntityContainerMapping(containerMapping);

            Assert.Same(containerMapping, mapping.EntityContainerMappings.Single());
        }
コード例 #12
0
        public void Can_add_container_mappings()
        {
            var mapping = new DbDatabaseMapping();

            Assert.Empty(mapping.EntityContainerMappings);

            var containerMapping = new StorageEntityContainerMapping(new EntityContainer());

            mapping.AddEntityContainerMapping(containerMapping);

            Assert.Same(containerMapping, mapping.EntityContainerMappings.Single());
        }
コード例 #13
0
        /// <summary>
        ///     Entry point for View Generation
        /// </summary>
        /// <param name="containerMapping"> </param>
        /// <param name="workSpace"> </param>
        /// <param name="config"> </param>
        /// <returns> Generated Views for EntitySets </returns>
        internal static ViewGenResults GenerateViewsFromMapping(StorageEntityContainerMapping containerMapping, ConfigViewGenerator config)
        {
            DebugCheck.NotNull(containerMapping);
            DebugCheck.NotNull(config);
            Debug.Assert(containerMapping.HasViews, "Precondition Violated: No mapping exists to generate views for!");

            //Create Cells from StorageEntityContainerMapping
            var cellCreator = new CellCreator(containerMapping);
            var cells = cellCreator.GenerateCells();
            var identifiers = cellCreator.Identifiers;

            return GenerateViewsFromCells(cells, config, identifiers, containerMapping);
        }
コード例 #14
0
        /// <summary>
        ///     Entry point for View Generation
        /// </summary>
        /// <param name="containerMapping"> </param>
        /// <param name="workSpace"> </param>
        /// <param name="config"> </param>
        /// <returns> Generated Views for EntitySets </returns>
        internal static ViewGenResults GenerateViewsFromMapping(StorageEntityContainerMapping containerMapping, ConfigViewGenerator config)
        {
            DebugCheck.NotNull(containerMapping);
            DebugCheck.NotNull(config);
            Debug.Assert(containerMapping.HasViews, "Precondition Violated: No mapping exists to generate views for!");

            //Create Cells from StorageEntityContainerMapping
            var cellCreator = new CellCreator(containerMapping);
            var cells       = cellCreator.GenerateCells();
            var identifiers = cellCreator.Identifiers;

            return(GenerateViewsFromCells(cells, config, identifiers, containerMapping));
        }
コード例 #15
0
        // effects: Creates a ViewGenerator object that is capable of
        // producing query or update mapping views given the relevant schema
        // given the "cells"
        internal ViewGenerator(
            CellGroup cellGroup, ConfigViewGenerator config,
            List <ForeignConstraint> foreignKeyConstraints,
            StorageEntityContainerMapping entityContainerMapping)
        {
            m_cellGroup              = cellGroup;
            m_config                 = config;
            m_queryRewriterCache     = new Dictionary <EntitySetBase, QueryRewriter>();
            m_foreignKeyConstraints  = foreignKeyConstraints;
            m_entityContainerMapping = entityContainerMapping;

            var inheritanceGraph =
                MetadataHelper.BuildUndirectedGraphOfTypes(entityContainerMapping.StorageMappingItemCollection.EdmItemCollection);

            SetConfiguration(entityContainerMapping);

            // We fix all the cells at this point
            m_queryDomainMap = new MemberDomainMap(
                ViewTarget.QueryView, m_config.IsValidationEnabled, cellGroup,
                entityContainerMapping.StorageMappingItemCollection.EdmItemCollection, m_config, inheritanceGraph);
            m_updateDomainMap = new MemberDomainMap(
                ViewTarget.UpdateView, m_config.IsValidationEnabled, cellGroup,
                entityContainerMapping.StorageMappingItemCollection.EdmItemCollection, m_config, inheritanceGraph);

            // We now go and fix the queryDomain map so that it has all the
            // values from the S-side as well -- this is needed for domain
            // constraint propagation, i.e., values from the S-side get
            // propagated to te oneOfConst on the C-side. So we better get
            // the "possiblveValues" stuff to contain those constants as well
            MemberDomainMap.PropagateUpdateDomainToQueryDomain(cellGroup, m_queryDomainMap, m_updateDomainMap);

            UpdateWhereClauseForEachCell(cellGroup, m_queryDomainMap, m_updateDomainMap, m_config);

            // We need to simplify cell queries, yet we don't want the conditions to disappear
            // So, add an extra value to the domain, temporarily
            var queryOpenDomain  = m_queryDomainMap.GetOpenDomain();
            var updateOpenDomain = m_updateDomainMap.GetOpenDomain();

            // Make sure the WHERE clauses of the cells reflect the changes
            foreach (var cell in cellGroup)
            {
                cell.CQuery.WhereClause.FixDomainMap(queryOpenDomain);
                cell.SQuery.WhereClause.FixDomainMap(updateOpenDomain);
                cell.CQuery.WhereClause.ExpensiveSimplify();
                cell.SQuery.WhereClause.ExpensiveSimplify();
                cell.CQuery.WhereClause.FixDomainMap(m_queryDomainMap);
                cell.SQuery.WhereClause.FixDomainMap(m_updateDomainMap);
            }
        }
コード例 #16
0
        public void Can_get_entity_type_mappings()
        {
            var entityContainerMapping = new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace));
            var entitySetMapping = new StorageEntitySetMapping(new EntitySet(), entityContainerMapping);

            Assert.Empty(entitySetMapping.EntityTypeMappings);

            var entityTypeMapping
                = new StorageEntityTypeMapping(
                    new StorageEntitySetMapping(new EntitySet(), entityContainerMapping));

            entitySetMapping.AddTypeMapping(entityTypeMapping);

            Assert.Same(entityTypeMapping, entitySetMapping.EntityTypeMappings.Single());
        }
コード例 #17
0
        public static DbDatabaseMapping Initialize(
            this DbDatabaseMapping databaseMapping, EdmModel model, EdmModel database)
        {
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(databaseMapping);
            DebugCheck.NotNull(database);

            databaseMapping.Model    = model;
            databaseMapping.Database = database;
            var entityContainerMapping = new StorageEntityContainerMapping(model.Containers.Single());

            databaseMapping.EntityContainerMappings.Add(entityContainerMapping);

            return(databaseMapping);
        }
コード例 #18
0
        // effects: Creates a ViewGenerator object that is capable of
        // producing query or update mapping views given the relevant schema
        // given the "cells"
        internal ViewGenerator(
            CellGroup cellGroup, ConfigViewGenerator config,
            List<ForeignConstraint> foreignKeyConstraints,
            StorageEntityContainerMapping entityContainerMapping)
        {
            m_cellGroup = cellGroup;
            m_config = config;
            m_queryRewriterCache = new Dictionary<EntitySetBase, QueryRewriter>();
            m_foreignKeyConstraints = foreignKeyConstraints;
            m_entityContainerMapping = entityContainerMapping;

            var inheritanceGraph =
                MetadataHelper.BuildUndirectedGraphOfTypes(entityContainerMapping.StorageMappingItemCollection.EdmItemCollection);
            SetConfiguration(entityContainerMapping);

            // We fix all the cells at this point
            m_queryDomainMap = new MemberDomainMap(
                ViewTarget.QueryView, m_config.IsValidationEnabled, cellGroup,
                entityContainerMapping.StorageMappingItemCollection.EdmItemCollection, m_config, inheritanceGraph);
            m_updateDomainMap = new MemberDomainMap(
                ViewTarget.UpdateView, m_config.IsValidationEnabled, cellGroup,
                entityContainerMapping.StorageMappingItemCollection.EdmItemCollection, m_config, inheritanceGraph);

            // We now go and fix the queryDomain map so that it has all the
            // values from the S-side as well -- this is needed for domain
            // constraint propagation, i.e., values from the S-side get
            // propagated to te oneOfConst on the C-side. So we better get
            // the "possiblveValues" stuff to contain those constants as well
            MemberDomainMap.PropagateUpdateDomainToQueryDomain(cellGroup, m_queryDomainMap, m_updateDomainMap);

            UpdateWhereClauseForEachCell(cellGroup, m_queryDomainMap, m_updateDomainMap, m_config);

            // We need to simplify cell queries, yet we don't want the conditions to disappear
            // So, add an extra value to the domain, temporarily
            var queryOpenDomain = m_queryDomainMap.GetOpenDomain();
            var updateOpenDomain = m_updateDomainMap.GetOpenDomain();

            // Make sure the WHERE clauses of the cells reflect the changes
            foreach (var cell in cellGroup)
            {
                cell.CQuery.WhereClause.FixDomainMap(queryOpenDomain);
                cell.SQuery.WhereClause.FixDomainMap(updateOpenDomain);
                cell.CQuery.WhereClause.ExpensiveSimplify();
                cell.SQuery.WhereClause.ExpensiveSimplify();
                cell.CQuery.WhereClause.FixDomainMap(m_queryDomainMap);
                cell.SQuery.WhereClause.FixDomainMap(m_updateDomainMap);
            }
        }
        public void Can_get_entity_set_mappings()
        {
            var entityContainerMapping = new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace));

            Assert.Empty(entityContainerMapping.EntitySetMappings);
            Assert.Empty(entityContainerMapping.EntitySetMaps);

            var entitySetMapping
                = new StorageEntitySetMapping(
                    new EntitySet("ES", null, null, null, new EntityType("E", "N", DataSpace.CSpace)), entityContainerMapping);

            entityContainerMapping.AddEntitySetMapping(entitySetMapping);

            Assert.Same(entitySetMapping, entityContainerMapping.EntitySetMappings.Single());
            Assert.Same(entitySetMapping, entityContainerMapping.EntitySetMaps.Single());
        }
        public void Can_get_association_set_mappings()
        {
            var entityContainerMapping = new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace));

            Assert.Empty(entityContainerMapping.AssociationSetMappings);
            Assert.Empty(entityContainerMapping.RelationshipSetMaps);

            var associationSetMapping
                = new StorageAssociationSetMapping(
                    new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace)), entityContainerMapping);

            entityContainerMapping.AddAssociationSetMapping(associationSetMapping);

            Assert.Same(associationSetMapping, entityContainerMapping.AssociationSetMappings.Single());
            Assert.Same(associationSetMapping, entityContainerMapping.RelationshipSetMaps.Single());
        }
コード例 #21
0
        internal static IEnumerable <StorageTypeMapping> GetMappingsForEntitySetAndType(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType)
        {
            Debug.Assert(entityType != null, "EntityType parameter should not be null.");
            StorageEntityContainerMapping containerMapping = GetEntityContainerMap(mappingCollection, container);
            StorageSetMapping             extentMap        = containerMapping.GetSetMapping(entitySet.Name);

            //The Set may have no mapping
            if (extentMap != null)
            {
                //for each mapping fragment of Type we are interested in within the given set
                //Check use of IsOfTypes in Code review
                foreach (StorageTypeMapping typeMap in extentMap.TypeMappings.Where(map => map.Types.Union(map.IsOfTypes).Contains(entityType)))
                {
                    yield return(typeMap);
                }
            }
        }
        public void Can_add_and_get_function_import_mapping()
        {
            var typeUsage = 
                TypeUsage.CreateDefaultTypeUsage(
                    PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32).GetCollectionType());

            var entityContainerMapping = new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.CSpace));

            var composableFuntionMapping =
                new FunctionImportMappingComposable(
                    new EdmFunction(
                        "f", "model", DataSpace.CSpace,
                        new EdmFunctionPayload()
                            {
                                IsComposable = true,
                                ReturnParameters =
                                    new[]
                                        {
                                            new FunctionParameter(
                                                "ReturnType",
                                                typeUsage,
                                                ParameterMode.ReturnValue),
                                        }

                            }),
                    new EdmFunction(
                        "f", "store", DataSpace.SSpace,
                        new EdmFunctionPayload()
                            {
                                IsComposable = true,
                                ReturnParameters =
                                    new[]
                                        {
                                            new FunctionParameter(
                                                "ReturnType",
                                                typeUsage,
                                                ParameterMode.ReturnValue),
                                        }
                            }),
                    null);

            Assert.Empty(entityContainerMapping.FunctionImportMappings);
            entityContainerMapping.AddFunctionImportMapping(composableFuntionMapping);
            Assert.Same(composableFuntionMapping, entityContainerMapping.FunctionImportMappings.Single());
        }
コード例 #23
0
        /// <summary>
        /// Entry point for View Generation
        /// </summary>
        /// <param name="containerMapping"></param>
        /// <param name="workSpace"></param>
        /// <param name="config"></param>
        /// <returns>Generated Views for EntitySets</returns>
        internal static ViewGenResults GenerateViewsFromMapping(StorageEntityContainerMapping containerMapping, ConfigViewGenerator config)
        {
            EntityUtil.CheckArgumentNull(containerMapping, "containerMapping");
            EntityUtil.CheckArgumentNull(config, "config");
            Debug.Assert(containerMapping.HasViews, "Precondition Violated: No mapping exists to generate views for!");

            if (config.IsNormalTracing)
            {
                containerMapping.Print(0);
            }

            //Create Cells from StorageEntityContainerMapping
            CellCreator    cellCreator = new CellCreator(containerMapping);
            List <Cell>    cells       = cellCreator.GenerateCells(config);
            CqlIdentifiers identifiers = cellCreator.Identifiers;

            return(GenerateViewsFromCells(cells, config, identifiers, containerMapping));
        }
コード例 #24
0
        /// <summary>
        /// Entry point for View Generation
        /// </summary>
        /// <param name="containerMapping"></param>
        /// <param name="workSpace"></param>
        /// <param name="config"></param>
        /// <returns>Generated Views for EntitySets</returns>
        internal static ViewGenResults GenerateViewsFromMapping(StorageEntityContainerMapping containerMapping, ConfigViewGenerator config)
        {
            EntityUtil.CheckArgumentNull(containerMapping, "containerMapping");
            EntityUtil.CheckArgumentNull(config, "config");
            Debug.Assert(containerMapping.HasViews, "Precondition Violated: No mapping exists to generate views for!");

            if (config.IsNormalTracing)
            {
                containerMapping.Print(0);
            }

            //Create Cells from StorageEntityContainerMapping
            CellCreator cellCreator = new CellCreator(containerMapping);
            List<Cell> cells = cellCreator.GenerateCells(config);
            CqlIdentifiers identifiers = cellCreator.Identifiers;

            return GenerateViewsFromCells(cells, config, identifiers, containerMapping);
        }
コード例 #25
0
        internal static IEnumerable <StorageEntityTypeModificationFunctionMapping> GetModificationFunctionMappingsForEntitySetAndType(StorageMappingItemCollection mappingCollection, EntityContainer container, EntitySetBase entitySet, EntityTypeBase entityType)
        {
            StorageEntityContainerMapping containerMapping = GetEntityContainerMap(mappingCollection, container);

            StorageSetMapping       extentMap        = containerMapping.GetSetMapping(entitySet.Name);
            StorageEntitySetMapping entitySetMapping = extentMap as StorageEntitySetMapping;

            //The Set may have no mapping
            if (entitySetMapping != null)
            {
                if (entitySetMapping != null) //could be association set mapping
                {
                    foreach (var v in entitySetMapping.ModificationFunctionMappings.Where(functionMap => functionMap.EntityType.Equals(entityType)))
                    {
                        yield return(v);
                    }
                }
            }
        }
コード例 #26
0
        internal static StorageEntityContainerMapping GetEntityContainerMap(StorageMappingItemCollection mappingCollection, EntityContainer entityContainer)
        {
            ReadOnlyCollection <StorageEntityContainerMapping> entityContainerMaps = mappingCollection.GetItems <StorageEntityContainerMapping>();
            StorageEntityContainerMapping entityContainerMap = null;

            foreach (StorageEntityContainerMapping map in entityContainerMaps)
            {
                if ((entityContainer.Equals(map.EdmEntityContainer)) ||
                    (entityContainer.Equals(map.StorageEntityContainer)))
                {
                    entityContainerMap = map;
                    break;
                }
            }
            if (entityContainerMap == null)
            {
                throw new MappingException(System.Data.Entity.Strings.Mapping_NotFound_EntityContainer(entityContainer.Name));
            }
            return(entityContainerMap);
        }
コード例 #27
0
        /// <summary>
        /// Entry point for View Generation
        /// </summary>
        /// <param name="containerMapping"></param>
        /// <param name="workSpace"></param>
        /// <param name="config"></param>
        /// <returns>Generated Views for EntitySets</returns>
        internal static ViewGenResults GenerateViewsFromMapping(StorageEntityContainerMapping containerMapping, ConfigViewGenerator config)
        {
            //Contract.Requires(containerMapping != null);
            //Contract.Requires(config != null);
            Debug.Assert(containerMapping.HasViews, "Precondition Violated: No mapping exists to generate views for!");

#if DEBUG
            if (config.IsNormalTracing)
            {
                containerMapping.Print(0);
            }
#endif

            //Create Cells from StorageEntityContainerMapping
            var cellCreator = new CellCreator(containerMapping);
            var cells = cellCreator.GenerateCells();
            var identifiers = cellCreator.Identifiers;

            return GenerateViewsFromCells(cells, config, identifiers, containerMapping);
        }
コード例 #28
0
        protected override void Visit(StorageEntityContainerMapping storageEntityContainerMapping)
        {
            Debug.Assert(storageEntityContainerMapping != null, "storageEntityContainerMapping cannot be null!");

            // at the entry point of visitor, we setup the versions
            Debug.Assert(m_MappingVersion == storageEntityContainerMapping.StorageMappingItemCollection.MappingVersion, "the original version and the mapping collection version are not the same");
            this.m_MappingVersion = storageEntityContainerMapping.StorageMappingItemCollection.MappingVersion;
            this.m_EdmVersion = storageEntityContainerMapping.StorageMappingItemCollection.EdmItemCollection.EdmVersion;

            this.m_EdmItemCollection = storageEntityContainerMapping.StorageMappingItemCollection.EdmItemCollection;

            int index;
            if (!this.AddObjectToSeenListAndHashBuilder(storageEntityContainerMapping, out index))
            {
                // if this has been add to the seen list, then just 
                return;
            }
            if (this.m_itemsAlreadySeen.Count > 1)
            {

                // this means user try another visit over SECM, this is allowed but all the previous visit all lost due to clean
                // user can visit different SECM objects by using the same visitor to load the SECM object
                this.Clean();
                Visit(storageEntityContainerMapping);
                return;
            }

            this.AddObjectStartDumpToHashBuilder(storageEntityContainerMapping, index);

            #region Inner data visit

            this.AddObjectContentToHashBuilder(storageEntityContainerMapping.Identity);

            this.AddV2ObjectContentToHashBuilder(storageEntityContainerMapping.GenerateUpdateViews, this.m_MappingVersion);

            base.Visit(storageEntityContainerMapping);

            #endregion

            this.AddObjectEndDumpToHashBuilder();
        }
コード例 #29
0
        private void WriteEntityContainerMappingElement(StorageEntityContainerMapping containerMapping)
        {
            DebugCheck.NotNull(containerMapping);

            _xmlWriter.WriteStartElement(StorageMslConstructs.EntityContainerMappingElement);
            _xmlWriter.WriteAttributeString(StorageMslConstructs.StorageEntityContainerAttribute, _dbSchemaName);
            _xmlWriter.WriteAttributeString(
                StorageMslConstructs.CdmEntityContainerAttribute, containerMapping.EdmEntityContainer.Name);

            foreach (var set in containerMapping.EntitySetMappings)
            {
                WriteEntitySetMappingElement(set);
            }

            foreach (var set in containerMapping.AssociationSetMappings)
            {
                WriteAssociationSetMappingElement(set);
            }

            _xmlWriter.WriteEndElement();
        }
コード例 #30
0
        /// <summary>
        /// Given a table EntitySet this function finds out all C-side EntitySets that are mapped to the table.
        /// </summary>
        internal static IEnumerable <EntitySet> GetInfluencingEntitySetsForTable(EntitySet table, MetadataWorkspace workspace)
        {
            Debug.Assert(table.EntityContainer.GetDataSpace() == DataSpace.SSpace);

            ItemCollection itemCollection = null;

            workspace.TryGetItemCollection(DataSpace.CSSpace, out itemCollection);
            StorageEntityContainerMapping containerMapping = MappingMetadataHelper.GetEntityContainerMap((StorageMappingItemCollection)itemCollection, table.EntityContainer);

            //find EntitySetMappings where one of the mapping fragment maps some type to the given table
            return(containerMapping.EntitySetMaps
                   .Where(
                       map => map.TypeMappings.Any(
                           typeMap => typeMap.MappingFragments.Any(
                               mappingFrag => mappingFrag.TableSet.EdmEquals(table)
                               )
                           )
                       )
                   .Select(m => m.Set)
                   .Cast <EntitySet>()
                   .Distinct());
        }
コード例 #31
0
 /// <summary>
 /// Construct the new StorageSetMapping object.
 /// </summary>
 /// <param name="extent">Extent metadata object</param>
 /// <param name="entityContainerMapping">The EntityContainer mapping that contains this extent mapping</param>
 internal StorageSetMapping(EntitySetBase extent, StorageEntityContainerMapping entityContainerMapping) {
     this.m_entityContainerMapping = entityContainerMapping;
     this.m_extent = extent;
     this.m_typeMappings = new List<StorageTypeMapping>();
 }
コード例 #32
0
 /// <summary>
 /// Construct a EntitySet mapping object
 /// </summary>
 /// <param name="extent">EntitySet metadata object</param>
 /// <param name="entityContainerMapping">The entity Container Mapping that contains this Set mapping</param>
 internal StorageEntitySetMapping(EntitySet extent, StorageEntityContainerMapping entityContainerMapping)
     : base(extent, entityContainerMapping) {
     m_modificationFunctionMappings = new List<StorageEntityTypeModificationFunctionMapping>();
     m_implicitlyMappedAssociationSetEnds = new List<AssociationSetEnd>();
 }
コード例 #33
0
        internal static string GetMappingClosureHash(double mappingVersion, StorageEntityContainerMapping storageEntityContainerMapping)
        {
            Debug.Assert(storageEntityContainerMapping != null, "storageEntityContainerMapping is null!");

            MetadataMappingHasherVisitor visitor = new MetadataMappingHasherVisitor(mappingVersion);
            visitor.Visit(storageEntityContainerMapping);
            return visitor.HashValue;
        }
コード例 #34
0
 private void SetConfiguration(StorageEntityContainerMapping entityContainerMapping)
 {
     m_config.IsValidationEnabled = entityContainerMapping.Validate;
     m_config.GenerateUpdateViews = entityContainerMapping.GenerateUpdateViews;
 }
コード例 #35
0
 private bool SerializedVerifyHashOverMmClosure(
     StorageEntityContainerMapping entityContainerMapping, EntityViewContainer entityViewContainer)
 {
     if (MetadataMappingHasherVisitor.GetMappingClosureHash(
         m_storageMappingItemCollection.MappingVersion, entityContainerMapping)
         ==
         entityViewContainer.HashOverMappingClosure)
     {
         return true;
     }
     return false;
 }
コード例 #36
0
        internal ViewgenContext(ViewTarget viewTarget, EntitySetBase extent, IEnumerable<Cell> extentCells,
                                CqlIdentifiers identifiers, ConfigViewGenerator config, MemberDomainMap queryDomainMap,
                                MemberDomainMap updateDomainMap, StorageEntityContainerMapping entityContainerMapping)
        {
            foreach (Cell cell in extentCells)
            {
                Debug.Assert(extent.Equals(cell.GetLeftQuery(viewTarget).Extent));
                Debug.Assert(cell.CQuery.NumProjectedSlots == cell.SQuery.NumProjectedSlots);
            }

            m_extent = extent;
            m_viewTarget = viewTarget;
            m_config = config;
            m_edmItemCollection = entityContainerMapping.StorageMappingItemCollection.EdmItemCollection;
            m_entityContainerMapping = entityContainerMapping;
            m_identifiers = identifiers;

            // create a copy of updateDomainMap so generation of query views later on is not affected
            // it is modified in QueryRewriter.AdjustMemberDomainsForUpdateViews
            updateDomainMap = updateDomainMap.MakeCopy();

            // Create a signature generator that handles all the
            // multiconstant work and generating the signatures
            MemberDomainMap domainMap = viewTarget == ViewTarget.QueryView ? queryDomainMap : updateDomainMap;

            m_memberMaps = new MemberMaps(viewTarget, MemberProjectionIndex.Create(extent, m_edmItemCollection), queryDomainMap, updateDomainMap);

            // Create left fragment KB: includes constraints for the extent to be constructed
            FragmentQueryKB leftKB = new FragmentQueryKB();
            leftKB.CreateVariableConstraints(extent, domainMap, m_edmItemCollection);
            m_leftFragmentQP = new FragmentQueryProcessor(leftKB);
            m_rewritingCache = new Dictionary<FragmentQuery, Tile<FragmentQuery>>(
                FragmentQuery.GetEqualityComparer(m_leftFragmentQP));

            // Now using the signatures, create new cells such that
            // "extent's" query (C or S) is described in terms of multiconstants
            if (!CreateLeftCellWrappers(extentCells, viewTarget))
            {
                return;
            }

            // Create right fragment KB: includes constraints for all extents and association roles of right queries
            FragmentQueryKB rightKB = new FragmentQueryKB();
            MemberDomainMap rightDomainMap = viewTarget == ViewTarget.QueryView ? updateDomainMap : queryDomainMap;
            foreach (LeftCellWrapper leftCellWrapper in m_cellWrappers)
            {
                EntitySetBase rightExtent = leftCellWrapper.RightExtent;
                rightKB.CreateVariableConstraints(rightExtent, rightDomainMap, m_edmItemCollection);
                rightKB.CreateAssociationConstraints(rightExtent, rightDomainMap, m_edmItemCollection);
            }
            
            if (m_viewTarget == ViewTarget.UpdateView)
            {
                CreateConstraintsForForeignKeyAssociationsAffectingThisWarapper(rightKB, rightDomainMap);
            }

            m_rightFragmentQP = new FragmentQueryProcessor(rightKB);

            // Check for concurrency control tokens
            if (m_viewTarget == ViewTarget.QueryView)
            {
                CheckConcurrencyControlTokens();
            }
            // For backward compatibility -
            // order wrappers by increasing domain size, decreasing number of attributes
            m_cellWrappers.Sort(LeftCellWrapper.Comparer);
        }
コード例 #37
0
        // effects: Given a list of cells in the schema, generates the query and
        // update mapping views for OFTYPE(Extent, Type) combinations in this schema
        // container. Returns a list of generated query and update views.
        // If it is false and some columns in a table are unmapped, an
        // exception is raised
        private static ViewGenResults GenerateViewsFromCells(
            List <Cell> cells, ConfigViewGenerator config,
            CqlIdentifiers identifiers,
            StorageEntityContainerMapping containerMapping)
        {
            DebugCheck.NotNull(cells);
            DebugCheck.NotNull(config);
            Debug.Assert(cells.Count > 0, "There must be at least one cell in the container mapping");

            // Go through each table and determine their foreign key constraints
            var container = containerMapping.StorageEntityContainer;

            Debug.Assert(container != null);

            var viewGenResults = new ViewGenResults();
            var tmpLog         = EnsureAllCSpaceContainerSetsAreMapped(cells, containerMapping);

            if (tmpLog.Count > 0)
            {
                viewGenResults.AddErrors(tmpLog);
                Helpers.StringTraceLine(viewGenResults.ErrorsToString());
                return(viewGenResults);
            }

            var foreignKeyConstraints = ForeignConstraint.GetForeignConstraints(container);

            var partitioner = new CellPartitioner(cells, foreignKeyConstraints);
            var cellGroups  = partitioner.GroupRelatedCells();

            foreach (var cellGroup in cellGroups)
            {
                ViewGenerator viewGenerator = null;
                var           groupErrorLog = new ErrorLog();
                try
                {
                    viewGenerator = new ViewGenerator(cellGroup, config, foreignKeyConstraints, containerMapping);
                }
                catch (InternalMappingException exception)
                {
                    // All exceptions have mapping errors in them
                    Debug.Assert(exception.ErrorLog.Count > 0, "Incorrectly created mapping exception");
                    groupErrorLog = exception.ErrorLog;
                }

                if (groupErrorLog.Count == 0)
                {
                    Debug.Assert(viewGenerator != null);
                    groupErrorLog = viewGenerator.GenerateAllBidirectionalViews(viewGenResults.Views, identifiers);
                }

                if (groupErrorLog.Count != 0)
                {
                    viewGenResults.AddErrors(groupErrorLog);
                }
            }
            // We used to print the errors here. Now we trace them as they are being thrown
            //if (viewGenResults.HasErrors && config.IsViewTracing) {
            //    Helpers.StringTraceLine(viewGenResults.ErrorsToString());
            //}
            return(viewGenResults);
        }
コード例 #38
0
            private static bool TryGetCorrespondingStorageEntityContainerMapping(
                EntityViewContainer viewContainer,
                IEnumerable<StorageEntityContainerMapping> storageEntityContainerMappingList,
                out StorageEntityContainerMapping storageEntityContainerMapping)
            {
                storageEntityContainerMapping = null;

                foreach (var entityContainerMapping in storageEntityContainerMappingList)
                {
                    // first check
                    if (entityContainerMapping.EdmEntityContainer.Name == viewContainer.EdmEntityContainerName
                        &&
                        entityContainerMapping.StorageEntityContainer.Name == viewContainer.StoreEntityContainerName)
                    {
                        storageEntityContainerMapping = entityContainerMapping;
                        return true;
                    }
                }
                return false;
            }
コード例 #39
0
        // Loads and registers any function mapping translators for the given extent (and related container)
        private void InitializeFunctionMappingTranslators(EntitySetBase entitySetBase, StorageEntityContainerMapping mapping)
        {
            KeyToListMap <AssociationSet, AssociationEndMember> requiredEnds = new KeyToListMap <AssociationSet, AssociationEndMember>(
                EqualityComparer <AssociationSet> .Default);

            // see if function mapping metadata needs to be processed
            if (!m_functionMappingTranslators.ContainsKey(entitySetBase))
            {
                // load all function mapping data from the current entity container
                foreach (StorageEntitySetMapping entitySetMapping in mapping.EntitySetMaps)
                {
                    if (0 < entitySetMapping.ModificationFunctionMappings.Count)
                    {
                        // register the function mapping
                        m_functionMappingTranslators.Add(entitySetMapping.Set, ModificationFunctionMappingTranslator.CreateEntitySetTranslator(entitySetMapping));

                        // register "null" function translators for all implicitly mapped association sets
                        foreach (AssociationSetEnd end in entitySetMapping.ImplicitlyMappedAssociationSetEnds)
                        {
                            AssociationSet associationSet = end.ParentAssociationSet;
                            if (!m_functionMappingTranslators.ContainsKey(associationSet))
                            {
                                m_functionMappingTranslators.Add(associationSet, ModificationFunctionMappingTranslator.CreateAssociationSetTranslator(null));
                            }

                            // Remember that the current entity set is required for all updates to the collocated
                            // relationship set. This entity set's end is opposite the target end for the mapping.
                            AssociationSetEnd oppositeEnd = MetadataHelper.GetOppositeEnd(end);
                            requiredEnds.Add(associationSet, oppositeEnd.CorrespondingAssociationEndMember);
                        }
                    }
                    else
                    {
                        // register null translator (so that we never attempt to process this extent again)
                        m_functionMappingTranslators.Add(entitySetMapping.Set, null);
                    }
                }

                foreach (StorageAssociationSetMapping associationSetMapping in mapping.RelationshipSetMaps)
                {
                    if (null != associationSetMapping.ModificationFunctionMapping)
                    {
                        AssociationSet set = (AssociationSet)associationSetMapping.Set;

                        // use indexer rather than Add since the association set may already have an implicit function
                        // mapping -- this explicit function mapping takes precedence in such cases
                        m_functionMappingTranslators.Add(set,
                                                         ModificationFunctionMappingTranslator.CreateAssociationSetTranslator(associationSetMapping));

                        // remember that we've seen a function mapping for this association set, which overrides
                        // any other behaviors for determining required/optional ends
                        requiredEnds.AddRange(set, Enumerable.Empty <AssociationEndMember>());
                    }
                    else
                    {
                        if (!m_functionMappingTranslators.ContainsKey(associationSetMapping.Set))
                        {
                            // register null translator (so that we never attempt to process this extent again)
                            m_functionMappingTranslators.Add(associationSetMapping.Set, null);
                        }
                    }
                }
            }

            // register association metadata for all association sets encountered
            foreach (AssociationSet associationSet in requiredEnds.Keys)
            {
                m_associationSetMetadata.Add(associationSet, new AssociationSetMetadata(
                                                 requiredEnds.EnumerateValues(associationSet)));
            }
        }
コード例 #40
0
        private void InitializeEntitySet(EntitySetBase entitySetBase, MetadataWorkspace workspace)
        {
            StorageEntityContainerMapping mapping = (StorageEntityContainerMapping)m_mappingCollection.GetMap(entitySetBase.EntityContainer);

            // make sure views have been generated for this sub-graph (trigger generation of the sub-graph
            // by retrieving a view for one of its components; not actually using the view here)
            if (mapping.HasViews)
            {
                m_mappingCollection.GetGeneratedView(entitySetBase, workspace);
            }

            Set <EntitySet> affectedTables = new Set <EntitySet>();


            if (null != mapping)
            {
                Set <EdmMember> isNullConditionColumns = new Set <EdmMember>();

                // find extent in the container mapping
                StorageSetMapping setMapping;
                if (entitySetBase.BuiltInTypeKind == BuiltInTypeKind.EntitySet)
                {
                    setMapping = mapping.GetEntitySetMapping(entitySetBase.Name);

                    // Check for members that have result bindings in a function mapping. If a
                    // function returns the member values, it indicates they are server-generated
                    m_serverGenProperties.Unite(GetMembersWithResultBinding((StorageEntitySetMapping)setMapping));
                }
                else if (entitySetBase.BuiltInTypeKind == BuiltInTypeKind.AssociationSet)
                {
                    setMapping = mapping.GetRelationshipSetMapping(entitySetBase.Name);
                }
                else
                {
                    Debug.Fail("unexpected extent type " + entitySetBase.BuiltInTypeKind);
                    throw EntityUtil.NotSupported();
                }

                // gather interesting tables, columns and properties from mapping fragments
                foreach (StorageMappingFragment mappingFragment in GetMappingFragments(setMapping))
                {
                    affectedTables.Add(mappingFragment.TableSet);

                    // get all property mappings to figure out if anything is server generated
                    m_serverGenProperties.AddRange(FindServerGenMembers(mappingFragment));

                    // get all columns participating in is null conditions
                    isNullConditionColumns.AddRange(FindIsNullConditionColumns(mappingFragment));
                }

                if (0 < isNullConditionColumns.Count)
                {
                    // gather is null condition properties based on is null condition columns
                    foreach (StorageMappingFragment mappingFragment in GetMappingFragments(setMapping))
                    {
                        m_isNullConditionProperties.AddRange(FindPropertiesMappedToColumns(isNullConditionColumns, mappingFragment));
                    }
                }
            }

            m_affectedTables.Add(entitySetBase, affectedTables.MakeReadOnly());

            InitializeFunctionMappingTranslators(entitySetBase, mapping);

            // for association sets, initialize AssociationSetMetadata if no function has claimed ownership
            // of the association yet
            if (entitySetBase.BuiltInTypeKind == BuiltInTypeKind.AssociationSet)
            {
                AssociationSet associationSet = (AssociationSet)entitySetBase;
                if (!m_associationSetMetadata.ContainsKey(associationSet))
                {
                    m_associationSetMetadata.Add(associationSet, new AssociationSetMetadata(
                                                     m_affectedTables[associationSet], associationSet, workspace));
                }
            }
        }
コード例 #41
0
        // effects: Given a list of cells in the schema, generates the query and
        // update mapping views for OFTYPE(Extent, Type) combinations in this schema
        // container. Returns a list of generated query and update views.
        // If it is false and some columns in a table are unmapped, an
        // exception is raised
        private static ViewGenResults GenerateViewsFromCells(List<Cell> cells, ConfigViewGenerator config,
                                                                   CqlIdentifiers identifiers,
                                                                   StorageEntityContainerMapping containerMapping)
        {
            EntityUtil.CheckArgumentNull(cells, "cells");
            EntityUtil.CheckArgumentNull(config, "config");
            Debug.Assert(cells.Count > 0, "There must be at least one cell in the container mapping");


            // Go through each table and determine their foreign key constraints
            EntityContainer container = containerMapping.StorageEntityContainer;
            Debug.Assert(container != null);

            ViewGenResults viewGenResults = new ViewGenResults();
            ErrorLog tmpLog = EnsureAllCSpaceContainerSetsAreMapped(cells, config, containerMapping);
            if (tmpLog.Count > 0)
            {
                viewGenResults.AddErrors(tmpLog);
                Helpers.StringTraceLine(viewGenResults.ErrorsToString());
                return viewGenResults;
            }

            List<ForeignConstraint> foreignKeyConstraints = ForeignConstraint.GetForeignConstraints(container);

            CellPartitioner partitioner = new CellPartitioner(cells, foreignKeyConstraints);
            List<CellGroup> cellGroups = partitioner.GroupRelatedCells();
            foreach (CellGroup cellGroup in cellGroups)
            {
                ViewGenerator viewGenerator = null;
                ErrorLog groupErrorLog = new ErrorLog();
                try
                {
                    viewGenerator = new ViewGenerator(cellGroup, config, foreignKeyConstraints, containerMapping);
                }
                catch (InternalMappingException exception)
                {
                    // All exceptions have mapping errors in them
                    Debug.Assert(exception.ErrorLog.Count > 0, "Incorrectly created mapping exception");
                    groupErrorLog = exception.ErrorLog;
                }

                if (groupErrorLog.Count == 0)
                {
                    Debug.Assert(viewGenerator != null);
                    groupErrorLog = viewGenerator.GenerateAllBidirectionalViews(viewGenResults.Views, identifiers);
                }

                if (groupErrorLog.Count != 0)
                {
                    viewGenResults.AddErrors(groupErrorLog);
                }
            }
            // We used to print the errors here. Now we trace them as they are being thrown
            //if (viewGenResults.HasErrors && config.IsViewTracing) {
            //    Helpers.StringTraceLine(viewGenResults.ErrorsToString());
            //}
            return viewGenResults;
        }
コード例 #42
0
        // effects: Given a container, ensures that all entity/association
        // sets in container on the C-side have been mapped
        private static ErrorLog EnsureAllCSpaceContainerSetsAreMapped(IEnumerable<Cell> cells,
                                                                      ConfigViewGenerator config,
                                                                      StorageEntityContainerMapping containerMapping)
        {

            Set<EntitySetBase> mappedExtents = new Set<EntitySetBase>();
            string mslFileLocation = null;
            EntityContainer container = null;
            // Determine the container and name of the file while determining
            // the set of mapped extents in the cells
            foreach (Cell cell in cells)
            {
                mappedExtents.Add(cell.CQuery.Extent);
                mslFileLocation = cell.CellLabel.SourceLocation;
                // All cells are from the same container
                container = cell.CQuery.Extent.EntityContainer;
            }
            Debug.Assert(container != null);

            List<EntitySetBase> missingExtents = new List<EntitySetBase>();
            // Go through all the extents in the container and determine
            // extents that are missing
            foreach (EntitySetBase extent in container.BaseEntitySets)
            {
                if (mappedExtents.Contains(extent) == false
                    && !(containerMapping.HasQueryViewForSetMap(extent.Name)))
                {
                    AssociationSet associationSet = extent as AssociationSet;
                    if (associationSet==null || !associationSet.ElementType.IsForeignKey)
                    {
                        missingExtents.Add(extent);
                    }
                }
            }
            ErrorLog errorLog = new ErrorLog();
            // If any extent is not mapped, add an error
            if (missingExtents.Count > 0)
            {
                StringBuilder extentBuilder = new StringBuilder();
                bool isFirst = true;
                foreach (EntitySetBase extent in missingExtents)
                {
                    if (isFirst == false)
                    {
                        extentBuilder.Append(", ");
                    }
                    isFirst = false;
                    extentBuilder.Append(extent.Name);
                }
                string message = System.Data.Entity.Strings.ViewGen_Missing_Set_Mapping(extentBuilder);
                // Find the cell with smallest line number - so that we can
                // point to the beginning of the file
                int lowestLineNum = -1;
                Cell smallestCell = null;
                foreach (Cell cell in cells)
                {
                    if (lowestLineNum == -1 || cell.CellLabel.StartLineNumber < lowestLineNum)
                    {
                        smallestCell = cell;
                        lowestLineNum = cell.CellLabel.StartLineNumber;
                    }
                }
                Debug.Assert(smallestCell != null && lowestLineNum >= 0);
                EdmSchemaError edmSchemaError = new EdmSchemaError(message, (int)ViewGenErrorCode.MissingExtentMapping,
                    EdmSchemaErrorSeverity.Error, containerMapping.SourceLocation, containerMapping.StartLineNumber,
                    containerMapping.StartLinePosition, null);
                ErrorLog.Record record = new ErrorLog.Record(edmSchemaError);
                errorLog.AddEntry(record);
            }
            return errorLog;
        }
コード例 #43
0
        // effects: Given a container, ensures that all entity/association
        // sets in container on the C-side have been mapped
        private static ErrorLog EnsureAllCSpaceContainerSetsAreMapped(
            IEnumerable <Cell> cells,
            StorageEntityContainerMapping containerMapping)
        {
            var             mappedExtents   = new Set <EntitySetBase>();
            string          mslFileLocation = null;
            EntityContainer container       = null;

            // Determine the container and name of the file while determining
            // the set of mapped extents in the cells
            foreach (var cell in cells)
            {
                mappedExtents.Add(cell.CQuery.Extent);
                mslFileLocation = cell.CellLabel.SourceLocation;
                // All cells are from the same container
                container = cell.CQuery.Extent.EntityContainer;
            }
            Debug.Assert(container != null);

            var missingExtents = new List <EntitySetBase>();

            // Go through all the extents in the container and determine
            // extents that are missing
            foreach (var extent in container.BaseEntitySets)
            {
                if (mappedExtents.Contains(extent) == false &&
                    !(containerMapping.HasQueryViewForSetMap(extent.Name)))
                {
                    var associationSet = extent as AssociationSet;
                    if (associationSet == null ||
                        !associationSet.ElementType.IsForeignKey)
                    {
                        missingExtents.Add(extent);
                    }
                }
            }
            var errorLog = new ErrorLog();

            // If any extent is not mapped, add an error
            if (missingExtents.Count > 0)
            {
                var extentBuilder = new StringBuilder();
                var isFirst       = true;
                foreach (var extent in missingExtents)
                {
                    if (isFirst == false)
                    {
                        extentBuilder.Append(", ");
                    }
                    isFirst = false;
                    extentBuilder.Append(extent.Name);
                }
                var message = Strings.ViewGen_Missing_Set_Mapping(extentBuilder);
                // Find the cell with smallest line number - so that we can
                // point to the beginning of the file
                var  lowestLineNum = -1;
                Cell smallestCell  = null;
                foreach (var cell in cells)
                {
                    if (lowestLineNum == -1 ||
                        cell.CellLabel.StartLineNumber < lowestLineNum)
                    {
                        smallestCell  = cell;
                        lowestLineNum = cell.CellLabel.StartLineNumber;
                    }
                }
                Debug.Assert(smallestCell != null && lowestLineNum >= 0);
                var edmSchemaError = new EdmSchemaError(
                    message, (int)ViewGenErrorCode.MissingExtentMapping,
                    EdmSchemaErrorSeverity.Error, containerMapping.SourceLocation, containerMapping.StartLineNumber,
                    containerMapping.StartLinePosition, null);
                var record = new ErrorLog.Record(edmSchemaError);
                errorLog.AddEntry(record);
            }
            return(errorLog);
        }
コード例 #44
0
        /// <summary>
        /// Entry point for Type specific generation of Query Views
        /// </summary>
        internal static ViewGenResults GenerateTypeSpecificQueryView(StorageEntityContainerMapping containerMapping,
                                                              ConfigViewGenerator config,
                                                              EntitySetBase entity,
                                                              EntityTypeBase type,
                                                              bool includeSubtypes,
                                                              out bool success)
        {
            EntityUtil.CheckArgumentNull(containerMapping, "containerMapping");
            EntityUtil.CheckArgumentNull(config, "config");
            EntityUtil.CheckArgumentNull(entity, "entity");
            EntityUtil.CheckArgumentNull(type, "type");
            Debug.Assert(!type.Abstract, "Can not generate OfType/OfTypeOnly query view for and abstract type");

            if (config.IsNormalTracing)
            {
                Helpers.StringTraceLine("");
                Helpers.StringTraceLine("<<<<<<<< Generating Query View for Entity [" + entity.Name + "] OfType" + (includeSubtypes ? "" : "Only") + "(" + type.Name + ") >>>>>>>");
            }

            if (containerMapping.GetEntitySetMapping(entity.Name).QueryView != null)
            {
                //Type-specific QV does not exist in the cache, but 
                // there is a EntitySet QV. So we can't generate the view (no mapping exists for this EntitySet)
                // and we rely on Query to call us again to get the EntitySet View.
                success = false;
                return null;
            }

            //Compute Cell Groups or get it from Memoizer
            InputForComputingCellGroups args = new InputForComputingCellGroups(containerMapping, config);
            OutputFromComputeCellGroups result = containerMapping.GetCellgroups(args);
            success = result.Success;

            if (!success)
            {
                return null;
            }

            List<ForeignConstraint> foreignKeyConstraints = result.ForeignKeyConstraints;
            // Get a Clone of cell groups from cache since cells are modified during viewgen, and we dont want the cached copy to change
            List<CellGroup> cellGroups = cellGroups = result.CellGroups.Select(setOfcells => new CellGroup(setOfcells.Select(cell => new Cell(cell)))).ToList();
            List<Cell> cells = result.Cells;
            CqlIdentifiers identifiers = result.Identifiers;


            ViewGenResults viewGenResults = new ViewGenResults();
            ErrorLog tmpLog = EnsureAllCSpaceContainerSetsAreMapped(cells, config, containerMapping);
            if (tmpLog.Count > 0)
            {
                viewGenResults.AddErrors(tmpLog);
                Helpers.StringTraceLine(viewGenResults.ErrorsToString());
                success = true; //atleast we tried successfully
                return viewGenResults;
            }

            foreach (CellGroup cellGroup in cellGroups)
            {
                if (!DoesCellGroupContainEntitySet(cellGroup, entity))
                {
                    continue;
                }

                ViewGenerator viewGenerator = null;
                ErrorLog groupErrorLog = new ErrorLog();
                try
                {
                    viewGenerator = new ViewGenerator(cellGroup, config, foreignKeyConstraints, containerMapping);
                }
                catch (InternalMappingException exception)
                {
                    // All exceptions have mapping errors in them
                    Debug.Assert(exception.ErrorLog.Count > 0, "Incorrectly created mapping exception");
                    groupErrorLog = exception.ErrorLog;
                }

                if (groupErrorLog.Count > 0)
                {
                    break;
                }
                Debug.Assert(viewGenerator != null); //make sure there is no exception thrown that does not add error to log

                ViewGenMode mode = includeSubtypes ? ViewGenMode.OfTypeViews : ViewGenMode.OfTypeOnlyViews;

                groupErrorLog = viewGenerator.GenerateQueryViewForSingleExtent(viewGenResults.Views, identifiers, entity, type, mode);

                if (groupErrorLog.Count != 0)
                {
                    viewGenResults.AddErrors(groupErrorLog);
                }
            }

            success = true;
            return viewGenResults;
        }
コード例 #45
0
 // effects: Creates a cell creator object for an entity container's
 // mappings (specified in "maps")
 internal CellCreator(StorageEntityContainerMapping containerMapping)
 {
     m_containerMapping = containerMapping;
     m_identifiers      = new CqlIdentifiers();
 }
コード例 #46
0
 private void SetConfiguration(StorageEntityContainerMapping entityContainerMapping)
 {
     m_config.IsValidationEnabled = entityContainerMapping.Validate;
     m_config.GenerateUpdateViews = entityContainerMapping.GenerateUpdateViews;
 }
コード例 #47
0
        internal ViewgenContext(
            ViewTarget viewTarget, EntitySetBase extent, IList <Cell> extentCells,
            CqlIdentifiers identifiers, ConfigViewGenerator config, MemberDomainMap queryDomainMap,
            MemberDomainMap updateDomainMap, StorageEntityContainerMapping entityContainerMapping)
        {
            foreach (var cell in extentCells)
            {
                Debug.Assert(extent.Equals(cell.GetLeftQuery(viewTarget).Extent));
                Debug.Assert(cell.CQuery.NumProjectedSlots == cell.SQuery.NumProjectedSlots);
            }

            m_extent                 = extent;
            m_viewTarget             = viewTarget;
            m_config                 = config;
            m_edmItemCollection      = entityContainerMapping.StorageMappingItemCollection.EdmItemCollection;
            m_entityContainerMapping = entityContainerMapping;
            m_identifiers            = identifiers;

            // create a copy of updateDomainMap so generation of query views later on is not affected
            // it is modified in QueryRewriter.AdjustMemberDomainsForUpdateViews
            updateDomainMap = updateDomainMap.MakeCopy();

            // Create a signature generator that handles all the
            // multiconstant work and generating the signatures
            var domainMap = viewTarget == ViewTarget.QueryView ? queryDomainMap : updateDomainMap;

            m_memberMaps = new MemberMaps(
                viewTarget, MemberProjectionIndex.Create(extent, m_edmItemCollection), queryDomainMap, updateDomainMap);

            // Create left fragment KB: includes constraints for the extent to be constructed
            var leftKB = new FragmentQueryKBChaseSupport();

            leftKB.CreateVariableConstraints(extent, domainMap, m_edmItemCollection);
            m_leftFragmentQP = new FragmentQueryProcessor(leftKB);
            m_rewritingCache = new Dictionary <FragmentQuery, Tile <FragmentQuery> >(
                FragmentQuery.GetEqualityComparer(m_leftFragmentQP));

            // Now using the signatures, create new cells such that
            // "extent's" query (C or S) is described in terms of multiconstants
            if (!CreateLeftCellWrappers(extentCells, viewTarget))
            {
                return;
            }

            // Create right fragment KB: includes constraints for all extents and association roles of right queries
            var rightKB        = new FragmentQueryKBChaseSupport();
            var rightDomainMap = viewTarget == ViewTarget.QueryView ? updateDomainMap : queryDomainMap;

            foreach (var leftCellWrapper in m_cellWrappers)
            {
                var rightExtent = leftCellWrapper.RightExtent;
                rightKB.CreateVariableConstraints(rightExtent, rightDomainMap, m_edmItemCollection);
                rightKB.CreateAssociationConstraints(rightExtent, rightDomainMap, m_edmItemCollection);
            }

            if (m_viewTarget == ViewTarget.UpdateView)
            {
                CreateConstraintsForForeignKeyAssociationsAffectingThisWrapper(rightKB, rightDomainMap);
            }

            m_rightFragmentQP = new FragmentQueryProcessor(rightKB);

            // Check for concurrency control tokens
            if (m_viewTarget == ViewTarget.QueryView)
            {
                CheckConcurrencyControlTokens();
            }
            // For backward compatibility -
            // order wrappers by increasing domain size, decreasing number of attributes
            m_cellWrappers.Sort(LeftCellWrapper.Comparer);
        }
コード例 #48
0
        /// <summary>
        ///     Entry point for Type specific generation of Query Views
        /// </summary>
        internal static ViewGenResults GenerateTypeSpecificQueryView(
            StorageEntityContainerMapping containerMapping,
            ConfigViewGenerator config,
            EntitySetBase entity,
            EntityTypeBase type,
            bool includeSubtypes,
            out bool success)
        {
            DebugCheck.NotNull(containerMapping);
            DebugCheck.NotNull(config);
            DebugCheck.NotNull(entity);
            DebugCheck.NotNull(type);
            Debug.Assert(!type.Abstract, "Can not generate OfType/OfTypeOnly query view for and abstract type");

            if (config.IsNormalTracing)
            {
                Helpers.StringTraceLine("");
                Helpers.StringTraceLine(
                    "<<<<<<<< Generating Query View for Entity [" + entity.Name + "] OfType" + (includeSubtypes ? "" : "Only") + "("
                    + type.Name + ") >>>>>>>");
            }

            if (containerMapping.GetEntitySetMapping(entity.Name).QueryView != null)
            {
                //Type-specific QV does not exist in the cache, but
                // there is a EntitySet QV. So we can't generate the view (no mapping exists for this EntitySet)
                // and we rely on Query to call us again to get the EntitySet View.
                success = false;
                return(null);
            }

            //Compute Cell Groups or get it from Memoizer
            var args   = new InputForComputingCellGroups(containerMapping, config);
            var result = containerMapping.GetCellgroups(args);

            success = result.Success;

            if (!success)
            {
                return(null);
            }

            var foreignKeyConstraints = result.ForeignKeyConstraints;
            // Get a Clone of cell groups from cache since cells are modified during viewgen, and we dont want the cached copy to change
            var cellGroups  = result.CellGroups.Select(setOfcells => new CellGroup(setOfcells.Select(cell => new Cell(cell)))).ToList();
            var cells       = result.Cells;
            var identifiers = result.Identifiers;

            var viewGenResults = new ViewGenResults();
            var tmpLog         = EnsureAllCSpaceContainerSetsAreMapped(cells, containerMapping);

            if (tmpLog.Count > 0)
            {
                viewGenResults.AddErrors(tmpLog);
                Helpers.StringTraceLine(viewGenResults.ErrorsToString());
                success = true; //atleast we tried successfully
                return(viewGenResults);
            }

            foreach (var cellGroup in cellGroups)
            {
                if (!DoesCellGroupContainEntitySet(cellGroup, entity))
                {
                    continue;
                }

                ViewGenerator viewGenerator = null;
                var           groupErrorLog = new ErrorLog();
                try
                {
                    viewGenerator = new ViewGenerator(cellGroup, config, foreignKeyConstraints, containerMapping);
                }
                catch (InternalMappingException exception)
                {
                    // All exceptions have mapping errors in them
                    Debug.Assert(exception.ErrorLog.Count > 0, "Incorrectly created mapping exception");
                    groupErrorLog = exception.ErrorLog;
                }

                if (groupErrorLog.Count > 0)
                {
                    break;
                }
                Debug.Assert(viewGenerator != null); //make sure there is no exception thrown that does not add error to log

                var mode = includeSubtypes ? ViewGenMode.OfTypeViews : ViewGenMode.OfTypeOnlyViews;

                groupErrorLog = viewGenerator.GenerateQueryViewForSingleExtent(viewGenResults.Views, identifiers, entity, type, mode);

                if (groupErrorLog.Count != 0)
                {
                    viewGenResults.AddErrors(groupErrorLog);
                }
            }

            success = true;
            return(viewGenResults);
        }
コード例 #49
0
 /// <summary>
 ///     Construct a new AssociationSetMapping object
 /// </summary>
 /// <param name="extent"> Represents the Association Set Metadata object. Will change this to Extent instead of MemberMetadata. </param>
 /// <param name="entityContainerMapping"> The entityContainerMapping mapping that contains this Set mapping </param>
 public StorageAssociationSetMapping(AssociationSet extent, StorageEntityContainerMapping entityContainerMapping)
     : base(extent, entityContainerMapping)
 {
 }
コード例 #50
0
        public void AddEntityContainerMapping(StorageEntityContainerMapping entityContainerMapping)
        {
            Check.NotNull(entityContainerMapping, "entityContainerMapping");

            _entityContainerMappings.Add(entityContainerMapping);
        }
コード例 #51
0
 // effects: Creates a cell creator object for an entity container's
 // mappings (specified in "maps")
 internal CellCreator(StorageEntityContainerMapping containerMapping)
 {
     m_containerMapping = containerMapping;
     m_identifiers = new CqlIdentifiers();
 }
コード例 #52
0
        public void WriteEntityContainerMappingElement_should_write_function_import_elements()
        {
            var typeUsage =
                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32));

            var complexTypeProperty1 = new EdmProperty("CTProperty1", typeUsage);
            var complexTypeProperty2 = new EdmProperty("CTProperty2", typeUsage);

            var complexType = new ComplexType("CT", "Ns", DataSpace.CSpace);

            complexType.AddMember(complexTypeProperty1);
            complexType.AddMember(complexTypeProperty2);

            var functionImport =
                new EdmFunction(
                    "f_c", "Ns", DataSpace.CSpace,
                    new EdmFunctionPayload
            {
                IsComposable     = true,
                IsFunctionImport = true,
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "ReturnValue",
                        TypeUsage.CreateDefaultTypeUsage(complexType.GetCollectionType()),
                        ParameterMode.ReturnValue)
                },
                Parameters =
                    new[]
                {
                    new FunctionParameter("param", typeUsage, ParameterMode.Out)
                }
            });

            var rowTypeProperty1 = new EdmProperty("RTProperty1", typeUsage);
            var rowTypeProperty2 = new EdmProperty("RTProperty2", typeUsage);
            var rowType          = new RowType(new[] { rowTypeProperty1, rowTypeProperty2 });

            var storeFunction =
                new EdmFunction(
                    "f_s", "Ns.Store", DataSpace.SSpace,
                    new EdmFunctionPayload
            {
                ReturnParameters =
                    new[]
                {
                    new FunctionParameter(
                        "Return",
                        TypeUsage.CreateDefaultTypeUsage(rowType),
                        ParameterMode.ReturnValue)
                },
                Parameters =
                    new[]
                {
                    new FunctionParameter("param", typeUsage, ParameterMode.Out)
                }
            });

            var structuralTypeMapping =
                new Tuple <StructuralType, List <StorageConditionPropertyMapping>, List <StoragePropertyMapping> >(
                    complexType, new List <StorageConditionPropertyMapping>(), new List <StoragePropertyMapping>());

            structuralTypeMapping.Item3.Add(new StorageScalarPropertyMapping(complexTypeProperty1, rowTypeProperty1));
            structuralTypeMapping.Item3.Add(new StorageScalarPropertyMapping(complexTypeProperty2, rowTypeProperty2));

            var functionImportMapping = new FunctionImportMappingComposable(
                functionImport,
                storeFunction,
                new List <Tuple <StructuralType, List <StorageConditionPropertyMapping>, List <StoragePropertyMapping> > >
            {
                structuralTypeMapping
            });

            var containerMapping = new StorageEntityContainerMapping(new EntityContainer("C", DataSpace.SSpace));

            containerMapping.AddFunctionImportMapping(functionImportMapping);

            var fixture = new Fixture();

            fixture.Writer.WriteEntityContainerMappingElement(containerMapping);

            Assert.Equal(
                @"<EntityContainerMapping StorageEntityContainer="""" CdmEntityContainer=""C"">
  <FunctionImportMapping FunctionName=""Ns.Store.f_s"" FunctionImportName=""f_c"">
    <ResultMapping>
      <ComplexTypeMapping TypeName=""Ns.CT"">
        <ScalarProperty Name=""CTProperty1"" ColumnName=""RTProperty1"" />
        <ScalarProperty Name=""CTProperty2"" ColumnName=""RTProperty2"" />
      </ComplexTypeMapping>
    </ResultMapping>
  </FunctionImportMapping>
</EntityContainerMapping>",
                fixture.ToString());
        }
コード例 #53
0
ファイル: ViewGenerator.cs プロジェクト: uQr/referencesource
        private ErrorLog GenerateQueryViewForExtentAndType(StorageEntityContainerMapping entityContainerMapping, CqlIdentifiers identifiers, ViewSet views, EntitySetBase entity, EntityTypeBase type, ViewGenMode mode)
        {
            Debug.Assert(mode != ViewGenMode.GenerateAllViews);

            // Keep track of the mapping exceptions that we have generated
            ErrorLog errorLog = new ErrorLog();

            if (m_config.IsViewTracing)
            {
                Helpers.StringTraceLine(String.Empty);
                Helpers.StringTraceLine(String.Empty);
                Helpers.FormatTraceLine("================= Generating {0} Query View for: {1} ===========================",
                                    (mode == ViewGenMode.OfTypeViews) ? "OfType" : "OfTypeOnly",
                                    entity.Name);
                Helpers.StringTraceLine(String.Empty);
                Helpers.StringTraceLine(String.Empty);
            }

            try
            {
                // (1) view generation (checks that extents are fully mapped)
                ViewgenContext context = CreateViewgenContext(entity, ViewTarget.QueryView, identifiers);
                QueryRewriter queryRewriter = GenerateViewsForExtentAndType(type, context, identifiers, views, mode);
            }
            catch (InternalMappingException exception)
            {
                // All exceptions have mapping errors in them
                Debug.Assert(exception.ErrorLog.Count > 0, "Incorrectly created mapping exception");
                errorLog.Merge(exception.ErrorLog);
            }

            return errorLog;
        }
コード例 #54
0
 private static bool HasQueryView(StorageEntityContainerMapping storageEntityContainerMapping)
 {
     foreach (EntitySetBase extent in storageEntityContainerMapping.EdmEntityContainer.BaseEntitySets)
     {
         if (storageEntityContainerMapping.HasQueryViewForSetMap(extent.Name))
         {
             return true;
         }
     }
     return false;
 }
コード例 #55
0
 /// <summary>
 /// Creates a concrete DbMappingViewCache corresponding to the specified container mapping.
 /// </summary>
 /// <param name="mapping">A mapping between a container in the conceptual model and a container in
 /// the store model.</param>
 /// <returns>A concrete DbMappingViewCache, or null if a creator was not found.</returns>
 internal DbMappingViewCache Create(StorageEntityContainerMapping mapping)
 {
     return(Create(mapping.EdmEntityContainer.Name, mapping.StorageEntityContainer.Name));
 }