code: def failsafe_add(_session, _instance, **filters):
      
      if _instance in _session:
          # This instance is already in the session, most likely due to a
          # save-update cascade. SQLAlchemy will flush before beginning a
          # nested transaction, which defeats the purpose of nesting, so
          # remove it for now and add it back inside the SAVEPOINT.
          _session.expunge(_instance)
      _session.begin_nested()
      try:
          _session.add(_instance)
          _session.commit()
          if filters:
              return _instance
      except IntegrityError as e:
          _session.rollback()
          if filters:
              try:
                  return _session.query(_instance.__class__).filter_by(**filters).one()
              except NoResultFound:  # Do not trap the other exception, MultipleResultsFound
                  raise e
docs: 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``.
  
      :param _session: Database session
      :param _instance: Instance to commit
      :param filters: Filters required to load existing instance from the
          database in case the commit fails (required)
      :return: Instance that is in the database