New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specify custom session class #327

Open
sssilver opened this Issue Aug 8, 2015 · 2 comments

Comments

Projects
None yet
3 participants
@sssilver

sssilver commented Aug 8, 2015

Hello,

SQLAlchemy allows us to use custom session classes in case we wanna override default behavior:

sqlalchemy.orm.scoped_session(
    sqlalchemy.orm.sessionmaker(
        autocommit=False,
        autoflush=False,
        bind=self.engine,
        class_=NoDeleteSession  # Custom session class
    )
)

This is critical, as in most business programs operations like DELETE do not physically delete data, but mark it as deleted instead:

class NoDeleteSession(sqlalchemy.orm.session.Session):
    def __init__(self, bind=None, autoflush=True, expire_on_commit=True,
                 _enable_transaction_accounting=True,
                 autocommit=False, twophase=False,
                 weak_identity_map=True, binds=None, extension=None,
                 info=None, query_cls=sqlalchemy.orm.query.Query):

        self._persist_deleted = set()

        super(NoDeleteSession, self).__init__(
            bind=bind,
            autoflush=autoflush,
            expire_on_commit=expire_on_commit,
            _enable_transaction_accounting=_enable_transaction_accounting,
            autocommit=autocommit,
            twophase=twophase,
            weak_identity_map=weak_identity_map,
            binds=binds,
            extension=extension,
            info=info,
            query_cls=query_cls
        )

    def delete(self, instance):
        # Do not actually delete the instance. Set the is_deleted flag instead.
        instance.is_deleted = True
        self._persist_deleted.add(instance)

Going through the flask-sqlalchemy source code and documentation, it seems that this isn't currently supported. Can we have this functionality?

Thanks.

@justanr

This comment has been minimized.

Contributor

justanr commented Aug 10, 2015

It looks like the best option right now is to subclass the SQLAlchemy class and override the create_session method.

@sssilver

This comment has been minimized.

sssilver commented Aug 13, 2015

Should we label this as an enhancement then?

@davidism davidism self-assigned this Dec 14, 2015

@davidism davidism removed their assignment Oct 4, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment