Skip to content

View the integration on GitHub

PgStack Audit plugs into Django and PostgreSQL to track database changes automatically. It supports audit trails with application context and historical queries in your application.

This Python package passes application-specific context with database changes through the Django integration. Context can include the 'where' (API endpoint, worker, etc.), 'who' (user, cron job, etc.), and 'how' behind a change.

  • PostgreSQL 14+
  • Django
  1. Install the Python package
Terminal window
pip install bemi-django
  1. Add bemi app to your Django project's INSTALLED_APPS
settings.py
INSTALLED_APPS = [
# Your other apps
'bemi',
]
  1. Run the migration add lightweight PostgreSQL triggers for passing application context with all data changes into PostgreSQL replication log
Terminal window
python manage.py migrate bemi

Add the PgStack Audit middleware to your Django project app and add the path to a custom get_bemi_context function to automatically pass application context with all tracked database changes made within an HTTP request:

settings.py
MIDDLEWARE = [
# Your other middlewares
'bemi.BemiMiddleware',
]
BEMI_CONTEXT_FUNCTION = 'your_project.utils.get_bemi_context'

You can specify custom application context:

your_project/utils.py
def get_bemi_context(request):
# Return any custom context dict
return {
'user_id': request.user.id,
'method': request.method,
'path': request.path,
}

Application context:

  • Is bound to the current execution thread within an HTTP request.
  • Is used only with INSERT, UPDATE, DELETE SQL queries performed via Django. Otherwise, it is a no-op.
  • Is passed directly into PG Write-Ahead Log with data changes without affecting the structure of the database and SQL queries.

Application context will automatically include the original SQL query that performed data changes, which is generally useful for troubleshooting purposes.

Connect your PostgreSQL database to PgStack Audit using the quickstart. Configure logical replication using the guide for your hosting platform.

With the integration installed, make a change through your application and check the project's Audit view. The change should include the application context supplied by your integration. Changes made outside the integrated application are still captured, but do not receive that application's context.

Use the PgStack database connection details from your project settings to query changes with SQL or your ORM. Replace [USERNAME], [HOSTNAME], and [DATABASE] with those details:

Terminal window
psql postgres://[USERNAME]@[HOSTNAME]:5432/[DATABASE] -c \
'SELECT "primary_key", "table", "operation", "before", "after", "context", "committed_at" FROM changes;'

Example output:

primary_key | table | operation | before | after | context | committed_at
-------------+-------+-----------+----------------------------------------------------+-----------------------------------------------------+-------------------------------------------------------------------------------------------+------------------------
26 | todo | CREATE | {} | {"id": 26, "task": "Sleep", "is_completed": false} | {"user_id": 187234, "endpoint": "/todo", "method": "POST", "SQL": "INSERT INTO ..."} | 2023-12-11 17:09:09+00
27 | todo | CREATE | {} | {"id": 27, "task": "Eat", "is_completed": false} | {"user_id": 187234, "endpoint": "/todo", "method": "POST", "SQL": "INSERT INTO ..."} | 2023-12-11 17:09:11+00
28 | todo | CREATE | {} | {"id": 28, "task": "Repeat", "is_completed": false} | {"user_id": 187234, "endpoint": "/todo", "method": "POST", "SQL": "INSERT INTO ..."} | 2023-12-11 17:09:13+00
26 | todo | UPDATE | {"id": 26, "task": "Sleep", "is_completed": false} | {"id": 26, "task": "Sleep", "is_completed": true} | {"user_id": 187234, "endpoint": "/todo/complete", "method": "PUT", "SQL": "UPDATE ..."} | 2023-12-11 17:09:15+00
27 | todo | DELETE | {"id": 27, "task": "Eat", "is_completed": false} | {} | {"user_id": 187234, "endpoint": "/todo/27", "method": "DELETE", "SQL": "DELETE FROM ..."} | 2023-12-11 17:09:18+00

Connect to the PgStack Audit PostgreSQL destination database to query change data from your application.

To query historical data, configure an additional database connection:

django/todo_project/settings.py
DATABASES = {
'default': ...
'bemi': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv('DESTINATION_DB_DATABASE'),
'USER': os.getenv('DESTINATION_DB_USERNAME'),
'PASSWORD': os.getenv('DESTINATION_DB_PASSWORD'),
'HOST': os.getenv('DESTINATION_DB_HOST'),
'PORT': os.getenv('DESTINATION_DB_PORT'),
}
}
DATABASE_ROUTERS = ['bemi.BemiDatabaseRouter']

Add inheritance to tracked models or query directly with the BemiChange model.

django/todos/models.py
class Todo(BemiRecordMixin, models.Model):
...
from bemi.models import BemiChange
BemiChange.objects.last()
# => <BemiChange: BemiChange object (cd9651ff-e378-41f7-add0-c4fdfa1575ae)>
# id: "cd9651ff-e378-41f7-add0-c4fdfa1575ae",
# committed_at: Tue, 25 Apr 2024 22:15:50.890000000 UTC +00:00,
# table: "todos",
# primary_key: "27",
# operation: "UPDATE",
# before: {"id"=>27, "task"=>"Walk", "is_completed"=>false}>
# after: {"id"=>27, "task"=>"Run", "is_completed"=>true},
# context:
# {"SQL"=> "UPDATE \"public\".\"todos\" SET \"task\" = $1, \"is_completed\" = $2 WHERE \"public\".\"todos\".\"id\" = $3",
# "user_id"=>1,
# "api_endpoint"=>"/todos/complete"},
# ...
from bemi.models import BemiChange
BemiChange.objects.last().diff()
# => { "task" => ["Walk", "Run"], "completed" => [false, true] }
from todos.models import Todo
record = Todo.objects.get(pk=...)
record.bemi_changes()
from todos.models import Todo
from bemi.models import BemiChange
# Last change that impacted the "task" field
record.bemi_changes(field_name='task').last()
BemiChange.objects.field_changed(table='todos', primary_key='cd9651ff-e378-41f7-add0-c4fdfa1575ae', field_name='task').last()
# Query by the previous values
record.bemi_changes().before({'task': 'Walk'})
record.bemi_changes().before({'task': 'Walk', 'completed': false})
record.bemi_changes().before_not({'task': 'Run'})
# Query by the new values
record.bemi_changes().after('task': 'Run')
record.bemi_changes().after('task': 'Run', 'completed': true)
record.bemi_changes().after_not('task': 'Walk')
# Query by the context values
record.bemi_changes().context({'user_id': 1})
record.bemi_changes().context({'user_id': 1, 'api_endpoint': '/tasks/complete'})
record.bemi_changes().context_not({'user_id': 123})
# Chain methods
record.bemi_changes.before({'task': 'Walk'}).after({'task': 'Run'})
record.bemi_changes().created()
record.bemi_changes().updated()
record.bemi_changes().deleted()
record.bemi_changes().asc()
record.bemi_changes().desc()
changes = BemiChange.objects.
.filter(table='todos', operation='UPDATE')
.filter(context__contains={"user_id": 1})
.order_by('-committed_at')
[:10]

Distributed under the terms of the LGPL-3.0. If you need to modify and distribute the code, please release it to contribute back to the open-source community. hide_title: true