python SQLAlchemy关键字参数等效于'Column('id',String,Enum((“foo”,“bar”))'

hjqgdpho  于 2022-12-21  发布在  Python
关注(0)|答案(1)|浏览(156)

我正在查看https://docs.sqlalchemy.org/en/14/core/type_basics.html#sqlalchemy.types.Enum和https://docs.sqlalchemy.org/en/14/core/metadata.html#sqlalchemy.schema.Column.init,但是我看不出下面的尝试有什么等价的东西:

Column(name='id', type_=String, server_default=Enum(("foo", "bar")))

我尝试了default=server_default=Enum(("foo", "bar")),但收到以下错误消息:

sqlalchemy.exc.ArgumentError: Argument 'arg' is expected to be one of type '<class 'str'>' or '<class 'sqlalchemy.sql.elements.ClauseElement'>' or '<class 'sqlalchemy.sql.elements.TextClause'>', got '<class 'sqlalchemy.sql.sqltypes.Enum'>'

我是要使用https://docs.sqlalchemy.org/en/14/core/defaults.html#sqlalchemy.schema.DefaultClause或sqlalchemy.schema.DefaultGenerator,还是根本不打算使用默认值/等效值?

hs1ihplo

hs1ihplo1#

如果后端数据库没有本地ENUM类型,SQLAlchemy可以自动将枚举值存储为字符串。
Enum类型将使用后端的本地“ENUM”类型(如果有);否则,它使用VARCHAR数据类型。
因此,对于像SQLite这样没有本地ENUM类型的数据库,列type_仍然声明为Enum

import enum
from sqlalchemy import Column, Enum, Integer, MetaData, Table, create_engine, insert, select

class SexEnum(enum.Enum):
    female = "F"
    male = "M"

engine = create_engine("sqlite://")

tbl = Table(
    "tbl",
    MetaData(),
    Column("id", Integer, primary_key=True),
    Column("sex", Enum(SexEnum, create_constraint=True, name="sex_enum")),
)
engine.echo = True
tbl.create(engine)
"""
CREATE TABLE tbl (
    id INTEGER NOT NULL, 
    sex VARCHAR(6), 
    PRIMARY KEY (id), 
    CONSTRAINT sex_enum CHECK (sex IN ('female', 'male'))
)
"""

with engine.begin() as conn:
    conn.execute(insert(tbl), dict(sex=SexEnum.male))
"""
INSERT INTO tbl (sex) VALUES (?)
[generated in 0.00033s] ('male',)
"""

with engine.begin() as conn:
    print(conn.execute(select(tbl)).all())
    # [(1, <SexEnum.male: 'M'>)]

相关问题