Re: Converter for decimal.Decimal (again)
Manlio Perillo <[email protected]>
| Newsgroups | gmane.comp.python.db.pysqlite.user |
|---|---|
| Message-ID | <[email protected]> |
Manlio Perillo ha scritto:
> 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.
> [...]
> 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).
>
Well, there is no need to use that BLOG_NUMERIC.
You need to add the detect_types option to the create_engine function
and to define a converter for NUMERIC that just returns the original string.
db = create_engine('sqlite:///',
connect_args={'detect_types': sqlite.PARSE_DECLTYPES}
)
sqlite.register_converter("NUMERIC", lambda s: s)
Then make sure to add a space in the col_spec
def get_col_spec(self):
# Make sure to add a space after the first string
return 'NUMERIC (%(precision)s, %(length)s)' % {'precision':
self.precision, 'length' : self.length}
Of course you can do all the job in the converter and the adapter, just
make sure to add the space after 'NUMERIC' (since SQLAlchemy does not
add it, maybe this is a bug).
Regards Manlio Perillo