Sub topic 14
DDL and Database Event Triggers
This chapter assumes you can write row and statement triggers, raise errors with RAISE_APPLICATION_ERROR, and know that a trigger body cannot normally COMMIT. The earlier chapters covered triggers on tables and views. Here the trigger fires on something other than a row change: a DDL statement such as DROP TABLE, or a database event such as a user logging on.
What System Triggers Are
A system trigger is attached to a schema or to the whole database rather than to a table. Oracle fires it when one of these happens:
- A DDL statement runs, such as
CREATE,ALTER,DROP,TRUNCATE,RENAME,GRANTorREVOKE. - A database event happens:
STARTUP,SHUTDOWN,LOGON,LOGOFForSERVERERROR.
The general form is:
CREATE OR REPLACE TRIGGER trigger_name
{BEFORE | AFTER} event [OR event ...]
ON {SCHEMA | DATABASE}
BEGIN
-- body
END;
/There are no FOR EACH ROW, :OLD or :NEW here, because no row is involved. The trigger gets information about the event from event attribute functions instead.
Scope: SCHEMA and DATABASE
ON SCHEMA fires only for events in the schema that owns the trigger. ON DATABASE fires for events in every schema. A database-level trigger needs the ADMINISTER DATABASE TRIGGER system privilege. A schema-level trigger needs only CREATE TRIGGER, so the examples below use ON SCHEMA.
Which Events Allow Which Timing
Not every event can be both BEFORE and AFTER. Oracle restricts timing to what makes sense.
| Event | Timing | Scope | Typical use |
|---|---|---|---|
| DDL (`CREATE`, `ALTER`, `DROP`, and others) | BEFORE or AFTER | SCHEMA or DATABASE | Block or log schema changes |
| `LOGON` | AFTER | SCHEMA or DATABASE | Audit logins, set session defaults |
| `LOGOFF` | BEFORE | SCHEMA or DATABASE | Record session end |
| `STARTUP` | AFTER | DATABASE | Pin objects, start housekeeping |
| `SHUTDOWN` | BEFORE | DATABASE | Record a clean shutdown |
| `SERVERERROR` | AFTER | SCHEMA or DATABASE | Log unhandled errors |
The reasoning is that a login cannot be "before" the session exists, and a shutdown cannot be "after" the instance is gone.
Some statements never fire DDL triggers, for example ALTER DATABASE and CREATE CONTROLFILE. A DDL trigger is a guard rail for ordinary schema work, not a security boundary.
Event Attribute Functions
Inside a system trigger, you ask about the event by calling attribute functions. They are not tied to a table, so you call them directly.
| Function | Returns |
|---|---|
| `ORA_SYSEVENT` | The event name, such as `DROP` or `LOGON` |
| `ORA_DICT_OBJ_TYPE` | The object type, such as `TABLE` or `INDEX` |
| `ORA_DICT_OBJ_NAME` | The name of the object being changed |
| `ORA_DICT_OBJ_OWNER` | The owner of that object |
| `ORA_LOGIN_USER` | The user who caused the event |
| `ORA_IS_SERVERERROR(n)` | `TRUE` if error number `n` is on the error stack |
| `ORA_SERVER_ERROR(1)` | The top error number on the stack |
SYS_CONTEXT('USERENV', ...) also works and gives session details such as IP_ADDRESS and SESSION_USER.
Example: Blocking DROP TABLE
This trigger stops anyone from dropping a table in the schema that owns it.
CREATE OR REPLACE TRIGGER no_drop_tables
BEFORE DROP ON SCHEMA
BEGIN
IF ORA_DICT_OBJ_TYPE = 'TABLE' THEN
RAISE_APPLICATION_ERROR(-20003, 'Dropping tables is not allowed in this schema');
END IF;
END no_drop_tables;
/The trigger fires for every DROP in the schema, whatever the object type. It therefore has to check ORA_DICT_OBJ_TYPE and let views, indexes and sequences through. When it blocks a table, the user sees the application error wrapped in ORA-00604:
DROP TABLE employees;
-- ORA-00604: error occurred at recursive SQL level 1
-- ORA-20003: Dropping tables is not allowed in this schemaBecause the trigger is BEFORE, the statement is stopped before Oracle changes anything, so the table stays.
Getting Past the Guard
Keep a way to lift the restriction on purpose. The simplest is to disable the trigger, run the drop, and enable it again:
ALTER TRIGGER no_drop_tables DISABLE;
DROP TABLE scratch_data;
ALTER TRIGGER no_drop_tables ENABLE;ALTER TRIGGER is itself DDL, but the trigger only blocks DROP of tables, so it does not interfere.
Example: Auditing Logins
A logon trigger can record who connects. The table needs a place to be written, and a trigger cannot commit in the caller's transaction. A logon has no business transaction to join, so the insert runs in an autonomous transaction.
CREATE TABLE logon_audit (
username VARCHAR2(128),
logon_time TIMESTAMP,
ip_address VARCHAR2(45)
);
CREATE OR REPLACE TRIGGER logon_audit_trg
AFTER LOGON ON SCHEMA
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO logon_audit (username, logon_time, ip_address)
VALUES (ORA_LOGIN_USER, SYSTIMESTAMP, SYS_CONTEXT('USERENV', 'IP_ADDRESS'));
COMMIT;
EXCEPTION
WHEN OTHERS THEN
NULL; -- never let auditing block a login
END logon_audit_trg;
/The COMMIT is legal because the autonomous transaction is separate from anything the session does later. The WHEN OTHERS THEN NULL handler is deliberate, and the warning below explains why.
Example: Logging Server Errors
A SERVERERROR trigger fires after an error is raised to the client. You can use it to capture errors that applications fail to log. Check which error occurred with ORA_SERVER_ERROR(1) and write it to a table through an autonomous transaction, as in the logon example. Two details matter:
- The trigger does not fire for some errors, such as
ORA-00600internal errors in certain states and errors that stop the session from running any code. - If the trigger itself raises an error, Oracle ignores it so the original error still reaches the user.
Practical Rules for System Triggers
- Keep the body short. DDL and logon triggers run on every matching event, so slow code makes every login or schema change slow.
- Never put a
COMMITin a DDL trigger body. DDL commits implicitly, and the trigger runs inside that statement. Use an autonomous transaction if you must write a log row. - Be careful with
ON DATABASE. It affects every schema, including ones you do not own. - Qualify what you test. Filter on
ORA_DICT_OBJ_TYPE,ORA_DICT_OBJ_NAMEorORA_LOGIN_USERso the trigger does only what you intend. - Remember the rollback behavior. If a
BEFOREDDL trigger raises an error, the DDL does not happen. If anAFTERDDL trigger raises an error, the DDL has already completed and cannot be undone.
Finding and Managing System Triggers
System triggers appear in USER_TRIGGERS with a BASE_OBJECT_TYPE of SCHEMA or DATABASE and no table name:
SELECT trigger_name, triggering_event, base_object_type, status
FROM user_triggers
WHERE base_object_type IN ('SCHEMA', 'DATABASE');Use ALTER TRIGGER ... DISABLE and ENABLE as with any other trigger. Compilation errors show up with SHOW ERRORS TRIGGER trigger_name. Note that ALTER TABLE ... DISABLE ALL TRIGGERS does not touch system triggers, because they have no base table.
Exercise
You create BEFORE DROP ON SCHEMA with a body that raises error -20003 unconditionally, with no check of ORA_DICT_OBJ_TYPE. A colleague then tries DROP VIEW emp_v. What happens, and how do you fix the trigger so that only table drops are blocked?
Show answer
The DROP VIEW fails with ORA-00604 and ORA-20003, because the trigger fires for every DROP in the schema and always raises the error. Fix it by wrapping the raise in IF ORA_DICT_OBJ_TYPE = 'TABLE' THEN ... END IF;, so views, indexes and other objects are dropped normally.
Exercise
A logon trigger inserts a row into an audit table, but the tablespace for that table is full. The body has no exception handler. What is the effect on users, and what two changes make the trigger safe?
Show answer
The insert raises an error, so the logon trigger fails and ordinary users cannot log in. Make it safe by adding a WHEN OTHERS exception handler so the error is swallowed, and by using PRAGMA AUTONOMOUS_TRANSACTION with its own COMMIT so the audit insert does not depend on the session's transaction.