Room Database Flashcards
DATA › Storage
- What are the three major components of a Room database?
- The @Database class (extends RoomDatabase, the access point), @Entity classes (mapped to tables), and @Dao interfaces (query/insert/update/delete methods). Room generates the implementations at compile time via KSP.
- When are SQL errors in a @Query caught, and why?
- At compile time. Room validates each @Query against the known schema during annotation processing, so typos in column names or bad syntax fail the build rather than crashing at runtime.
- You increment the @Database version but add no Migration. What happens?
- At runtime Room cannot find a migration path and throws an IllegalStateException when opening the database, unless you opt into destructive migration or provide an auto-migration.
- What does fallbackToDestructiveMigration do, and what is the risk?
- When no migration path exists, Room drops and recreates all tables, permanently deleting all existing user data. It is a last resort, fine for dev but dangerous in production.
- What is a Room type converter and when do you need one?
- SQLite stores only primitives, String, and byte[]. A @TypeConverter method pair converts unsupported types (Date, enum, List) to/from a storable type; you register them with @TypeConverters on the database, entity, or DAO.
- How do you model a one-to-many relationship in Room?
- Create a POJO that holds the parent with @Embedded and the children as a List annotated with @Relation(parentColumn, entityColumn). Querying the parent table makes Room run a second query and populate the children automatically.
- Why return Flow from a DAO query, and how does it behave?
- Flow makes the query observable: Room re-emits a fresh result whenever any queried table changes. Collection runs asynchronously, so it pairs with coroutines and a background dispatcher to keep the UI updated without manual refetching.
- Can a Flow-returning DAO query be marked suspend?
- No. Flow- (and LiveData-) returning queries must not be suspend because the stream itself is asynchronous and observable. Mark one-shot operations (inserts, updates, single reads) as suspend instead.
- How do @Update and @Delete decide which rows to act on, and what do @Insert methods return?
- @Update and @Delete match rows by primary key, doing nothing if no row matches. @Insert returns the new rowId as a Long for a single item, or a List<Long> for a collection.