DatabaseUpdateScript.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System.Linq.Expressions;
  2. using InABox.Core;
  3. namespace InABox.Database;
  4. public abstract class DatabaseUpdateScript
  5. {
  6. public abstract VersionNumber Version { get; }
  7. public abstract bool Update();
  8. protected struct Map<T>
  9. {
  10. public String Old;
  11. public Expression<Func<T, object>> New;
  12. public Map(String oldcolumn, Expression<Func<T, object>> newcolumn)
  13. {
  14. Old = oldcolumn;
  15. New = newcolumn;
  16. }
  17. }
  18. protected void Convert<T>(
  19. Filter<T> filter,
  20. params Map<T>[] maps
  21. ) where T : Entity, IPersistent, IRemotable, new()
  22. {
  23. Logger.Send(LogType.Information, "", $"Converting {typeof(T).EntityName().Split('.').Last()}...");
  24. List<T> updates = new List<T>();
  25. var columns = Columns.None<T>().Add(x => x.ID);
  26. foreach (var map in maps)
  27. {
  28. columns.Add(map.Old);
  29. columns.Add(map.New);
  30. }
  31. CoreTable table = DbFactory.NewProvider(Logger.Main).Query<T>(filter,columns);
  32. int iCount = 0;
  33. foreach (var row in table.Rows)
  34. {
  35. var update = row.ToObject<T>();
  36. foreach (var map in maps)
  37. CoreUtils.SetPropertyValue(update, CoreUtils.GetFullPropertyName<T, object>(map.New, "."), CoreUtils.GetPropertyValue(update, map.Old));
  38. if (update.IsChanged())
  39. updates.Add(update);
  40. if (updates.Count == 100)
  41. {
  42. iCount += updates.Count;
  43. Logger.Send(LogType.Information, "", $"Converting {typeof(T).EntityName().Split('.').Last()} Times ({iCount}/{table.Rows.Count}");
  44. DbFactory.NewProvider(Logger.Main).Save(updates);
  45. updates.Clear();
  46. }
  47. }
  48. if (updates.Count > 0)
  49. {
  50. iCount += updates.Count;
  51. Logger.Send(LogType.Information, "", $"Converting {typeof(T).EntityName().Split('.').Last()} Times ({iCount}/{table.Rows.Count})");
  52. DbFactory.NewProvider(Logger.Main).Save(updates);
  53. updates.Clear();
  54. }
  55. }
  56. }