Search code examples
androidkotlinsqliteandroid-room

How to make Room work with "pre-packaged" databases with different schemas?


I'm experimenting to make an app that requires to hold a lot of info, like a database about the city and it's places. Currently I'm using SQLite file to send this data from server to client - it is stored this way both on server and client, so I'd like to avoid converting it back and forth to json, not to mention increazed payload size. App downloads that file and then uses Room createFromFile method to open it. But anytime I add a new column to the table, Room throws:

Pre-packaged database has an invalid schema

This error is totally understandable for fields that are required but missing - but it also throws it if there is added field, which should not impact existing queries. Yes, ideally would be for clients to update the app along with API changes, but I'd like to handle it more gracefully, to allow them to use existing version with existing functions with update reminders, instead of just blocking the app altogether. So/TLDR:

Is there a way to tell Room to just ignore columns in shema that it does not expect? Or maybe an automagical way to remove unexpected columns (without listing every table and column in constants and manually update that list for every version, preferably)


Solution

  • So here’s what I ended up with, for now:

    I’m using a “template” — an empty database instance that Room sets up with the schema it expects. Then, I compare the “template” with the incoming file using plain old SQL queries and remove columns from the incoming file that aren’t present in the expected schema.

    But to me this looks like trying to fit a square peg into a round hole. I think, the proper approach might be one of the following:

    1. Drop Room in favor of a another solution that isn’t so strict with schemas. In my case, I can probably manage with just plain SQL queries.
    2. Change API to serve different files based on the client version.