<commit_before># ext/automap.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php

"""Define an extension to the :mod:`sqlalchemy.ext.declarative` system
which automatically generates mapped classes and relationships from a database
schema, typically though not necessarily one which is reflected.

.. versionadded:: 0.9.1 Added :mod:`sqlalchemy.ext.automap`.

.. note::

    The :mod:`sqlalchemy.ext.automap` extension should be considered
    **experimental** as of 0.9.1.   Featureset and API stability is
    not guaranteed at this time.

It is hoped that the :class:`.AutomapBase` system provides a quick
and modernized solution to the problem that the very famous
`SQLSoup <https://sqlsoup.readthedocs.org/en/latest/>`_
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, :class:`.AutomapBase` seeks to provide
a well-integrated approach to the issue of expediently auto-generating ad-hoc
mappings.


Basic Use
=========

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

    from sqlalchemy.ext.automap import automap_base
    from sqlalchemy.orm import Session
    from sqlalchemy import create_engine

    Base = automap_base()

    # engine, suppose it has two tables 'user' and 'address' set up
    engine = create_engine("sqlite:///mydatabase.db")

    # reflect the tables
    Base.prepare(engine, reflect=True)

    # mapped classes are now created with names by default
    # matching that of the table name.
    User = Base.classes.user
    Address = Base.classes.address

    session = Session(engine)

    # rudimentary relationships are produced
    session.add(Address(email_address="<EMAIL>", user=User(name="foo")))
    session.commit()

    # collection-based relationships are by default named
    # "<classname>_collection"
    print (u1.address_collection)

Above, calling :meth:`.AutomapBase.prepare` while passing along the
:paramref:`.AutomapBase.prepare.reflect` parameter indicates that the
:meth:`.MetaData.reflect` method will be called on this declarative base
classes' :class:`.MetaData` collection; then, each viable
:class:`.Table` within the :class:`.MetaData` will get a new mapped class
generated automatically.  The :class:`.ForeignKeyConstraint` objects which
link the various tables together will be used to produce new, bidirectional
:func:`.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.

Generating Mappings from an Existing MetaData
=============================================

We can pass a pre-declared :class:`.MetaData` object to :func:`.automap_base`.
This object can be constructed in any way, including programmatically, from
a serialized file, or from itself being reflected using
:meth:`.MetaData.reflect`.  Below we illustrate a combination of reflection and
explicit table declaration::

    from sqlalchemy import create_engine, MetaData, Table, Column, ForeignKey
    engine = create_engine("sqlite:///mydatabase.db")

    # produce our own MetaData object
    metadata = MetaData()

    # we can reflect it ourselves from a database, using options
    # such as 'only' to limit what tables we look at...
    metadata.reflect(engine, only=['user', 'address'])

    # ... or just define our own Table objects with it (or combine both)
    Table('user_order', metadata,
                    Column('id', Integer, primary_key=True),
                    Column('user_id', ForeignKey('user.id'))
                )

    # we can then produce a set of mappings from this MetaData.
    Base = automap_base(metadata=metadata)

    # calling prepare() just sets up mapped classes and relationships.
    Base.prepare()<commit_msg>- add boldface for "viable" plus a note describing that this refers to the table having a primary key.  fixes #3398<commit_after># ext/automap.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php

"""Define an extension to the :mod:`sqlalchemy.ext.declarative` system
which automatically generates mapped classes and relationships from a database
schema, typically though not necessarily one which is reflected.

.. versionadded:: 0.9.1 Added :mod:`sqlalchemy.ext.automap`.

.. note::

    The :mod:`sqlalchemy.ext.automap` extension should be considered
    **experimental** as of 0.9.1.   Featureset and API stability is
    not guaranteed at this time.

It is hoped that the :class:`.AutomapBase` system provides a quick
and modernized solution to the problem that the very famous
`SQLSoup <https://sqlsoup.readthedocs.org/en/latest/>`_
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, :class:`.AutomapBase` seeks to provide
a well-integrated approach to the issue of expediently auto-generating ad-hoc
mappings.


Basic Use
=========

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

    from sqlalchemy.ext.automap import automap_base
    from sqlalchemy.orm import Session
    from sqlalchemy import create_engine

    Base = automap_base()

    # engine, suppose it has two tables 'user' and 'address' set up
    engine = create_engine("sqlite:///mydatabase.db")

    # reflect the tables
    Base.prepare(engine, reflect=True)

    # mapped classes are now created with names by default
    # matching that of the table name.
    User = Base.classes.user
    Address = Base.classes.address

    session = Session(engine)

    # rudimentary relationships are produced
    session.add(Address(email_address="<EMAIL>", user=User(name="foo")))
    session.commit()

    # collection-based relationships are by default named
    # "<classname>_collection"
    print (u1.address_collection)

Above, calling :meth:`.AutomapBase.prepare` while passing along the
:paramref:`.AutomapBase.prepare.reflect` parameter indicates that the
:meth:`.MetaData.reflect` method will be called on this declarative base
classes' :class:`.MetaData` collection; then, each **viable**
:class:`.Table` within the :class:`.MetaData` will get a new mapped class
generated automatically.  The :class:`.ForeignKeyConstraint` objects which
link the various tables together will be used to produce new, bidirectional
:func:`.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 :class:`.MetaData` object to :func:`.automap_base`.
This object can be constructed in any way, including programmatically, from
a serialized file, or from itself being reflected using
:meth:`.MetaData.reflect`.  Below we illustrate a combination of reflection and
explicit table declaration::

    from sqlalchemy import create_engine, MetaData, Table, Column, ForeignKey
    engine = create_engine("sqlite:///mydatabase.db")

    # produce our own MetaData object
    metadata = MetaData()

    # we can reflect it ourselves from a database, using options
    # such as 'only' to limit what tables we look at...
    metadata.reflect(engine, only=['user', 'address'])

    # ... or just define our own Table objects with it (or combine both)
    Table('user_order', metadata,
                    Column('id', Integer, primary_key=True),
                    Column('user_id', ForeignKey('user.id'))
                )

    # we can then produce a set of mappings from this MetaData.
    Base = automap_base(metadata=metadata)

    # calling prepare() just sets up mapped classes and relationships.
    Base.prepare()
{'fraction_non_alphanumeric': 0.09087017018088409, 'fraction_numerical': 0.003639088087338114, 'mean_word_length': 4.111597374179431, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1528679', 'n_tokens_mistral': 2512, 'n_tokens_neox': 2393, 'n_words': 1074}