Automap

Define an extension to the sqlalchemy.ext.declarative systemwhich automatically generates mapped classes and relationships from a databaseschema, typically though not necessarily one which is reflected.

New in version 0.9.1: Added sqlalchemy.ext.automap.

It is hoped that the AutomapBase system provides a quickand modernized solution to the problem that the very famousSQLSoupalso tries to solve, that of generating a quick and rudimentary objectmodel from an existing database on the fly. By addressing the issue strictlyat the mapper configuration level, and integrating fully with existingDeclarative class techniques, AutomapBase seeks to providea well-integrated approach to the issue of expediently auto-generating ad-hocmappings.

Basic Use

The simplest usage is to reflect an existing database into a new model.We create a new AutomapBase class in a similar manner as to howwe create a declarative base class, using automap_base().We then call AutomapBase.prepare() on the resulting base class,asking it to reflect the schema and produce mappings:

  1. from sqlalchemy.ext.automap import automap_base
  2. from sqlalchemy.orm import Session
  3. from sqlalchemy import create_engine
  4.  
  5. Base = automap_base()
  6.  
  7. # engine, suppose it has two tables 'user' and 'address' set up
  8. engine = create_engine("sqlite:///mydatabase.db")
  9.  
  10. # reflect the tables
  11. Base.prepare(engine, reflect=True)
  12.  
  13. # mapped classes are now created with names by default
  14. # matching that of the table name.
  15. User = Base.classes.user
  16. Address = Base.classes.address
  17.  
  18. session = Session(engine)
  19.  
  20. # rudimentary relationships are produced
  21. session.add(Address(email_address="foo@bar.com", user=User(name="foo")))
  22. session.commit()
  23.  
  24. # collection-based relationships are by default named
  25. # "<classname>_collection"
  26. print (u1.address_collection)

Above, calling AutomapBase.prepare() while passing along theAutomapBase.prepare.reflect parameter indicates that theMetaData.reflect() method will be called on this declarative baseclasses’ MetaData collection; then, each viableTable within the MetaData will get a new mapped classgenerated automatically. The ForeignKeyConstraint objects whichlink the various tables together will be used to produce new, bidirectionalrelationship() objects between classes. The classes and relationshipsfollow along a default naming scheme that we can customize. At this point,our basic mapping consisting of related User and Address classes isready to use in the traditional way.

Note

By viable, we mean that for a table to be mapped, it mustspecify a primary key. Additionally, if the table is detected as beinga pure association table between two other tables, it will not be directlymapped and will instead be configured as a many-to-many table betweenthe mappings for the two referring tables.

Generating Mappings from an Existing MetaData

We can pass a pre-declared MetaData object to automap_base().This object can be constructed in any way, including programmatically, froma serialized file, or from itself being reflected usingMetaData.reflect(). Below we illustrate a combination of reflection andexplicit table declaration:

  1. from sqlalchemy import create_engine, MetaData, Table, Column, ForeignKey
  2. from sqlalchemy.ext.automap import automap_base
  3. engine = create_engine("sqlite:///mydatabase.db")
  4.  
  5. # produce our own MetaData object
  6. metadata = MetaData()
  7.  
  8. # we can reflect it ourselves from a database, using options
  9. # such as 'only' to limit what tables we look at...
  10. metadata.reflect(engine, only=['user', 'address'])
  11.  
  12. # ... or just define our own Table objects with it (or combine both)
  13. Table('user_order', metadata,
  14. Column('id', Integer, primary_key=True),
  15. Column('user_id', ForeignKey('user.id'))
  16. )
  17.  
  18. # we can then produce a set of mappings from this MetaData.
  19. Base = automap_base(metadata=metadata)
  20.  
  21. # calling prepare() just sets up mapped classes and relationships.
  22. Base.prepare()
  23.  
  24. # mapped classes are ready
  25. User, Address, Order = Base.classes.user, Base.classes.address,\
  26. Base.classes.user_order

Specifying Classes Explicitly

The sqlalchemy.ext.automap extension allows classes to be definedexplicitly, in a way similar to that of the DeferredReflection class.Classes that extend from AutomapBase act like regular declarativeclasses, but are not immediately mapped after their construction, and areinstead mapped when we call AutomapBase.prepare(). TheAutomapBase.prepare() method will make use of the classes we’veestablished based on the table name we use. If our schema contains tablesuser and address, we can define one or both of the classes to be used:

  1. from sqlalchemy.ext.automap import automap_base
  2. from sqlalchemy import create_engine
  3.  
  4. # automap base
  5. Base = automap_base()
  6.  
  7. # pre-declare User for the 'user' table
  8. class User(Base):
  9. __tablename__ = 'user'
  10.  
  11. # override schema elements like Columns
  12. user_name = Column('name', String)
  13.  
  14. # override relationships too, if desired.
  15. # we must use the same name that automap would use for the
  16. # relationship, and also must refer to the class name that automap will
  17. # generate for "address"
  18. address_collection = relationship("address", collection_class=set)
  19.  
  20. # reflect
  21. engine = create_engine("sqlite:///mydatabase.db")
  22. Base.prepare(engine, reflect=True)
  23.  
  24. # we still have Address generated from the tablename "address",
  25. # but User is the same as Base.classes.User now
  26.  
  27. Address = Base.classes.address
  28.  
  29. u1 = session.query(User).first()
  30. print (u1.address_collection)
  31.  
  32. # the backref is still there:
  33. a1 = session.query(Address).first()
  34. print (a1.user)

Above, one of the more intricate details is that we illustrated overridingone of the relationship() objects that automap would have created.To do this, we needed to make sure the names match up with what automapwould normally generate, in that the relationship name would beUser.address_collection and the name of the class referred to, fromautomap’s perspective, is called address, even though we are referring toit as Address within our usage of this class.

Overriding Naming Schemes

sqlalchemy.ext.automap is tasked with producing mapped classes andrelationship names based on a schema, which means it has decision points in howthese names are determined. These three decision points are provided usingfunctions which can be passed to the AutomapBase.prepare() method, andare known as classname_for_table(),name_for_scalar_relationship(),and name_for_collection_relationship(). Any or all of thesefunctions are provided as in the example below, where we use a “camel case”scheme for class names and a “pluralizer” for collection names using theInflect package:

  1. import re
  2. import inflect
  3.  
  4. def camelize_classname(base, tablename, table):
  5. "Produce a 'camelized' class name, e.g. "
  6. "'words_and_underscores' -> 'WordsAndUnderscores'"
  7.  
  8. return str(tablename[0].upper() + \
  9. re.sub(r'_([a-z])', lambda m: m.group(1).upper(), tablename[1:]))
  10.  
  11. _pluralizer = inflect.engine()
  12. def pluralize_collection(base, local_cls, referred_cls, constraint):
  13. "Produce an 'uncamelized', 'pluralized' class name, e.g. "
  14. "'SomeTerm' -> 'some_terms'"
  15.  
  16. referred_name = referred_cls.__name__
  17. uncamelized = re.sub(r'[A-Z]',
  18. lambda m: "_%s" % m.group(0).lower(),
  19. referred_name)[1:]
  20. pluralized = _pluralizer.plural(uncamelized)
  21. return pluralized
  22.  
  23. from sqlalchemy.ext.automap import automap_base
  24.  
  25. Base = automap_base()
  26.  
  27. engine = create_engine("sqlite:///mydatabase.db")
  28.  
  29. Base.prepare(engine, reflect=True,
  30. classname_for_table=camelize_classname,
  31. name_for_collection_relationship=pluralize_collection
  32. )

From the above mapping, we would now have classes User and Address,where the collection from User to Address is calledUser.addresses:

  1. User, Address = Base.classes.User, Base.classes.Address
  2.  
  3. u1 = User(addresses=[Address(email="foo@bar.com")])

Relationship Detection

The vast majority of what automap accomplishes is the generation ofrelationship() structures based on foreign keys. The mechanismby which this works for many-to-one and one-to-many relationships is asfollows:

  • A given Table, known to be mapped to a particular class,is examined for ForeignKeyConstraint objects.

  • From each ForeignKeyConstraint, the remote Tableobject present is matched up to the class to which it is to be mapped,if any, else it is skipped.

  • As the ForeignKeyConstraint we are examining corresponds to areference from the immediate mapped class, the relationship will be set upas a many-to-one referring to the referred class; a correspondingone-to-many backref will be created on the referred class referringto this class.

  • If any of the columns that are part of the ForeignKeyConstraintare not nullable (e.g. nullable=False), acascade keyword argumentof all, delete-orphan will be added to the keyword arguments tobe passed to the relationship or backref. If theForeignKeyConstraint reports thatForeignKeyConstraint.ondeleteis set to CASCADE for a not null or SET NULL for a nullableset of columns, the option passive_deletesflag is set to True in the set of relationship keyword arguments.Note that not all backends support reflection of ON DELETE.

New in version 1.0.0: - automap will detect non-nullable foreign keyconstraints when producing a one-to-many relationship and establisha default cascade of all, delete-orphan if so; additionally,if the constraint specifies ForeignKeyConstraint.ondeleteof CASCADE for non-nullable or SET NULL for nullable columns,the passive_deletes=True option is also added.

Custom Relationship Arguments

The AutomapBase.prepare.generate_relationship hook can be usedto add parameters to relationships. For most cases, we can make use of theexisting automap.generate_relationship() function to returnthe object, after augmenting the given keyword dictionary with our ownarguments.

Below is an illustration of how to sendrelationship.cascade andrelationship.passive_deletesoptions along to all one-to-many relationships:

  1. from sqlalchemy.ext.automap import generate_relationship
  2.  
  3. def _gen_relationship(base, direction, return_fn,
  4. attrname, local_cls, referred_cls, **kw):
  5. if direction is interfaces.ONETOMANY:
  6. kw['cascade'] = 'all, delete-orphan'
  7. kw['passive_deletes'] = True
  8. # make use of the built-in function to actually return
  9. # the result.
  10. return generate_relationship(base, direction, return_fn,
  11. attrname, local_cls, referred_cls, **kw)
  12.  
  13. from sqlalchemy.ext.automap import automap_base
  14. from sqlalchemy import create_engine
  15.  
  16. # automap base
  17. Base = automap_base()
  18.  
  19. engine = create_engine("sqlite:///mydatabase.db")
  20. Base.prepare(engine, reflect=True,
  21. generate_relationship=_gen_relationship)

Many-to-Many relationships

sqlalchemy.ext.automap will generate many-to-many relationships, e.g.those which contain a secondary argument. The process for producing theseis as follows:

  • A given Table is examined for ForeignKeyConstraintobjects, before any mapped class has been assigned to it.

  • If the table contains two and exactly two ForeignKeyConstraintobjects, and all columns within this table are members of these twoForeignKeyConstraint objects, the table is assumed to be a“secondary” table, and will not be mapped directly.

  • The two (or one, for self-referential) external tables to which theTable refers to are matched to the classes to which they will bemapped, if any.

  • If mapped classes for both sides are located, a many-to-many bi-directionalrelationship() / backref() pair is created between the twoclasses.

  • The override logic for many-to-many works the same as that of one-to-many/many-to-one; the generate_relationship() function is called uponto generate the structures and existing attributes will be maintained.

Relationships with Inheritance

sqlalchemy.ext.automap will not generate any relationships betweentwo classes that are in an inheritance relationship. That is, with twoclasses given as follows:

  1. class Employee(Base):
  2. __tablename__ = 'employee'
  3. id = Column(Integer, primary_key=True)
  4. type = Column(String(50))
  5. __mapper_args__ = {
  6. 'polymorphic_identity':'employee', 'polymorphic_on': type
  7. }
  8.  
  9. class Engineer(Employee):
  10. __tablename__ = 'engineer'
  11. id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
  12. __mapper_args__ = {
  13. 'polymorphic_identity':'engineer',
  14. }

The foreign key from Engineer to Employee is used not for arelationship, but to establish joined inheritance between the two classes.

Note that this means automap will not generate any relationshipsfor foreign keys that link from a subclass to a superclass. If a mappinghas actual relationships from subclass to superclass as well, thoseneed to be explicit. Below, as we have two separate foreign keysfrom Engineer to Employee, we need to set up both the relationshipwe want as well as the inherit_condition, as these are not thingsSQLAlchemy can guess:

  1. class Employee(Base):
  2. __tablename__ = 'employee'
  3. id = Column(Integer, primary_key=True)
  4. type = Column(String(50))
  5.  
  6. __mapper_args__ = {
  7. 'polymorphic_identity':'employee', 'polymorphic_on':type
  8. }
  9.  
  10. class Engineer(Employee):
  11. __tablename__ = 'engineer'
  12. id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
  13. favorite_employee_id = Column(Integer, ForeignKey('employee.id'))
  14.  
  15. favorite_employee = relationship(Employee,
  16. foreign_keys=favorite_employee_id)
  17.  
  18. __mapper_args__ = {
  19. 'polymorphic_identity':'engineer',
  20. 'inherit_condition': id == Employee.id
  21. }

Handling Simple Naming Conflicts

In the case of naming conflicts during mapping, override any ofclassname_for_table(), name_for_scalar_relationship(),and name_for_collection_relationship() as needed. For example, ifautomap is attempting to name a many-to-one relationship the same as anexisting column, an alternate convention can be conditionally selected. Givena schema:

  1. CREATE TABLE table_a (
  2. id INTEGER PRIMARY KEY
  3. );
  4.  
  5. CREATE TABLE table_b (
  6. id INTEGER PRIMARY KEY,
  7. table_a INTEGER,
  8. FOREIGN KEY(table_a) REFERENCES table_a(id)
  9. );

The above schema will first automap the table_a table as a class namedtable_a; it will then automap a relationship onto the class for table_bwith the same name as this related class, e.g. table_a. Thisrelationship name conflicts with the mapping column table_b.table_a,and will emit an error on mapping.

We can resolve this conflict by using an underscore as follows:

  1. def name_for_scalar_relationship(base, local_cls, referred_cls, constraint):
  2. name = referred_cls.__name__.lower()
  3. local_table = local_cls.__table__
  4. if name in local_table.columns:
  5. newname = name + "_"
  6. warnings.warn(
  7. "Already detected name %s present. using %s" %
  8. (name, newname))
  9. return newname
  10. return name
  11.  
  12.  
  13. Base.prepare(engine, reflect=True,
  14. name_for_scalar_relationship=name_for_scalar_relationship)

Alternatively, we can change the name on the column side. The columnsthat are mapped can be modified using the technique described atNaming Columns Distinctly from Attribute Names, by assigning the column explicitlyto a new name:

  1. Base = automap_base()
  2.  
  3. class TableB(Base):
  4. __tablename__ = 'table_b'
  5. _table_a = Column('table_a', ForeignKey('table_a.id'))
  6.  
  7. Base.prepare(engine, reflect=True)

Using Automap with Explicit Declarations

As noted previously, automap has no dependency on reflection, and can makeuse of any collection of Table objects within a MetaDatacollection. From this, it follows that automap can also be usedgenerate missing relationships given an otherwise complete model that fullydefines table metadata:

  1. from sqlalchemy.ext.automap import automap_base
  2. from sqlalchemy import Column, Integer, String, ForeignKey
  3.  
  4. Base = automap_base()
  5.  
  6. class User(Base):
  7. __tablename__ = 'user'
  8.  
  9. id = Column(Integer, primary_key=True)
  10. name = Column(String)
  11.  
  12. class Address(Base):
  13. __tablename__ = 'address'
  14.  
  15. id = Column(Integer, primary_key=True)
  16. email = Column(String)
  17. user_id = Column(ForeignKey('user.id'))
  18.  
  19. # produce relationships
  20. Base.prepare()
  21.  
  22. # mapping is complete, with "address_collection" and
  23. # "user" relationships
  24. a1 = Address(email='u1')
  25. a2 = Address(email='u2')
  26. u1 = User(address_collection=[a1, a2])
  27. assert a1.user is u1

Above, given mostly complete User and Address mappings, theForeignKey which we defined on Address.user_id allowed abidirectional relationship pair Address.user andUser.address_collection to be generated on the mapped classes.

Note that when subclassing AutomapBase,the AutomapBase.prepare() method is required; if not called, the classeswe’ve declared are in an un-mapped state.

API Reference

  • sqlalchemy.ext.automap.automapbase(_declarative_base=None, **kw)
  • Produce a declarative automap base.

This function produces a new base class that is a product of theAutomapBase class as well a declarative base produced bydeclarative.declarative_base().

All parameters other than declarative_base are keyword argumentsthat are passed directly to the declarative.declarative_base()function.

  • class sqlalchemy.ext.automap.AutomapBase
  • Base class for an “automap” schema.

The AutomapBase class can be compared to the “declarative base”class that is produced by the declarative.declarative_base()function. In practice, the AutomapBase class is always usedas a mixin along with an actual declarative base.

A new subclassable AutomapBase is typically instantiatedusing the automap_base() function.

See also

Automap

  • classes = None
  • An instance of util.Properties containing classes.

This object behaves much like the .c collection on a table. Classesare present under the name they were given, e.g.:

  1. Base = automap_base()
  2. Base.prepare(engine=some_engine, reflect=True)
  3.  
  4. User, Address = Base.classes.User, Base.classes.Address
  • classmethod prepare(engine=None, reflect=False, schema=None, classname_for_table=, collection_class=, name_for_scalar_relationship=, name_for_collection_relationship=, generate_relationship=)
  • Extract mapped classes and relationships from the MetaData andperform mappings.

When present in conjunction with theAutomapBase.prepare.reflect flag, is passed toMetaData.reflect() to indicate the primary schema where tablesshould be reflected from. When omitted, the default schema in useby the database connection is used.

New in version 1.1.

  • sqlalchemy.ext.automap.classnamefor_table(_base, tablename, table)
  • Return the class name that should be used, given the nameof a table.

The default implementation is:

  1. return str(tablename)

Alternate implementations can be specified using theAutomapBase.prepare.classname_for_tableparameter.

  • Parameters
    • base – the AutomapBase class doing the prepare.

    • tablename – string name of the Table.

    • table – the Table object itself.

  • Returns

a string class name.

Note

In Python 2, the string used for the class name must be anon-Unicode object, e.g. a str() object. The .name attributeof Table is typically a Python unicode subclass, so thestr() function should be applied to this name, after accounting forany non-ASCII characters.

  • sqlalchemy.ext.automap.namefor_scalar_relationship(_base, local_cls, referred_cls, constraint)
  • Return the attribute name that should be used to refer from oneclass to another, for a scalar object reference.

The default implementation is:

  1. return referred_cls.__name__.lower()

Alternate implementations can be specified using theAutomapBase.prepare.name_for_scalar_relationshipparameter.

  • Parameters
    • base – the AutomapBase class doing the prepare.

    • local_cls – the class to be mapped on the local side.

    • referred_cls – the class to be mapped on the referring side.

    • constraint – the ForeignKeyConstraint that is beinginspected to produce this relationship.

  • sqlalchemy.ext.automap.namefor_collection_relationship(_base, local_cls, referred_cls, constraint)
  • Return the attribute name that should be used to refer from oneclass to another, for a collection reference.

The default implementation is:

  1. return referred_cls.__name__.lower() + "_collection"

Alternate implementationscan be specified using theAutomapBase.prepare.name_for_collection_relationshipparameter.

  • Parameters
    • base – the AutomapBase class doing the prepare.

    • local_cls – the class to be mapped on the local side.

    • referred_cls – the class to be mapped on the referring side.

    • constraint – the ForeignKeyConstraint that is beinginspected to produce this relationship.

  • sqlalchemy.ext.automap.generaterelationship(_base, direction, return_fn, attrname, local_cls, referred_cls, **kw)
  • Generate a relationship() or backref() on behalf of twomapped classes.

An alternate implementation of this function can be specified using theAutomapBase.prepare.generate_relationship parameter.

The default implementation of this function is as follows:

  1. if return_fn is backref:
  2. return return_fn(attrname, **kw)
  3. elif return_fn is relationship:
  4. return return_fn(referred_cls, **kw)
  5. else:
  6. raise TypeError("Unknown relationship function: %s" % return_fn)
  • Parameters
    • base – the AutomapBase class doing the prepare.

    • direction – indicate the “direction” of the relationship; this willbe one of ONETOMANY, MANYTOONE, MANYTOMANY.

    • return_fn – the function that is used by default to create therelationship. This will be either relationship() orbackref(). The backref() function’s result will be used toproduce a new relationship() in a second step, so it is criticalthat user-defined implementations correctly differentiate between the twofunctions, if a custom relationship function is being used.

    • attrname – the attribute name to which this relationship is beingassigned. If the value of generate_relationship.return_fn isthe backref() function, then this name is the name that is beingassigned to the backref.

    • local_cls – the “local” class to which this relationship or backrefwill be locally present.

    • referred_cls – the “referred” class to which the relationship orbackref refers to.

    • **kw – all additional keyword arguments are passed along to thefunction.

  • Returns

  • a relationship() or backref() construct, as dictatedby the generate_relationship.return_fn parameter.