package eu.friedcutlet.yokan.database.room import androidx.room.Room import androidx.sqlite.driver.bundled.BundledSQLiteDriver import androidx.sqlite.execSQL import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.domain.TitleCredit import java.io.File import java.nio.file.Files import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.* import kotlin.test.* class CastStorageTest { @Test fun version14UpgradeKeepsProgressAndNormalizedCreditsAvoidProgressWriteAmplification() = runBlocking { val directory = Files.createTempDirectory("yokan-cast-storage") val path = directory.resolve("yokan.db").toString() fun open() = RoomYokanDatabase(Room.databaseBuilder(name = path).buildYokanRoom()) fun writes(): Long = BundledSQLiteDriver().open(path).use { connection -> connection.prepare("SELECT count FROM test_credit_writes").use { statement -> check(statement.step()); statement.getLong(0) } } try { val schema = DatabaseJson.parseToJsonElement(File("schemas/eu.friedcutlet.yokan.database.room.YokanRoomDatabase/14.json").readText()) .jsonObject.getValue("database").jsonObject BundledSQLiteDriver().open(path).use { connection -> for (entity in schema.getValue("entities").jsonArray) { val row = entity.jsonObject val table = row.getValue("tableName").jsonPrimitive.content connection.execSQL(row.getValue("createSql").jsonPrimitive.content.replace("\${TABLE_NAME}", table)) row["indices"]?.jsonArray.orEmpty().forEach { connection.execSQL(it.jsonObject.getValue("createSql").jsonPrimitive.content.replace("\${TABLE_NAME}", table)) } } schema.getValue("setupQueries").jsonArray.forEach { connection.execSQL(it.jsonPrimitive.content) } connection.execSQL("INSERT INTO manga(id,name,link,status,itemType,favorite,lastRead,isLocalArchive,updatedAt,privateNote) VALUES(1,'Show','/show','Licensed','Anime',1,123,1,1,'Saved note')") connection.execSQL("INSERT INTO chapter(id,mangaId,name,url,dateUpload,scanlator,isBookmarked,isRead,lastPageRead,archivePath,isFiller,updatedAt,fetchedAt) VALUES(2,1,'Episode 1','/episode','','',1,1,'2345','/offline/file',0,1,1)") connection.execSQL("PRAGMA user_version = 14") } val cast = List(500) { TitleCredit("Actor $it", "Voice actor", "Character $it") } val first = open() try { val original = requireNotNull(first.manga(1)) assertEquals(emptyList(), original.cast) assertEquals(DbStatus.Licensed, original.status) first.upsertManga(original.copy(cast = cast)) first.awaitPersistence() BundledSQLiteDriver().open(path).use { connection -> connection.execSQL("CREATE TABLE test_credit_writes(count INTEGER NOT NULL)") connection.execSQL("INSERT INTO test_credit_writes VALUES(0)") connection.execSQL("CREATE TRIGGER test_credit_insert AFTER INSERT ON manga_credit BEGIN UPDATE test_credit_writes SET count=count+1; END") connection.execSQL("CREATE TRIGGER test_credit_delete AFTER DELETE ON manga_credit BEGIN UPDATE test_credit_writes SET count=count+1; END") } repeat(3) { first.upsertManga(requireNotNull(first.manga(1)).copy(lastRead = 200L + it)) } first.awaitPersistence() assertEquals(0L, writes(), "Reading progress must not delete/reinsert 500 credits") first.upsertManga(requireNotNull(first.manga(1)).copy(cast = cast.drop(1))) first.awaitPersistence() assertTrue(writes() > 0) } finally { first.close() } val second = open() try { assertEquals(cast.drop(1), second.manga(1)?.cast) assertEquals("Saved note", second.manga(1)?.privateNote) assertEquals(202L, second.manga(1)?.lastRead) assertEquals("2345", second.chapter(2)?.lastPageRead) val snapshot = second.snapshot() second.replaceAllAtomically(snapshot.copy(mangas = listOf(requireNotNull(second.manga(1)).copy(cast = cast.reversed()))), snapshot) } finally { second.close() } val third = open() try { assertEquals(cast.reversed(), third.manga(1)?.cast) third.removeManga(1) third.awaitPersistence() assertEquals(emptyList(), third.room.mangaCreditDao().all(), "Deleting a title removes its owned credits") } finally { third.close() } } finally { directory.toFile().deleteRecursively() } } }