public static int ExtractTypeId(TypeInfo type, TypeIdRegistry typeIdRegistry, Tuple tuple, int typeIdIndex, out TypeReferenceAccuracy accuracy)
        {
            accuracy = TypeReferenceAccuracy.Hierarchy;
            if (type.IsInterface)
            {
                accuracy = TypeReferenceAccuracy.BaseType;
            }

            if (typeIdIndex < 0)
            {
                if (type.IsLeaf)
                {
                    accuracy = TypeReferenceAccuracy.ExactType;
                }
                return(typeIdRegistry.GetTypeId(type));
            }

            accuracy = TypeReferenceAccuracy.ExactType;
            TupleFieldState state;
            var             value = tuple.GetValue <int>(typeIdIndex, out state);

            if (type.IsLeaf)
            {
                return(state.HasValue() ? typeIdRegistry.GetTypeId(type) : TypeInfo.NoTypeId);
            }
            // Hack here: 0 (default) = TypeInfo.NoTypeId
            return(value);
        }
        public void BuildTypeIds(TypeIdRegistry registry)
        {
            // Import static type identifiers.
            // Static types are system types, which don't change their type identifiers.
            // User types are not static by default.
            foreach (var type in GetTypesWithStaticTypeIds())
            {
                registry.Register(type.TypeId, type);
            }

            // Load old type identifiers from database
            foreach (var type in GetTypesWithoutTypeId(registry))
            {
                var typeId = typeIdProvider.GetTypeId(type.UnderlyingType);
                if (typeId != TypeInfo.NoTypeId)
                {
                    registry.Register(typeId, type);
                }
            }

            // Generate type identifiers for remaining types
            var typeGroups = GetTypesWithoutTypeId(registry)
                             .GroupBy(t => t.MappingDatabase ?? string.Empty)
                             .OrderBy(g => g.Key);

            foreach (var group in typeGroups)
            {
                var sequence = GetTypeIdSequence(registry, group.Key);
                foreach (var type in group.OrderBy(i => i.Name))
                {
                    registry.Register(sequence.GetNextValue(), type);
                }
            }
        }
        public static Tuple DeserializeKeyFields(TypeInfo entityType, TypeIdRegistry registry, SerializationInfo info, StreamingContext context)
        {
            var keyTuple = Tuple.Create(entityType.Hierarchy.Key.TupleDescriptor);

            foreach (FieldInfo keyField in entityType.Fields.Where(f => f.IsPrimaryKey && f.Parent == null))
            {
                if (keyField.IsTypeId)
                {
                    keyTuple.SetValue(keyField.MappingInfo.Offset, registry[entityType]);
                }
                else
                {
                    var value = info.GetValue(keyField.Name, keyField.ValueType);
                    if (keyField.IsEntity)
                    {
                        var referencedEntity = (Entity)value;
                        if (!IsInitialized(referencedEntity))
                        {
                            DeserializationContext.Demand().InitializeEntity(referencedEntity);
                        }
                        var referencedTuple = referencedEntity.Key.Value;
                        referencedTuple.CopyTo(keyTuple, keyField.MappingInfo.Offset);
                    }
                    else
                    {
                        keyTuple.SetValue(keyField.MappingInfo.Offset, value);
                    }
                }
            }
            return(keyTuple);
        }
 public void SetDefaultTypeIds(TypeIdRegistry registry)
 {
     foreach (var type in GetTypesWithoutTypeId())
     {
         type.TypeId = registry[type];
     }
     domain.Model.Types.TypeIdRegistry = registry;
 }
        // ReSharper restore UnusedMember.Global


        // Constructors

        public ItemMaterializationContext(MaterializationContext materializationContext, Session session)
        {
            MaterializationContext = materializationContext;
            Session = session;

            typeIdRegistry = session.StorageNode.TypeIdRegistry;
            entities       = new Entity[materializationContext.EntitiesInRow];
        }
        // ReSharper restore UnusedMember.Global


        // Constructors

        public ItemMaterializationContext(MaterializationContext materializationContext, ParameterContext parameterContext)
        {
            ParameterContext       = parameterContext;
            MaterializationContext = materializationContext;
            Session = materializationContext.Session;

            typeIdRegistry = Session.StorageNode.TypeIdRegistry;
            entities       = new Entity[materializationContext.EntitiesInRow];
        }
        private TypeIdSequence GetTypeIdSequence(TypeIdRegistry registry, int minTypeId, int maxTypeId, string mappingDatabase)
        {
            var current = registry.TypeIdentifiers
                          .Where(id => id >= minTypeId && id <= maxTypeId)
                          .DefaultIfEmpty(minTypeId - 1)
                          .Max();

            return(new TypeIdSequence(current, minTypeId, maxTypeId, mappingDatabase));
        }
        private TypeIdSequence GetTypeIdSequence(TypeIdRegistry registry, string mappingDatabase)
        {
            if (domain.Model.Databases.Count == 0)
            {
                // Multidatabase mode is not enabled, use default range
                return(GetTypeIdSequence(registry, TypeInfo.MinTypeId, int.MaxValue, Strings.NA));
            }

            // Query configuration for a particular database
            var configurationEntry = domain.Model.Databases[mappingDatabase].Configuration;

            return(GetTypeIdSequence(registry,
                                     configurationEntry.MinTypeId, configurationEntry.MaxTypeId, configurationEntry.Name));
        }
        // Constructors

        internal StorageNode(NodeConfiguration configuration, ModelMapping mapping, TypeIdRegistry typeIdRegistry)
        {
            ArgumentValidator.EnsureArgumentNotNull(configuration, "configuration");
            ArgumentValidator.EnsureArgumentNotNull(mapping, "mapping");
            ArgumentValidator.EnsureArgumentNotNull(typeIdRegistry, "typeIdRegistry");

            Configuration  = configuration;
            Mapping        = mapping;
            TypeIdRegistry = typeIdRegistry;

            KeySequencesCache   = new ConcurrentDictionary <SequenceInfo, object>();
            PersistRequestCache = new ConcurrentDictionary <PersistRequestBuilderTask, ICollection <PersistRequest> >();
            InternalQueryCache  = new ConcurrentDictionary <object, object>();
        }
        public StoredDomainModel Convert(DomainModel model, TypeIdRegistry typeIdRegistry, Func <TypeInfo, bool> filter)
        {
            processedAssociations = new HashSet <string>();
            var typesToProcess = model.Types.AsEnumerable();

            if (filter != null)
            {
                typesToProcess = typesToProcess.Where(filter);
            }
            registry = typeIdRegistry;
            var processedTypes = typesToProcess.Select(ConvertType).ToArray();

            return(new StoredDomainModel {
                Types = processedTypes
            });
        }
        private Dictionary <string, MetadataSet> BuildMetadata(Domain domain, TypeIdRegistry registry)
        {
            var model          = domain.Model;
            var metadataGroups = model.Databases.ToDictionary(db => db.Name, db => new MetadataSet());

            if (metadataGroups.Count == 0)
            {
                metadataGroups.Add(string.Empty, new MetadataSet());
            }

            foreach (var group in metadataGroups)
            {
                var database = group.Key;
                var metadata = group.Value;
                Func <TypeInfo, bool> filter = t => t.MappingDatabase == database;
                var types            = model.Types.Where(filter).ToList();
                var typeMetadata     = GetTypeMetadata(types, registry);
                var assemblies       = types.Select(t => t.UnderlyingType.Assembly).ToHashSet();
                var assemblyMetadata = GetAssemblyMetadata(assemblies);
                var storedModel      = model.ToStoredModel(registry, filter);
                // Since we support storage nodes, stored domain model and real model of a node
                // must be synchronized. So we must update types' mappings
                storedModel.UpdateMappings(UpgradeContext.NodeConfiguration);
                var serializedModel  = storedModel.Serialize();
                var modelExtension   = new ExtensionMetadata(WellKnown.DomainModelExtensionName, serializedModel);
                var indexesExtension = GetPartialIndexes(domain, types);
                metadata.Assemblies.AddRange(assemblyMetadata);
                metadata.Types.AddRange(typeMetadata);
                metadata.Extensions.Add(modelExtension);
                if (indexesExtension != null)
                {
                    metadata.Extensions.Add(indexesExtension);
                }
            }

            return(metadataGroups);
        }
 private IEnumerable <TypeInfo> GetTypesWithoutTypeId(TypeIdRegistry registry)
 {
     return(domain.Model.Types.Where(t => t.IsEntity && !registry.Contains(t)));
 }
 private void SaveFullTypeMap(TypeIdRegistry registry)
 {
     UpgradeContext.FullTypeMap = registry.Types.ToDictionary(t => t.UnderlyingType.GetFullName(), t => registry[t]);
 }
 private static IEnumerable <TypeMetadata> GetTypeMetadata(IEnumerable <TypeInfo> types, TypeIdRegistry registry)
 {
     return(types
            .Where(t => t.IsEntity && registry.Contains(t))
            .Select(type => new TypeMetadata(registry[type], type.UnderlyingType.GetFullName())));
 }