Files
tryton/trytond/model/fields/numeric.py
T

62 lines
2.0 KiB
Python
Raw Normal View History

2014-12-02 12:54:01 +01:00
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
2013-09-06 22:32:37 +02:00
from decimal import Decimal
from sql import Query, Expression, Cast, Literal, Select, CombiningQuery, As
2009-02-03 18:58:25 +01:00
from ... import backend
2013-09-06 22:32:37 +02:00
from .field import SQLType
from .float import Float
2009-02-03 18:58:25 +01:00
class SQLite_Cast(Cast):
def as_(self, output_name):
# Use PARSE_COLNAMES instead of CAST for final column
return As(self.expression, '%s [NUMERIC]' % output_name)
2009-02-03 18:58:25 +01:00
class Numeric(Float):
2009-03-01 13:37:31 +01:00
'''
2009-09-13 15:37:11 +02:00
Define a numeric field (``decimal``).
2009-03-01 13:37:31 +01:00
'''
2009-02-03 18:58:25 +01:00
_type = 'numeric'
2013-09-06 22:32:37 +02:00
@staticmethod
def sql_format(value):
if isinstance(value, (Query, Expression)):
return value
if value is None:
return None
if isinstance(value, (int, long)):
value = Decimal(str(value))
assert isinstance(value, Decimal)
return value
def sql_type(self):
db_type = backend.name()
2013-09-06 22:32:37 +02:00
if db_type == 'mysql':
return SQLType('DECIMAL', 'DECIMAL(65, 30)')
return SQLType('NUMERIC', 'NUMERIC')
def sql_column(self, table):
column = super(Numeric, self).sql_column(table)
db_type = backend.name()
if db_type == 'sqlite':
# Must be casted as Decimal is stored as bytes
column = SQLite_Cast(column, self.sql_type().base)
return column
def _domain_value(self, operator, value):
value = super(Numeric, self)._domain_value(operator, value)
db_type = backend.name()
if db_type == 'sqlite':
if isinstance(value, (Select, CombiningQuery)):
return value
# Must be casted as Decimal is adapted to bytes
type_ = self.sql_type().base
if operator in ('in', 'not in'):
return [Cast(Literal(v), type_) for v in value]
2014-06-13 19:11:44 +02:00
elif value is not None:
return Cast(Literal(value), type_)
return value