Yokan / rebuild
Course 1 8624561

SyncIdentityMigration.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIdentityMigration.kt

implementation108 lines
1package eu.friedcutlet.yokan.database.sync23import eu.friedcutlet.yokan.database.YokanDatabase4import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot56/**7 * One-time rewrite of local auto-increment ids to [SyncIds] so this device can merge with others.8 * Runs once per install (tracked in `DbSettings.syncIdentityVersion`); every foreign key and every9 * keyed settings list follows the rewritten ids. Duplicates that collapse onto one stable id keep10 * the most recently updated row.11 */12object SyncIdentityMigration {13    const val VERSION = 11415    fun ensure(db: YokanDatabase) {16        val current = db.snapshot()17        if (current.settings.syncIdentityVersion >= VERSION) return18        val remapped = remap(current)19        db.replaceAll(20            remapped.copy(settings = remapped.settings.copy(syncIdentityVersion = VERSION)),21            expectedSnapshot = current,22        )23    }2425    fun remap(s: YokanDatabaseSnapshot): YokanDatabaseSnapshot {26        val mangaIds = HashMap<Long, Long>()27        val mangas = s.mangas28            .map { m -> m.copy(id = SyncIds.forManga(m) ?: m.id).also { mangaIds[m.id] = it.id } }29            .dedupe { it.id to it.updatedAt }3031        val categoryIds = HashMap<Long, Long>()32        val categories = s.categories.map { c -> c.copy(id = SyncIds.random()).also { categoryIds[c.id] = it.id } }33        val mangasWithCategories = mangas.map { m -> m.copy(categories = m.categories?.map { categoryIds[it] ?: it }?.distinct()) }3435        val chapterIds = HashMap<Long, Long>()36        val chapters = s.chapters37            .map { c ->38                val moved = c.copy(mangaId = c.mangaId?.let { mangaIds[it] ?: it })39                moved.copy(id = SyncIds.forChapter(moved) ?: c.id).also { chapterIds[c.id] = it.id }40            }41            .dedupe { it.id to it.updatedAt }4243        fun manga(id: Long?) = id?.let { mangaIds[it] ?: it }44        fun chapter(id: Long?) = id?.let { chapterIds[it] ?: it }4546        val histories = s.histories47            .map { h ->48                val moved = h.copy(mangaId = manga(h.mangaId), chapterId = chapter(h.chapterId))49                moved.copy(id = SyncIds.forHistory(moved) ?: h.id)50            }51            .dedupe { it.id to it.updatedAt }52        val updates = s.updates53            .map { u ->54                val moved = u.copy(mangaId = manga(u.mangaId), chapterId = chapter(u.chapterId))55                moved.copy(id = SyncIds.forUpdate(moved) ?: u.id)56            }57            .dedupe { it.id to it.updatedAt }58        val tracks = s.tracks59            .map { t ->60                val moved = t.copy(mangaId = manga(t.mangaId))61                moved.copy(id = SyncIds.forTrack(moved) ?: t.id)62            }63            .dedupe { it.id to it.updatedAt }64        val downloads = s.downloads.map { d -> d.copy(chapterId = chapter(d.chapterId)) }65        val pageCache = s.pageCache.map { p -> p.copy(chapterId = chapter(p.chapterId)) }6667        val st = s.settings68        val settings = st.copy(69            chapterReleasePreferences = st.chapterReleasePreferences.map { it.copy(mangaId = manga(it.mangaId)) },70            automaticReaderLayouts = st.automaticReaderLayouts.map { it.copy(mangaId = manga(it.mangaId) ?: it.mangaId) },71            sortChapterList = st.sortChapterList?.map { it.copy(mangaId = manga(it.mangaId)) },72            chapterFilterDownloadedList = st.chapterFilterDownloadedList?.map { it.copy(mangaId = manga(it.mangaId)) },73            chapterFilterUnreadList = st.chapterFilterUnreadList?.map { it.copy(mangaId = manga(it.mangaId)) },74            chapterFilterBookmarkedList = st.chapterFilterBookmarkedList?.map { it.copy(mangaId = manga(it.mangaId)) },75            chapterPageIndexList = st.chapterPageIndexList?.map { it.copy(chapterId = chapter(it.chapterId)) },76            personalReaderModeList = st.personalReaderModeList?.map { it.copy(mangaId = manga(it.mangaId)) },77            filterScanlatorList = st.filterScanlatorList?.map { it.copy(mangaId = manga(it.mangaId)) },78            personalPageModeList = st.personalPageModeList?.map { it.copy(mangaId = manga(it.mangaId)) },79            autoScrollPages = st.autoScrollPages?.map { it.copy(mangaId = manga(it.mangaId)) },80            titleMetadata = st.titleMetadata?.map { it.copy(mangaId = manga(it.mangaId) ?: it.mangaId) },81        )8283        return s.copy(84            settings = settings,85            mangas = mangasWithCategories,86            chapters = chapters,87            categories = categories,88            histories = histories,89            updates = updates,90            tracks = tracks,91            downloads = downloads,92            pageCache = pageCache,93            changedParts = emptyList(),94            outbox = emptyList(),95        )96    }9798    /** Keep one row per id: the one with the greatest secondary key (updatedAt). */99    private inline fun <T> List<T>.dedupe(key: (T) -> Pair<Long, Long>): List<T> {100        val best = LinkedHashMap<Long, T>()101        for (item in this) {102            val (id, stamp) = key(item)103            val current = best[id]104            if (current == null || key(current).second <= stamp) best[id] = item105        }106        return best.values.toList()107    }108}109

Search chapters, reference and source filenames.