package win.taptap.musicmanager.db import java.nio.file.Files import java.nio.file.Path import java.sql.DriverManager import java.time.Instant import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue import org.flywaydb.core.Flyway import org.flywaydb.core.api.MigrationVersion import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll import org.jetbrains.exposed.sql.transactions.transaction import org.junit.jupiter.api.io.TempDir import win.taptap.musicmanager.config.AppConfig import win.taptap.musicmanager.config.UserAccount import win.taptap.musicmanager.config.UsersConfig class DatabaseFactoryTest { @TempDir lateinit var tempDir: Path @Test fun `migrates the schema and configures sqlite`() { val db = DatabaseFactory.connect(appConfig()) try { assertEquals("wal", pragma(db, "journal_mode")) assertEquals("1", pragma(db, "foreign_keys")) val migrations = queryInt(db, "SELECT COUNT(*) FROM flyway_schema_history") assertTrue(migrations >= 9, "Expected at least the V1..V9 migrations") // The new schema exists and the mounted-library tables do not. assertTrue(tableExists(db, "songs")) assertTrue(tableExists(db, "mood_songs")) assertTrue(tableExists(db, "mood_recommendations")) assertTrue(tableExists(db, "download_jobs")) assertFalse(tableExists(db, "music_folders")) assertFalse(tableExists(db, "artists")) assertFalse(tableExists(db, "longform_progress")) } finally { db.close() } } @Test fun `V8 wipes content but keeps users and device tokens`() { val config = appConfig() Files.createDirectories(config.dataDir) val url = "jdbc:sqlite:${config.databasePath.toAbsolutePath()}" Flyway.configure() .dataSource(url, null, null) .locations("classpath:db/migration") .target(MigrationVersion.fromVersion("7")) .load() .migrate() DriverManager.getConnection(url).use { connection -> connection.createStatement().use { statement -> statement.executeUpdate( "INSERT INTO users (name, is_admin, updated_at) VALUES ('alice', 1, 'now')", ) statement.executeUpdate( "INSERT INTO api_tokens " + "(id, user_name, token_hash, device_name, platform, created_at, last_used_at, expires_at) " + "VALUES ('tk-1', 'alice', 'hash', 'phone', 'android', 'now', 'now', 'later')", ) statement.executeUpdate( "INSERT INTO music_folders (id, name, type, root_path) VALUES (1, 'Music', 'music', '/m')", ) statement.executeUpdate( "INSERT INTO artists (id, name, sort_name, search_text) VALUES ('ar-1', 'Artist', 'artist', 'artist')", ) statement.executeUpdate( "INSERT INTO albums (id, name, created_at, search_text) VALUES ('al-1', 'Album', 'now', 'album')", ) statement.executeUpdate( "INSERT INTO songs " + "(id, album_id, folder_id, title, display_artist, album_name, duration, bit_rate, " + "size, suffix, content_type, relative_path, file_mtime, created_at, updated_at, search_text) " + "VALUES ('sg-1', 'al-1', 1, 'Song', 'Artist', 'Album', 120, 128, 10, 'mp3', " + "'audio/mpeg', 'a/b.mp3', 0, 'now', 'now', 'song')", ) statement.executeUpdate( "INSERT INTO moods " + "(id, owner, name, genres, target_size, refresh_hours, yt_enabled, created_at, changed_at, seed_percent) " + "VALUES ('mo-1', 'alice', 'Focus', '[]', 30, 24, 1, 'now', 'now', 50)", ) statement.executeUpdate( "INSERT INTO mood_seeds (mood_id, song_id, origin, added_at) VALUES ('mo-1', 'sg-1', 'manual', 'now')", ) statement.executeUpdate( "INSERT INTO playback_sessions (id, user_name, mood_id, created_at, last_seen_at) " + "VALUES ('ps-1', 'alice', 'mo-1', 'now', 'now')", ) statement.executeUpdate( "INSERT INTO playback_session_items " + "(session_id, position, song_id, state, queued_at, updated_at) " + "VALUES ('ps-1', 0, 'sg-1', 'queued', 'now', 'now')", ) } } val db = DatabaseFactory.connect(config) try { assertEquals( 1, queryInt(db, "SELECT COUNT(*) FROM users WHERE name = 'alice'"), "Users must survive the wipe", ) assertEquals( 1, queryInt(db, "SELECT COUNT(*) FROM api_tokens WHERE id = 'tk-1'"), "Device tokens must survive the wipe", ) assertEquals(0, queryInt(db, "SELECT COUNT(*) FROM songs")) assertEquals(0, queryInt(db, "SELECT COUNT(*) FROM moods")) assertEquals(0, queryInt(db, "SELECT COUNT(*) FROM playback_sessions")) assertTrue(tableExists(db, "mood_songs")) assertFalse(tableExists(db, "music_folders")) } finally { db.close() } } @Test fun `syncs users idempotently`() { val db = DatabaseFactory.connect(appConfig()) try { val users = UsersConfig( listOf( UserAccount("alice", "pw", admin = true), UserAccount("bob", "pw", admin = false), ), ) ConfigRepository.sync(users) ConfigRepository.sync(users) transaction(db.database) { assertEquals(2L, UsersTable.selectAll().count()) } } finally { db.close() } } @Test fun `removing a user cascades their moods and playback state`() { val db = DatabaseFactory.connect(appConfig()) try { ConfigRepository.sync( UsersConfig( listOf( UserAccount("alice", "pw", admin = true), UserAccount("bob", "pw", admin = false), ), ), ) val now = Instant.now().toString() val moodId = "mo-1" transaction(db.database) { SongsTable.insert { it[id] = "sg-1" it[musicSource] = "youtube" it[externalId] = "video-1" it[title] = "Song" it[artist] = "Artist" it[relativePath] = "video-1/song.mp3" it[createdAt] = now it[updatedAt] = now } MoodsTable.insert { it[id] = moodId it[owner] = "alice" it[name] = "Focus" it[createdAt] = now it[changedAt] = now } MoodSongsTable.insert { it[this.moodId] = moodId it[songId] = "sg-1" it[addedAt] = now } PlaybackSessionsTable.insert { it[id] = "ps-1" it[userName] = "alice" it[this.moodId] = moodId it[createdAt] = now it[lastSeenAt] = now } SessionItemsTable.insert { it[sessionId] = "ps-1" it[position] = 0 it[songId] = "sg-1" it[queuedAt] = now it[updatedAt] = now } } ConfigRepository.sync( UsersConfig(listOf(UserAccount("bob", "pw", admin = false))), ) transaction(db.database) { assertEquals(1L, UsersTable.selectAll().count()) assertEquals(0L, MoodsTable.selectAll().count()) assertEquals(0L, MoodSongsTable.selectAll().count()) assertEquals(0L, PlaybackSessionsTable.selectAll().count()) // Songs are shared and have no owner, so they survive. assertEquals(1L, SongsTable.selectAll().count()) } } finally { db.close() } } private fun appConfig(): AppConfig = AppConfig( port = 8080, dataDir = tempDir.resolve("data"), usersFile = tempDir.resolve("users.yaml"), ffmpegPath = "ffmpeg", ) private fun pragma(db: DatabaseHandle, name: String): String = db.dataSource.connection.use { connection -> connection.createStatement().use { statement -> statement.executeQuery("PRAGMA $name").use { result -> assertTrue(result.next(), "PRAGMA $name returned no row") result.getString(1) } } } private fun queryInt(db: DatabaseHandle, sql: String): Int = db.dataSource.connection.use { connection -> connection.createStatement().use { statement -> statement.executeQuery(sql).use { result -> assertTrue(result.next(), "$sql returned no row") result.getInt(1) } } } private fun tableExists(db: DatabaseHandle, name: String): Boolean = queryInt( db, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '$name'", ) > 0 }