Automap

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

    It is hoped that the system provides a quick and modernized solution to the problem that the very famous SQLSoup also tries to solve, that of generating a quick and rudimentary object model from an existing database on the fly. By addressing the issue strictly at the mapper configuration level, and integrating fully with existing Declarative class techniques, seeks to provide a well-integrated approach to the issue of expediently auto-generating ad-hoc mappings.

    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 how we create a declarative base class, using . We then call AutomapBase.prepare() on the resulting base class, asking it to reflect the schema and produce mappings:

    Above, calling while passing along the AutomapBase.prepare.reflect parameter indicates that the method will be called on this declarative base classes’ MetaData collection; then, each viable within the MetaData will get a new mapped class generated automatically. The objects which link the various tables together will be used to produce new, bidirectional relationship() objects between classes. The classes and relationships follow along a default naming scheme that we can customize. At this point, our basic mapping consisting of related User and Address classes is ready to use in the traditional way.

    Note

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

    Generating Mappings from an Existing MetaData

    We can pass a pre-declared MetaData object to . This object can be constructed in any way, including programmatically, from a serialized file, or from itself being reflected using MetaData.reflect(). Below we illustrate a combination of reflection and explicit 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. # produce our own MetaData object
    5. metadata = MetaData()
    6. # we can reflect it ourselves from a database, using options
    7. # such as 'only' to limit what tables we look at...
    8. metadata.reflect(engine, only=['user', 'address'])
    9. # ... or just define our own Table objects with it (or combine both)
    10. Table('user_order', metadata,
    11. Column('id', Integer, primary_key=True),
    12. Column('user_id', ForeignKey('user.id'))
    13. )
    14. # we can then produce a set of mappings from this MetaData.
    15. Base = automap_base(metadata=metadata)
    16. # calling prepare() just sets up mapped classes and relationships.
    17. Base.prepare()
    18. # mapped classes are ready
    19. User, Address, Order = Base.classes.user, Base.classes.address,\
    20. Base.classes.user_order

    The extension allows classes to be defined explicitly, in a way similar to that of the DeferredReflection class. Classes that extend from act like regular declarative classes, but are not immediately mapped after their construction, and are instead mapped when we call AutomapBase.prepare(). The method will make use of the classes we’ve established based on the table name we use. If our schema contains tables user 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. # automap base
    4. Base = automap_base()
    5. # pre-declare User for the 'user' table
    6. class User(Base):
    7. __tablename__ = 'user'
    8. # override schema elements like Columns
    9. user_name = Column('name', String)
    10. # override relationships too, if desired.
    11. # we must use the same name that automap would use for the
    12. # relationship, and also must refer to the class name that automap will
    13. # generate for "address"
    14. address_collection = relationship("address", collection_class=set)
    15. # reflect
    16. engine = create_engine("sqlite:///mydatabase.db")
    17. Base.prepare(engine, reflect=True)
    18. # we still have Address generated from the tablename "address",
    19. # but User is the same as Base.classes.User now
    20. Address = Base.classes.address
    21. u1 = session.query(User).first()
    22. print (u1.address_collection)
    23. # the backref is still there:
    24. a1 = session.query(Address).first()
    25. print (a1.user)

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

    Overriding Naming Schemes

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

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

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

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

    The vast majority of what automap accomplishes is the generation of relationship() structures based on foreign keys. The mechanism by which this works for many-to-one and one-to-many relationships is as follows:

    1. A given , known to be mapped to a particular class, is examined for objects.

    2. From each , the remote Table object present is matched up to the class to which it is to be mapped, if any, else it is skipped.

    3. As the we are examining corresponds to a reference from the immediate mapped class, the relationship will be set up as a many-to-one referring to the referred class; a corresponding one-to-many backref will be created on the referred class referring to this class.

    4. If any of the columns that are part of the ForeignKeyConstraint are not nullable (e.g. nullable=False), a keyword argument of all, delete-orphan will be added to the keyword arguments to be passed to the relationship or backref. If the ForeignKeyConstraint reports that is set to CASCADE for a not null or SET NULL for a nullable set of columns, the option relationship.passive_deletes flag 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 key constraints when producing a one-to-many relationship and establish a default cascade of all, delete-orphan if so; additionally, if the constraint specifies of CASCADE for non-nullable or SET NULL for nullable columns, the passive_deletes=True option is also added.

    5. The names of the relationships are determined using the AutomapBase.prepare.name_for_scalar_relationship and callable functions. It is important to note that the default relationship naming derives the name from the the actual class name. If you’ve given a particular class an explicit name by declaring it, or specified an alternate class naming scheme, that’s the name from which the relationship name will be derived.

    6. The classes are inspected for an existing mapped property matching these names. If one is detected on one side, but none on the other side, AutomapBase attempts to create a relationship on the missing side, then uses the parameter in order to point the new relationship to the other side.

    7. In the usual case where no relationship is on either side, AutomapBase.prepare() produces a on the “many-to-one” side and matches it to the other using the relationship.backref parameter.

    8. Production of the and optionally the backref() is handed off to the function, which can be supplied by the end-user in order to augment the arguments passed to relationship() or or to make use of custom implementations of these functions.

    The AutomapBase.prepare.generate_relationship hook can be used to add parameters to relationships. For most cases, we can make use of the existing function to return the object, after augmenting the given keyword dictionary with our own arguments.

    Below is an illustration of how to send relationship.cascade and options along to all one-to-many relationships:

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

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

    1. A given is examined for ForeignKeyConstraint objects, before any mapped class has been assigned to it.

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

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

    4. If mapped classes for both sides are located, a many-to-many bi-directional relationship() / pair is created between the two classes.

    5. 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 upon to generate the structures and existing attributes will be maintained.

    will not generate any relationships between two classes that are in an inheritance relationship. That is, with two classes given as follows:

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

    Note that this means automap will not generate any relationships for foreign keys that link from a subclass to a superclass. If a mapping has actual relationships from subclass to superclass as well, those need to be explicit. Below, as we have two separate foreign keys from Engineer to Employee, we need to set up both the relationship we want as well as the inherit_condition, as these are not things SQLAlchemy can guess:

    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. class Engineer(Employee):
    9. __tablename__ = 'engineer'
    10. id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    11. favorite_employee_id = Column(Integer, ForeignKey('employee.id'))
    12. favorite_employee = relationship(Employee,
    13. foreign_keys=favorite_employee_id)
    14. __mapper_args__ = {
    15. 'polymorphic_identity':'engineer',
    16. 'inherit_condition': id == Employee.id
    17. }

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

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

    The above schema will first automap the table_a table as a class named table_a; it will then automap a relationship onto the class for table_b with the same name as this related class, e.g. table_a. This relationship 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 name
    10. Base.prepare(engine, reflect=True,
    11. name_for_scalar_relationship=name_for_scalar_relationship)

    Alternatively, we can change the name on the column side. The columns that are mapped can be modified using the technique described at , by assigning the column explicitly to a new name:

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

    Using Automap with Explicit Declarations

    As noted previously, automap has no dependency on reflection, and can make use of any collection of objects within a MetaData collection. From this, it follows that automap can also be used generate missing relationships given an otherwise complete model that fully defines table metadata:

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

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

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

    The MetaData and objects support an event hook DDLEvents.column_reflect() that may be used to intercept the information reflected about a database column before the object is constructed. For example if we wanted to map columns using a naming convention such as "attr_<columnname>", the event could be applied as:

    New in version 1.4.0b2: the DDLEvents.column_reflect() event may be applied to a object.

    See also

    DDLEvents.column_reflect()

    - in the ORM mapping documentation

    API Reference

    function sqlalchemy.ext.automap.``automap_base(declarative_base=None, \*kw*)

    Produce a declarative automap base.

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

    All parameters other than declarative_base are keyword arguments that are passed directly to the declarative_base() function.

    • Parameters

      • declarative_base – an existing class produced by declarative_base(). When this is passed, the function no longer invokes declarative_base() itself, and all other keyword arguments are ignored.

      • **kw – keyword arguments are passed along to declarative_base().

    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_base() function. In practice, the class is always used as a mixin along with an actual declarative base.

    A new subclassable AutomapBase is typically instantiated using the function.

    See also

    Automap

    • attribute classes = None

      An instance of Properties containing classes.

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

      1. Base = automap_base()
      2. Base.prepare(engine=some_engine, reflect=True)
      3. User, Address = Base.classes.User, Base.classes.Address
    • method sqlalchemy.ext.automap.AutomapBase.classmethod prepare(autoload_with=None, engine=None, reflect=False, schema=None, classname_for_table=None, collection_class=None, name_for_scalar_relationship=None, name_for_collection_relationship=None, generate_relationship=None, reflection_options={})

      Extract mapped classes and relationships from the and perform mappings.

      • Parameters

        • engine

          an Engine or with which to perform schema reflection, if specified. If the AutomapBase.prepare.reflect argument is False, this object is not used.

          Deprecated since version 1.4: The parameter is deprecated and will be removed in a future release. Please use the AutomapBase.prepare.autoload_with parameter.

        • reflect

          if True, the method is called on the MetaData associated with this . The Engine passed via will be used to perform the reflection if present; else, the MetaData should already be bound to some engine else the operation will fail.

          Deprecated since version 1.4: The parameter is deprecated and will be removed in a future release. Reflection is enabled when AutomapBase.prepare.autoload_with is passed.

        • classname_for_table – callable function which will be used to produce new class names, given a table name. Defaults to .

        • name_for_scalar_relationship – callable function which will be used to produce relationship names for scalar relationships. Defaults to name_for_scalar_relationship().

        • name_for_collection_relationship – callable function which will be used to produce relationship names for collection-oriented relationships. Defaults to .

        • generate_relationship – callable function which will be used to actually generate relationship() and constructs. Defaults to generate_relationship().

        • collection_class – the Python collection class that will be used when a new object is created that represents a collection. Defaults to list.

        • schema

          When present in conjunction with the AutomapBase.prepare.reflect flag, is passed to to indicate the primary schema where tables should be reflected from. When omitted, the default schema in use by the database connection is used.

          New in version 1.1.

        • When present, this dictionary of options will be passed to MetaData.reflect() to supply general reflection-specific options like only and/or dialect-specific options like oracle_resolve_synonyms.

          New in version 1.4.

    function sqlalchemy.ext.automap.``classname_for_table(base, tablename, table)

    Return the class name that should be used, given the name of a table.

    The default implementation is:

    1. return str(tablename)

    Alternate implementations can be specified using the parameter.

    • Parameters

      • base – the AutomapBase class doing the prepare.

      • tablename – string name of the .

      • table – the Table object itself.

      Returns

      a string class name.

      Note

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

    function sqlalchemy.ext.automap.``name_for_scalar_relationship(base, local_cls, referred_cls, constraint)

    Return the attribute name that should be used to refer from one class to another, for a scalar object reference.

    The default implementation is:

    1. return referred_cls.__name__.lower()

    Alternate implementations can be specified using the AutomapBase.prepare.name_for_scalar_relationship parameter.

    • Parameters

      • base – the 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 being inspected to produce this relationship.

    function sqlalchemy.ext.automap.``name_for_collection_relationship(base, local_cls, referred_cls, constraint)

    Return the attribute name that should be used to refer from one class to another, for a collection reference.

    The default implementation is:

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

    Alternate implementations can be specified using the parameter.

    • 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 that is being inspected to produce this relationship.

    function sqlalchemy.ext.automap.``generate_relationship(base, direction, return_fn, attrname, local_cls, referred_cls, \*kw*)

    Generate a relationship() or on behalf of two mapped classes.

    An alternate implementation of this function can be specified using the AutomapBase.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 class doing the prepare.

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

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

      • attrname – the attribute name to which this relationship is being assigned. If the value of is the backref() function, then this name is the name that is being assigned to the backref.

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

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

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

      a or construct, as dictated by the parameter.