How to use the User column for transactions?

1.3k Views Asked by At

I got a recommendation to use sqlalchemy-continuum, which seems to do very much what I want out of the box.

By default, the ORM assumes that there is a user column. I do indeed want to save originators of an edit, but the documentation only says “This is how you specify a User class”, without saying anything about how to specify such an object when actually using versioned tables.

How do I specify the User responsible for a transaction? Is there a similar way to add a commit message/reason/citation (a VARCHAR) to each transaction?

2

There are 2 best solutions below

0
On BEST ANSWER

If you can get the user from some global scope (like flask.g or flask.request), you can create a plugin, implementing the transaction_args() method:

from sqlalchemy_continuum.plugins import Plugin


class UserPlugin(Plugin):

    def transaction_args(self, uow, session):
        return {
            'user_id': get_user_from_globals()
        }

See plugins/flask.py or pyramid_plugin.py. You should return primary key value of your User model.

You can save additional data with TransactionMeta plugin in a separate table. There is no documented API for extending the Transaction class itself. It is created by TransactionFactory, but that could change in later versions. It is probably a good idea to keep additional data separate.

0
On

Use this for native versioning:

from sqlalchemy_continuum import make_versioned
make_versioned(options={'native_versioning': True},
               user_cls=None)

It creates version tables for each table in db. Whenever there is update in a table, it creates entry in version table for old data.

This creates these new columns: transaction_id,end_transaction_id,operation_type in {orgion_table}_version