sharp-oodb/descriptor/Descriptor.cs

125 lines
4.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Reflection;
using oodb.mapping;
using System.Linq.Expressions;
using sharp.logging;
using oodb.attributes;
using oodb.index;
namespace oodb.descriptor
{
public class Descriptor
{
public OODB OODB { get; }
public Type NativeType { get; }
public Descriptor BaseDescriptor { get; }
public IEnumerable<KeyValuePair<FieldInfo, FlatTypeMapping>> FlatMappings => flatMappings;
Dictionary<FieldInfo, FlatTypeMapping> flatMappings = new Dictionary<FieldInfo, FlatTypeMapping>();
Dictionary<FieldInfo, ExtendedFieldHandling> extendedFieldHandlers = new Dictionary<FieldInfo, ExtendedFieldHandling>();
public Descriptor(OODB oodb,Type type)
{
OODB = oodb;
NativeType = type;
OODB.descriptors.Add(NativeType, this);
OODB.flatTypeMappings[type] = new ReferenceMapping(oodb, type);
if (type.BaseType != typeof(Persistent))
{
BaseDescriptor = OODB.GetDescriptor(type.BaseType);
}
ConstructMappings();
}
public void Initialize()
{
foreach (ExtendedFieldHandling extendedFieldHandling in extendedFieldHandlers.Values)
{
extendedFieldHandling.Initialize();
}
}
public void Attach(Persistent persistent)
{
foreach (ExtendedFieldHandling extendedFieldHandling in extendedFieldHandlers.Values)
{
extendedFieldHandling.Attach(persistent);
}
}
public void Detach(Persistent persistent)
{
foreach (ExtendedFieldHandling extendedFieldHandling in extendedFieldHandlers.Values)
{
extendedFieldHandling.Detach(persistent);
}
}
public FieldInfo GetFieldInfo(string fieldName)
{
foreach (FieldInfo fieldInfo in flatMappings.Keys)
if (fieldInfo.Name.Equals(fieldName))
return fieldInfo;
throw new KeyNotFoundException();
}
public FlatTypeMapping GetFlatTypeMapping(FieldInfo fieldInfo)
{
return flatMappings[fieldInfo];
}
private void ConstructMappings()
{
if (BaseDescriptor != null)
{
foreach (FieldInfo baseField in BaseDescriptor.flatMappings.Keys)
{
flatMappings.Add(baseField, BaseDescriptor.flatMappings[baseField]);
}
foreach (FieldInfo baseField in BaseDescriptor.extendedFieldHandlers.Keys)
{
extendedFieldHandlers.Add(baseField, BaseDescriptor.extendedFieldHandlers[baseField]);
}
}
foreach (FieldInfo fieldInfo in NativeType.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic))
{
if (fieldInfo.GetCustomAttribute<IndexedAttribute>() != null)
{
OODB.StorageAdapter.GetSearchIndex(fieldInfo);
}
try
{
FlatTypeMapping flatTypeMapping = OODB.GetFlatTypeMapping(fieldInfo.FieldType);
flatMappings.Add(fieldInfo, flatTypeMapping);
if (fieldInfo.GetCustomAttribute<UniqueAttribute>() != null)
{
Unique uniqueIndex = new Unique(OODB, fieldInfo);
}
} catch (KeyNotFoundException)
{
try {
ExtendedFieldHandling extendedFieldHandling = OODB.CreateExtendedFieldHandling(fieldInfo);
extendedFieldHandlers.Add(fieldInfo, extendedFieldHandling);
} catch (NotSupportedException)
{
Logger.Default.Log("Ignoring unsupported Field {0}", fieldInfo);
}
}
}
}
}
}