Declarative SQLAlchemy CREATE SQLITE in memory tables

6k views Asked by At

This is how I setup my database for an application (in Flask):

from sqlalchemy.engine import create_engine
from sqlalchemy.orm import scoped_session, create_session
from sqlalchemy.ext.declarative import declarative_base

engine = None
db_session = scoped_session(lambda: create_session(bind=engine,
                                                   autoflush=False, autocommit=False, expire_on_commit=True))

Base = declarative_base()
Base.query = db_session.query_property()

def init_engine(uri, **kwargs):
    global engine
    engine = create_engine(uri, **kwargs)

    Base.metadata.create_all(bind=engine)

    return engine

If I connect to a file database that has had tables created already, everything works fine, but using sqlite:///:memory: as a target database gives me:

OperationalError: (OperationalError) no such table: users u'DELETE FROM users' ()

when querying like so for ex.:

UsersTable.query.delete()
db_session.commit()

I am accessing this code from a unit test. What is the problem?

Thanks

Edit:

Working setup of the application:

app = Flask(__name__)
app.config.from_object(__name__)
app.secret_key = 'XXX'

# presenters
from presenters.users import users

# register modules (presenters)
app.register_module(users)

# initialize the database
init_engine(db)
1

There are 1 answers

1
jd. On BEST ANSWER

The code you posted doesn't contain any table/class declaration. Are you sure that the declaration is done before init_engine() is called?