DatabaseSchema.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.Immutable;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Linq;
  7. using System.Linq.Expressions;
  8. using System.Reflection;
  9. namespace InABox.Core
  10. {
  11. public static class DatabaseSchema
  12. {
  13. // {className: {propertyName: property}}
  14. private static ConcurrentDictionary<Type, ImmutableSortedDictionary<string, IProperty>> _properties
  15. = new ConcurrentDictionary<Type, ImmutableSortedDictionary<string, IProperty>>();
  16. private struct SubObject
  17. {
  18. public Type PropertyType { get; set; }
  19. public string Name { get; set; }
  20. public Action<object, object> Setter { get; set; }
  21. public Func<object, object> Getter { get; set; }
  22. public SubObject(Type objectType, Type propertyType, string name)
  23. {
  24. PropertyType = propertyType;
  25. Name = name;
  26. Setter = Expressions.Setter(objectType, name);
  27. Getter = Expressions.Getter(objectType, name);
  28. }
  29. }
  30. private static ConcurrentDictionary<Type, ImmutableList<SubObject>> _subObjects { get; } = new ConcurrentDictionary<Type, ImmutableList<SubObject>>();
  31. private static IReadOnlyCollection<SubObject>? GetSubObjectDefs(Type t)
  32. {
  33. CheckPropertiesInternal(t);
  34. return _subObjects.GetValueOrDefault(t);
  35. }
  36. public static IEnumerable<BaseObject> GetSubObjects(BaseObject obj)
  37. {
  38. var objs = GetSubObjectDefs(obj.GetType());
  39. if(objs is null)
  40. {
  41. yield break;
  42. }
  43. foreach (var subObjectDef in objs)
  44. {
  45. var subObj = subObjectDef.Getter(obj);
  46. if(subObj is BaseObject bObj)
  47. {
  48. yield return bObj;
  49. }
  50. }
  51. }
  52. public static void InitializeSubObjects(BaseObject obj)
  53. {
  54. var objs = GetSubObjectDefs(obj.GetType());
  55. if(objs is null)
  56. {
  57. return;
  58. }
  59. foreach (var subObjectDef in objs)
  60. {
  61. var subObj = (Activator.CreateInstance(subObjectDef.PropertyType) as ISubObject)!;
  62. subObjectDef.Setter(obj, subObj);
  63. subObj.SetLinkedParent(obj);
  64. subObj.SetLinkedPath(subObjectDef.Name);
  65. }
  66. }
  67. // For synchronisation purposes, we register sub objects in bulk, removing the need for nested concurrent dictionaries.
  68. private static void RegisterSubObjects(Type objectType, IEnumerable<Tuple<Type, string>> objects)
  69. {
  70. if (!_subObjects.TryGetValue(objectType, out var subObjects))
  71. {
  72. subObjects = ImmutableList<SubObject>.Empty;
  73. }
  74. // No synchronisation issues, since the original collection is not being modified, just the entry in the concurrent dictionary is updated.
  75. _subObjects[objectType] = subObjects.AddRange(
  76. objects.Where(x => !subObjects.Any(y => x.Item1 == y.PropertyType && x.Item2 == y.Name))
  77. .Select(x => new SubObject(objectType, x.Item1, x.Item2)));
  78. }
  79. public static void Clear()
  80. {
  81. _properties = new ConcurrentDictionary<Type, ImmutableSortedDictionary<string, IProperty>>();
  82. }
  83. /// <summary>
  84. /// Gets the editor for the specified property. If the property has a <see cref="BaseEditor"/> defined, then returns that.<br/>
  85. /// Otherwise, gets a default for the property type. (<see cref="GetEditor(Type)"/>), which can be <see langword="null"/>.
  86. /// </summary>
  87. /// <param name="prop"></param>
  88. /// <returns></returns>
  89. private static BaseEditor? GetEditor(PropertyInfo prop)
  90. {
  91. var attribute = prop.GetCustomAttributes<BaseEditor>(true).FirstOrDefault();
  92. var editor = attribute ?? EditorUtils.GetEditor(prop.PropertyType);
  93. if (editor != null && !prop.CanWrite && !prop.PropertyType.HasInterface<ISubObject>())
  94. {
  95. editor = editor.CloneEditor();
  96. editor.Editable = editor.Editable.Combine(Editable.Disabled);
  97. }
  98. return editor;
  99. }
  100. private static void RegisterProperties(Type master, Type type, string prefix, StandardProperty? parent, Dictionary<string, IProperty> newProperties)
  101. {
  102. try
  103. {
  104. var properties = CoreUtils.PropertyList(
  105. type,
  106. x => !x.PropertyType.IsInterface && x.DeclaringType != typeof(BaseObject)
  107. );
  108. var subObjects = new List<Tuple<Type, string>>();
  109. foreach (var prop in properties)
  110. {
  111. var name = prefix + prop.Name;
  112. if (newProperties.ContainsKey(name)) continue;
  113. var getMethod = prop.GetGetMethod();
  114. if (getMethod is null || !getMethod.IsPublic || getMethod.IsStatic) continue;
  115. BaseEditor? editor;
  116. if (parent != null && parent.HasEditor && parent.Editor is NullEditor)
  117. {
  118. editor = parent.Editor;
  119. }
  120. else
  121. {
  122. editor = GetEditor(prop);
  123. }
  124. var captionAttr = prop.GetCustomAttribute<Caption>();
  125. var subCaption = captionAttr != null ? captionAttr.Text : prop.Name;
  126. var path = captionAttr == null || captionAttr.IncludePath; // If no caption attribute, we should always include the path
  127. var caption = parent?.Caption ?? string.Empty; // We default to the parent caption if subCaption doesn't exist
  128. if (!string.IsNullOrWhiteSpace(subCaption))
  129. {
  130. if (!string.IsNullOrWhiteSpace(caption) && path)
  131. {
  132. caption = $"{caption} {subCaption}";
  133. }
  134. else
  135. {
  136. caption = subCaption;
  137. }
  138. }
  139. // Once the parent page has been found, this property is cemented to that page - it cannot change page to its parent
  140. var page = parent?.Page;
  141. var sequence = parent?.Sequence;
  142. var sequenceAttribute = prop.GetCustomAttribute<EditorSequence>();
  143. if (sequenceAttribute != null)
  144. {
  145. if (string.IsNullOrWhiteSpace(page))
  146. {
  147. page = sequenceAttribute.Page;
  148. }
  149. sequence = sequenceAttribute.Sequence;
  150. }
  151. editor = editor?.Clone() as BaseEditor;
  152. if (editor != null)
  153. {
  154. editor.Page = page;
  155. editor.Caption = caption;
  156. editor.EditorSequence = (int)(sequence ?? 999);
  157. editor.Security = prop.GetCustomAttributes<SecurityAttribute>().ToArray();
  158. }
  159. var comment = prop.GetCustomAttribute<CommentAttribute>()?.Comment;
  160. if(editor != null && editor.ToolTip.IsNullOrWhiteSpace() && !comment.IsNullOrWhiteSpace())
  161. {
  162. editor.ToolTip = comment;
  163. }
  164. bool required = false;
  165. if (parent == null || parent.Required)
  166. {
  167. required = prop.GetCustomAttribute<RequiredColumnAttribute>() != null;
  168. }
  169. LoggablePropertyAttribute? loggable = null;
  170. if (parent == null || parent.Loggable != null)
  171. {
  172. loggable = prop.GetCustomAttribute<LoggablePropertyAttribute>();
  173. }
  174. var newProperty = new StandardProperty
  175. {
  176. _class = master,
  177. Name = name,
  178. PropertyType = prop.PropertyType,
  179. Editor = editor ?? new NullEditor(),
  180. HasEditor = editor != null,
  181. Caption = caption,
  182. Sequence = sequence ?? 999,
  183. Page = page ?? string.Empty,
  184. Required = required,
  185. Loggable = loggable,
  186. Parent = parent,
  187. Property = prop,
  188. Comment = comment ?? ""
  189. };
  190. var parentWithEditable = newProperty.GetOuterParent(x =>
  191. x is StandardProperty st
  192. && st.Property.GetCustomAttribute<EditableAttribute>() != null);
  193. if(parentWithEditable != null)
  194. {
  195. var attr = (parentWithEditable as StandardProperty)!.Property.GetCustomAttribute<EditableAttribute>()!;
  196. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  197. }
  198. else if(prop.GetCustomAttribute<EditableAttribute>() is EditableAttribute attr)
  199. {
  200. newProperty.Editor.Editable = newProperty.Editor.Editable.Combine(attr.Editable);
  201. }
  202. var isLink = prop.PropertyType.HasInterface<IEntityLink>();
  203. var isEnclosedEntity = prop.PropertyType.HasInterface<IEnclosedEntity>();
  204. var isBaseEditor = prop.PropertyType.HasInterface<IBaseEditor>();
  205. if ((isLink || isEnclosedEntity) && !isBaseEditor)
  206. {
  207. subObjects.Add(new Tuple<Type, string>(prop.PropertyType, prop.Name));
  208. }
  209. if (isLink || isEnclosedEntity || isBaseEditor)
  210. {
  211. RegisterProperties(master, prop.PropertyType, name + ".", newProperty, newProperties);
  212. }
  213. newProperties.Add(newProperty.Name, newProperty);
  214. }
  215. RegisterSubObjects(type, subObjects);
  216. // I don't actually think we need this, since PropertyList gives us properties of our parent.
  217. //if (type.IsSubclassOf(typeof(BaseObject)) && type.BaseType != typeof(BaseObject))
  218. // RegisterProperties(master, type.BaseType, prefix, parent, newProperties);
  219. }
  220. catch (Exception e)
  221. {
  222. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  223. }
  224. }
  225. private static void RegisterProperties(Type type)
  226. {
  227. var properties = new Dictionary<string, IProperty>();
  228. RegisterProperties(type, type, "", null, properties);
  229. if(properties.Count > 0)
  230. {
  231. RegisterProperties(type, properties.Values);
  232. }
  233. }
  234. public static object? DefaultValue(Type type)
  235. {
  236. if (type.IsValueType)
  237. return Activator.CreateInstance(type);
  238. if (type.Equals(typeof(string)))
  239. return "";
  240. return null;
  241. }
  242. private static readonly object _updatelock = new object();
  243. private static void RegisterProperties(Type master, IEnumerable<IProperty> toAdd)
  244. {
  245. if (!_properties.TryGetValue(master, out var properties))
  246. {
  247. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  248. }
  249. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  250. foreach(var prop in toAdd)
  251. {
  252. newDict[prop.Name] = prop;
  253. }
  254. _properties[master] = newDict.ToImmutableSortedDictionary();
  255. }
  256. private static void UnregisterProperties(Type master, IEnumerable<IProperty> toRemove)
  257. {
  258. if (!_properties.TryGetValue(master, out var properties))
  259. {
  260. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  261. }
  262. var newDict = properties.ToDictionary(x => x.Key, x => x.Value);
  263. foreach(var prop in toRemove)
  264. {
  265. newDict.Remove(prop.Name);
  266. }
  267. _properties[master] = newDict.ToImmutableSortedDictionary();
  268. }
  269. public static void RegisterProperty(IProperty entry)
  270. {
  271. var type = entry.ClassType;
  272. if (type is null) return;
  273. if (!_properties.TryGetValue(type, out var properties))
  274. {
  275. properties = ImmutableSortedDictionary<string, IProperty>.Empty;
  276. }
  277. _properties[type] = properties.Add(entry.Name, entry);
  278. }
  279. public static void Load(CustomProperty[] customproperties)
  280. {
  281. var perType = customproperties.GroupBy(x => x.ClassType);
  282. foreach(var group in perType)
  283. {
  284. if (group.Key is null) continue;
  285. RegisterProperties(group.Key, group);
  286. }
  287. }
  288. public static void Unload(CustomProperty[] customProperties)
  289. {
  290. var perType = customProperties.GroupBy(x => x.ClassType);
  291. foreach(var group in perType)
  292. {
  293. if (group.Key is null) continue;
  294. UnregisterProperties(group.Key, group);
  295. }
  296. }
  297. private static ImmutableSortedDictionary<string, IProperty>? CheckPropertiesInternal(Type type)
  298. {
  299. try
  300. {
  301. var props = _properties.GetValueOrDefault(type);
  302. var hasprops = props?.Any(x => x.Value is StandardProperty) == true;
  303. if (!hasprops)
  304. {
  305. RegisterProperties(type);
  306. return _properties.GetValueOrDefault(type);
  307. }
  308. else
  309. {
  310. return props;
  311. }
  312. }
  313. catch (Exception e)
  314. {
  315. // This seems to be an intermittent error "Collection has been modified" when checking if the Dictionary has been populated already
  316. // I've added a .ToArray() to concretise the list, but who knows?
  317. Logger.Send(LogType.Error,"",$"Error Checking Properties for Type: {type.EntityName()}\n{e.Message}\n{e.StackTrace}");
  318. return null;
  319. }
  320. }
  321. public static void CheckProperties(Type type)
  322. {
  323. CheckPropertiesInternal(type);
  324. }
  325. private static IEnumerable<IProperty> PropertiesInternal(Type type)
  326. => CheckPropertiesInternal(type)?.Values ?? Enumerable.Empty<IProperty>();
  327. /// <summary>
  328. /// Returns every property, both parents and children, for <paramref name="type"/>.
  329. /// </summary>
  330. public static IEnumerable<IProperty> AllProperties(Type type)
  331. => PropertiesInternal(type);
  332. /// <summary>
  333. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  334. /// </summary>
  335. /// <param name="type"></param>
  336. /// <returns></returns>
  337. public static IEnumerable<IProperty> Properties(Type type)
  338. => PropertiesInternal(type).Where(x => !x.IsParent);
  339. /// <summary>
  340. /// Return all properties that are defined directly on <paramref name="type"/>, and does not follow sub objects, but rather includes the
  341. /// sub object property itself.
  342. /// </summary>
  343. /// <param name="type"></param>
  344. /// <returns></returns>
  345. public static IEnumerable<IProperty> RootProperties(Type type)
  346. => PropertiesInternal(type).Where(x => x.Parent is null);
  347. /// <summary>
  348. /// Return all properties that are defined locally on <paramref name="type"/>, following sub-objects but not entity links; does not retrieve calculated fields. (On entity links, the ID property is retrieved.)
  349. /// </summary>
  350. /// <param name="type"></param>
  351. /// <returns></returns>
  352. public static IEnumerable<IProperty> LocalProperties(Type type)
  353. => PropertiesInternal(type).Where(
  354. x => !x.IsParent && (!x.HasParentEntityLink() || (x.Parent?.HasParentEntityLink() != true && x.Name.EndsWith(".ID")))
  355. && !x.IsCalculated);
  356. /// <summary>
  357. /// Return the standard property list for <paramref name="type"/>; this includes nested properties.
  358. /// </summary>
  359. /// <param name="type"></param>
  360. /// <returns></returns>
  361. public static IEnumerable<IProperty> Properties<T>() => Properties(typeof(T));
  362. public static IProperty? Property(Type type, string name)
  363. {
  364. var prop = CheckPropertiesInternal(type)?.GetValueOrDefault(name);
  365. // Walk up the inheritance tree, see if an ancestor has this property.
  366. // KENRIC: not sure if this is necessary.
  367. if (prop == null && type.BaseType != null)
  368. prop = Property(type.BaseType, name);
  369. return prop;
  370. }
  371. public static IProperty? Property<T>(Expression<Func<T, object?>> expression) =>
  372. Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  373. public static IProperty? Property<T, TType>(Expression<Func<T, TType>> expression) =>
  374. Property(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  375. public static IProperty PropertyStrict(Type type, string name) =>
  376. Property(type, name) ?? throw new PropertyNotFoundException(type, name);
  377. public static IProperty PropertyStrict<T>(Expression<Func<T, object?>> expression) =>
  378. Property(expression) ?? throw new PropertyNotFoundException(typeof(T), CoreUtils.GetFullPropertyName(expression, "."));
  379. public class PropertyNotFoundException : Exception
  380. {
  381. public Type Type { get; set; }
  382. public string Property { get; set; }
  383. public PropertyNotFoundException(Type T, string property) : base($"Property '{property}' not found on type {T.FullName}")
  384. {
  385. Type = T;
  386. Property = property;
  387. }
  388. }
  389. }
  390. }