SQLAlchemy 不插入默认值

SQLAlchemy does not insert default values

我有workspacestable

workspaces_table = Table(
    "workspaces", metadata_obj,
    Column("id", UUID(as_uuid=False), primary_key=True, default=uuid.uuid4),
    Column("name", JSONB(), nullable=False),
    Column("created_at", TIMESTAMP(timezone=False), default=datetime.datetime.now(), nullable=False),
    Column("updated_at", TIMESTAMP(timezone=False), default=datetime.datetime.now(), nullable=False),
    Column("created_by", UUID(as_uuid=False), ForeignKey('users.id'), nullable=False),
    Column("updated_by", UUID(as_uuid=False), ForeignKey('users.id'), nullable=False),
    Column("email", Text(), nullable=False)
)

在此 table 列中,created_atupdated_at 具有默认值 datetime.datetime.now()

但是当我尝试在此 table 中插入行时

  await conn.execute(text(
        f"""
            WITH workspace_create AS (
                INSERT INTO workspaces(id, name, created_by, updated_by, email)
                VALUES (:workspace_id, :workspace_name, :user_id, :user_id, :workspace_email)
            ),
            
            workspace_roles_create AS (
                INSERT INTO workspace_roles(id, name, export_data, users, settings, projects, roles, system_name,
                    workspace_id)
                VALUES {sql_query_workspace_roles_values}
            )
            
            INSERT INTO m2m_users_to_workspace_or_project_roles(user_id, role_id, role_type, user_status) 
            VALUES(:user_id, :superuser_id, '{RoleTypes.Workspace.name}', '{UserStatuses.Active.name}')
        """
    ), params
    )

我收到以下错误:

null value in column "created_at" of relation "workspaces" violates not-null constraint
DETAIL:  Failing row contains (dd31dfb6-6d22-4794-b804-631e60b6e063, [{"locale": "ru", "text_value": "ru_team_1"}], null, null, 481b7a55-52b7-48f2-89ea-4ae0673d4ab6, 481b7a55-52b7-48f2-89ea-4ae0673d4ab6, ruslpogo@gmail.com).

我看到该行包含 null 而不是 created_at updated_at 列中的默认值。

如何自动插入默认值?

Column(…, default=…) 是一个 client-side 默认值,当您执行类似 workspaces_table.insert() 的操作时,SQLAlchemy Core(和 SQLAlchemy ORM)会使用该默认值。请注意,如果 SQLAlchemy 创建 table,则该列没有 server-side DEFAULT:

workspaces_table = Table(
    "workspaces",
    MetaData(),
    Column("id", Integer(), primary_key=True),
    Column("created_at", DateTime(), default=datetime.now()),
)
engine.echo = False
workspaces_table.drop(engine, checkfirst=True)
engine.echo = True
workspaces_table.create(engine)
""" DDL emitted:
CREATE TABLE workspaces (
    id SERIAL NOT NULL, 
    created_at TIMESTAMP WITHOUT TIME ZONE, 
    PRIMARY KEY (id)
)
"""

Column(…, server_default=…) 是指定 server-side DEFAULT 的内容,它将可用于纯文本 INSERT 语句,例如您问题中的语句:

workspaces_table = Table(
    "workspaces",
    MetaData(),
    Column("id", Integer(), primary_key=True),
    Column("created_at", DateTime(), server_default=text("CURRENT_TIMESTAMP")),
)
engine.echo = False
workspaces_table.drop(engine, checkfirst=True)
engine.echo = True
workspaces_table.create(engine)
""" DDL emitted:
CREATE TABLE workspaces (
    id SERIAL NOT NULL, 
    created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP, 
    PRIMARY KEY (id)
)
"""

请注意,将 Table() 定义从 default= 更改为 server_default= 不会 更新现有的 table;为此,您需要使用 ALTER TABLE