使用具有唯一约束的SQLAlchemy的on_conflict_do_update()

时间:2019-06-04 09:28:37

标签: postgresql sqlalchemy

我正在使用SQLAlchemy 1.3.4和PostgreSQL 11.3。

我有以下(简化的)表定义:

class MyModel(Base):
    __tablename__ = 'mymodel'

    id = Column(Integer, primary_key=True)
    col1 = Column(Unicode, nullable=False)
    col2 = Column(Unicode, nullable=False)
    col3 = Column(Unicode, nullable=False)
    col4 = Column(Boolean)

    created_at = Column(DateTime(timezone=True), nullable=False)
    updated_at = Column(DateTime(timezone=True), nullable=False)

    __table_args__ = (
        Index('uq_mymodel_col1_col2_col3_col4',
              col1, col2, col3, col4,
              unique=True, postgresql_where=col4.isnot(None)),
        Index('uq_mymodel_col1_col2_col3',
              col1, col2, col3,
              unique=True, postgresql_where=col4.is_(None)),
    )

(我必须创建2个唯一索引而不是UniqueConstraint,因为UniqueConstraint允许具有相同(col1, col2, col3)的多行是col4为空,我这样做不需要)

我正在尝试执行以下查询:

INSERT INTO mymodel (col1, col2, col3, col4, created_at, updated_at)
VALUES (%(col1)s, %(col2)s, %(col3)s, %(col4)s, %(created_at)s, %(updated_at)s)
ON CONFLICT DO UPDATE SET updated_at = %(param_1)s
RETURNING mymodel.id

我不知道如何正确使用SQLAlchemy的on_conflict_do_update()。 :-/

这是我尝试过的:

values = {…}

stmt = insert(MyModel.__table__).values(**values)
stmt = stmt.returning(MyModel.__table__.c.id)
stmt = stmt.on_conflict_do_update(set_={'updated_at': values['updated_at']})
result = dbsession.connection().execute(stmt)

但是SQLAlchemy抱怨:Either constraint or index_elements, but not both, must be specified unless DO NOTHING

我不清楚如何使用constraintindex_elements

我尝试了几件事,无济于事。例如:

values = {…}

stmt = insert(MyModel.__table__).values(**values)
stmt = stmt.returning(MyModel.__table__.c.id)
stmt = stmt.on_conflict_do_update(constraint='uq_mymodel_col1_col2_col3_col4'
                                  set_={'updated_at': values['updated_at']})
result = dbsession.connection().execute(stmt)

但是,这也不起作用:constraint "uq_mymodel_col1_col2_col3_col4" for table "mymodel" does not exist。但是它确实存在。 (我什至从pgsql复制粘贴,以确保我没有打错字)

无论如何,我有两个可能引发冲突的独特约束,但是on_conflict_do_update()似乎只有一个约束。所以我也尝试同时指定两者:

values = {…}

stmt = insert(MyModel.__table__).values(**values)
stmt = stmt.returning(MyModel.__table__.c.id)
stmt = stmt.on_conflict_do_update(constraint='uq_mymodel_col1_col2_col3_col4'
                                  set_={'updated_at': values['updated_at']})
stmt = stmt.on_conflict_do_update(constraint='uq_mymodel_col1_col2_col3'
                                  set_={'updated_at': values['updated_at']})
result = dbsession.connection().execute(stmt)

但是我遇到了同样的错误,即uq_mymodel_col1_col2_col3_col4不存在。

在这一点上,我只是无法弄清楚如何执行上述查询,并且会非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

好吧,我想我明白了。因此问题根本不是来自SQLAlchemy,实际上我是在滥用PostgreSQL。

首先,我上面粘贴的SQL查询不起作用,因为PostgreSQL与SQLAlchemy一样,需要指定索引列或约束名称。

当我指定我的约束之一时,PostgreSQL给了我与SQLAlchemy相同的错误。那是因为我的约束实际上不是约束,而是唯一索引。看来它确实必须是唯一的约束,而不是唯一的索引。 (即使该索引与唯一约束具有相同的效果)

所以我将模型重写如下:

# Feel free to use the following code under the MIT license


class NullableBoolean(TypeDecorator):
    """A three-states boolean, which allows working with UNIQUE constraints

    In PostgreSQL, when making a composite UNIQUE constraint where one of the
    columns is a nullable boolean, then null values for that column are counted
    as always different.

    So if you have:

        class MyModel(Base):
            __tablename__ = 'mymodel'

            id = Column(Integer, primary_key=True)
            col1 = Column(Unicode, nullable=False)
            col2 = Column(Unicode, nullable=False)
            col3 = Column(Boolean)

            __table_args__ = (
                UniqueConstraint(col1, col2, col3,
                                 name='uq_mymodel_col1_col2_col3'),
            }

    Then you could INSERT multiple records which have the same (col1, col2)
    when col3 is None.

    If you want None to be considered a "proper" value that triggers the
    unicity constraint, then use this type instead of a nullable Boolean.
    """
    impl = Enum

    def __init__(self, **kwargs):
        kwargs['name'] = 'nullable_boolean_enum'

        super().__init__('true', 'false', 'unknown', **kwargs)

    def process_bind_param(self, value, dialect):
        """Convert the Python values into the SQL ones"""
        return {
            True: 'true',
            False: 'false',
            None: 'unknown',
        }[value]

    def process_result_value(self, value, dialect):
        """Convert the SQL values into the Python ones"""
        return {
            'true': True,
            'false': False,
            'unknown': None,
        }[value]


class MyModel(Base):
    __tablename__ = 'mymodel'

    id = Column(Integer, primary_key=True)
    col1 = Column(Unicode, nullable=False)
    col2 = Column(Unicode, nullable=False)
    col3 = Column(Unicode, nullable=False)
    col4 = Column(Boolean)

    created_at = Column(DateTime(timezone=True), nullable=False)
    updated_at = Column(DateTime(timezone=True), nullable=False)

    __table_args__ = (
        UniqueConstraint(col1, col2, col3, col4,
                         name='uq_mymodel_col1_col2_col3_col4')
    )

现在它似乎按预期运行。

希望对以后的人有所帮助。如果有人有更好的主意,我很感兴趣。 :)