With Version 2.3.0-alpha03 Room has a prepackagedDatabaseCallback it says:-
-
This callback will be invoked after the pre-package DB is copied but before Room had a chance to open it and therefore before the RoomDatabase.Callback methods are invoked. This callback can be useful for updating the pre-package DB schema to satisfy Room's schema validation.
So how could I uses this to circumvent the Invalid Schema expected .... found ....?
Could I use this to introduce Triggers, as room doesn't have annotations for the creation of triggers?
Note this is intended as an ask, and answer, your own question
The following, albeit long winded shows an example that corrects a schema accordingly.
Yes, although this hasn't actually been tested but the example caters for the creation of the triggers.
Notes regrading the example First, it should be noted that when the callback was initially being looked at that there were issues. These have now been addressed BUT requires 2.4.0-beta02 or greater. The issues were:-
The fix applied being
The Flow
When control is passed to the callback the asset database has been copied. So it's just a matter, in theory, of ALTERing the TABLES and VIEWS (if any) to match the schema that room expects.
Often trying to match what room expects with what room finds frustrates some. The example below will overcome minor/small/often missed issues. It works by:-
INSERT OR IGNOREto justINSERTto fail)It does expect that the source (asset) has the columns in the correct order, that nulls are are not included in columns that room has a NOT NULL constraint. However, as INSERT OR IGNORE is used then such rows will not be inserted rather than resulting in an exception.
Other than copying come code from the generated java, the process is automated and should cope with most/many assets without modification.
The Code
The vast majority of the code is in the @Database class OtherDatabase. Note that this should cope with many databases with a little tailoring (see comments for changes to make):-
Working Example
The Asset database
The asset database contains 3 tables, person, company and company_person_map
person DDL is
Room expects:-
company DDL is
Room expects:-
company_person_map DDL is
Room expects:-
The asset table contains the following data:-
person
company
company_person_map
AllDao is
The invoking Activity is :-
Result