SQLAlchemyFactory
===================

Basic usage is like other factories

.. literalinclude:: /examples/library_factories/sqlalchemy_factory/test_example_1.py
    :caption: Declaring a factory for a SQLAlchemy model
    :language: python

.. note::
    The examples here require SQLAlchemy 2 to be installed. The factory itself supports both 1.4 and 2.

Configuration
------------------------------

By default, relationships will not be set. This can be overridden via ``__set_relationships__``.

.. literalinclude:: /examples/library_factories/sqlalchemy_factory/test_example_2.py
    :caption: Setting relationships
    :language: python

.. note::
    In general, foreign keys are not automatically generated by ``.build``. This can be resolved by setting the fields yourself and/or using ``create_sync``/ ``create_async`` so models can be added to a SQLA session so these are set.


Persistence
------------------------------

A handler is provided to allow persistence. This can be used by setting ``__session__`` attribute on a factory.

.. literalinclude:: /examples/library_factories/sqlalchemy_factory/test_example_3.py
    :caption: Using persistence
    :language: python

By default, this will add generated models to the session and then commit. This can be customised further by setting ``__sync_persistence__``.

Similarly for ``__async_session__`` and ``create_async``.


Adding global overrides
------------------------------

By combining the above and using other settings, a global base factory can be set up for other factories.

.. literalinclude:: /examples/library_factories/sqlalchemy_factory/test_example_4.py
    :caption: Using persistence
    :language: python


API reference
------------------------------
Full API docs are available :class:`here <polyfactory.factories.sqlalchemy_factory.SQLAlchemyFactory>`.
