Room persistence model
The Room persistence model gives the local library a durable store for media records, user state, playback history, and cached data. MusicDatabase exposes this store through focused data access objects (DAOs), while entities and relation records preserve links between songs, albums, artists, playlists, and their supporting data. For the library view, this page complements Local library and Library workflows.
Persistence boundary
Database boundary
app/…/MusicDatabase.kt defines the database boundary for the app. MusicDatabase presents the main DatabaseDao and the separate SpeedDialDao, and it also provides query and transaction entry points so callers use one shared persistence model.
The database uses song.db by default. Room owns the database schema and applies its registered migration path when the stored schema version changes. The database uses write-ahead logging and keeps a backup before an upgrade or downgrade so a schema change does not silently remove the only durable copy of library data.
flowchart LR
Library[Library and playback features] --> DB[MusicDatabase]
DB --> Main[DatabaseDao]
DB --> Dial[SpeedDialDao]
Main --> Tables[Media, relation, history, and cache tables]
Dial --> Speed[Speed dial records]
Tables --> Views[Room views and joined read models]
References: app/…/MusicDatabase.kt• L57-87 app/…/MusicDatabase.kt• L90-160 app/…/MusicDatabase.kt• L186-230
DAO boundary
DatabaseDao is the main contract for reading and changing persistent music data. It returns simple entities for direct records and joined models such as songs with artists, albums with songs, or playlists with their ordered songs. Flow-based queries let library screens observe durable changes instead of taking a one-time snapshot.
The DAO groups changes that must remain consistent into transactions. For example, adding songs to a playlist checks that the songs exist, assigns positions, updates library membership when needed, and updates the playlist timestamp as one unit. SpeedDialDao handles pinned items as a separate, small contract with observable reads and replace-on-conflict writes.
References: app/…/DatabaseDao.kt• L80-156 app/…/DatabaseDao.kt• L1082-1214 app/…/SpeedDialDao.kt• L10-23
Durable data model
Core media relationships
The core model stores songs, artists, albums, and playlists as durable records with stable string IDs. Separate relation records connect these records and preserve order where the user sees an ordered list. This keeps shared media data separate from membership in a playlist or association with an artist.
| Relationship | Durable record | Meaning |
|---|---|---|
| Song to artist | SongArtistMap | A song has one or more artists with display order. |
| Song to album | SongAlbumMap | A song belongs to an album with track order. |
| Album to artist | AlbumArtistMap | An album has one or more artists with artist order. |
| Playlist to song | PlaylistSongMap | A playlist contains a song with a position and optional set-video ID. |
Each relation points to both parent records through foreign keys. Deleting a parent removes its relation records. This prevents playlist, album, or artist links from surviving after the related media record is removed.
References: app/…/SongEntity.kt• L19-67 app/…/ArtistEntity.kt• L18-36 app/…/AlbumEntity.kt• L18-38 app/…/PlaylistEntity.kt• L25-44 app/…/SongArtistMap.kt• L12-33 app/…/SongAlbumMap.kt• L12-33 app/…/AlbumArtistMap.kt• L12-33 app/…/PlaylistSongMap.kt• L13-35
Media state
Media entities hold both catalog identity and local user state. A song can record library membership, like state, download state, playback position, cache state, and upload state. Albums, artists, playlists, and podcasts use related bookmark or library fields so the app can keep local choices even when remote catalog data changes.
The model also supports local and remote records in the same tables. Local IDs and flags distinguish locally owned items from remote items without requiring a second library model. A playlist can also carry a remote browse ID while remaining editable and locally stored.
References: app/…/SongEntity.kt• L28-66 app/…/ArtistEntity.kt• L20-36 app/…/AlbumEntity.kt• L20-38 app/…/PlaylistEntity.kt• L27-44 app/…/PodcastEntity.kt• L23-41
Supporting records
Supporting entities retain information that should outlive one screen or one network response. Playback events and monthly play counts support statistics. Lyrics and format records support playback and display. Search history, recognition history, related songs, saved video IDs, and speed-dial items support app features without changing the core media relationships.
Some supporting records belong to a song and use the song ID as their durable link. Others are independent history or cache records. The database therefore separates user history from catalog identity while still allowing DAO queries to combine them for library and statistics views.
References: app/…/Event.kt• L15-32 app/…/PlayCountEntity.kt• L11-20 app/…/FormatEntity.kt• L11-24 app/…/LyricsEntity.kt• L12-23 app/…/SearchHistory.kt• L12-24 app/…/RecognitionHistory.kt• L13-40 app/…/RelatedSongMap.kt• L13-33 app/…/SetVideoIdEntity.kt• L11-16 app/…/SpeedDialItem.kt• L14-26
Value conversion and schema management
Time values
Room stores LocalDateTime values as nullable integer timestamps. Converters maps these values to and from epoch milliseconds in UTC. This gives SQL queries a stable numeric value while the Kotlin model exposes a date type to the rest of the app.
The UTC rule is part of the stored-data contract. It affects library order, bookmark dates, download dates, playback events, and statistics ranges. A change to the conversion rule can change the meaning of existing records even when the table shape stays the same.
References: app/…/Converters.kt• L8-25 app/…/MusicDatabase.kt• L157-158 app/…/Event.kt• L27-32
Schema lifecycle
The schema is currently version 38. Room uses automatic migrations for many version steps and explicit migrations where data must be reshaped or repaired. The migration history includes changes to core columns, relation tables, cached playback fields, lyrics data, and audio format data.
Migration safety depends on preserving old data while the model changes. The database backs up the database file before upgrade or downgrade and does not allow an unplanned destructive migration. The migration tests verify that older schemas can reach the current model without losing the durable relationships that the library needs.
When a schema change needs data movement rather than a simple table change, its migration must preserve IDs and rebuild dependent relation records. The earliest schema transition shows this pattern by mapping old artist and playlist IDs before recreating their records and links.
References: app/…/MusicDatabase.kt• L116-155 app/…/MusicDatabase.kt• L186-230 app/…/MusicDatabase.kt• L253-346 app/…/MusicDatabase.kt• L348-591 app/…/MusicDatabaseMigrationTest.kt• L1-200
Read models
The durable tables are not the only shape exposed to the app. Room views and transaction queries assemble the related records that screens need. Examples include ordered song-artist and song-album relations and a short playlist preview.
This separation lets the stored model keep normalized links while the read model presents a useful library object. Changes to an entity or relation must therefore remain compatible with both the table schema and the joined DAO result.
References: app/…/MusicDatabase.kt• L111-115 app/…/DatabaseDao.kt• L136-154 app/…/DatabaseDao.kt• L245-270 app/…/DatabaseDao.kt• L1082-1093
Change checklist
When these files or sections are changed, remember to consider these:
- A new or changed Room entity must stay aligned with the
@Databaseentity list, the schema version, and the migration path. - A changed ID or relation key must be checked against foreign keys, DAO joins, ordering fields, and any migration that copies the related rows.
- A changed
LocalDateTimefield must keep the UTC timestamp contract for old rows and range queries. - A changed
SpeedDialItem.typevalue must stay compatible with bothfromYTItemandtoYTItem. - A changed playlist insertion rule must preserve song existence checks, position ordering, and playlist update time in the same transaction.
- A changed entity projection must be checked against Room views and transaction return models.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A schema version changes without a complete migration path | The database cannot open an older library safely | Add the matching migration or auto-migration and preserve the stored IDs and links. |
| A parent song, album, artist, or playlist is removed | Foreign-key cascade removes its relation rows | Treat parent deletion as a relationship change and preserve needed data before deletion. |
| A playlist row is added for a missing song | The foreign-key contract rejects the write | Resolve the song first, as the playlist transaction does. |
| The date converter changes its time zone or unit | Existing dates and statistics ranges no longer represent the same moments | Keep epoch milliseconds in UTC for both read and write conversion. |
| A speed-dial item has an unknown type | Rebuilding the pinned item fails with an argument error | Keep stored type values within the supported item set. |
Key files
| File | Why to read it |
|---|---|
| app/…/MusicDatabase.kt | Defines the database boundary, registered entities, schema version, migrations, backups, and transaction setup. |
| app/…/DatabaseDao.kt | Shows how durable rows become library, playlist, album, artist, playback, and statistics data. |
| app/…/SpeedDialDao.kt | Defines the separate persistence contract for pinned items. |
| app/…/Converters.kt | Defines the stored representation of date and time values. |
| app/…/SongEntity.kt | Shows the central song record and its local library and playback state. |
| app/…/PlaylistSongMap.kt | Shows how ordered playlist membership is stored and linked to songs. |
| app/…/SongArtistMap.kt | Shows the ordered many-to-many song and artist relationship. |
| app/…/SongAlbumMap.kt | Shows the ordered song and album relationship. |
| app/…/MusicDatabaseMigrationTest.kt | Shows the compatibility guarantee for moving older database schemas forward. |