SQLite.Net-PCL icon indicating copy to clipboard operation
SQLite.Net-PCL copied to clipboard

Question: Why construct `SQLiteAsyncConnection` with a function?

Open rudmer90 opened this issue 11 years ago • 5 comments

I ran into an issue where I was creating my app's sole SQLiteAsyncConnection in the following manner:

var conn = new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(...));

Looking at the source code for SQLiteAsyncConnection, the function passed in as a constructor parameter is called in GetConnection(), which is called any time the SQLiteAsyncConnection needs to read or write to the database.

So this caused a new connection to be instantiated any time conn performed a read or write. In effect, even though I was being very deliberate to only have one database connection for the entire app, the "hidden" inner workings (I am using the Nuget packages) of SQLiteAsyncConnection were causing my app to have multiple connections at any given time, which caused database locking issues once I reached a critical mass of database read/write operation calls.

My question: why is SQLiteAsyncConnection designed this way? Why not simply pass in a SQLiteConnectionWithLock to the constructor, instead of a function that returns one? Or have SQLiteAsyncConnection call the function once, store its result in a private member variable, and then return that variable in GetConnection() instead of running the constructor function parameter every time?

I guess the issue, once realized, is easy to get around -- I simply instantiated a SQLiteConnectionWithLock outside of the function and then passed in that object's accessor as the construction function parameter -- but it's still an unnecessary "gotcha" in my opinion.

rudmer90 avatar Jun 28 '14 00:06 rudmer90

I agree this is not a really good pattern, I did it this way originally to avoid any type dependencies, if I remember correctly it had something to do with the unit tests. The tests were/are still designed in such a way that the current functionality is needed, I would welcome any PR's to change this entire mess:)

oysteinkrog avatar Jul 01 '14 18:07 oysteinkrog

I'd be happy to make the changes. What are the backwards-compatibility concerns?

rudmer90 avatar Jul 01 '14 20:07 rudmer90

surely you could just have multiple constructors?

mgwalm avatar Jul 19 '14 10:07 mgwalm

Thanks for your learning, saved me heaps of time! I had the same gotcha!

mohitsinghbaweja avatar Oct 09 '14 12:10 mohitsinghbaweja

@rudmer90, I am using the "SQLiteAsyncConnection". As you said in the issue,I am getting the SQLite Exception that "Database Locked".

Please suggest me,how to avoid database locking issue. I am thinking that,I need to implement some kind of lock while performing the database operations.

Please suggest the best way to resolve this issue.

Harikrishnav21 avatar Feb 22 '16 09:02 Harikrishnav21