postgresql 让 SQLAlchemy 在 create_all 上发出 CREATE SCHEMA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13677781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:36:29  来源:igfitidea点击:

Getting SQLAlchemy to issue CREATE SCHEMA on create_all

pythonpostgresqlsqlalchemy

提问by Rory Hart

I have a SqlAlchemy model with a schema argument like so:

我有一个带有架构参数的 SqlAlchemy 模型,如下所示:

Base = declarative_base()

class Road(Base):
  __tablename__ = "roads"
  __table_args__ = {'schema': 'my_schema'}
  id = Column(Integer, primary_key=True)

When I use Base.metadata.create_all(engine) it correctly issues a CREATE TABLE with the schema name on the front like so "CREATE TABLE my_schema.roads (" but Postgresql rightly complains that the schema doesn't exist.

当我使用 Base.metadata.create_all(engine) 时,它会正确地发出一个 CREATE TABLE 前面有架构名称,就像“CREATE TABLE my_schema.roads (”但 Postgresql 正确地抱怨架构不存在。

Am I missing a step to get SqlAlchemy to issue the CREATE SCHEMA my_schema or do I have to call this manually?

我是否缺少让 SqlAlchemy 发出 CREATE SCHEMA my_schema 的步骤,还是我必须手动调用它?

采纳答案by vicvicvic

I ran into the same issue and believe the "cleanest" way of issuing the DDL is something like this:

我遇到了同样的问题,并相信发布 DDL 的“最干净”的方式是这样的:

from sqlalchemy import event
from sqlalchemy.schema import CreateSchema

event.listen(Base.metadata, 'before_create', CreateSchema('my_schema'))

This will ensure that before anything contained in the metadata of your base is created, you have the schema for it. This does, however, not check if the schema already exists.

这将确保在创建基础元数据中包含的任何内容之前,您已经拥有了它的架构。但是,这不会检查模式是否已经存在。

You can do CreateSchema('my_schema').execute_if(callback_=check_schema)if you can be bothered to write the check_schemacallback ("Controlling DDL Sequences" on should_createin docs). Or, as an easy way out, just use DDL("CREATE SCHEMA IF NOT EXISTS my_schema")instead (for Postgres):

CreateSchema('my_schema').execute_if(callback_=check_schema)如果您不愿意编写check_schema回调(“控制 DDL 序列should_create在文档中),您可以这样做。或者,作为一种简单的方法,只需使用DDL("CREATE SCHEMA IF NOT EXISTS my_schema")(对于 Postgres):

from sqlalchemy import DDL

event.listen(Base.metadata, 'before_create', DDL("CREATE SCHEMA IF NOT EXISTS my_schema"))

回答by Rory Hart

I have done it manually on my db init script like so:

我已经在我的 db init 脚本上手动完成了,如下所示:

from sqlalchemy.schema import CreateSchema
engine.execute(CreateSchema('my_schema'))

But this seems less magical than I was expecting.

但这似乎没有我预期的那么神奇。