This lab focuses on mastering PL/pgSQL (PostgreSQL's procedural language) and exploring PostgreSQL internals by working with triggers. The goal is to create a script that retrieves information about triggers assigned to a specific table, using advanced PostgreSQL features like GUC variables, anonymous blocks, and system catalogs.
The main task is to create an SQL script that:
- Takes a table name as user input using GUC variables and metacommands.
- Uses an anonymous PL/pgSQL block to:
- Retrieve all triggers assigned to the specified table.
- Display the triggers and their associated columns in a formatted manner.
- Handles exceptions, such as missing tables or insufficient privileges.
- Includes a separate script (
add-triggers.sql) to:- Indelibly create a table (
point_model) with sample data. - Add triggers to the table for testing purposes.
- Indelibly create a table (
add-triggers.sql: SQL script to create thepoint_modeltable, populate it with data, and add triggers.find-triggers.sql: SQL script to find and display triggers assigned to a user-specified table.
For testing purposes, the following triggers were created on the point_model
table:
after_update_point_model: Executes after anUPDATEoperation.before_insert_point_model: Executes before anINSERToperation.trigger_x: Executes after anUPDATEon thexcolumn.trigger_y: Executes after anUPDATEon theycolumn.
Run the add-triggers.sql script to create the point_model table and add
triggers:
psql -h your_host -d your_database -v "my_table=s368090.point_model" -f add-triggers.sqlUse the find-triggers.sql script to retrieve triggers for a specific table:
psql -h your_host -d your_database -v "my_table=s368090.your_table" -f find-triggers.sqlThe find-triggers.sql script will display output like this:
COLUMN NAME TRIGGER NAME
------------------- ------------------------
ALL after_update_point_model
ALL before_insert_point_model
x trigger_x
y trigger_y
By completing this lab, you will:
-
Master PL/pgSQL for writing procedural code in PostgreSQL.
-
Understand how to use GUC variables and metacommands for user input.
-
Learn to query PostgreSQL system catalogs (e.g., pg_trigger, pg_class) to retrieve metadata.
-
Handle exceptions and errors gracefully in PL/pgSQL.
-
Gain experience in writing idempotent scripts for database operations.