Skip to content

insert_username

functions for tracking who changed a table

insert_username · functions for tracking who changed a table

Overview

IDExtensionPackageVersionCategoryLicenseLanguage
4882insert_usernameinsert_username1.0FUNCPostgreSQLC
AttributeHas BinaryHas LibraryNeed LoadHas DDLRelocatableTrusted
--s-d-rNoYesNoYesyesno
Relationships
See Alsotcn refint autoinc moddatetime table_log

Packages

PG19PG18PG17PG16PG15
1.01.01.01.01.0
This contrib extension ships with PostgreSQL.

Install

Create this extension with:

CREATE EXTENSION insert_username;

Usage

insert_username: track who modified a table row

Provides a trigger function that stores the current user’s name into a specified text column.

CREATE EXTENSION insert_username;

Trigger Function

FunctionDescription
insert_username()Store current username in the specified column

Parameter: name of the text column to store the username.

Examples

CREATE TABLE audit_log (
  id serial PRIMARY KEY,
  data text,
  modified_by text
);

-- Track who inserts
CREATE TRIGGER set_insert_user
  BEFORE INSERT ON audit_log
  FOR EACH ROW
  EXECUTE FUNCTION insert_username('modified_by');

-- Track who updates
CREATE TRIGGER set_update_user
  BEFORE UPDATE ON audit_log
  FOR EACH ROW
  EXECUTE FUNCTION insert_username('modified_by');

INSERT INTO audit_log (data) VALUES ('test');
SELECT modified_by FROM audit_log;  -- returns current user

Table reader