如何在CAST操作中包装列

Gra*_*art 10 python sqlalchemy

我有一个带有表的MSSQL数据库,我无法更改,只能与它进行只读(SELECT语句).我正在使用sqlalchemy.我需要做的是为每个查询自动包装CAST()SQL操作中的特定列.我想在较低级别执行此操作,因此我的代码永远不需要考虑问题.我在这个问题上解释了我这样做的原因.

我的桌子是这样的:

from sqlalchemy import Column, Integer, Sequence
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class myTable(Base):
    __tablename__ = u'mytable'
    id = Column(Integer, Sequence('table_id_seq'), primary_key=True)
    problem_field = Column(DECIMAL(12, 4), nullable=True)
Run Code Online (Sandbox Code Playgroud)

我一直在尝试使用这样的TypeDecorator:

from sqlalchemy import Column, Integer, Sequence, types
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.expression import cast

Base = declarative_base()

class CastToFloatType(types.TypeDecorator):
    '''Converts stored Decimal values to Floats via CAST operation
    '''
    impl = types.Numeric
    def column_expression(self, col):
        return cast(col, Float)

class myTable(Base):
    __tablename__ = u'mytable'
    id = Column(Integer, Sequence('table_id_seq'), primary_key=True)
    wrapped_field = Column(CastToFloatType, nullable=True)
Run Code Online (Sandbox Code Playgroud)

但它似乎没有做任何事情.

zzz*_*eek 8

我认为您需要确保至少在SQLAlchemy的0.8版本column_expression()中添加了该功能.对此代码的简单测试就是为此:

from sqlalchemy import Column, Integer, Sequence, types, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.expression import cast

Base = declarative_base()

class CastToFloatType(types.TypeDecorator):
    '''Converts stored Decimal values to Floats via CAST operation
    '''
    impl = types.Numeric
    def column_expression(self, col):
        return cast(col, Float)

class myTable(Base):
    __tablename__ = u'mytable'
    id = Column(Integer, Sequence('table_id_seq'), primary_key=True)
    wrapped_field = Column(CastToFloatType, nullable=True)

from sqlalchemy.orm import Session
s = Session()
print s.query(myTable)
Run Code Online (Sandbox Code Playgroud)

输出:

SELECT mytable.id AS mytable_id, CAST(mytable.wrapped_field AS FLOAT) AS mytable_wrapped_field 
FROM mytable
Run Code Online (Sandbox Code Playgroud)