Helper functions

coaster.sqlalchemy.functions.make_timestamp_columns()[source]

Return two columns, created_at and updated_at, with appropriate defaults

coaster.sqlalchemy.functions.failsafe_add(_session, _instance, **filters)[source]

Add and commit a new instance in a nested transaction (using SQL SAVEPOINT), gracefully handling failure in case a conflicting entry is already in the database (which may occur due to parallel requests causing race conditions in a production environment with multiple workers).

Returns the instance saved to database if no error occurred, or loaded from database using the provided filters if an error occurred. If the filters fail to load from the database, the original IntegrityError is re-raised, as it is assumed to imply that the commit failed because of missing or invalid data, not because of a duplicate entry.

However, when no filters are provided, nothing is returned and IntegrityError is also suppressed as there is no way to distinguish between data validation failure and an existing conflicting record in the database. Use this option when failures are acceptable but the cost of verification is not.

Usage: failsafe_add(db.session, instance, **filters) where filters are the parameters passed to Model.query.filter_by(**filters).one() to load the instance.

You must commit the transaction as usual after calling failsafe_add.

Parameters:
  • _session – Database session
  • _instance – Instance to commit
  • filters – Filters required to load existing instance from the database in case the commit fails (required)
Returns:

Instance that is in the database

coaster.sqlalchemy.functions.add_primary_relationship(parent, childrel, child, parentrel, parentcol)[source]

When a parent-child relationship is defined as one-to-many, add_primary_relationship() lets the parent refer to one child as the primary, by creating a secondary table to hold the reference. Under PostgreSQL, a trigger is added as well to ensure foreign key integrity.

A SQLAlchemy relationship named parent.childrel is added that makes usage seamless within SQLAlchemy.

The secondary table is named after the parent and child tables, with _primary appended, in the form parent_child_primary. This table can be found in the metadata in the parent.metadata.tables dictionary.

Multi-column primary keys on either parent or child are unsupported at this time.

Parameters:
  • parent – The parent model (on which this relationship will be added)
  • childrel – The name of the relationship to the child that will be added
  • child – The child model
  • parentrel (str) – Name of the existing relationship on the child model that refers back to the parent model
  • parentcol (str) – Name of the existing table column on the child model that refers back to the parent model
Returns:

None

coaster.sqlalchemy.functions.auto_init_default(column)[source]

Set the default value for a column when it’s first accessed rather than first committed to the database.