Entity Mixins

class keg_elements.db.mixins.DefaultColsMixin

Basic entity mixin providing int primary key and created/updated timestamps.

class keg_elements.db.mixins.DefaultMixin

Entity mixin combining DefaultColsMixin and MethodsMixin.

exception keg_elements.db.mixins.HardDeleteProhibitedError
class keg_elements.db.mixins.LookupMixin

Provides a base for id/label pair tables, used in one-to-many relationships.

Based on SoftDeleteMixin, so any lookup record that is deleted/deactivated is still available for existing records.

A code field is provided for developer reference in code, so a changeable label does not need to be hard-coded for lookup.

Developer expectations: - LookupMixin will precede DefaultMixin or MethodsMixin in entity base classes - Only active labels will be listed for linking to new related records - include_ids will be used for ensuring existing records preserve lookup

classmethod get_by_code(code)

Fetch a lookup record by its code (internal) field.

classmethod get_by_label(label)

Fetch a lookup record by its label field.

is_active

Hybrid property returning a record’s active status.

By default, deleted == inactive.

classmethod list_active(include_ids=None, order_by=None)

Fetch all records marked as active.

Parameters:
  • include_ids – iterable of int ids that should be included even if inactive.

  • order_by – column designation to use for SQLAlchemy when sorting values.

classmethod pairs_active(include_ids=None, order_by=None)

Fetch a list of (id, label) pairs for active records.

Parameters:
  • include_ids – iterable of int ids that should be included even if inactive.

  • order_by – column designation to use for SQLAlchemy when sorting values.

class keg_elements.db.mixins.MethodsMixin

Entity mixin providing developer/testing-centered methods.

classmethod add(**kwargs)

Create a new persisted record constructed from the given kwargs.

Parameters:
  • _commit – enable/disable commit. Default True.

  • _flush – enable/disable flush. Default True.

Returns:

entity instance created and optionally persisted.

classmethod add_or_edit(data)

Creates or updates the record associated with data

add_or_edit supports multiple primary key entities.

classmethod column_names()

Return a set of column keys, which may not match attribute names.

classmethod delete(oid)

Delete an object from the session

Parameters:

oid – the object identifier, normally the primary key

Return type:

bool

Returns:

The result of the operation

classmethod delete_cascaded()

For testing, remove all records from the table. Extend for dependencies.

By default, this affects only this entity. By design, though, the entity should override to call delete_cascaded on any entities that have foreign key dependence on this entity. Key cascades may cover some of these cases, but db cascades are not always desireable, and tests often need to easily clear a number of tables to ensure good starting state.

classmethod edit(_oid=None, **kwargs)

Edit an object in session with the kwargs, and optionally flush or commit.

Parameters:
  • oid – the object identifier, normally the primary key

  • _commit – enable/disable commit. Default True.

  • _flush – enable/disable flush. Default True.

Returns:

entity instance edited and optionally flushed/committed

classmethod fake(**kwargs)

Create an object for testing with default data appropriate for the field type

  • Will automatically set most field types ignoring those passed in via kwargs.

  • Subclasses that have foreign key relationships should setup those relationships before calling this method. See testing_set_related for additional information.

Random data that is set on a column comes from one of these sources:

  • random_data_for_column entity method provides randoms for most normal column types

  • randomdata is given in column info as the name of an entity method to call for data:

    class MyEntity(MethodsMixin, db.Model):
        foo = sa.Column(sa.Unicode, info={'randomdata': 'foo_generator'})
    
        @classmethod
        def foo_generator(cls):
            return 'bar'
    
  • random_magnitude is given in column info to be treated as the +/- random range.

  • random_range is given specifically as a low/high random range.

Special kwargs: _numeric_defaults_range: a tuple of (HIGH, LOW) which controls the acceptable defaults of the two number types. Both integer and numeric (float) fields are controlled by this setting.

from_dict(data)

Update the instance with the passed information in data.

from_dict will also update relationships either, 1:1, 1:N, M:M.

Note

from_dict intentionally does not commit and for related entities turns off auto flushing. This is to prevent premature flushes with incomplete objects

classmethod get(ident, **kwargs)

Wraps db.session.get

classmethod get_by(**kwargs)

Returns the instance of this class matching the given criteria or None if there is no record matching the criteria.

If multiple records are returned, an exception is raised.

classmethod get_where(*clauses)

Returns the instance of this class matching the given clause(s) or None if there is no record matching the criteria.

If multiple records are returned, an exception is raised.

classmethod insert(values=None, **kwargs)

Similar to add but without the ORM overhead. Useful for high data throughput cases where having kwargs name validation and ORM ops/session on every iteration would be inefficient.

Assumes the calling code is handling session flush/commit.

Parameters:
  • values – optional dict of values to insert

  • kwargs – values to insert, can be combined with the values dict

Returns:

primary key value(s). Note: SQLite does not support this

classmethod pairs(key_field, value_field, order_by=(), query=None, items=None)

Return a list of two item tuples

Parameters:
  • key_field – string representing the key

  • value_field – string representing the value

  • order_by – iterable of columns to order the query by

  • query – a base query from which to generate the pairs

  • items – a function which takes one record returned by query and returns the tuple object

classmethod primary_keys()

Helper to get the table’s primary key columns.

classmethod random_data_for_column(column, numeric_range)

Provides random testing data for a number of column types.

Raises a ValueError if the type is not handled. In that case, override as needed.

Create a related object for testing, if it is not specified in kwargs.

Designed to be used by testing_create. A common issue is that related test records need to be set up with the test entity instance, but they could be specified already in kwargs. In addition, relationships already specified may be given on the relationship attribute or the foreign-key field.

This method takes existing testing_create kwargs and the related entity, and makes the necessary updates.

Relationship name is generated from the given entity by default, but may be passed in as a _relationship_name keyword argument. The foreign key field is assumed to be the relationship name with an _id suffix, but may be specified with the _relationship_field keyword argument.

Any additional args/kwargs are passed to the given model’s testing_create.

to_dict(exclude=frozenset({}), hybrids=frozenset({}))

Covert the object properties to a dictionary.

Parameters:
  • exclude – a list of columns to ignore

  • hybrids – a list of the hybrid properties to include in the dictionary.

Returns:

a dictionary representation of the object

classmethod update(ent_id, values=None, **kwargs)

Similar to edit but without the ORM overhead. Useful for high data throughput cases where having kwargs name validation and ORM ops/session on every iteration would be inefficient.

Assumes the calling code is handling session flush/commit.

Note: if the entitiy has multiple primary key columns, ent_id should be an iterable with the values to match in the order of the column definitions as specified in the SA model (i.e. the order of columns returned by cls.primary_keys()).

Parameters:
  • ent_id – primary key value(s) to match for update

  • values – optional dict of values to insert

  • kwargs – values to insert, can be combined with the values dict

Returns:

db cursor result

update_collection(attr_name, data)

Update the specified relationship collection with the given data.

Attempt will be made to match existing collection records to update. If an existing record is not in the data set, it will be removed.

Parameters:
  • attr_name – relationship attribute to update.

  • data – iterable of dicts representing records to add/update.

class keg_elements.db.mixins.SoftDeleteMixin

SoftDeleteMixin alters the way deletes are performed by adding a deleted_utc column

A soft-delete doesn’t actually remove the row, instead, it adds a time to the deleted_utc column which indicates when it was deleted.

This event is not fired for bulk operations (session.delete) and makes it possible to delete everything.

To have finer grained control of this event for every entity, you can override the behavior by implementing before_delete_event on the entity:

class MyEntity(SoftDeleteMixin, Model):
    column1 = sa.Column(sa.Numeric)

    # `mapper` and `connection` are passed through from the parent handler
    def before_delete_event(self, mapper, connection):
        # .. custom logic
classmethod delete(oid)

Add the deleted_utc timestamp

Parameters:

oid – the object identifier, normally the primary key

Return type:

bool

Returns:

The result of the operation

keg_elements.db.mixins.kwargs_match_entity(wrapper=None, enabled=None, adapter=None, proxy=<class 'FunctionWrapper'>)

Asserts that the kwargs passed to the wrapped method match the columns/relationships of the entity.

keg_elements.db.mixins.might_commit(wrapper=None, enabled=None, adapter=None, proxy=<class 'FunctionWrapper'>)

Decorator directing the wrapped method to commit db session upon completion.

A _commit bool kwarg is added to the wrapped method’s definition, allowing a developer to turn off the commit when calling.

Exceptions during commit are raised after the session is rolled back.

keg_elements.db.mixins.might_flush(wrapper=None, enabled=None, adapter=None, proxy=<class 'FunctionWrapper'>)

Decorator directing the wrapped method to flush db session upon completion.

A _flush bool kwarg is added to the wrapped method’s definition, allowing a developer to turn off the flush when calling.

Exceptions during flush are raised after the session is rolled back.