IDynamicMemoryEntityGrid.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. using InABox.Clients;
  2. using InABox.Core;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace InABox.DynamicGrid;
  10. /// <summary>
  11. /// Defines a common interface for dealing with grids like <see cref="DynamicOneToManyGrid{TOne, TMany}"/>
  12. /// or <see cref="DynamicManyToManyGrid{TManyToMany, TThis}"/>, which display <see cref="Entity"/>s, but do not load them necessarily from the database,
  13. /// instead keeping them in memory.
  14. /// <br/>
  15. /// This interface then allows other functions, like
  16. /// <see cref="DynamicMemoryEntityGridExtensions.EnsureColumns{T}(InABox.DynamicGrid.IDynamicMemoryEntityGrid{T}, Columns{T})"/>, to work based on <see cref="IDynamicMemoryEntityGrid{T}.LoadedColumns"/> and manage our column handling better.
  17. /// </summary>
  18. /// <typeparam name="T"></typeparam>
  19. public interface IDynamicMemoryEntityGrid<T>
  20. where T : Entity, IRemotable, IPersistent, new()
  21. {
  22. /// <summary>
  23. /// A set of columns representing which columns have been loaded from the database.
  24. /// </summary>
  25. /// <remarks>
  26. /// This is used to refresh the data when the columns change.<br/>
  27. ///
  28. /// It is <see langword="null"/> if no data has been loaded from the database (that is, the data was gotten from
  29. /// a page data handler instead.)
  30. /// </remarks>
  31. public HashSet<string>? LoadedColumns { get; }
  32. public IEnumerable<T> Items { get; }
  33. }
  34. public static class DynamicMemoryEntityGridExtensions
  35. {
  36. public static void EnsureColumns<T>(this IDynamicMemoryEntityGrid<T> grid, Columns<T> columns)
  37. where T : Entity, IRemotable, IPersistent, new()
  38. {
  39. RequireColumns(grid, columns);
  40. LoadForeignProperties(grid, columns);
  41. }
  42. /// <summary>
  43. /// Load the properties of any <see cref="EntityLink{T}"/>s on this <see cref="TMany"/> where the <see cref="IEntityLink.ID"/> is not <see cref="Guid.Empty"/>.
  44. /// This allows us to populate columns of transient objects, as long as they are linked by the ID. What this actually then does is query each
  45. /// linked table with the required columns.
  46. /// </summary>
  47. /// <param name="columns"></param>
  48. public static void LoadForeignProperties<T>(this IDynamicMemoryEntityGrid<T> grid, Columns<T> columns)
  49. where T : Entity, IRemotable, IPersistent, new()
  50. {
  51. // Lists of properties that we need, arranged by the entity link property which is their parent.
  52. // LinkIDProperty : (Type, Properties: [(columnName, property)], Objects)
  53. var newData = new Dictionary<IProperty, Tuple<Type, List<Tuple<string, IProperty>>, HashSet<T>>>();
  54. foreach (var column in columns)
  55. {
  56. var property = DatabaseSchema.Property(typeof(T), column.Property);
  57. if (property?.GetOuterParent(x => x.IsEntityLink) is IProperty linkProperty)
  58. {
  59. var remaining = column.Property[(linkProperty.Name.Length + 1)..];
  60. if (remaining.Equals(nameof(IEntityLink.ID)))
  61. {
  62. // This guy isn't foreign, so we don't pull him.
  63. continue;
  64. }
  65. var idProperty = DatabaseSchema.Property(typeof(T), linkProperty.Name + "." + nameof(IEntityLink.ID))!;
  66. var linkType = linkProperty.PropertyType.GetInterfaceDefinition(typeof(IEntityLink<>))!.GenericTypeArguments[0];
  67. if (!newData.TryGetValue(idProperty, out var data))
  68. {
  69. data = new Tuple<Type, List<Tuple<string, IProperty>>, HashSet<T>>(
  70. linkType,
  71. new List<Tuple<string, IProperty>>(),
  72. new HashSet<T>());
  73. newData.Add(idProperty, data);
  74. }
  75. var any = false;
  76. foreach (var item in grid.Items)
  77. {
  78. if (!item.LoadedColumns.Contains(column.Property))
  79. {
  80. var linkID = (Guid)idProperty.Getter()(item);
  81. if (linkID != Guid.Empty)
  82. {
  83. any = true;
  84. data.Item3.Add(item);
  85. }
  86. }
  87. }
  88. if (any)
  89. {
  90. data.Item2.Add(new(remaining, property));
  91. }
  92. }
  93. }
  94. var queryDefs = new List<IKeyedQueryDef>();
  95. foreach (var (prop, data) in newData)
  96. {
  97. if (data.Item2.Any())
  98. {
  99. var ids = data.Item3.Select(prop.Getter()).Cast<Guid>().ToArray();
  100. queryDefs.Add(new KeyedQueryDef(prop.Name, data.Item1,
  101. Filter.Create<Entity>(data.Item1, x => x.ID).InList(ids),
  102. Columns.Create(data.Item1, data.Item2.Select(x => x.Item1).ToArray()).Add<Entity>(x => x.ID)));
  103. }
  104. }
  105. var results = Client.QueryMultiple(queryDefs);
  106. foreach(var (prop, data) in newData)
  107. {
  108. var table = results.GetOrDefault(prop.Name);
  109. if(table is null)
  110. {
  111. continue;
  112. }
  113. foreach (var entity in data.Item3)
  114. {
  115. var linkID = (Guid)prop.Getter()(entity);
  116. var row = table.Rows.FirstOrDefault(x => x.Get<Entity, Guid>(x => x.ID) == linkID);
  117. if (row is not null)
  118. {
  119. foreach (var (name, property) in data.Item2)
  120. {
  121. if (!entity.LoadedColumns.Contains(property.Name))
  122. {
  123. property.Setter()(entity, row[name]);
  124. entity.LoadedColumns.Add(property.Name);
  125. }
  126. }
  127. }
  128. }
  129. }
  130. }
  131. public static void RequireColumns<T>(this IDynamicMemoryEntityGrid<T> grid, Columns<T> columns)
  132. where T : Entity, IRemotable, IPersistent, new()
  133. {
  134. if (grid.LoadedColumns is null) return;
  135. // Figure out which columns we still need.
  136. var newColumns = columns.Where(x => !grid.LoadedColumns.Contains(x.Property)).ToColumns();
  137. if (newColumns.Any() && typeof(T).GetCustomAttribute<AutoEntity>() is null)
  138. {
  139. var data = Client.Query(
  140. new Filter<T>(x => x.ID).InList(grid.Items.Select(x => x.ID).Where(x => x != Guid.Empty).ToArray()),
  141. // We also need to add ID, so we know which item to fill.
  142. newColumns.Add(x => x.ID));
  143. foreach (var row in data.Rows)
  144. {
  145. var item = grid.Items.FirstOrDefault(x => x.ID == row.Get<T, Guid>(y => y.ID));
  146. if (item is not null)
  147. {
  148. row.FillObject(item, overrideExisting: false);
  149. }
  150. }
  151. // Remember that we have now loaded this data.
  152. foreach (var column in newColumns)
  153. {
  154. grid.LoadedColumns.Add(column.Property);
  155. }
  156. }
  157. }
  158. }