the func.XYZ() construct returns an object that is untyped in most cases, meaning SQLAlchemy has no opinion about the data that’s returned by the database. This type can be specified using “type_=<sometype>”.
However, that should not be necessary for sum() - there’s a small subset of known SQL functions for which we assign a fixed type. sum() is actually one of them, and should be using the same type as that of the given expression. So if you hand it a Column with type Numeric(asdecimal=True), that will be the return type of the func, and the dialect-specific logic will take effect.
A test case (below) confirms this is the case for sum() - the type of column is maintained, whether asdecimal is True or False, succeeds on both MySQL and SQLite. If you’re using some function other than sum() which isn’t one of the known types, then you need to add type_=<yourtype> to it, like func.myfunc(table.c.column, type_=Float(asdecimal=True)).
from sqlalchemy import func, Table, Column, MetaData, Float, select, create_engine
from decimal import Decimal
# create a table with a Float column not using decimal.
m = MetaData()
t = Table('t', m, Column('data', Float))
dburl = "sqlite://"
#dburl = "mysql://scott:tiger@localhost/test"
e = create_engine(dburl, echo=True)
m.drop_all(e)
m.create_all(e)
e.execute(t.insert(), data=45.67)
# now let's query func.sum() using a Float with asdecimal:
m2 = MetaData()
t_with_decimal = Table('t', m2, Column('data', Float(asdecimal=True)))
# with the Float column, we get float
assert isinstance(
e.scalar(select([func.sum(t.c.data)])),
float
)
# with the Float(asdecimal=True) column, we get Decimal
assert isinstance(
e.scalar(select([func.sum(t_with_decimal.c.data)])),
Decimal
)
>
>
> Cheers,
> Robert
>
> --
> You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to
sqlalchemy+...@googlegroups.com.
> To post to this group, send email to
sqlal...@googlegroups.com.
> Visit this group at
http://groups.google.com/group/sqlalchemy.
> For more options, visit
https://groups.google.com/groups/opt_out.