简体   繁体   English

为现有数据库手动创建ORM的利弊?

[英]Pros and Cons of manually creating an ORM for an existing database?

What are the pros and cons of manually creating an ORM for an existing database vs using database reflection? 手动为现有数据库创建ORM与使用数据库反射的优缺点是什么?

I'm writing some code using SQLAlchemy to access a pre-existing database. 我正在使用SQLAlchemy编写一些代码来访问预先存在的数据库。 I know I can use sqlalchemy.ext.automap to automagically reflect the schema and create the mappings. 我知道我可以使用sqlalchemy.ext.automap自动反映架构并创建映射。

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 ? 如果有明显的好处,SQLAlchemy可以自动生成python映射类(如Django的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 . 编辑:正如@iuridiniz在下面说的那样,有一些解决方案可以模仿Django的inspectdb See Is there a Django's inspectdb equivalent for SQLAlchemy? 请参见是否存在与SQLAlchemy等效的Django的inspectdb? . 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. 该线程中的答案与Python3不兼容,因此,如果要查找实际维护的内容,请查看sqlacodegenflask-sqlacodegen

I see a lot of tables that were created with: CREATE TABLE suppliers AS (SELECT * FROM companies WHERE 1 = 2 ); 我看到很多用以下方式CREATE TABLE suppliers AS (SELECT * FROM companies WHERE 1 = 2 );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. 如果现有表没有主键,则必须不断捕获异常并将Column对象馈送到映射器中。 If you've got column objects handy, you're already halfway to writing your own ORM layer. 如果您有方便的列对象,那么您已经在编写自己的ORM层了。 If you just complete the ORM, you won't have to worry about whether tables have primary keys set. 如果您只是完成ORM,则不必担心表是否设置了主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM