Here’s a pretty interesting question…
I’m writing a program to manipulate several remote databases with same schema via SQLAlchemy. The connection string is not static — it is stored in a local SQLite database.
I need to create a session at runtime, and use that session to reflect the database schema. All databases have same schema.
I have already know the table names.
Anyway to implement this?
def connect(connstr):
engine = create_engine(connstr)
metadata = MetaData(bind=engine)
session = create_session(bind=engine)
return session
class User(Base):
# How it's possible to create a dummy model class without predefined metadata?
__table__ = Table('users', metadata, autoload=True)
EDIT: finally I solved this problem by myself:
Base = declarative_base()
def connect(connstr):
engine = create_engine(connstr)
metadata = MetaData(bind=engine)
session = create_session(bind=engine)
return metadata, session
def get_model(metadata, modelname, tablename):
cls = type(modelname, (Base,), dict(
__table__ = Table(tablename, metadata, autoload = True)
))
return cls
However, @Gary van der Merwe’s answer is pretty cool!
You have to manually map the orm classes to the reflected tables.
Assuming a database with the following structure:
you can do: