From d3333ec637ecf090bb2eae3a2dcc1975f3ab6a40 Mon Sep 17 00:00:00 2001 From: Kyle McCullough Date: Wed, 14 Mar 2012 11:43:09 -0500 Subject: [PATCH] Support for defining CompositeTypes with custom inner types. E.g.: Given the following custom type: Class MyDateType(CassandraType): @staticmethod def pack(v, *args, **kwargs): """custom pack implementation""" @staticmethod def unpack(v, *args, **kwargs): """custom unpack implementation""" You can now do the following: c = CompositeType(MyDateType, LongType) And the following: cf = ColumnFamily(pool, 'MyColumnFamily') cf.column_name_class = CompositeType(MyDateType, LongType) --- pycassa/marshal.py | 18 ++++++++++++++---- pycassa/types.py | 8 ++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/pycassa/marshal.py b/pycassa/marshal.py index 2aedb554..4742b306 100644 --- a/pycassa/marshal.py +++ b/pycassa/marshal.py @@ -74,8 +74,13 @@ def _to_timestamp(v): converted = v * 1e3 return long(converted) -def get_composite_packer(typestr): - packers = map(packer_for, _get_inner_types(typestr)) +def get_composite_packer(typestr=None, composite_type=None): + assert (typestr or composite_type), "Must provide typestr or " + \ + "CompositeType instance" + if typestr: + packers = map(packer_for, _get_inner_types(typestr)) + elif composite_type: + packers = [c.pack for c in composite_type.components] if _have_struct: len_packer = _short_packer.pack @@ -104,8 +109,13 @@ def pack_composite(items, slice_start=None): return pack_composite -def get_composite_unpacker(typestr): - unpackers = map(unpacker_for, _get_inner_types(typestr)) +def get_composite_unpacker(typestr=None, composite_type=None): + assert (typestr or composite_type), "Must provide typestr or " + \ + "CompositeType instance" + if typestr: + unpackers = map(unpacker_for, _get_inner_types(typestr)) + elif composite_type: + unpackers = [c.unpack for c in composite_type.components] if _have_struct: len_unpacker = lambda v: _short_packer.unpack(v)[0] diff --git a/pycassa/types.py b/pycassa/types.py index 4ad2dec0..94fce973 100644 --- a/pycassa/types.py +++ b/pycassa/types.py @@ -226,3 +226,11 @@ def __init__(self, *components): def __str__(self): return "CompositeType(" + ", ".join(map(str, self.components)) + ")" + + @property + def pack(self): + return marshal.get_composite_packer(composite_type=self) + + @property + def unpack(self): + return marshal.get_composite_unpacker(composite_type=self)