Create the Event Log Table and Trigger Function
In this step, you will create the event_log
table and the log_ddl_event
function. The event_log
table will store the details of the database events, and the log_ddl_event
function will be executed when a specific event occurs.
First, connect to the PostgreSQL database as the postgres
user:
sudo -u postgres psql
Now, create the event_log
table by executing the following SQL command:
CREATE TABLE event_log (
event_time timestamp without time zone,
event_type text,
schema_name text,
object_name text,
command_tag text
);
This command creates a table named event_log
with columns to store the event time, event type, schema name, object name, and command tag.
Next, create the event trigger function log_ddl_event
. Execute the following SQL command:
CREATE OR REPLACE FUNCTION log_ddl_event()
RETURNS event_trigger
AS $$
BEGIN
INSERT INTO event_log (event_time, event_type, schema_name, object_name, command_tag)
VALUES (NOW(), TG_EVENT, TG_TABLE_SCHEMA, TG_TABLE_NAME, TG_TAG);
END;
$$ LANGUAGE plpgsql;
This command creates a function named log_ddl_event
. Let's break down what this function does:
CREATE OR REPLACE FUNCTION log_ddl_event()
: Creates or replaces a function named log_ddl_event
.
RETURNS event_trigger
: Specifies that the function is an event trigger function.
AS $$ ... $$ LANGUAGE plpgsql
: Defines the function body using the plpgsql
language.
INSERT INTO event_log ...
: Inserts a new row into the event_log
table with the event details.
NOW()
: Gets the current timestamp.
TG_EVENT
: A special variable containing the type of event that triggered the function (e.g., CREATE TABLE
).
TG_TABLE_SCHEMA
: A special variable containing the schema name of the object that triggered the function.
TG_TABLE_NAME
: A special variable containing the name of the object that triggered the function.
TG_TAG
: A special variable containing the command tag of the event (e.g., CREATE TABLE
).
After executing the above commands, you should see CREATE TABLE
and CREATE FUNCTION
in the output, indicating that the table and function have been created successfully.