DataUpdater.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. using InABox.Configuration;
  2. using InABox.Core;
  3. using Microsoft.CodeAnalysis.Scripting;
  4. using System.Collections.Generic;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading.Tasks;
  10. namespace InABox.Database;
  11. public class DatabaseVersion : BaseObject, IGlobalConfigurationSettings
  12. {
  13. public string Version { get; set; }
  14. public DatabaseVersion()
  15. {
  16. Version = "0.00";
  17. }
  18. }
  19. public class VersionNumber
  20. {
  21. public int MajorVersion { get; set; }
  22. public int MinorVersion { get; set; }
  23. public string Release { get; set; }
  24. public bool IsDevelopmentVersion { get; set; }
  25. public VersionNumber(int majorVersion, int minorVersion, string release = "", bool isDevelopmentVersion = false)
  26. {
  27. MajorVersion = majorVersion;
  28. MinorVersion = minorVersion;
  29. Release = release;
  30. IsDevelopmentVersion = isDevelopmentVersion;
  31. }
  32. private static Regex _format = new(@"^(\d+)\.(\d+)([a-zA-Z]*)$");
  33. public static VersionNumber Parse(string versionStr)
  34. {
  35. if(versionStr == "???")
  36. {
  37. return new(0, 0, "", true);
  38. }
  39. var match = _format.Match(versionStr);
  40. if (!match.Success)
  41. throw new FormatException($"'{versionStr}' is not a valid version!");
  42. return new(int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value), match.Groups[3].Value, false);
  43. }
  44. public static bool TryParse(string versionStr, [NotNullWhen(true)] out VersionNumber? version)
  45. {
  46. if (versionStr == "???")
  47. {
  48. version = new(0, 0, "", true);
  49. return true;
  50. }
  51. var match = _format.Match(versionStr);
  52. if (!match.Success)
  53. {
  54. version = null;
  55. return false;
  56. }
  57. version = new(int.Parse(match.Groups[1].Value), int.Parse(match.Groups[2].Value), match.Groups[3].Value, false);
  58. return true;
  59. }
  60. public static bool operator <(VersionNumber a, VersionNumber b)
  61. {
  62. if (a.IsDevelopmentVersion)
  63. {
  64. return false;
  65. }
  66. else if (b.IsDevelopmentVersion)
  67. {
  68. return true;
  69. }
  70. return a.MajorVersion < b.MajorVersion ||
  71. (a.MajorVersion == b.MajorVersion &&
  72. (a.MinorVersion < b.MinorVersion ||
  73. (a.MinorVersion == b.MinorVersion && string.Compare(a.Release, b.Release, StringComparison.Ordinal) < 0)));
  74. }
  75. public static bool operator >(VersionNumber a, VersionNumber b)
  76. {
  77. return b < a;
  78. }
  79. public static bool operator <=(VersionNumber a, VersionNumber b)
  80. {
  81. return !(b < a);
  82. }
  83. public static bool operator >=(VersionNumber a, VersionNumber b)
  84. {
  85. return !(a < b);
  86. }
  87. public override bool Equals(object? obj)
  88. {
  89. if(obj is VersionNumber v)
  90. {
  91. return this == v;
  92. }
  93. return false;
  94. }
  95. public override int GetHashCode()
  96. {
  97. if (IsDevelopmentVersion)
  98. return 0;
  99. return MajorVersion ^ MinorVersion ^ Release.GetHashCode();
  100. }
  101. public static bool operator ==(VersionNumber a, VersionNumber b)
  102. {
  103. if (a.IsDevelopmentVersion)
  104. return b.IsDevelopmentVersion;
  105. if (b.IsDevelopmentVersion)
  106. return false;
  107. return a.MajorVersion == b.MajorVersion && a.MinorVersion == b.MinorVersion && a.Release == b.Release;
  108. }
  109. public static bool operator !=(VersionNumber a, VersionNumber b)
  110. {
  111. if (a.IsDevelopmentVersion)
  112. return !b.IsDevelopmentVersion;
  113. if (b.IsDevelopmentVersion)
  114. return true;
  115. return a.MajorVersion != b.MajorVersion || a.MinorVersion != b.MinorVersion || a.Release != b.Release;
  116. }
  117. public override string ToString()
  118. {
  119. return IsDevelopmentVersion ? "???" : $"{MajorVersion}.{MinorVersion:D2}{Release}";
  120. }
  121. }
  122. public static class DataUpdater
  123. {
  124. private static Dictionary<VersionNumber, List<DatabaseUpdateScript>> updateScripts = new();
  125. /// <summary>
  126. /// Register a migration script to run when updating to this version.
  127. ///
  128. /// <para>The <paramref name="action"/> should probably be repeatable;
  129. /// that is, if you run it a second time, it only updates data that needed updating. This way if it accidentally somehow gets run twice, there is no issue.
  130. /// </para>
  131. /// </summary>
  132. /// <param name="version">The version to update to.</param>
  133. /// <param name="action">The action to be run.</param>
  134. public static void RegisterUpdateScript<TUpdater>()
  135. where TUpdater : DatabaseUpdateScript, new()
  136. {
  137. var updater = new TUpdater();
  138. if(!updateScripts.TryGetValue(updater.Version, out var list))
  139. {
  140. list = new();
  141. updateScripts[updater.Version] = list;
  142. }
  143. list.Add(updater);
  144. }
  145. private static bool MigrateDatabase(VersionNumber fromVersion, VersionNumber toVersion, out VersionNumber newVersion)
  146. {
  147. var versionNumbers = updateScripts.Keys.ToList();
  148. versionNumbers.Sort((x, y) => x == y ? 0 : x < y ? -1 : 1);
  149. newVersion = fromVersion;
  150. int? index = null;
  151. foreach (var (i, number) in versionNumbers.Select((x, i) => new Tuple<int, VersionNumber>(i, x)))
  152. {
  153. if (number > fromVersion)
  154. {
  155. index = i;
  156. break;
  157. }
  158. }
  159. if(index != null && fromVersion < toVersion)
  160. {
  161. Logger.Send(LogType.Information, "", $"Updating database from {fromVersion} to {toVersion}");
  162. for (int i = (int)index; i < versionNumbers.Count; i++)
  163. {
  164. var version = versionNumbers[i];
  165. if (toVersion < version)
  166. {
  167. break;
  168. }
  169. Logger.Send(LogType.Information, "", $"Executing update to {version}");
  170. foreach(var updater in updateScripts[version])
  171. {
  172. if (!updater.Update())
  173. {
  174. Logger.Send(LogType.Error, "", $"Script failed, cancelling migration");
  175. return false;
  176. }
  177. }
  178. newVersion = version;
  179. }
  180. Logger.Send(LogType.Information, "", $"Data migration complete!");
  181. }
  182. newVersion = toVersion;
  183. return true;
  184. }
  185. private static DatabaseVersion GetVersionSettings()
  186. {
  187. var result = DbFactory.NewProvider(Logger.Main).Query(new Filter<GlobalSettings>(x => x.Section).IsEqualTo(nameof(DatabaseVersion)))
  188. .Rows.FirstOrDefault()?.ToObject<GlobalSettings>();
  189. if(result != null)
  190. {
  191. return Serialization.Deserialize<DatabaseVersion>(result.Contents);
  192. }
  193. var settings = new GlobalSettings() { Section = nameof(DatabaseVersion), Key = "" };
  194. var dbVersion = new DatabaseVersion() { Version = "6.30b" };
  195. settings.Contents = Serialization.Serialize(dbVersion);
  196. DbFactory.NewProvider(Logger.Main).Save(settings);
  197. return dbVersion;
  198. }
  199. private static VersionNumber GetDatabaseVersion()
  200. {
  201. var dbVersion = GetVersionSettings();
  202. return VersionNumber.Parse(dbVersion.Version);
  203. }
  204. private static void UpdateVersionNumber(VersionNumber version)
  205. {
  206. if (version.IsDevelopmentVersion)
  207. {
  208. return;
  209. }
  210. var dbVersion = GetVersionSettings();
  211. dbVersion.Version = version.ToString();
  212. var result = DbFactory.NewProvider(Logger.Main).Query(new Filter<GlobalSettings>(x => x.Section).IsEqualTo(nameof(DatabaseVersion)))
  213. .Rows.FirstOrDefault()?.ToObject<GlobalSettings>() ?? new GlobalSettings() { Section = nameof(DatabaseVersion), Key = "" };
  214. result.OriginalValues["Contents"] = result.Contents;
  215. result.Contents = Serialization.Serialize(dbVersion);
  216. DbFactory.NewProvider(Logger.Main).Save(result);
  217. }
  218. /// <summary>
  219. /// Migrates the database to the current version.
  220. /// </summary>
  221. /// <returns><c>false</c> if the migration fails.</returns>
  222. public static bool MigrateDatabase()
  223. {
  224. try
  225. {
  226. var from = GetDatabaseVersion();
  227. var to = VersionNumber.Parse(CoreUtils.GetVersion());
  228. var success = MigrateDatabase(from, to, out var newVersion);
  229. if (newVersion != from)
  230. {
  231. UpdateVersionNumber(newVersion);
  232. }
  233. return success;
  234. }
  235. catch(Exception e)
  236. {
  237. Logger.Send(LogType.Error, "", $"Error while migrating database: {CoreUtils.FormatException(e)}");
  238. return false;
  239. }
  240. }
  241. }