kvesteri / postgresql-audit

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

Auto detection of audited tables doesn't work. #19

Closed antoine-lizee closed 7 years ago

antoine-lizee commented 7 years ago

This doesn't work if I remove the two lines where I explicitly declare which table to audit.

from sqlalchemy import create_engine, Table, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref, sessionmaker
from postgresql_audit import versioning_manager

engine = create_engine('postgres://localhost/sandbox_db', echo = True)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

versioning_manager.init(Base)

class Country(Base):
    __tablename__ = 'countries'
    __versioned__ = {}

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))

    def __repr__(self):
        return '<Country {} [{}]>'.format(self.name, self.id)

class Capital(Base):
    __tablename__ = 'capitals'
    __versioned__ = {}

    id = Column(Integer(), primary_key=True)
    name = Column(String(255))
    country_id = Column(Integer(), ForeignKey(Country.id), unique=True, nullable=False)
    country = relationship('Country', backref=backref('capital', uselist=False))

    def __repr__(self):
        return '<Capital {} [{}]>'.format(self.name, self.id)

# Removing these lines prevents audit trailing to work because the `audit_table` trigger is never attached.
tables = Base.metadata.tables
versioning_manager.audit_table(tables['capitals'])
versioning_manager.audit_table(tables['countries'])

Base.metadata.create_all(engine)
kvesteri commented 7 years ago

Before the create_all() you need to configure the mappers. This can be easily done with the following command:

import sqlalchemy as sa

sa.orm.configure_mappers()
antoine-lizee commented 7 years ago

Thanks!