Quantcast
Channel: プログラミング
Viewing all articles
Browse latest Browse all 8686

sqlalchemyで sqlがprintできない - Screaming Loud

$
0
0

表題の通り

sqlalchemyでsqlがちゃんと想定のSQLが吐き出されているか確認したかったが、以下のようなコンパイルエラーが発生してしまった。

sqlalchemy.exc.UnsupportedCompilationError: Compiler <sqlalchemy.sql.compiler.StrSQLCompiler object at 0x107a3cb90> can't render element of type <class 'models.utils.utcnow'>: <class 'models.utils.utcnow'> construct has no default compilation handler. (Background on this error at: https://sqlalche.me/e/20/l7de)

utcnowは以下のように設定していました。

classutcnow(expression.FunctionElement):
    type = DateTime()
    inherit_cache = True@compiles(utcnow, "postgresql")
defpg_utcnow(element, compiler, **kw) -> str:
    return"TIMEZONE('utc', CURRENT_TIMESTAMP)"

実際のprintしている部分のコードはこれ

from sqlalchemy import select, update


## session は async_sessionmaker経由で作成

stmt = update(User).where(id = 1).values(name="name")
print(stmt)
await session.execute(stmt)
await session.commit()

この場合、compilesのアノテーションがついているので以下のようにcompileを使ったprintをさせる必要がありました。

from sqlalchemy.dialects import postgresql

print(stmt.compile(dialect=postgresql.dialect()))

参考リンク

Custom SQL Constructs and Compilation Extension — SQLAlchemy 2.0 Documentation

SQL Expressions — SQLAlchemy 2.0 Documentation


Viewing all articles
Browse latest Browse all 8686

Latest Images

Trending Articles