Yokan / rebuild
Course 1 8624561

06-room-db.md

.codex/skills/compose-kotlin-agent-skills/references/06-room-db.md

documentation / design asset403 lines
1# Room Database — Entities, DAOs, Migrations, Offline-First23## Contents45- Entity design — domain models vs entities6- DAO patterns — Flow, suspend, transactions7- TypeConverters8- Database migrations9- Offline-first architecture10- Repository pattern11- Anti-patterns1213## Entity Design1415### Separate Entity from Domain Model1617```kotlin18// domain/ — pure, no Room annotations19data class AuthAccount(20    val id: String,21    val serviceName: String,22    val accountName: String,23    val secretKey: String,24    val iconEmoji: String25)2627// data/ — Room entity28@Entity(tableName = "auth_accounts")29data class AuthAccountEntity(30    @PrimaryKey val id: String,31    @ColumnInfo(name = "service_name") val serviceName: String,32    @ColumnInfo(name = "account_name") val accountName: String,33    @ColumnInfo(name = "secret_key") val secretKey: String,34    @ColumnInfo(name = "icon_emoji") val iconEmoji: String35)3637// Mappers38fun AuthAccountEntity.toDomain() = AuthAccount(39    id = id,40    serviceName = serviceName,41    accountName = accountName,42    secretKey = secretKey,43    iconEmoji = iconEmoji44)4546fun AuthAccount.toEntity() = AuthAccountEntity(47    id = id,48    serviceName = serviceName,49    accountName = accountName,50    secretKey = secretKey,51    iconEmoji = iconEmoji52)53```5455**When single model is OK:** small app, no network layer, entity IS the domain model. Split when Room annotations would leak into shared KMP modules or when DTO shapes differ.5657### Composite Primary Keys5859```kotlin60@Entity(61    tableName = "workout_records",62    primaryKeys = ["date", "workoutType"]63)64data class WorkoutRecordEntity(65    val date: String,           // "2026-05-21"66    val workoutType: String,    // "pushups"67    val repCount: Int,68    val durationMs: Long69)70```7172### Indices for Query Performance7374```kotlin75@Entity(76    tableName = "auth_accounts",77    indices = [78        Index(value = ["service_name"]),79        Index(value = ["account_name", "service_name"], unique = true)80    ]81)82data class AuthAccountEntity(/* ... */)83```8485Add indices on columns used in `WHERE`, `ORDER BY`, and `JOIN`. Don't index everything — each index costs write performance.8687## DAO Patterns8889From Authenticator:9091```kotlin92@Dao93interface AuthAccountDao {94    // Reactive query — returns Flow, auto-emits on data change95    @Query("SELECT * FROM auth_accounts ORDER BY serviceName ASC")96    fun getAllAccounts(): Flow<List<AuthAccountEntity>>9798    // Search with LIKE — Flow for reactive search results99    @Query("""100        SELECT * FROM auth_accounts 101        WHERE service_name LIKE '%' || :query || '%' 102           OR account_name LIKE '%' || :query || '%'103    """)104    fun searchAccounts(query: String): Flow<List<AuthAccountEntity>>105106    // Single item — suspend for one-shot107    @Query("SELECT * FROM auth_accounts WHERE id = :id")108    suspend fun getAccountById(id: String): AuthAccountEntity?109110    // Count — suspend111    @Query("SELECT COUNT(*) FROM auth_accounts")112    suspend fun getAccountCount(): Int113114    // Insert — REPLACE strategy for upsert115    @Insert(onConflict = OnConflictStrategy.REPLACE)116    suspend fun insertAccount(account: AuthAccountEntity)117118    // Batch insert119    @Insert(onConflict = OnConflictStrategy.REPLACE)120    suspend fun insertAccounts(accounts: List<AuthAccountEntity>)121122    // Update123    @Update124    suspend fun updateAccount(account: AuthAccountEntity)125126    // Delete by object127    @Delete128    suspend fun deleteAccount(account: AuthAccountEntity)129130    // Delete by ID — more practical from UI131    @Query("DELETE FROM auth_accounts WHERE id = :id")132    suspend fun deleteAccountById(id: String)133134    // Delete all135    @Query("DELETE FROM auth_accounts")136    suspend fun deleteAllAccounts()137}138```139140### DAO Rules141142| Return Type | Use for | Thread |143|------------|---------|--------|144| `Flow<List<T>>` | Reactive queries (lists, search) | Background (auto) |145| `Flow<T?>` | Single item observation | Background (auto) |146| `suspend fun` | One-shot reads, all writes | Background (auto) |147| `fun` (no suspend, no Flow) | **WRONG** — blocks main thread | |148149### Transactions150151```kotlin152@Dao153interface AuthAccountDao {154    // Transaction for multi-statement operations155    @Transaction156    suspend fun replaceAllAccounts(newAccounts: List<AuthAccountEntity>) {157        deleteAllAccounts()158        insertAccounts(newAccounts)159    }160161    // NOT needed for single operations162    // @Transaction  ← unnecessary on single @Insert163    @Insert164    suspend fun insertAccount(account: AuthAccountEntity)165}166```167168**When to use `@Transaction`:**169- Multiple write operations that must succeed/fail together170- Read that involves multiple tables (relations)171- Batch operations where partial failure is unacceptable172173**NOT needed for:** single `@Insert`, single `@Update`, single `@Delete`, single `@Query`.174175## TypeConverters176177```kotlin178class Converters {179    // Enum180    @TypeConverter181    fun fromWorkoutType(type: WorkoutType): String = type.name182183    @TypeConverter184    fun toWorkoutType(value: String): WorkoutType = WorkoutType.valueOf(value)185186    // Date (store as epoch millis)187    @TypeConverter188    fun fromDate(date: LocalDate): Long =189        date.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli()190191    @TypeConverter192    fun toDate(millis: Long): LocalDate =193        Instant.ofEpochMilli(millis).atZone(ZoneOffset.UTC).toLocalDate()194195    // List<String> (store as JSON)196    @TypeConverter197    fun fromStringList(list: List<String>): String = Json.encodeToString(list)198199    @TypeConverter200    fun toStringList(json: String): List<String> = Json.decodeFromString(json)201202    // Color (store as Int argb)203    @TypeConverter204    fun fromColor(color: Color): Int = color.toArgb()205206    @TypeConverter207    fun toColor(argb: Int): Color = Color(argb)208}209210// Register in Database211@Database(entities = [AuthAccountEntity::class], version = 1)212@TypeConverters(Converters::class)213abstract class AppDatabase : RoomDatabase() {214    abstract fun authAccountDao(): AuthAccountDao215}216```217218**Gotcha:** TypeConverter for `Color` stores as `Int`. Compose `Color` and Android `Color` both have `toArgb()`.219220## Database Migrations221222### Safe Migration Pattern223224```kotlin225val MIGRATION_1_2 = object : Migration(1, 2) {226    override fun migrate(db: SupportSQLiteDatabase) {227        // Add column with default value — safe for existing data228        db.execSQL("ALTER TABLE auth_accounts ADD COLUMN icon_emoji TEXT NOT NULL DEFAULT '🔐'")229    }230}231232val MIGRATION_2_3 = object : Migration(2, 3) {233    override fun migrate(db: SupportSQLiteDatabase) {234        // Create new table for added feature235        db.execSQL("""236            CREATE TABLE IF NOT EXISTS workout_records (237                date TEXT NOT NULL,238                workout_type TEXT NOT NULL,239                rep_count INTEGER NOT NULL,240                duration_ms INTEGER NOT NULL,241                PRIMARY KEY(date, workout_type)242            )243        """)244    }245}246247// Build with migrations248Room.databaseBuilder(context, AppDatabase::class.java, "app_database")249    .addMigrations(MIGRATION_1_2, MIGRATION_2_3)250    .build()251```252253### Auto-Migration (Room 2.4+)254255```kotlin256@Database(257    entities = [AuthAccountEntity::class],258    version = 3,259    autoMigrations = [260        AutoMigration(from = 1, to = 2),261        AutoMigration(from = 2, to = 3, spec = Migration2To3Spec::class)262    ]263)264abstract class AppDatabase : RoomDatabase()265266@RenameColumn(tableName = "auth_accounts", fromColumnName = "name", toColumnName = "service_name")267class Migration2To3Spec : AutoMigrationSpec268```269270Auto-migration handles simple cases (add column, rename). Manual migration for complex changes (data transformation, table restructure).271272### Testing Migrations273274```kotlin275@RunWith(AndroidJUnit4::class)276class MigrationTest {277    @get:Rule278    val helper = MigrationTestHelper(279        InstrumentationRegistry.getInstrumentation(),280        AppDatabase::class.java281    )282283    @Test284    fun migrate1To2() {285        // Create DB at version 1286        helper.createDatabase("test_db", 1).apply {287            execSQL("INSERT INTO auth_accounts (id, service_name) VALUES ('1', 'Google')")288            close()289        }290291        // Migrate to version 2292        helper.runMigrationsAndValidate("test_db", 2, true, MIGRATION_1_2)293294        // Verify data survived295        val db = helper.runMigrationsAndValidate("test_db", 2, true)296        val cursor = db.query("SELECT icon_emoji FROM auth_accounts WHERE id = '1'")297        cursor.moveToFirst()298        assertEquals("🔐", cursor.getString(0))299    }300}301```302303## Offline-First Architecture304305```306┌──────────────┐     ┌──────────────┐     ┌──────────────┐307│   Composable │────▶│  Repository  │────▶│   Room DAO   │308│   (collect)  │     │  (mediator)  │     │  (source of  │309│              │◀────│              │◀────│   truth)     │310└──────────────┘     └──────┬───────┘     └──────────────┘311                            │312                            ▼313                     ┌──────────────┐314                     │  Remote API  │315                     │  (sync only) │316                     └──────────────┘317```318319```kotlin320class AuthRepositoryImpl(321    private val dao: AuthAccountDao,322    private val api: AuthApi323) : AuthRepository {324325    // UI always reads from Room — single source of truth326    override fun getAllAccounts(): Flow<List<AuthAccount>> =327        dao.getAllAccounts().map { entities ->328            entities.map { it.toDomain() }329        }330331    // Sync: fetch remote → write to Room → UI auto-updates via Flow332    override suspend fun sync(): Result<Unit> {333        return try {334            val remote = api.getAccounts()335            val entities = remote.map { it.toEntity() }336            dao.replaceAllAccounts(entities)337            Result.success(Unit)338        } catch (e: IOException) {339            Result.failure(e)  // offline — stale local data still shown340        }341    }342343    override suspend fun addAccount(account: AuthAccount): Result<Unit> {344        return try {345            dao.insertAccount(account.toEntity())  // write locally first346            api.createAccount(account.toDto())      // sync to remote347            Result.success(Unit)348        } catch (e: IOException) {349            // Local write succeeded, remote failed350            // Queue for later sync or just keep local351            Result.success(Unit)352        }353    }354}355```356357**Key principle:** UI reads from Room only. Network writes to Room. Room notifies UI via Flow. User always sees data, even offline.358359## Repository Pattern360361```kotlin362// domain/ — interface363interface AuthRepository {364    fun getAllAccounts(): Flow<List<AuthAccount>>365    fun searchAccounts(query: String): Flow<List<AuthAccount>>366    suspend fun getAccountById(id: String): AuthAccount?367    suspend fun insertAccount(account: AuthAccount)368    suspend fun deleteAccountById(id: String)369    suspend fun sync(): Result<Unit>370}371372// data/ — implementation373class AuthRepositoryImpl(374    private val dao: AuthAccountDao,375    private val api: AuthApi  // optional, for sync376) : AuthRepository {377378    override fun getAllAccounts(): Flow<List<AuthAccount>> =379        dao.getAllAccounts().map { list -> list.map { it.toDomain() } }380381    override suspend fun insertAccount(account: AuthAccount) {382        dao.insertAccount(account.toEntity())383    }384385    // ... other methods386}387```388389**Repository value:**3901. Abstracts data source — ViewModel doesn't know about Room/Retrofit3912. Testable — swap with FakeRepository in tests3923. Mapping layer — entity/DTO → domain model conversion3934. Offline-first logic — sync coordination394395## Anti-Patterns396397- **`@Transaction` on single query** → overhead for nothing. Only for multi-statement operations398- **`OnConflictStrategy.REPLACE` with foreign keys** → REPLACE = DELETE + INSERT. Cascades foreign keys. Use IGNORE + manual UPDATE399- **Returning `LiveData` from DAO** → use `Flow`. LiveData is lifecycle-aware but inflexible for transformation. Flow supports `map`, `combine`, `filter`, `stateIn`400- **`allowMainThreadQueries()`** → jank. Room queries always on background thread via suspend/Flow401- **Storing JSON blobs in single column** → defeats purpose of relational DB. Normalize into proper tables with relations402- **No migration strategy** → `fallbackToDestructiveMigration()` deletes all user data. Users will uninstall your app. Always write migrations403- **Fat entities with UI state** → entity stores persistent data. `isExpanded`, `isSelected` are transient — keep in UiState, not Room404

Search chapters, reference and source filenames.