API Reference

The sqlservice package imports commonly used objects into it’s top-level namespace:

from sqlservice import (
    ModelBase,
    SQLClient,
    SQLQuery,
    as_declarative,
    declarative_base,
    destroy,
    event,
    make_identity,
    save,
    transaction)

Client

The database client module.

class sqlservice.client.SQLClient(config=None, model_class=None, query_class=<class 'sqlservice.query.SQLQuery'>, session_class=<class 'sqlalchemy.orm.session.Session'>, session_options=None, engine_options=None)

Database client for interacting with a database.

The following configuration values can be passed into a new SQLClient instance as a dict. Alternatively, this class can be subclassed and DEFAULT_CONFIG overridden with a custom defaults.

SQL_DATABASE_URI URI used to connect to the database. Defaults to sqlite://.
SQL_ECHO When True have SQLAlchemy log all SQL statements. Defaults to False.
SQL_ECHO_POOL When True have SQLAlchemy log all log all checkouts/checkins of the connection pool. Defaults to False.
SQL_ENCODING The string encoding used by SQLAlchemy for string encode/decode operations which occur within SQLAlchemy, outside of the DBAPI. Defaults to utf-8.
SQL_CONVERT_UNICODE When True it sets the default behavior of convert_unicode on the String type to True, regardless of a setting of False on an individual String type, thus causing all String -based columns to accommodate Python unicode objects.
SQL_ISOLATION_LEVEL String parameter interpreted by various dialects in order to affect the transaction isolation level of the database connection. The parameter essentially accepts some subset of these string arguments: "SERIALIZABLE", "REPEATABLE_READ", "READ_COMMITTED", "READ_UNCOMMITTED" and "AUTOCOMMIT". Behavior here varies per backend, and individual dialects should be consulted directly. Defaults to None.
SQL_POOL_SIZE The size of the database pool. Defaults to the engine’s default (usually 5).
SQL_POOL_TIMEOUT Specifies the connection timeout for the pool. Defaults to 10.
SQL_POOL_RECYCLE Number of seconds after which a connection is automatically recycled.
SQL_MAX_OVERFLOW Controls the number of connections that can be created after the pool reached its maximum size. When those additional connections are returned to the pool, they are disconnected and discarded.
SQL_AUTOCOMMIT When True, the Session does not keep a persistent transaction running, and will acquire connections from the engine on an as-needed basis, returning them immediately after their use. Defaults to False.
SQL_AUTOFLUSH When True, all query operations will issue a flush() call to the Session before proceeding. This is a convenience feature so that flush() need not be called repeatedly in order for database queries to retrieve results.
SQL_EXPIRE_ON_COMMIT When True all instances will be fully expired after each commit(), so that all attribute/object access subsequent to a completed transaction will load from the most recent database state. Defaults to True.
SQL_POOL_PRE_PING When True` will enable SQLAlchemy's connection pool “pre-ping” feature that tests connections for liveness upon each checkout. Defaults to ``False. Requires SQLAlchemy >= 1.2.
Parameters:
  • config (dict|str) – Database engine configuration options or database URI string. Defaults to None which uses an in-memory SQLite database.
  • model_class (object) – A SQLAlchemy ORM declarative base model.
  • query_class (Query, optional) – SQLAlchemy Query derived class to use as the default class when creating a new query object.
  • session_class (Session, optional) – SQLAlchemy Session derived class to use by the session maker.
  • session_options (dict, optional) – Additional session options use when creating the database session.
add

Proxy property to session.add().

add_all

Proxy property to session.add_all().

bulk_common_update(mapper, key_columns, mappings)

Perform a bulk UPDATE on common shared values among mappings. What this means is that if multiple records are being updated to the same values, then issue only a single update for that value-set using the identity of the records in the WHERE clause.

Parameters:
  • mapper – An ORM class or SQLAlchemy insert-statement object.
  • key_columns (tuple) – A tuple of SQLAlchemy columns that represent the identity of each row (typically this would be a table’s primary key values but they can be any set of columns).
  • mappings (list) – List of dict objects to update.
Returns:

list[ResultProxy]

bulk_diff_update(mapper, key_columns, previous_mappings, mappings)

Perform a bulk INSERT/UPDATE on the difference between mappings and previous_mappings such that only the values that have changed are included in the update. If a mapping in mappings doesn’t exist in previous_mappings, then it will be inclued in the bulk INSERT. The bulk INSERT will be deferred to bulk_insert(). The bulk UPDATE will be deferred to bulk_common_update().

Parameters:
  • mapper – An ORM class or SQLAlchemy insert-statement object.
  • mappings (list) – List of dict objects to update.
  • previous_mappings (list) – List of dict objects that represent the previous values of all mappings found for this update set (i.e. these are the current database records).
  • key_columns (tuple) – A tuple of SQLAlchemy columns that represent the identity of each row (typically this would be a table’s primary key values but they can be any set of columns).
Returns:

list[ResultProxy]

bulk_insert(mapper, mappings)

Perform a bulk insert into table/statement represented by mapper while utilizing a special syntax that replaces the tradtional executemany() DBAPI call with a multi-row VALUES clause for a single INSERT statement.

See bulk_insert_many() for bulk inserts using executemany().

Parameters:
  • mapper – An ORM class or SQLAlchemy insert-statement object.
  • mappings (list) – List of dict objects to insert.
Returns:

ResultProxy

bulk_insert_many(mapper, mappings)

Perform a bulk insert into table/statement represented by mapper while utilizing the executemany() DBAPI call.

See bulk_insert() for bulk inserts using a multi-row VALUES clause for a single INSERT statement.

Parameters:
  • mapper – An ORM class or SQLAlchemy insert-statement object.
  • mappings (list) – List of dict objects to insert.
Returns:

ResultProxy

bulk_insert_mappings

Proxy property to session.bulk_insert_mappings().

bulk_save_objects

Proxy property to session.bulk_save_objects().

bulk_update_mappings

Proxy property to session.bulk_update_mappings().

close

Proxy property to session.close().

close_all

Proxy property to _Session.close_all().

commit()

Commit a session transaction but rollback if an error occurs. This helps ensure that the session is not left in an unsable state.

create_all()

Create all metadata (tables, etc) contained within metadata.

create_engine(uri, options=None)

Factory function to create a database engine using config options.

Parameters:config (dict) – Database client configuration.
Returns:SQLAlchemy engine instance.
Return type:Engine
create_models_registry(model_class)

Return model registry dict with model names as keys and corresponding model classes as values.

create_session(bind, options=None, session_class=<class 'sqlalchemy.orm.session.Session'>, query_class=<class 'sqlservice.query.SQLQuery'>)

Factory function to create a scoped session using bind.

Parameters:
  • bind (Engine|Connection) – Database engine or connection instance.
  • options (dict, optional) – Session configuration options.
  • session_class (obj, optional) – Session class to use when creating new session instances. Defaults to Session.
  • query_class (obj, optional) – Query class used for session.query instances. Defaults to SQLQuery.
Returns:

SQLAlchemy session instance bound to bind.

Return type:

Session

database

Proxy property to database engine’s database name.

delete

Proxy property to session.delete().

destroy(data, model_class=None, synchronize_session=False)

Delete bulk records from data.

The data argument can be any of the following:

  • dict
  • model_class instance
  • list/tuple of dict objects
  • list/tuple of model_class instances

If a dict or list of dict is passed in, then model_class must be provided

Parameters:
  • data (mixed) – Data to delete from database.
  • synchronize_session (bool|str) – Argument passed to Query.delete.
Returns:

Number of deleted records.

Return type:

int

disconnect()

Disconnect all database sessions and connections.

drop_all()

Drop all metadata (tables, etc) contained within metadata.

execute

Proxy property to session.execute().

expire

Proxy property to session.expire().

expire_all

Proxy property to session.expire().

expunge(*instances)

Remove all instances from session.

expunge_all

Proxy property to session.expunge().

flush

Proxy property to session.flush().

get_metadata()

Return MetaData from model or raise an exception if model was never given.

invalidate

Proxy property to session.invalidate().

is_active

Proxy property to session.is_active.

is_modified

Proxy property to session.is_modified().

make_engine_options(extra_options=None)

Return engine options from config for use in sqlalchemy.create_engine.

make_session_options(extra_options=None)

Return session options from config for use in sqlalchemy.orm.sessionmaker.

merge

Proxy property to session.merge().

metadata

Return MetaData from model or None.

no_autoflush

Proxy property to session.no_autoflush().

ping()

Ping the database to check whether the connection is valid.

Returns:True when connection check passes.
Return type:bool
Raises:sqlalche.exc.SQLAlchemyError – When the connection check fails.
prepare

Proxy property to session.prepare().

prune

Proxy property to session.prune().

query

Proxy property to session.query().

reflect()

Reflect tables from database into metadata.

refresh

Proxy property to session.refresh().

remove

Proxy propery to _Session.remove().

rollback

Proxy property to session.rollback().

save(models, before=None, after=None, identity=None)

Save models into the database using insert, update, or upsert-on-primary-key.

The models argument can be any of the following:

  • Model instance
  • list/tuple of Model instances
Parameters:
  • models (mixed) – Models to save to database.
  • before (function, optional) – Function to call before each model is saved via session.add. Function should have signature before(model, is_new).
  • after (function, optional) – Function to call after each model is saved via session.add. Function should have signature after(model, is_new).
  • identity (function, optional) – Function used to return an idenity map for a given model. Function should have the signature identity(model). By default core.primary_identity_map() is used.
Returns:

If a single item passed in. list: A list of Model instaces if multiple items passed in.

Return type:

Model

scalar

Proxy property to session.scalar().

session

Proxy to threadlocal session object returned by scoped session object.

Note

Generally, the scoped session is sufficient to work with directly. However, the scoped session doesn’t provide access to the custom session class used by the session factory. This property returns an instance of our custom session class. Multiple calls to the scoped session always returns the same active theadlocal session (i.e. self._Session() is self._Session()).

tables

Return dict of table instances found in metadata with table names as keys and corresponding table objects as values.

transaction(commit=True, rollback=False, autoflush=None)

Nestable session transaction context manager where only a single commit will be issued once all contexts have been exited. If an exception occurs either at commit time or before, the transaction will be rolled back and the original exception re-raised.

Parameters:
  • commit (bool, optional) – Whether to commit the transaction or leave it open. Defaults to True.
  • rollback (bool, optional) – Whether to rollback the transaction. Defaults to False. WARNING: This overrides commit.
  • autoflush (bool, optional) – Whether to override session.autoflush. Original session.autoflush will be restored after transaction. Defaults to None which doesn’t modify session.autoflush.
Yields:

session

update_models_registry()

Update models registry as computed from model_class.

url

Proxy property to database engine’s database URL.

Query

The query module.

class sqlservice.query.SQLQuery(entities, session=None)

Extended SQLAlchemy query class.

all_entities

Return list of all entities for query.

all_model_classes

Return list of all model classes for query.

destroy(data, synchronize_session=False)

Delete bulk records identified by data.

Warning

This requires that the Query has been generated using Query(<ModelClass>); otherwise, and exception will be raised.

The data argument can be any of the following:

Parameters:
  • data (mixed) – Data to delete from database.
  • synchronize_session (bool|str) – Argument passed to Query.delete.
Returns:

Number of deleted records.

Return type:

int

Raises:

InvalidRequestError – When model_class is None.

entities

Return list of entity classes for query.

find(*criterion, **kargs)

Return list of models matching criterion.

Parameters:

*criterion (sqlaexpr, optional) – SQLA expression to filter against.

Keyword Arguments:
 
  • per_page (int, optional) – Number of results to return per page. Defaults to None (i.e. no limit).
  • page (int, optional) – Which page offset of results to return. Defaults to 1.
  • order_by (sqlaexpr, optional) – Order by expression. Defaults to None.
Returns:

List of model_class

Return type:

list

find_one(*criterion, **criterion_kargs)

Return a single model or None given criterion dict or keyword arguments.

Parameters:
  • criterion (dict, optional) – Filter-by dict.
  • **criterion_kargs (optional) – Mapping of filter-by arguments.
Returns:

When filtered record exists. None: When filtered record does not exist.

Return type:

model_class

join_entities

Return list of the joined entity classes for query.

join_model_classes

Return model classes contained in joins for query.

mapper_entities

Return mapper entities for query.

model_class

Return primary model class if query generated using session.query(model_class) or None otherwise.

model_classes

Return model classes used as selectable for query.

paginate(pagination)

Return paginated query.

Parameters:pagination (tuple|int) – A tuple containing (per_page, page) or an int value for per_page.
Returns:
New Query instance with limit and offset
parameters applied.
Return type:Query
save(data, before=None, after=None, identity=None)

Save data into the database using insert, update, or upsert-on-primary-key.

Warning

This requires that the Query has been generated using Query(<ModelClass>); otherwise, and exception will be raised.

The data argument can be any of the following:

This method will attempt to do the “right” thing by mapping any items in data that have their primary key set with the corresponding record in the database if it exists.

Parameters:
  • data (mixed) – Data to save to database.
  • before (function, optional) – Function to call before each model is saved via session.add. Function should have signature before(model, is_new).
  • after (function, optional) – Function to call after each model is saved via session.add. Function should have signature after(model, is_new).
  • identity (function, optional) – Function used to return an idenity map for a given model. Function should have the signature identity(model). By default core.primary_identity_map() is used.
Returns:

If a single item passed in. list: A list of model_class when multiple items passed.

Return type:

model_class

Raises:

InvalidRequestError – When model_class is None.

search(*criterion, **kargs)

Return search query object.

Parameters:

*criterion (sqlaexpr, optional) – SQLA expression to filter against.

Keyword Arguments:
 
  • per_page (int, optional) – Number of results to return per page. Defaults to None (i.e. no limit).
  • page (int, optional) – Which page offset of results to return. Defaults to 1.
  • order_by (sqlaexpr, optional) – Order by expression. Defaults to None.
Returns:

New Query instance with criteria and parameters

applied.

Return type:

Query

Model

The declarative base model class for SQLAlchemy ORM.

class sqlservice.model.ModelBase(data=None, **kargs)

Declarative base for all ORM model classes.

classmethod class_mapper()

Return class mapper instance of model.

classmethod class_registry()

Returns declarative class registry containing declarative model class names mapped to class objects.

classmethod columns()

Return model columns as dict like OrderProperties object.

classmethod descriptors()

Return all ORM descriptors

descriptors_to_dict()

Return a dict that maps data loaded in __dict__ to this model’s descriptors. The data contained in __dict__ represents the model’s state that has been loaded from the database. Accessing values in __dict__ will prevent SQLAlchemy from issuing database queries for any ORM data that hasn’t been loaded from the database already.

Note

The dict returned will contain model instances for any relationship data that is loaded. To get a dict containing all non-ORM objects, use to_dict().

Returns:dict
identity()

Return primary key identity of model instance. If there is only a single primary key defined, this method returns the primary key value. If there are multiple primary keys, a tuple containing the primary key values is returned.

identity_map()

Return primary key identity map of model instance as an ordered dict mapping each primary key column to the corresponding primary key value.

classmethod pk_columns()

Return tuple of primary key(s) for model.

classmethod relationships()

Return ORM relationships

to_dict()

Return a dict of the current model’s state (i.e. data returned is limited to data already fetched from the database) if some state is loaded. If no state is loaded, perform a session refresh on the model which will result in a database query. For any relationship data that is loaded, to_dict be called recursively for those objects.

Returns:dict
update(data=None, **kargs)

Update model by positional dict or keyword arguments.

Note

If both data and keyword arguments are passed in, the keyword arguments take precedence.

Parameters:
  • data (dict, optional) – Data to update model with.
  • **kargs (optional) – Mapping of attributes to values to update model with.
Raises:

- TypeError – If data is not None or not a dict.

class sqlservice.model.ModelMeta(name, bases, dct)

Model metaclass that prepares model classes for event registration hooks.

sqlservice.model.as_declarative(**kargs)

Decorator version of declarative_base().

sqlservice.model.declarative_base(cls=<class 'sqlservice.model.ModelBase'>, metadata=None, metaclass=<class 'sqlservice.model.ModelMeta'>, **kargs)

Function that converts a normal class into a SQLAlchemy declarative base class.

Parameters:
  • cls (type) – A type to use as the base for the generated declarative base class. May be a class or tuple of classes. Defaults to ModelBase.
  • metadata (MetaData, optional) – 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. If not passed in, cls.metadata will be used if set. Defaults to None.
  • metaclass (DeclarativeMeta, optional) – A metaclass or __metaclass__ compatible callable to use as the meta type of the generated declarative base class. If not passed in, cls.metaclass will be used if set. Defaults to ModelMeta.
Keyword Arguments:
 
  • other keyword arguments are passed to (All) –
  • sqlalchemy.ext.declarative.declarative_base.
Returns:

Declarative base class

Return type:

class

sqlservice.model.default_dict_adapter(value, key, model)

Default ModelBase.to_dict() adapter that handles nested serialization of model objects.

Event

The event module with declarative ORM event decorators and event registration.

class sqlservice.event.AttributeEventDecorator(attribute, **event_kargs)

Base class for an attribute event decorators.

class sqlservice.event.Event(name, attribute, listener, kargs)

Universal event class used when registering events.

class sqlservice.event.EventDecorator(**event_kargs)

Base class for event decorators that attaches metadata to function object so that register() can find the event definition.

class sqlservice.event.after_delete(**event_kargs)

Event decorator for the after_delete event.

class sqlservice.event.after_insert(**event_kargs)

Event decorator for the after_insert event.

class sqlservice.event.after_save(**event_kargs)

Event decorator for the after_insert and after_update events.

class sqlservice.event.after_update(**event_kargs)

Event decorator for the after_update event.

class sqlservice.event.before_delete(**event_kargs)

Event decorator for the before_delete event.

class sqlservice.event.before_insert(**event_kargs)

Event decorator for the before_insert event.

class sqlservice.event.before_save(**event_kargs)

Event decorator for the before_insert and before_update events.

class sqlservice.event.before_update(**event_kargs)

Event decorator for the before_update event.

class sqlservice.event.on_append(attribute, **event_kargs)

Event decorator for the append event.

class sqlservice.event.on_bulk_replace(attribute, **event_kargs)

Event decorator for the bulk_replace event.

class sqlservice.event.on_dispose_collection(attribute, **event_kargs)

Event decorator for the dispose_collection event.

class sqlservice.event.on_expire(**event_kargs)

Event decorator for the expire event.

class sqlservice.event.on_init_collection(attribute, **event_kargs)

Event decorator for the init_collection event.

class sqlservice.event.on_init_scalar(attribute, **event_kargs)

Event decorator for the init_scalar event.

class sqlservice.event.on_load(**event_kargs)

Event decorator for the load event.

class sqlservice.event.on_modified(attribute, **event_kargs)

Event decorator for the modified event.

class sqlservice.event.on_refresh(**event_kargs)

Event decorator for the refresh event.

class sqlservice.event.on_remove(attribute, **event_kargs)

Event decorator for the remove event.

class sqlservice.event.on_set(attribute, **event_kargs)

Event decorator for the set event.

sqlservice.event.register(cls, dct)

Register events defined on a class during metaclass creation.

sqlservice.core.bulk_common_update(session, mapper, key_columns, mappings)

Perform a bulk UPDATE on common shared values among mappings. What this means is that if multiple records are being updated to the same values, then issue only a single update for that value-set using the identity of the records in the WHERE clause.

Parameters:
  • session (Session) – SQLAlchemy session object.
  • mapper – An ORM class or SQLAlchemy insert-statement object.
  • key_columns (tuple) – A tuple of SQLAlchemy columns that represent the identity of each row (typically this would be a table’s primary key values but they can be any set of columns).
  • mappings (list) – List of dict objects to update.
Returns:

list[ResultProxy]

sqlservice.core.bulk_diff_update(session, mapper, key_columns, previous_mappings, mappings)

Perform a bulk INSERT/UPDATE on the difference between mappings and previous_mappings such that only the values that have changed are included in the update. If a mapping in mappings doesn’t exist in previous_mappings, then it will be inclued in the bulk INSERT. The bulk INSERT will be deferred to bulk_insert(). The bulk UPDATE will be deferred to bulk_common_update().

Parameters:
  • session (Session) – SQLAlchemy session object.
  • mapper – An ORM class or SQLAlchemy insert-statement object.
  • key_columns (tuple) – A tuple of SQLAlchemy columns that represent the identity of each row (typically this would be a table’s primary key values but they can be any set of columns).
  • previous_mappings (list) – List of dict objects that represent the previous values of all mappings found for this update set (i.e. these are the current database records).
  • mappings (list) – List of dict objects to update.
Returns:

list[ResultProxy]

sqlservice.core.bulk_insert(session, mapper, mappings)

Perform a bulk insert into table/statement represented by mapper while utilizing a special syntax that replaces the tradtional executemany() DBAPI call with a multi-row VALUES clause for a single INSERT statement.

See bulk_insert_many() for bulk inserts using executemany().

Parameters:
  • session (Session) – SQLAlchemy session object.
  • mapper – An ORM class or SQLAlchemy insert-statement object.
  • mappings (list) – List of dict objects to insert.
Returns:

ResultProxy

sqlservice.core.bulk_insert_many(session, mapper, mappings)

Perform a bulk insert into table/statement represented by mapper while utilizing the executemany() DBAPI call.

See bulk_insert() for bulk inserts using a multi-row VALUES clause for a single INSERT statement.

Parameters:
  • session (Session) – SQLAlchemy session object.
  • mapper – An ORM class or SQLAlchemy insert-statement object.
  • mappings (list) – List of dict objects to insert.
Returns:

ResultProxy

sqlservice.core.destroy(session, data, model_class=None, synchronize_session=False)

Delete bulk data.

The data argument can be any of the following:

  • Single instance of model_class
  • List of model_class instances
  • Primary key value (single value or tuple of values for composite keys)
  • List of primary key values.
  • Dict containing primary key(s) mapping
  • List of dicts with primary key(s) mappings

If a non-model_class instances are passed in, then model_class is required to know which table to delete from.

Parameters:
  • session (Session) – SQLAlchemy session object.
  • data (mixed) – Data to delete from database.
  • synchronize_session (bool|str) – Argument passed to Query.delete.
Returns:

Number of deleted records.

Return type:

int

sqlservice.core.identity_map_filter(models, identity=None)

Return SQLAlchemy filter expression for a list of models based on the identity map returned by the given identity function.

sqlservice.core.make_identity(*columns)

Factory function that returns an identity function that can be used in save(). The identity function returns an identity-tuple mapping from a model instance with the given columns and their values.

sqlservice.core.mapper_primary_key(model_class)

Return primary keys of model_class.

sqlservice.core.primary_identity_map(model)

Return identity-map of a model as a N-element tuple where N is the number of primary key columns. Each element of the tuple is a 2-element tuple containing the primary key column and the corresponding model value.

sqlservice.core.primary_identity_value(model)

Return primary key identity of model instance. If there is only a single primary key defined, this function returns the primary key value. If there are multiple primary keys, a tuple containing the primary key values is returned.

sqlservice.core.primary_key_filter(items, model_class)

Given a set of items that have their primary key(s) set and that may or may not exist in the database, return a filter that queries for those records.

Parameters:
  • items (list) – List of dict or model_class instances to query.
  • model_class (Model) – ORM model class to query against.
Returns:

sqlalchemy.sql.elements.BinaryExpression

sqlservice.core.save(session, models, before=None, after=None, identity=None)

Save models into the database using insert, update, or upsert on identity.

The models argument can be any of the following:

  • Model instance
  • list/tuple of Model instances

The required function signature and return of identity is:

def identity(model):
    return ((column1, value1), (column2, value2), ... (colN, valN))

For example, a model with a single primary key, the return might look like:

model = Model(id=1)
identity(model) == ((Model.id, 1))

And for a model with a composite primary key:

model = Model(id1=1, id2=2)
identity(model) == ((Model.id1, 1), (Model.id2, 2))

This requirement is necessary so that the save() function can correctly generate a query filter to select existing records to determine which of those records should be updated vs inserted.

If no identity function is provided, then primary_identity_map() will be used which will result in upserting on primary key.

Parameters:
  • session (Session) – SQLAlchemy session object.
  • models (mixed) – Models to save to database.
  • before (function, optional) – Function to call before each model is saved via session.add. Function should have signature before(model, is_new).
  • after (function, optional) – Function to call after each model is saved via session.add. Function should have signature after(model, is_new).
  • identity (function, optional) – Function used to return an idenity map for a given model. Function should have the signature identity(model). By default primary_identity_map() is used.
Returns:

If a single item passed in. list: A list of Model instaces if multiple items passed in.

Return type:

Model

sqlservice.core.transaction(session, commit=True, rollback=False, autoflush=None)

Nestable session transaction context manager where only a single commit will be issued once all contexts have been exited. If an exception occurs either at commit time or before, the transaction will be rolled back and the original exception re-raised.

Parameters:
  • session (Session) – SQLAlchemy session object.
  • commit (bool, optional) – Whether to commit the transaction or leave it open. Defaults to True.
  • rollback (bool, optional) – Whether to rollback the transaction. Defaults to False. WARNING: This overrides commit.
  • autoflush (bool, optional) – Whether to override session.autoflush. Original session.autoflush will be restored after transaction. Defaults to None which doesn’t modify session.autoflush.
Yields:

session