How can I share sqlite3::Connection between threads?

#1

Hi, I am trying to use right now sqlite3 in my project but I cannot seems to share the connection between threads. I wrap it inside an Arc and RwLock so personally, I guarantee that there won’t be any race conditions thanks to RwLock. Is there any way I can tell the compiler that im the guarantee of this. One of the main reasons why im trying to do this is first of all not to hit too many open files issue. And secondly, I don’t know exactly how SQLite works but seems every time to parse the DB file seems too much unnecessary job to do

#2

Arc<Mutex<Connection>> does this.

#3

so is the problem concurrent read access ?

#4

Yes, one Connection object can be used by one thread at a time.

#5

That makes sense.

#6

BTW, sqlite is very single-threaded, especially if you do writes. Most of the time it may not make sense to parallelize code that uses sqlite. You can just as well use it on a single thread, and then maybe send results to be processed on other threads.

#7

I actually cache everything so i dont expect any response from sequelite the reason im trying to add it in my state and duplicate in my endpoints is that rust does not allow global static variables so i have no way of putting it in a module and initializing it when i first run and then keep using the same variable

#8

duplicate in my endpoints is that rust does not allow global static variables so i have no way of putting it in a module and initializing it when i first run and then keep using the same variable

you can use lazy_static! to define global arc<mutex and use it inside one module and do not export it to outside world

#9

I know the existence of lazy_static but theres just too much magic in there which i dont understand. So i prefer not to do that.

#10

Last time I look at it, it was rather simple. You can write lazy_static and then execute cargo expand to see that lazy_static! is not complex or magic thing.

#11

the magic goes inside the lazy_static