Search code examples
pythonsqlitepeewee

Multiple SQLite connections to a database in :memory:


Is it possible to access an in-memory SQLite database from different threads?

In the following sample code I create a SQLite database in memory and create a table. When I now go to a different execution context, which I think have to do when I go to a different thread, the created table isn't there anymore. If I would open a file based SQLite database, the table would be there.

Can I achieve the same behavior for an in-memory database?

from peewee import *
db = SqliteDatabase(':memory:')

class BaseModel(Model):
    class Meta:
        database = db

class Names(BaseModel):
    name = CharField(unique=True)

print(Names.table_exists())  # this returns False 
Names.create_table()
print(Names.table_exists())  # this returns True

print id(db.get_conn())  # Our main thread's connection.

with db.execution_context():
    print(Names.table_exists())  # going to another context, this returns False if we are in :memory: and True if we work on a file *.db
    print id(db.get_conn())  # A separate connection.

print id(db.get_conn())  # Back to the original connection.

Solution

  • Working!!

    cacheDB = SqliteDatabase('file:cachedb?mode=memory&cache=shared')

    Link