SQLAlchemy attribute annotations

Annotations are strings attached to attributes that serve as a programmer reference on how those attributes are meant to be used. They can be used to indicate that a column’s value should be immutable and should never change, or that it’s a cached copy of a value from another source that can be safely discarded in case of a conflict.

This module’s exports may be imported via coaster.sqlalchemy.

Sample usage:

from coaster.db import db
from coaster.sqlalchemy import annotation_wrapper, immutable

natural_key = annotation_wrapper('natural_key', "Natural key for this model")

class MyModel(db.Model):
    __tablename__ = 'my_model'
    id = immutable(db.Column(db.Integer, primary_key=True))
    name = natural_key(db.Column(db.Unicode(250), unique=True))

    @classmethod
    def get(cls, **kwargs):
        for key in kwargs:
            if key in cls.__column_annotations__[natural_key.name]:
                return cls.query.filter_by(**{key: kwargs[key]}).one_or_none()

Annotations are saved to the model’s class as a __column_annotations__ dictionary, mapping annotation names to a list of attribute names, and to a reverse lookup __column_annotations_by_attr__ of attribute names to annotations.

coaster.sqlalchemy.annotations.annotation_wrapper(annotation, doc=None)[source]

Define an annotation, which can be applied to attributes in a database model.