yahoo / squidb

SquiDB is a SQLite database library for Android and iOS
https://github.com/yahoo/squidb/wiki
Apache License 2.0
1.31k stars 132 forks source link

Detecting when the database is ready for access #143

Closed bleuf1shi closed 8 years ago

bleuf1shi commented 8 years ago

I've had experiences using SQLite on Android where the Database could take some time until it's ready for use.

I'd like to be able to know if the database is ready and if it isn't, be able to queue up in memory the actions.

I thought that I could set the flag that it's ready at the end of "onOpen" but I find that it isn't being triggered except for the first time the Database is created.

Any ideas?

protected void onOpen(SQLiteDatabaseWrapper db) Description copied from class: SquidDatabase Called when the database has been opened. This method is called after the database connection has been configured and after the database schema has been created, upgraded, or downgraded as necessary. Overrides: onOpen in class SquidDatabase Parameters: db - the SQLiteDatabaseWrapper being opened

sbosley commented 8 years ago

SquidDatabase is designed such that the database is opened synchronously the first time it's accessed -- by a query, any write operation, or a call to getDatabase(). I'm not sure why putting a flag in onOpen isn't working for you -- our unit tests confirm that the onOpen hook is called both after db creation and after open of an existing db. If you can create a different unit test exhibiting the issue you describe I'd be happy to take a look.

If you are planning on queueing up DB actions in memory, I'd simply add an action to call myDatabase.getDatabase() at the head of the queue. That call will force the db to open (and maybe upgrade if the version has changed) without doing any other db operations, so if it's the first in the queue, other operations wouldn't be dequeued until after the db is open.

Or, if you'd rather forego the queueing approach, you could simply launch a background thread in your application or main activity onCreate to call getDatabase() if you detect the db isn't open yet, and set the flag when that has finished -- although this feels pretty much the same to me as using the onOpen hook. This approach could also for example allow you to offer some UI feedback to users if there's a long-running db migration.

Does that help?

bleuf1shi commented 8 years ago

@sbosley , thanks. I'll take a look and see if I can figure it out. I'll get back to ya.

Thanks for the prompt answer.

bleuf1shi commented 8 years ago

Thanks. I see now that calling .getDatabase() does allow me to init the database before the first access to allow for the performance speedup.