Python SQLAlchemy in-memory database connect

Viewed 5717

I'm creating a in-memory database with python and I want to use SQLAlchemy with it.

All my application is currently working directly with queries to the db.

I've seen multiple ways of connecting but none of it is working. My current attempt stands as:

# Creates an sqlite database in memory
db = Database(filename=':memory:', schema='schema.sql')
db.recreate()

# ORM
engine = create_engine('sqlite:///:memory:')

Base = automap_base()
Base.prepare(engine, reflect=True)
User = Base.classes.user

session = Session(engine)

This gives AttributeError: user. How do I properly connect my database to the SQLAlchemy?

2 Answers

ATTACH is your friend.

You can attach an in-memory database to the current database session.

E.g.,

db.init('sqlite://')
db.execute("ATTACH DATABASE ':memory:' AS my_database")
db.create_all()
from sqlalchemy import create_engine   
from sqlalchemy.orm import registry, Session
 
engine = create_engine("sqlite+pysqlite:///:memory:", echo=True, future=True)
session = Session(engine)
registry().metadata.create_all(engine)
Related