0
votes

What are the pros and cons of manually creating an ORM for an existing database vs using database reflection?

I'm writing some code using SQLAlchemy to access a pre-existing database. I know I can use sqlalchemy.ext.automap to automagically reflect the schema and create the mappings.

However, I'm wondering if there is any significant benefit of manually creating the mapping classes vs letting the automap do it's magic.


If there is significant benefit, can SQLAlchemy auto-generate the python mapping classes like Django's inspectdb? That would make creating all of the declarative base mappings much faster, as I'd only have to verify and tweak rather than write from scratch.

Edit: As @iuridiniz says below, there are a few solutions that mimic Django's inspectdb. See Is there a Django's inspectdb equivalent for SQLAlchemy?. The answers in that thread are not Python3 compatible, so look into sqlacodegen or flask-sqlacodegen if you're looking for something that's actually maintained.

1
Thanks for finding that! So that takes care of the 2nd half of the question. Any thoughts on the 1st half? - dthor

1 Answers

0
votes

I see a lot of tables that were created with: CREATE TABLE suppliers AS (SELECT * FROM companies WHERE 1 = 2 );, (a poor man's table copy), which will have no primary keys. If existing tables don't have primary keys, you'll have to constantly catch exceptions and feed Column objects into the mapper. If you've got column objects handy, you're already halfway to writing your own ORM layer. If you just complete the ORM, you won't have to worry about whether tables have primary keys set.