簡體   English   中英

如何使用 SQLAlchemy TypeDecorators 編譯原始 SQL

[英]How to use SQLAlchemy TypeDecorators to compile raw SQL

我有一個使用uuid.UUID的 SqlAlchemy Query 對象:

import uuid
import sqlalchemy

foreign_uuid = '822965bb-c67e-47ee-ad12-a3b060ef79ae'
qry = Query(MyModel).filter(MyOtherModel.uuid == uuid.UUID(foreign_uuid))

現在我想從 SQLAlchemy 獲取原始 postgresql:

qry.statement.compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}))

這給出了以下錯誤: NotImplementedError: Don't know how to literal-quote value UUID('822965bb-c67e-47ee-ad12-a3b060ef79ae')

這似乎是因為 SqlAlchemy 只知道如何處理基本類型。 該文檔建議使用TypeDecorator ,甚至為 GUID 提供了一個:

from sqlalchemy.dialects.postgresql import UUID
import uuid

class GUID(TypeDecorator):
    """Platform-independent GUID type.

    Uses PostgreSQL's UUID type, otherwise uses
    CHAR(32), storing as stringified hex values.

    """
    impl = CHAR

    def load_dialect_impl(self, dialect):
        if dialect.name == 'postgresql':
            return dialect.type_descriptor(UUID())
        else:
            return dialect.type_descriptor(CHAR(32))

    def process_bind_param(self, value, dialect):
        if value is None:
            return value
        elif dialect.name == 'postgresql':
            return str(value)
        else:
            if not isinstance(value, uuid.UUID):
                return "%.32x" % uuid.UUID(value).int
            else:
                # hexstring
                return "%.32x" % value.int

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        else:
            if not isinstance(value, uuid.UUID):
                value = uuid.UUID(value)
            return value

但是它沒有說明如何使用這個TypeDecorator 我需要在我的模型中以某種方式引用它嗎? 我是否以某種方式使其可用於.statement.compile調用?

您使用裝飾類型作為列類型。 另一組文檔更清楚地解釋了它: https : //docs.sqlalchemy.org/en/14/faq/sqlexpressions.html#faq-sql-expression-string

   from sqlalchemy import TypeDecorator, Integer

 
   class MyFancyType(TypeDecorator):
       impl = Integer

       def process_literal_param(self, value, dialect):
           return "my_fancy_formatting(%s)" % value

   from sqlalchemy import Table, Column, MetaData

      tab = Table('mytable', MetaData(), Column('x', MyFancyType()))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM