kvesteri / postgresql-audit

Audit trigger for PostgreSQL
BSD 2-Clause "Simplified" License
126 stars 28 forks source link

Custom Activity model (table name, and extra columns) #18

Open ksesong opened 7 years ago

ksesong commented 7 years ago

Things are working properly when I setup the versioning_manager as is. I cannot manage to use the extra_values function (via postgresql_audit.flask) with target_id pointing towards the parent class of a given versioned model (as suggested in the docs): it seems that the Activity model does not contain any column for target_id. In the same spirit, I would also like to use the extra_values function for other attributes than target_id, for example if I want to detail the reason of an update.

So I created another VersioningManager class based on the postgresql_audit.flask's one, but it does not seem to work. (I have tried adding the columns to the transaction model instead, without success, stating (psycopg2.ProgrammingError) column "motive" of relation "transaction" does not exist).

# -*- coding: utf-8 -*-

import sqlalchemy as sa

from postgresql_audit.base import activity_base, transaction_base
from postgresql_audit.flask import VersioningManager as _VersioningManager
from sqlalchemy_utils import UUIDType

class VersioningManager(_VersioningManager):
    def activity_model_factory(self, base):
        class Activity(activity_base(base, self.schema_name)):
            __tablename__ = 'activities'

            transaction_id = sa.Column(
                sa.BigInteger, sa.ForeignKey(self.transaction_cls.id)
            )
            transaction = sa.orm.relationship(
                self.transaction_cls,
                backref='activities'
            )

            target_id = sa.Column(UUIDType)
            motive = sa.Column(sa.String(255))

        return Activity

    def transaction_model_factory(self, base):
        class Transaction(transaction_base(base, self.schema_name)):
            __tablename__ = 'transactions'

        return Transaction

    def init(self, base):
        self.base = base
        self.transaction_cls = self.transaction_model_factory(base)
        self.activity_cls = self.activity_model_factory(base)
        self.attach_listeners()

versioning_manager = VersioningManager()

I also want to rename the table name of both models (I have used plurals for my tables), but I realised that the SQL statements are hardcoded with the default ones (for example here).