1

I am using SQlAlchemy automap extension for my preference to avoid manually writing up the declarative base classes. Mostly because I am not very familiar with the db schema and need to interact only with a small subset of tables and columns

I am using the following code to set up a SQlAlchemy session and then interact with my database. Things seem to work well using this.

        engine = create_engine('mssql+pymssql://xx:xxx@xxx/xxx', implicit_returning=False)
        metadata = MetaData()
        tables = ['xxx', 'xxx', 'xxx']
        metadata.reflect(engine, only=tables)
        base = automap_base(metadata=metadata)
        base.prepare()
        session_maker = sessionmaker(bind=engine)
        session = session_maker()

Since the database has a large number of tables and columns, it takes a fair amount of time for the session to load, since each time reflection has to be done.

Also, the IDE I use (PyCharm) gives me very useful auto completion when it can infer the object type correctly. It does not work when I use automap, for obvious reasons. It is often a challenge to get the column name strings right, and requires me to repeatedly verify them from db management studio.

Is there a way to generate declarative base classes using reflection? Can I at least persist the reflected metadata in some other way? It is safe to assume that db schema won't change.

1 Answer 1

1

You can define models that represent the tables in the database. Given that the database is not expected to change much this only needs to be done once, possibly with some column changes later on.

Example:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class SomeClass(Base):
    __tablename__ = 'some_table'
    id = Column(Integer, primary_key=True)
    name =  Column(String(50))

Documentation

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, of course. I should have mentioned I was hopping to avoid doing that and therefore went the reflection route.
I'm not aware of code that will generate the above Python code from reflected metadata within SQLAlchemy. Also, even when it's possible to persist the metadata in some text/binary file format, it's probably more maintainable to write it in Python code.
I've used SQLACodeGen to get models initially, then clean them up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.