1. Michael Bayer
  2. sqlalchemy
  3. Issues


Issue #114 resolved

"types" document needs update to "custom types"

Michael Bayer
repo owner created an issue

the TypeDecorator class is deprecated and is no longer needed. the "types.myt" document should be updated.

The TypeEngine base class now looks like:

class TypeEngine(object):
    def get_col_spec(self):
    def convert_bind_param(self, value, engine):
    def convert_result_value(self, value, engine):
    def set_impl(self, impltype):
    def get_constructor_args(self):
    def adapt_args(self):

so a user-defined type would want to override usually get_col_spec to provide the "type" used in a CREATE TABLE statement, and convert_bind_param/convert_result_value to provide translation rules for bind parameters and result-set values.

get_constructor_args should return a dictionary consisting of the arguments sent to this TypeEngine object's init method. such as, if the object were constructed like:

    t = MyType(foo=5, blahblah=7)

then get_constructor_args should return:

     {'foo':5, 'blahblah':7}

it is only necessary to override get_constructor_args if you are overriding one of the existing types such as String, Date, Float, etc. AND you are providing new constructor arguments for your type.

so a typical overridden type, like overriding Binary with a Pickle type, looks like:

import cPickle

class PickleType(types.Binary):
      def __init__(self, protocol=cPickle.HIGHEST_PROTOCOL):
           """allows the pickle protocol to be specified"""
           self.protocol = protocol
      def convert_result_value(self, value, engine):
            return cpickle.loads(super(PickleType, self).convert_result_value(value, engine), self.protocol)
      def convert_bind_param(self, value, engine):
            return super(PickleType, self).convert_bind_param(cpickle.dumps(value, self.protocol), engine)
      def get_constructor_args(self):
            return {'protocol':self.protocol}

and a totally custom user type, to store a hypothetical object called a CrazyObject, looks like:

    class MyType(TypeEngine):
       def __init__(param=12):
           self.param = param
       def get_col_spec(self):
            return "MY_CRAZY_TYPE(%d)" % self.param
       def convert_bind_param(self, value, engine):
            return "%s:%d - %s" % (value.param1, value.count, value.param2)
       def convert_result_value(self, value, engine):
            return CrazyObject.parse_from_string(value)
       def set_impl(self, impltype):

Comments (1)

  1. Log in to comment