Composite Column Types

Sets of columns can be associated with a single user-defined datatype. The ORM provides a single attribute which represents the group of columns using the class you provide.

A simple example represents pairs of columns as a Point object. Point represents such a pair as .x and .y:

  1. class Point(object):
  2. def __init__(self, x, y):
  3. self.x = x
  4. self.y = y
  5. def __composite_values__(self):
  6. return self.x, self.y
  7. def __repr__(self):
  8. return "Point(x=%r, y=%r)" % (self.x, self.y)
  9. def __eq__(self, other):
  10. return isinstance(other, Point) and \
  11. other.x == self.x and \
  12. other.y == self.y
  13. def __ne__(self, other):
  14. return not self.__eq__(other)

The requirements for the custom datatype class are that it have a constructor which accepts positional arguments corresponding to its column format, and also provides a method __composite_values__() which returns the state of the object as a list or tuple, in order of its column-based attributes. It also should supply adequate __eq__() and __ne__() methods which test the equality of two instances.

We will create a mapping to a table vertices, which represents two points as x1/y1 and x2/y2. These are created normally as Column objects. Then, the composite() function is used to assign new attributes that will represent sets of columns via the Point class:

  1. from sqlalchemy import Column, Integer
  2. from sqlalchemy.orm import composite
  3. from sqlalchemy.ext.declarative import declarative_base
  4. Base = declarative_base()
  5. class Vertex(Base):
  6. __tablename__ = 'vertices'
  7. id = Column(Integer, primary_key=True)
  8. x1 = Column(Integer)
  9. y1 = Column(Integer)
  10. x2 = Column(Integer)
  11. y2 = Column(Integer)
  12. start = composite(Point, x1, y1)
  13. end = composite(Point, x2, y2)

A classical mapping above would define each composite() against the existing table:

  1. mapper_registry.map_imperatively(Vertex, vertices_table, properties={
  2. 'start':composite(Point, vertices_table.c.x1, vertices_table.c.y1),
  3. 'end':composite(Point, vertices_table.c.x2, vertices_table.c.y2),
  4. })

We can now persist and use Vertex instances, as well as query for them, using the .start and .end attributes against ad-hoc Point instances:

  1. >>> v = Vertex(start=Point(3, 4), end=Point(5, 6))
  2. >>> session.add(v)
  3. >>> q = session.query(Vertex).filter(Vertex.start == Point(3, 4))
  4. sql>>> print(q.first().start)
  5. BEGIN (implicit)
  6. INSERT INTO vertices (x1, y1, x2, y2) VALUES (?, ?, ?, ?)
  7. (3, 4, 5, 6)
  8. SELECT vertices.id AS vertices_id,
  9. vertices.x1 AS vertices_x1,
  10. vertices.y1 AS vertices_y1,
  11. vertices.x2 AS vertices_x2,
  12. vertices.y2 AS vertices_y2
  13. FROM vertices
  14. WHERE vertices.x1 = ? AND vertices.y1 = ?
  15. LIMIT ? OFFSET ?
  16. (3, 4, 1, 0)
  17. Point(x=3, y=4)
Object NameDescription

composite(class_, attrs, *kwargs)

Return a composite column-based property for use with a Mapper.

function sqlalchemy.orm.``composite(class_, \attrs, **kwargs*)

Return a composite column-based property for use with a Mapper.

See the mapping documentation section Composite Column Types for a full usage example.

The MapperProperty returned by composite() is the CompositeProperty.

  • Parameters

    • class_ – The “composite type” class, or any classmethod or callable which will produce a new instance of the composite object given the column values in order.

    • *cols – List of Column objects to be mapped.

    • active_history=False – When True, indicates that the “previous” value for a scalar attribute should be loaded when replaced, if not already loaded. See the same flag on column_property().

    • group – A group name for this property when marked as deferred.

    • deferred – When True, the column property is “deferred”, meaning that it does not load immediately, and is instead loaded when the attribute is first accessed on an instance. See also deferred().

    • comparator_factory – a class which extends Comparator which provides custom SQL clause generation for comparison operations.

    • doc – optional string that will be applied as the doc on the class-bound descriptor.

    • info – Optional data dictionary which will be populated into the MapperProperty.info attribute of this object.

Tracking In-Place Mutations on Composites

In-place changes to an existing composite value are not tracked automatically. Instead, the composite class needs to provide events to its parent object explicitly. This task is largely automated via the usage of the MutableComposite mixin, which uses events to associate each user-defined composite object with all parent associations. Please see the example in Establishing Mutability on Composites.

Redefining Comparison Operations for Composites

The “equals” comparison operation by default produces an AND of all corresponding columns equated to one another. This can be changed using the comparator_factory argument to composite(), where we specify a custom Comparator class to define existing or new operations. Below we illustrate the “greater than” operator, implementing the same expression that the base “greater than” does:

  1. from sqlalchemy.orm.properties import CompositeProperty
  2. from sqlalchemy import sql
  3. class PointComparator(CompositeProperty.Comparator):
  4. def __gt__(self, other):
  5. """redefine the 'greater than' operation"""
  6. return sql.and_(*[a>b for a, b in
  7. zip(self.__clause_element__().clauses,
  8. other.__composite_values__())])
  9. class Vertex(Base):
  10. ___tablename__ = 'vertices'
  11. id = Column(Integer, primary_key=True)
  12. x1 = Column(Integer)
  13. y1 = Column(Integer)
  14. x2 = Column(Integer)
  15. y2 = Column(Integer)
  16. start = composite(Point, x1, y1,
  17. comparator_factory=PointComparator)
  18. end = composite(Point, x2, y2,
  19. comparator_factory=PointComparator)

Nesting Composites

Composite objects can be defined to work in simple nested schemes, by redefining behaviors within the composite class to work as desired, then mapping the composite class to the full length of individual columns normally. Typically, it is convenient to define separate constructors for user-defined use and generate-from-row use. Below we reorganize the Vertex class to itself be a composite object, which is then mapped to a class HasVertex:

  1. from sqlalchemy.orm import composite
  2. class Point(object):
  3. def __init__(self, x, y):
  4. self.x = x
  5. self.y = y
  6. def __composite_values__(self):
  7. return self.x, self.y
  8. def __repr__(self):
  9. return "Point(x=%r, y=%r)" % (self.x, self.y)
  10. def __eq__(self, other):
  11. return isinstance(other, Point) and \
  12. other.x == self.x and \
  13. other.y == self.y
  14. def __ne__(self, other):
  15. return not self.__eq__(other)
  16. class Vertex(object):
  17. def __init__(self, start, end):
  18. self.start = start
  19. self.end = end
  20. @classmethod
  21. def _generate(self, x1, y1, x2, y2):
  22. """generate a Vertex from a row"""
  23. return Vertex(
  24. Point(x1, y1),
  25. Point(x2, y2)
  26. )
  27. def __composite_values__(self):
  28. return \
  29. self.start.__composite_values__() + \
  30. self.end.__composite_values__()
  31. class HasVertex(Base):
  32. __tablename__ = 'has_vertex'
  33. id = Column(Integer, primary_key=True)
  34. x1 = Column(Integer)
  35. y1 = Column(Integer)
  36. x2 = Column(Integer)
  37. y2 = Column(Integer)
  38. vertex = composite(Vertex._generate, x1, y1, x2, y2)

We can then use the above mapping as:

  1. hv = HasVertex(vertex=Vertex(Point(1, 2), Point(3, 4)))
  2. s.add(hv)
  3. s.commit()
  4. hv = s.query(HasVertex).filter(
  5. HasVertex.vertex == Vertex(Point(1, 2), Point(3, 4))).first()
  6. print(hv.vertex.start)
  7. print(hv.vertex.end)