expression.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:pyetje 作者: rorlika 项目源码 文件源码
def type_coerce(expr, type_):
    """Coerce the given expression into the given type,
    on the Python side only.

    :func:`.type_coerce` is roughly similar to :func:`.cast`, except no
    "CAST" expression is rendered - the given type is only applied towards
    expression typing and against received result values.

    e.g.::

        from sqlalchemy.types import TypeDecorator
        import uuid

        class AsGuid(TypeDecorator):
            impl = String

            def process_bind_param(self, value, dialect):
                if value is not None:
                    return str(value)
                else:
                    return None

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

        conn.execute(
            select([type_coerce(mytable.c.ident, AsGuid)]).\\
                    where(
                        type_coerce(mytable.c.ident, AsGuid) ==
                        uuid.uuid3(uuid.NAMESPACE_URL, 'bar')
                    )
        )

    """
    type_ = sqltypes.to_instance(type_)

    if hasattr(expr, '__clause_element__'):
        return type_coerce(expr.__clause_element__(), type_)
    elif isinstance(expr, BindParameter):
        bp = expr._clone()
        bp.type = type_
        return bp
    elif not isinstance(expr, Visitable):
        if expr is None:
            return null()
        else:
            return literal(expr, type_=type_)
    else:
        return Label(None, expr, type_=type_)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号