Re: Converter for decimal.Decimal (again)
Manlio Perillo <[email protected]>
| Newsgroups | gmane.comp.python.db.pysqlite.user |
|---|---|
| Message-ID | <[email protected]> |
Antonio Valente ha scritto:
> Hi, all!
> Some months ago (in september 2006) I asked how to deal with python
> decimal.Decimal values. While adapting them is trivial (an adapter
> function must only call str(value)), converting the return values from
> sqlite is a big problem for me.
>
> If I declare a column like:
>
> DECIMAL(9,2)
>
> or such, and I register a converter function like:
>
> register_converter("DECIMAL", a_converter_function)
>
> it won't work. The call should be something like:
>
> register_converter("DECIMAL(9,2)", a_converter_function)
>
> That's not very useful, because I cannot register a converter for each
> variant of length and precision I use. The solution was to use a row
> factory.
> Now, I feel the problem again, since I use sqlalchemy and I cannot
> figure out how to use a row factory with it.
>
> Anybody can help me?
>
You should post the message on the sqlalchemy mailing list, since
SQLAlchemy has a full type system.
Here is what you need:
import decimal
from sqlalchemy import types
class Decimal(types.TypeEngine):
def __init__(self, precision=10, length=2):
self.precision = precision
self.length = length
def get_col_spec(self):
return 'BLOB_NUMERIC(%(precision)s, %(length)s)' %
{'precision': self.precision, 'length' : self.length}
def convert_bind_param(self, value, dialect):
return str(value)
def convert_result_value(self, value, dialect):
print self.precision, self.length
return decimal.Decimal(value)
I use that ugly BLOB_NUMERIC to force the type affinity to be None.
If I do not use the 'BLOG' prefix, the type affinity will be NUMERIC;
this will cause the value to be converted to a float (with a precision
loss).
> Thanks a lot
Regards Manlio Perillo