// Copyright (c) 2007-2017 ppy Pty Ltd . // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Logging; using osu.Game.Database; using SQLite.Net; using SQLiteNetExtensions.Extensions; namespace osu.Game.Beatmaps { /// /// Handles the storage and retrieval of Beatmaps/BeatmapSets to the database backing /// public class BeatmapDatabase : DatabaseStore { public event Action BeatmapSetAdded; public event Action BeatmapSetRemoved; public BeatmapDatabase(SQLiteConnection connection) : base(connection) { } protected override Type[] ValidTypes => new[] { typeof(BeatmapSetInfo), typeof(BeatmapInfo), typeof(BeatmapMetadata), typeof(BeatmapDifficulty), }; protected override void Prepare(bool reset = false) { if (reset) { Connection.DropTable(); Connection.DropTable(); Connection.DropTable(); Connection.DropTable(); Connection.DropTable(); } Connection.CreateTable(); Connection.CreateTable(); Connection.CreateTable(); Connection.CreateTable(); Connection.CreateTable(); cleanupPendingDeletions(); } /// /// Add a to the database. /// /// The beatmap to add. public void Add(BeatmapSetInfo beatmapSet) { Connection.InsertOrReplaceWithChildren(beatmapSet, true); BeatmapSetAdded?.Invoke(beatmapSet); } /// /// Delete a to the database. /// /// The beatmap to delete. /// Whether the beatmap's was changed. public bool Delete(BeatmapSetInfo beatmapSet) { if (beatmapSet.DeletePending) return false; beatmapSet.DeletePending = true; Connection.Update(beatmapSet); BeatmapSetRemoved?.Invoke(beatmapSet); return true; } /// /// Restore a previously deleted . /// /// The beatmap to restore. /// Whether the beatmap's was changed. public bool Undelete(BeatmapSetInfo beatmapSet) { if (!beatmapSet.DeletePending) return false; beatmapSet.DeletePending = false; Connection.Update(beatmapSet); BeatmapSetAdded?.Invoke(beatmapSet); return true; } private void cleanupPendingDeletions() { foreach (var b in GetAllWithChildren(b => b.DeletePending && !b.Protected)) { try { foreach (var i in b.Beatmaps) { if (i.Metadata != null) Connection.Delete(i.Metadata); if (i.Difficulty != null) Connection.Delete(i.Difficulty); Connection.Delete(i); } if (b.Metadata != null) Connection.Delete(b.Metadata); // many-to-many join table entries are not automatically tidied. Connection.Table().Delete(f => f.BeatmapSetInfoID == b.ID); Connection.Delete(b); } catch (Exception e) { Logger.Error(e, $@"Could not delete beatmap {b}"); } } //this is required because sqlite migrations don't work, initially inserting nulls into this field. //see https://github.com/praeclarum/sqlite-net/issues/326 Connection.Query("UPDATE BeatmapSetInfo SET DeletePending = 0 WHERE DeletePending IS NULL"); } } }