Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 643
Randrian Avatar asked Mar 12 '23 16:03

Randrian


1 Answers

Working!!

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

Link

  • http://charlesleifer.com/blog/managing-database-connections-with-peewee/
  • https://groups.google.com/forum/#!topic/peewee-orm/78invrt3xyo
like image 103
traeper Avatar answered Mar 27 '23 02:03

traeper