declarative — SQLAlchemy 0.6.1 Documentation

# SQLAlchemy 0.6.1 Documentation

Search:
Version: 0.6.1 Last Updated: 05/31/2010 14:48:10

# declarative

## Synopsis

SQLAlchemy object-relational configuration involves the use of `Table`, `mapper()`, and class objects to define the three areas of configuration. `declarative` allows all three types of configuration to be expressed declaratively on an individual mapped class. Regular SQLAlchemy schema elements and ORM constructs are used in most cases.

As a simple example:

    from sqlalchemy.ext.declarative import declarative_base

    Base = declarative_base()

    class SomeClass(Base):
        __tablename__ = 'some_table'
        id = Column(Integer, primary_key=True)
        name =  Column(String(50))

Above, the `declarative_base()` callable returns a new base class from which all mapped classes should inherit. When the class definition is completed, a new `Table` and `mapper` will have been generated, accessible via the `__table__` and `__mapper__` attributes on the `SomeClass` class.

## Defining Attributes

In the above example, the `Column` objects are automatically named with the name of the attribute to which they are assigned.

They can also be explicitly named, and that name does not have to be the same as name assigned on the class. The column will be assigned to the `Table` using the given name, and mapped to the class using the attribute name:

    class SomeClass(Base):
        __tablename__ = 'some_table'
        id = Column("some_table_id", Integer, primary_key=True)
        name = Column("name", String(50))

Attributes may be added to the class after its construction, and they will be added to the underlying `Table` and `mapper()` definitions as appropriate:

    SomeClass.data = Column('data', Unicode)
    SomeClass.related = relationship(RelatedInfo)

Classes which are mapped explicitly using `mapper()` can interact freely with declarative classes.

It is recommended, though not required, that all tables share the same underlying `MetaData` object, so that string-configured `ForeignKey` references can be resolved without issue.

## Association of Metadata and Engine

The `declarative_base()` base class contains a `MetaData` object where newly defined `Table` objects are collected. This is accessed via the `MetaData` class level accessor, so to create tables we can say:

    engine = create_engine('sqlite://')
    Base.metadata.create_all(engine)

The `Engine` created above may also be directly associated with the declarative base class using the `bind` keyword argument, where it will be associated with the underlying `MetaData` object and allow SQL operations involving that metadata and its tables to make use of that engine automatically:

    Base = declarative_base(bind=create_engine('sqlite://'))

Alternatively, by way of the normal `MetaData` behaviour, the `bind` attribute of the class level accessor can be assigned at any time as follows:

    Base.metadata.bind = create_engine('sqlite://')

The `declarative_base()` can also receive a pre-created `MetaData` object, which allows a declarative setup to be associated with an already existing traditional collection of `Table` objects:

    mymetadata = MetaData()
    Base = declarative_base(metadata=mymetadata)

## Configuring Relationships

Relationships to other classes are done in the usual way, with the added feature that the class specified to `relationship()` may be a string name (note that `relationship()` is only available as of SQLAlchemy 0.6beta2, and in all prior versions is known as `relation()`, including 0.5 and 0.4). The “class registry” associated with `Base` is used at mapper compilation time to resolve the name into the actual class object, which is expected to have been defined once the mapper configuration is used:

    class User(Base):
        __tablename__ = 'users'

        id = Column(Integer, primary_key=True)
        name = Column(String(50))
        addresses = relationship("Address", backref="user")

    class Address(Base):
        __tablename__ = 'addresses'

        id = Column(Integer, primary_key=True)
        email = Column(String(50))
        user_id = Column(Integer, ForeignKey('users.id'))

Column constructs, since they are just that, are immediately usable, as below where we define a primary join condition on the `Address` class using them:

    class Address(Base):
        __tablename__ = 'addresses'

        id = Column(Integer, primary_key=True)
        email = Column(String(50))
        user_id = Column(Integer, ForeignKey('users.id'))
        user = relationship(User, primaryjoin=user_id == User.id)

In addition to the main argument for `relationship()`, other arguments which depend upon the columns present on an as-yet undefined class may also be specified as strings. These strings are evaluated as Python expressions. The full namespace available within this evaluation includes all classes mapped for this declarative base, as well as the contents of the `sqlalchemy` package, including expression functions like `desc()` and `func`:

    class User(Base):
        # ....
        addresses = relationship("Address",
                             order_by="desc(Address.email)",
                             primaryjoin="Address.user_id==User.id")

As an alternative to string-based attributes, attributes may also be defined after all classes have been created. Just add them to the target class after the fact:

    User.addresses = relationship(Address,
                              primaryjoin=Address.user_id==User.id)

## Configuring Many-to-Many Relationships

There’s nothing special about many-to-many with declarative. The `secondary` argument to `relationship()` still requires a `Table` object, not a declarative class. The `Table` should share the same `MetaData` object used by the declarative base:

    keywords = Table(
        'keywords', Base.metadata,
        Column('author_id', Integer, ForeignKey('authors.id')),
        Column('keyword_id', Integer, ForeignKey('keywords.id'))
        )

    class Author(Base):
        __tablename__ = 'authors'
        id = Column(Integer, primary_key=True)
        keywords = relationship("Keyword", secondary=keywords)

You should generally not map a class and also specify its table in a many-to-many relationship, since the ORM may issue duplicate INSERT and DELETE statements.

## Defining Synonyms

Synonyms are introduced in Using Descriptors. To define a getter/setter which proxies to an underlying attribute, use `synonym()` with the `descriptor` argument:

    class MyClass(Base):
        __tablename__ = 'sometable'

        _attr = Column('attr', String)

        def _get_attr(self):
            return self._some_attr
        def _set_attr(self, attr):
            self._some_attr = attr
        attr = synonym('_attr', descriptor=property(_get_attr, _set_attr))

The above synonym is then usable as an instance attribute as well as a class-level expression construct:

    x = MyClass()
    x.attr = "some value"
    session.query(MyClass).filter(MyClass.attr == 'some other value').all()

For simple getters, the `synonym_for()` decorator can be used in conjunction with `@property`:

    class MyClass(Base):
        __tablename__ = 'sometable'

        _attr = Column('attr', String)

        @synonym_for('_attr')
        @property
        def attr(self):
            return self._some_attr

Similarly, `comparable_using()` is a front end for the `comparable_property()` ORM function:

    class MyClass(Base):
        __tablename__ = 'sometable'

        name = Column('name', String)

        @comparable_using(MyUpperCaseComparator)
        @property
        def uc_name(self):
            return self.name.upper()

## Table Configuration

Table arguments other than the name, metadata, and mapped Column arguments are specified using the `__table_args__` class attribute. This attribute accommodates both positional as well as keyword arguments that are normally sent to the `Table` constructor. The attribute can be specified in one of two forms. One is as a dictionary:

    class MyClass(Base):
        __tablename__ = 'sometable'
        __table_args__ = {'mysql_engine':'InnoDB'}

The other, a tuple of the form `(arg1, arg2, ..., {kwarg1:value, ...})`, which allows positional arguments to be specified as well (usually constraints):

    class MyClass(Base):
        __tablename__ = 'sometable'
        __table_args__ = (
                ForeignKeyConstraint(['id'], ['remote_table.id']),
                UniqueConstraint('foo'),
                {'autoload':True}
                )

Note that the keyword parameters dictionary is required in the tuple form even if empty.

As an alternative to `__tablename__`, a direct `Table` construct may be used. The `Column` objects, which in this case require their names, will be added to the mapping just like a regular mapping to a table:

    class MyClass(Base):
        __table__ = Table('my_table', Base.metadata,
            Column('id', Integer, primary_key=True),
            Column('name', String(50))
        )

## Mapper Configuration

Configuration of mappers is done with the `mapper()` function and all the possible mapper configuration parameters can be found in the documentation for that function.

`mapper()` is still used by declaratively mapped classes and keyword parameters to the function can be passed by placing them in the `__mapper_args__` class variable:

    class Widget(Base):
        __tablename__ = 'widgets'
        id = Column(Integer, primary_key=True)

        __mapper_args__ = {'extension': MyWidgetExtension()}

## Inheritance Configuration

Declarative supports all three forms of inheritance as intuitively as possible. The `inherits` mapper keyword argument is not needed as declarative will determine this from the class itself. The various “polymorphic” keyword arguments are specified using `__mapper_args__`.

### Joined Table Inheritance

Joined table inheritance is defined as a subclass that defines its own table:

    class Person(Base):
        __tablename__ = 'people'
        id = Column(Integer, primary_key=True)
        discriminator = Column('type', String(50))
        __mapper_args__ = {'polymorphic_on': discriminator}

    class Engineer(Person):
        __tablename__ = 'engineers'
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        id = Column(Integer, ForeignKey('people.id'), primary_key=True)
        primary_language = Column(String(50))

Note that above, the `Engineer.id` attribute, since it shares the same attribute name as the `Person.id` attribute, will in fact represent the `people.id` and `engineers.id` columns together, and will render inside a query as `"people.id"`. To provide the `Engineer` class with an attribute that represents only the `engineers.id` column, give it a different attribute name:

    class Engineer(Person):
        __tablename__ = 'engineers'
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        engineer_id = Column('id', Integer, ForeignKey('people.id'), primary_key=True)
        primary_language = Column(String(50))

### Single Table Inheritance

Single table inheritance is defined as a subclass that does not have its own table; you just leave out the `__table__` and `__tablename__` attributes:

    class Person(Base):
        __tablename__ = 'people'
        id = Column(Integer, primary_key=True)
        discriminator = Column('type', String(50))
        __mapper_args__ = {'polymorphic_on': discriminator}

    class Engineer(Person):
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        primary_language = Column(String(50))

When the above mappers are configured, the `Person` class is mapped to the `people` table before the `primary_language` column is defined, and this column will not be included in its own mapping. When `Engineer` then defines the `primary_language` column, the column is added to the `people` table so that it is included in the mapping for `Engineer` and is also part of the table’s full set of columns. Columns which are not mapped to `Person` are also excluded from any other single or joined inheriting classes using the `exclude_properties` mapper argument. Below, `Manager` will have all the attributes of `Person` and `Manager` but not the `primary_language` attribute of `Engineer`:

    class Manager(Person):
        __mapper_args__ = {'polymorphic_identity': 'manager'}
        golf_swing = Column(String(50))

The attribute exclusion logic is provided by the `exclude_properties` mapper argument, and declarative’s default behavior can be disabled by passing an explicit `exclude_properties` collection (empty or otherwise) to the `__mapper_args__`.

### Concrete Table Inheritance

Concrete is defined as a subclass which has its own table and sets the `concrete` keyword argument to `True`:

    class Person(Base):
        __tablename__ = 'people'
        id = Column(Integer, primary_key=True)
        name = Column(String(50))

    class Engineer(Person):
        __tablename__ = 'engineers'
        __mapper_args__ = {'concrete':True}
        id = Column(Integer, primary_key=True)
        primary_language = Column(String(50))
        name = Column(String(50))

Usage of an abstract base class is a little less straightforward as it requires usage of `polymorphic_union()`:

    engineers = Table('engineers', Base.metadata,
                    Column('id', Integer, primary_key=True),
                    Column('name', String(50)),
                    Column('primary_language', String(50))
                )
    managers = Table('managers', Base.metadata,
                    Column('id', Integer, primary_key=True),
                    Column('name', String(50)),
                    Column('golf_swing', String(50))
                )

    punion = polymorphic_union({
        'engineer':engineers,
        'manager':managers
    }, 'type', 'punion')

    class Person(Base):
        __table__ = punion
        __mapper_args__ = {'polymorphic_on':punion.c.type}

    class Engineer(Person):
        __table__ = engineers
        __mapper_args__ = {'polymorphic_identity':'engineer', 'concrete':True}

    class Manager(Person):
        __table__ = managers
        __mapper_args__ = {'polymorphic_identity':'manager', 'concrete':True}

## Mix-in Classes

A common need when using `declarative` is to share some functionality, often a set of columns, across many classes. The normal python idiom would be to put this common code into a base class and have all the other classes subclass this class.

When using `declarative`, this need is met by using a “mix-in class”. A mix-in class is one that isn’t mapped to a table and doesn’t subclass the declarative `Base`. For example:

    class MyMixin(object):

        __table_args__ = {'mysql_engine':'InnoDB'}
        __mapper_args__=dict(always_refresh=True)
        id =  Column(Integer, primary_key=True)

        def foo(self):
            return 'bar'+str(self.id)

    class MyModel(Base,MyMixin):
        __tablename__='test'
        name = Column(String(1000), nullable=False, index=True)

As the above example shows, `__table_args__` and `__mapper_args__` can both be abstracted out into a mix-in if you use common values for these across many classes.

However, particularly in the case of `__table_args__`, you may want to combine some parameters from several mix-ins with those you wish to define on the class iteself. To help with this, a `classproperty()` decorator is provided that lets you implement a class property with a function. For example:

    from sqlalchemy.util import classproperty

    class MySQLSettings:
        __table_args__ = {'mysql_engine':'InnoDB'}

    class MyOtherMixin:
        __table_args__ = {'info':'foo'}

    class MyModel(Base,MySQLSettings,MyOtherMixin):
        __tablename__='my_model'

        @classproperty
        def __table_args__(self):
            args = dict()
            args.update(MySQLSettings.__table_args__)
            args.update(MyOtherMixin.__table_args__)
            return args

        id =  Column(Integer, primary_key=True)

### Controlling table inheritance with mix-ins

The `__tablename__` attribute in conjunction with the hierarchy of the classes involved controls what type of table inheritance, if any, is configured by the declarative extension.

If the `__tablename__` is computed by a mix-in, you may need to control which classes get the computed attribute in order to get the type of table inheritance you require.

For example, if you had a mix-in that computes `__tablename__` but where you wanted to use that mix-in in a single table inheritance hierarchy, you can explicitly specify `__tablename__` as `None` to indicate that the class should not have a table mapped:

    from sqlalchemy.util import classproperty

    class Tablename:
        @classproperty
        def __tablename__(cls):
            return cls.__name__.lower()

    class Person(Base,Tablename):
        id = Column(Integer, primary_key=True)
        discriminator = Column('type', String(50))
        __mapper_args__ = {'polymorphic_on': discriminator}

    class Engineer(Person):
        __tablename__ = None
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        primary_language = Column(String(50))

Alternatively, you can make the mix-in intelligent enough to only return a `__tablename__` in the event that no table is already mapped in the inheritance hierarchy. To help with this, a `has_inherited_table()` helper function is provided that returns `True` if a parent class already has a mapped table.

As an examply, here’s a mix-in that will only allow single table inheritance:

    from sqlalchemy.util import classproperty
    from sqlalchemy.ext.declarative import has_inherited_table

    class Tablename:
        @classproperty
        def __tablename__(cls):
            if has_inherited_table(cls):
                return None
            return cls.__name__.lower()

    class Person(Base,Tablename):
        id = Column(Integer, primary_key=True)
        discriminator = Column('type', String(50))
        __mapper_args__ = {'polymorphic_on': discriminator}

    class Engineer(Person):
        __tablename__ = None
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        primary_language = Column(String(50))

If you want to use a similar pattern with a mix of single and joined table inheritance, you would need a slightly different mix-in and use it on any joined table child classes in addition to their parent classes:

    from sqlalchemy.util import classproperty
    from sqlalchemy.ext.declarative import has_inherited_table

    class Tablename:
        @classproperty
        def __tablename__(cls):
            if (decl.has_inherited_table(cls) and
                TableNameMixin not in cls.__bases__):
                return None
            return cls.__name__.lower()

    class Person(Base,Tablename):
        id = Column(Integer, primary_key=True)
        discriminator = Column('type', String(50))
        __mapper_args__ = {'polymorphic_on': discriminator}

    class Engineer(Person):
        # This is single table inheritance
        __tablename__ = None
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        primary_language = Column(String(50))

    class Manager(Person,Tablename):
        # This is joinded table inheritance
        __tablename__ = None
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        preferred_recreation = Column(String(50))

## Class Constructor

As a convenience feature, the `declarative_base()` sets a default constructor on classes which takes keyword arguments, and assigns them to the named attributes:

    e = Engineer(primary_language='python')

## Sessions

Note that `declarative` does nothing special with sessions, and is only intended as an easier way to configure mappers and `Table` objects. A typical application setup using `scoped_session()` might look like:

    engine = create_engine('postgresql://scott:tiger@localhost/test')
    Session = scoped_session(sessionmaker(autocommit=False,
                                          autoflush=False,
                                          bind=engine))
    Base = declarative_base()

Mapped instances then make usage of `Session` in the usual way.

## API Reference

`sqlalchemy.ext.declarative.` `declarative_base`(bind=None, metadata=None, mapper=None, cls=<type 'object'>, name='Base', constructor=<function __init__ at 0x42b1eb0>, metaclass=<class 'sqlalchemy.ext.declarative.DeclarativeMeta'>)

  Construct a base class for declarative class definitions.

  The new base class will be given a metaclass that produces appropriate `Table` objects and makes the appropriate `mapper()` calls based on the information provided declaratively in the class and any subclasses of the class.

  Parameters: | bind – An optional `Connectable`, will be assigned the `bind` attribute on the `MetaData` instance. metadata – An optional `MetaData` instance. All `Table` objects implicitly declared by subclasses of the base will share this MetaData. A MetaData instance will be created if none is provided. The `MetaData` instance will be available via the metadata attribute of the generated declarative base class. mapper – An optional callable, defaults to `mapper()`. Will be used to map subclasses to their Tables. cls – Defaults to `object`. A type to use as the base for the generated declarative base class. May be a class or tuple of classes. name – Defaults to `Base`. The display name for the generated class. Customizing this is not required, but can improve clarity in tracebacks and debugging. constructor – Defaults to `_declarative_constructor()`, an __init__ implementation that assigns **kwargs for declared fields and relationships to an instance. If `None` is supplied, no __init__ will be provided and construction will fall back to cls.__init__ by way of the normal Python semantics. metaclass – Defaults to `DeclarativeMeta`. A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class.

`sqlalchemy.ext.declarative.` `_declarative_constructor`(self, **kwargs)

  A simple constructor that allows initialization from kwargs.

  Sets attributes on the constructed instance using the names and values in `kwargs`.

  Only keys that are present as attributes of the instance’s class are allowed. These could be, for example, any mapped columns or relationships.

`sqlalchemy.ext.declarative.` `has_inherited_table`(cls)
  Given a class, return True if any of the classes it inherits from has a mapped table, otherwise return False.

`sqlalchemy.ext.declarative.` `synonym_for`(name, map_column=False)

  Decorator, make a Python @property a query synonym for a column.

  A decorator version of `synonym()`. The function being decorated is the ‘descriptor’, otherwise passes its arguments through to synonym():

      @synonym_for('col')
      @property
      def prop(self):
          return 'special sauce'

  The regular `synonym()` is also usable directly in a declarative setting and may be convenient for read/write properties:

      prop = synonym('col', descriptor=property(_read_prop, _write_prop))

`sqlalchemy.ext.declarative.` `comparable_using`(comparator_factory)

  Decorator, allow a Python @property to be used in query criteria.

  This is a decorator front end to `comparable_property()` that passes through the comparator_factory and the function being decorated:

      @comparable_using(MyComparatorType)
      @property
      def prop(self):
          return 'special sauce'

  The regular `comparable_property()` is also usable directly in a declarative setting and may be convenient for read/write properties:

      prop = comparable_property(MyComparatorType)

`sqlalchemy.ext.declarative.` `instrument_declarative`(cls, registry, metadata)
  Given a class, configure the class declaratively, using the given registry, which can be any dictionary, and MetaData object.