SQLAlchemy 在 PostgreSQL 数据库上用于 GENERATED ALWAYS AS IDENTITY 的语法是:

huangapple go评论86阅读模式
英文:

SQLAlchemy syntax for GENERATED ALWAYS AS IDENTITY on postgres database

问题

以下是代码部分的翻译,不包括问题的回答:

class X(Base):
    __tablename__ = "x"
    x_id = Column(Integer, primary_key=True, server_default=text("GENERATED ALWAYS AS IDENTITY"))
    x_name = Column(Text, unique=True)

这里的关键是在x_id列上使用server_default参数,并将其设置为GENERATED ALWAYS AS IDENTITY。这将确保生成的SQL中使用正确的语法。

英文:

How could the following table be represented as an SQLA model?

CREATE TABLE x
(
    x_id    integer GENERATED ALWAYS AS IDENTITY,
    x_name  text unique
);

I think that if I create a column using:

    id = Column(Integer, nullable=False, primary_key=True)

The generated SQL won't use GENERATED ALWAYS AS IDENTITY, but will instead use SERIAL.

Completing the following, in order to use the GENERATED ALWAYS AS IDENTITY syntax, is what I'm unsure of:

class X(Base):
    __tablename__ = "x"
    x_id = Column( <something here> ) 
    x_name = Column(Text, unique = True)

答案1

得分: 2

你可以在列定义中使用 Identity

class X(Base):
    __tablename__ = "x"
    x_id = Column(Integer, Identity(always=True), primary_key=True)
    x_name = Column(Text, unique=True)

PS. 如果你设置了 primary_key=True,则不需要设置 nullable=False

英文:

You can use an Identity in your column definition.

class X(Base):
    __tablename__ = "x"
    x_id = Column(Integer, Identity(always=True), primary_key=True)
    x_name = Column(Text, unique=True)

PS. no need to set nullable=False if you set primary_key=True.

huangapple
  • 本文由 发表于 2023年2月14日 20:16:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447713.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定