Skip to content

Commit a7411dd

Browse files
Add trigger and audit logging example to PostgreSQL advanced concepts (#22)
* Fixed bugs in psql-query.md file * Add triggers example with audit logging
1 parent 5e8cbda commit a7411dd

1 file changed

Lines changed: 29 additions & 6 deletions

File tree

psql/advance.md

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ CREATE TABLE example_table (
5757
);
5858
```
5959

60-
Constraints can be defined when a table is created or added later using the ALTER TABLE statement. Constraints can also be dropped using tthe ALTER TABLE statement.
60+
Constraints can be defined when a table is created or added later using the ALTER TABLE statement. Constraints can also be dropped using the ALTER TABLE statement.
6161

6262
## Joins
6363

@@ -198,25 +198,48 @@ In the above syntax, the trigger function trigger_function_name is created using
198198

199199
Example:
200200
```sql
201-
-- Example of creating a trigger
201+
-- 1. Create target table
202+
CREATE TABLE target_table (
203+
id SERIAL PRIMARY KEY,
204+
name TEXT,
205+
age INT
206+
);
207+
208+
-- 2. Create audit table
209+
CREATE TABLE audit_table (
210+
audit_id SERIAL PRIMARY KEY,
211+
event_type TEXT NOT NULL,
212+
event_time TIMESTAMP NOT NULL DEFAULT NOW(),
213+
table_name TEXT NOT NULL,
214+
old_data JSONB,
215+
new_data JSONB
216+
);
217+
218+
-- 3. Create trigger function
202219
CREATE OR REPLACE FUNCTION log_changes()
203220
RETURNS TRIGGER AS $$
204221
BEGIN
205222
IF TG_OP = 'INSERT' THEN
206223
INSERT INTO audit_table (event_type, event_time, table_name, new_data)
207-
VALUES ('INSERT', NOW(), TG_TABLE_NAME, NEW);
224+
VALUES ('INSERT', NOW(), TG_TABLE_NAME, to_jsonb(NEW));
225+
RETURN NEW;
226+
208227
ELSIF TG_OP = 'UPDATE' THEN
209228
INSERT INTO audit_table (event_type, event_time, table_name, old_data, new_data)
210-
VALUES ('UPDATE', NOW(), TG_TABLE_NAME, OLD, NEW);
229+
VALUES ('UPDATE', NOW(), TG_TABLE_NAME, to_jsonb(OLD), to_jsonb(NEW));
230+
RETURN NEW;
231+
211232
ELSIF TG_OP = 'DELETE' THEN
212233
INSERT INTO audit_table (event_type, event_time, table_name, old_data)
213-
VALUES ('DELETE', NOW(), TG_TABLE_NAME, OLD);
234+
VALUES ('DELETE', NOW(), TG_TABLE_NAME, to_jsonb(OLD));
235+
RETURN OLD;
214236
END IF;
215237

216-
RETURN NEW;
238+
RETURN NULL;
217239
END;
218240
$$ LANGUAGE plpgsql;
219241

242+
-- 4. Attach trigger to target table
220243
CREATE TRIGGER audit_trigger
221244
AFTER INSERT OR UPDATE OR DELETE
222245
ON target_table

0 commit comments

Comments
 (0)