sqlalchemy更新bindparam主键

sqalchemy update bindparam primary key

以下代码抛出 "sqlalchemy.exc.CompileError: Unconsumed column names: _id".

User = Table('users', metadata,
 Column('id', Integer, primary_key=True),
 Column('score', Integer)
)

values = [
    {'score': 2, '_id': 1},
    {'score': 3, '_id': 3}
]
query = User.update().where(User.c.id == bindparam('_id')).values(score=bindparam('score'))
await db.execute_many(query, values)

dbdatabases.Database 的实例。请注意,我必须使用名称“_id”,因为 SQLalchemy 表示 'id' 已保留。

除了单独更新每一行之外,还有其他解决方案吗?

Database.execute_many() 调用 Connection.execute_many() 将您的查询分解为单独的查询(values 中的每个元素一个),这是方法 (source):

    async def execute_many(
        self, query: typing.Union[ClauseElement, str], values: list
    ) -> None:
        queries = [self._build_query(query, values_set) for values_set in values]
        async with self._query_lock:
            await self._connection.execute_many(queries)

注意它调用了_build_query()方法(source):

    @staticmethod
    def _build_query(
        query: typing.Union[ClauseElement, str], values: dict = None
    ) -> ClauseElement:
        if isinstance(query, str):
            query = text(query)

            return query.bindparams(**values) if values is not None else query
        elif values:
            return query.values(**values)

        return query

由于您没有传递 str 查询,而是传递值,控制进入 elif values: 条件处理,其中单个值的字典被解压缩到 .values() 方法中关于您的查询(Update.values())。这实质上使得它试图编译的查询是这样的:

query = (
    User.update()
    .where(User.c.id == bindparam("_id"))
    .values(score=bindparam("score"))
    .values(score=2, _id=1)
)

第二个 values 子句导致新的 Update 具有新的绑定参数,这些参数试图为 score_id 设置值。这会导致查询编译失败,因为 table.

上没有 _id

所以重现错误的 MCVE 确实是这样的:

from sqlalchemy.dialects import postgresql

User.update().values(score=2, _id=1).compile(dialect=postgresql.dialect())

其中加注:

Traceback (most recent call last):
  File ".\main.py", line 31, in <module>
    User.update().values(score=2, _id=1).compile(dialect=postgresql.dialect())
  File "<string>", line 1, in <lambda>
  File "C:\Users\peter\Documents\git\Whosebug668615-sqalchemy-update-bindparam-primary-key\.venv\lib\site-packages\sqlalchemy\sql\elements.py", line 462, in compile
    return self._compiler(dialect, bind=bind, **kw)
  File "C:\Users\peter\Documents\git\Whosebug668615-sqalchemy-update-bindparam-primary-key\.venv\lib\site-packages\sqlalchemy\sql\elements.py", line 468, in _compiler
    return dialect.statement_compiler(dialect, self, **kw)
  File "C:\Users\peter\Documents\git\Whosebug668615-sqalchemy-update-bindparam-primary-key\.venv\lib\site-packages\sqlalchemy\sql\compiler.py", line 571, in __init__
    Compiled.__init__(self, dialect, statement, **kwargs)
  File "C:\Users\peter\Documents\git\Whosebug668615-sqalchemy-update-bindparam-primary-key\.venv\lib\site-packages\sqlalchemy\sql\compiler.py", line 319, in __init__
    self.string = self.process(self.statement, **compile_kwargs)
  File "C:\Users\peter\Documents\git\Whosebug668615-sqalchemy-update-bindparam-primary-key\.venv\lib\site-packages\sqlalchemy\sql\compiler.py", line 350, in process
    return obj._compiler_dispatch(self, **kwargs)
  File "C:\Users\peter\Documents\git\Whosebug668615-sqalchemy-update-bindparam-primary-key\.venv\lib\site-packages\sqlalchemy\sql\visitors.py", line 92, in _compiler_dispatch
    return meth(self, **kw)
  File "C:\Users\peter\Documents\git\Whosebug668615-sqalchemy-update-bindparam-primary-key\.venv\lib\site-packages\sqlalchemy\sql\compiler.py", line 2569, in visit_update
    self, update_stmt, crud.ISUPDATE, **kw
  File "C:\Users\peter\Documents\git\Whosebug668615-sqalchemy-update-bindparam-primary-key\.venv\lib\site-packages\sqlalchemy\sql\crud.py", line 62, in _setup_crud_params
    return _get_crud_params(compiler, stmt, **kw)
  File "C:\Users\peter\Documents\git\Whosebug668615-sqalchemy-update-bindparam-primary-key\.venv\lib\site-packages\sqlalchemy\sql\crud.py", line 177, in _get_crud_params
    % (", ".join("%s" % c for c in check))
sqlalchemy.exc.CompileError: Unconsumed column names: _id

为了总结这个问题,您构建了一个查询,其中绑定参数传递给 Update.where()Update.values()。然后,您将该查询和您的值传递给 Database.execute_many(),在那里它们将您的值列表的各个元素解压缩到对您的查询的第二次调用 Update.values() 中,该查询将您的查询替换为尝试设置值的查询_id 列不存在。

Is there any solution other than updating each row individullay?

好吧,当使用 sqlalchemy 引擎和查询时,查询工作得很好:

# using a sqlalchemy engine
engine.execute(query, values)

否则,应该做的是将查询作为字符串发送到 Database.execute_many(),因为这意味着查询将在 _build_query() 方法的 if isinstance(query, str): 部分处理,这将避免对查询进行第二次 .values() 调用:

db.execute_many(str(query), values)