1

将 SQLAlchemyliteraldate对象一起使用时,会引发异常。

演示

# Versions used:
# databases 0.4.1
# asyncpg 0.21.0
# SQLAlchemy 1.3.20

import asyncio
from datetime import date
from databases import Database
from sqlalchemy import select, literal

database = Database('postgresql://user:password@localhost/dbname')

async def run():
    await database.connect()

    today = date.today()
    query = select([
        literal(today).label('today') # <-- The problem is here
    ])

    await database.fetch_all(query)

    await database.disconnect()

loop = asyncio.get_event_loop()
loop.run_until_complete(run())

例外

Traceback (most recent call last):
  File "test.py", line 21, in <module>
    loop.run_until_complete(run())
  File "C:\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
    return future.result()
  File "test.py", line 14, in run
    rows = await database.fetch_all(query)
  File "C:\Python38\lib\site-packages\databases\core.py", line 140, in fetch_all
    return await connection.fetch_all(query, values)
  File "C:\Python38\lib\site-packages\databases\core.py", line 239, in fetch_all
    return await self._connection.fetch_all(built_query)
  File "C:\Python38\lib\site-packages\databases\backends\postgres.py", line 160, in fetch_all
    rows = await self._connection.fetch(query, *args)
  File "C:\Python38\lib\site-packages\asyncpg\connection.py", line 443, in fetch
    return await self._execute(query, args, 0, timeout)
  File "C:\Python38\lib\site-packages\asyncpg\connection.py", line 1445, in _execute
    result, _ = await self.__execute(
  File "C:\Python38\lib\site-packages\asyncpg\connection.py", line 1454, in __execute
    return await self._do_execute(query, executor, timeout)
  File "C:\Python38\lib\site-packages\asyncpg\connection.py", line 1476, in _do_execute
    result = await executor(stmt, None)
  File "asyncpg\protocol\protocol.pyx", line 178, in bind_execute
  File "asyncpg\protocol\prepared_stmt.pyx", line 160, in asyncpg.protocol.protocol.PreparedStatementState._encode_bind_msg
asyncpg.exceptions.DataError: invalid input for query argument $1: datetime.date(2020, 11, 30) (expected str, got date)

为什么它期待一个str?

编辑

它适用于 MySQL,所以我的猜测是问题出在asyncpg中。

4

1 回答 1

1

这当然是关于 asyncpg 框架的一个问题,因为数据库驱动程序正在处理数据库文字和 python 对象之间的类型转换。

第 169 行prepared_stmt.pyx 中_encode_bind_msg的函数抛出了您的错误:

raise exceptions.DataError(
    'invalid input for query argument'
    ' ${n}: {v} ({msg})'.format(
        n=idx + 1, v=value_repr, msg=e)) from e

asyncpg 文档表明,由于输入无效,此错误被假定为编码问题。

我相信可以在此处找到用于 postgres 的 asyncpg 编解码器,并且在pgproto.date_encode功能期间可能会出现问题。

您应该尝试根据asyncpg API-reference手动设置编码/解码,以进一步验证此问题的根源。

于 2020-11-30T10:54:32.787 回答