The Oracle-compatible mode of OceanBase Database supports system triggers. System triggers are classified into two categories based on the triggering event: database event triggers and DDL event triggers. Database event triggers are triggered by LOGON and LOGOFF events, while DDL event triggers are triggered by DDL statements. Starting from V4.4.2 BP4, OceanBase Database supports creating BEFORE DDL triggers.
DDL triggers are automatically executed before the execution of a DDL statement. They are commonly used to record DDL operation logs, audit DDL changes, and block non-compliant DDL operations by throwing exceptions.
Scope of application
- Only user tenants in Oracle-compatible mode support DDL triggers. Creating system triggers that listen for the
SYSschema is not allowed, meaningON SYS.SCHEMAis not supported. - Only the
BEFOREtrigger timing is supported.AFTER DDLtriggers are not currently supported. - Standby tenants in primary/standby databases do not trigger DDL triggers.
- DDL triggers are controlled by the overall system trigger switch, which is enabled by default.
Syntax
CREATE [OR REPLACE] TRIGGER [schema.]trigger_name
BEFORE ddl_event [OR ddl_event]...
ON {[schema.]SCHEMA | DATABASE}
[FOLLOWS [owner.]other_trigger]
[ENABLE | DISABLE]
[WHEN (condition)]
DECLARE
...
BEGIN
...
END;
/
Parameters
Parameter |
Description |
|---|---|
trigger_name |
The name of the trigger. The trigger name must be unique within the same schema and can be the same as that of a table or stored procedure. |
BEFORE |
Specifies that the trigger fires before a DDL statement is executed. DDL event triggers support onlyBEFORE. |
ddl_event |
Trigger events. You can specify one or more events. Separate multiple events with commas (,).ORSeparation. For supported events, see DDL Events below. |
ON SCHEMA |
Specifies the scope of the trigger to be schema-level. If not specified, the default scope isschemaBy default, it is bound to the execution time of the creation statement.CURRENT_SCHEMA, which is not necessarily the schema where the logged-in user belongs. The owner of a trigger is determined bytrigger_nameThe schema before the comma determines whether it can be different from the target schema being listened on. |
ON DATABASE |
Specifies that the trigger's scope applies to all users within the current user tenant, not across tenants. |
FOLLOWS |
Specify the execution order of triggers, that is, for new triggers in theother_triggerThen execute. |
ENABLE \ | DISABLE |
Specifies the trigger's enable status. Default value:ENABLE. |
WHEN (condition) |
Specify the trigger condition.conditionA boolean expression. You can use event attribute functions to construct boolean conditions, but cannot reference:OLD、:NEWand other pseudo-records. |
DDL events
Events ( ORA_SYSEVENT(return value) |
Trigger Statement |
|---|---|
CREATE |
CREATE TABLE(CTAS, GTT),CREATE INDEX、CREATE VIEW、CREATE MATERIALIZED VIEW、CREATE MATERIALIZED VIEW LOG、CREATE SEQUENCE、CREATE PROCEDURE、CREATE FUNCTION、CREATE PACKAGE/PACKAGE BODY、CREATE TRIGGER、CREATE TYPE/TYPE BODY、CREATE SYNONYM、CREATE DATABASE LINK、CREATE TABLESPACE、CREATE DIRECTORY、CREATE CONTEXT、CREATE OUTLINE、CREATE USER、CREATE ROLE、CREATE PROFILE.CREATE OR REPLACEIt is triggered only once. |
ALTER |
ALTER TABLE、ALTER INDEX、ALTER VIEW、ALTER MATERIALIZED VIEW、ALTER SEQUENCE、ALTER PROCEDURE、ALTER FUNCTION、ALTER PACKAGE、ALTER TRIGGER、ALTER TYPE、ALTER TABLESPACE、ALTER OUTLINE、ALTER USER(including changing passwords, locking users, and modifying profiles),ALTER ROLE、ALTER PROFILE.ALTER TABLE ... RENAMEandALTER TABLE ... DROP COLUMNAll belong toALTEREvents. |
DROP |
DROP TABLE、DROP INDEX、DROP VIEW、DROP MATERIALIZED VIEW、DROP MATERIALIZED VIEW LOG、DROP SEQUENCE、DROP PROCEDURE、DROP FUNCTION、DROP PACKAGE、DROP TRIGGER、DROP TYPE、DROP SYNONYM、DROP DATABASE LINK、DROP TABLESPACE、DROP DIRECTORY、DROP CONTEXT、DROP OUTLINE、DROP USER、DROP ROLE、DROP PROFILE.DROP TABLE ... PURGEBelongs toDROPEvents,CASCADEDeletion cascades are not triggered individually for each object being cascaded. |
TRUNCATE |
TRUNCATE TABLE.ALTER TABLEThe partitioning operations in the middle will not be mapped toTRUNCATEEvents. |
RENAME |
standaloneRENAMEstatement.ALTER ... RENAMEThis event is not triggered. |
COMMENT |
COMMENT ON TABLE、COMMENT ON COLUMN. |
ANALYZE |
For queries executed on a single tableANALYZE TABLE. |
AUDIT / NOAUDIT |
AUDIT、NOAUDITThe statement must be supported by the Enterprise Edition audit feature. |
GRANT / REVOKE |
The granting and revoking of object privileges, system privileges, and roles are triggered only once per statement. |
DDL |
Captures all the preceding DDL events to define a generic DDL trigger. |
Note
DDL events can also capture events that are not listed separately, such as FLASHBACK TABLE ... TO BEFORE DROP (ORA_SYSEVENT returns UNDROP) and PURGE TABLE (ORA_SYSEVENT returns PURGE).
The following operations do not trigger DDL triggers:
- OceanBase resource and tenant management statements, such as
RESOURCE POOL,RESOURCE UNIT,TENANT,STANDBY TENANT,TABLEGROUP, etc. - OceanBase or MySQL-compatible extension statements, such as
OPTIMIZE,SET GLOBAL,CREATE TABLE LIKE,LOCATION,CATALOG, throttling rules, etc. - Statements with different semantics in Oracle-compatible mode, such as
CREATE DATABASE,ALTER DATABASE,ALTER SYSTEM,ALTER SESSION, etc. - Internally derived actions of DDL, such as insertions and failure cleanup of CTAS, implicitly created or deleted indexes, container tables of materialized views, etc.
- Kernel internal actions, such as RootService internal SQL, subtasks and recovery of DDL tasks, RPC retransmission, log replay, standby database applications, etc.
Event attribute functions
In the trigger body and WHEN conditions of a DDL trigger, you can call event attribute functions to obtain information related to the current DDL event. OceanBase Database provides the following 16 ORA_* functions:
Function |
Applicable Events |
Return value |
|---|---|---|
ORA_SYSEVENT |
All Events | The name of the current event, which is the event name in the table above. |
ORA_LOGIN_USER |
All Events | The currently logged-in username, which does not depend on the DDL event context. |
ORA_INSTANCE_NUM |
All Events | The instance number of the current OBServer node, which is independent of the DDL event context. |
ORA_DATABASE_NAME |
All Events | The name of the current tenant, which is independent of the DDL event context. |
ORA_DICT_OBJ_OWNER |
Object DDL,GRANT/REVOKE |
Owner of the DDL target object. |
ORA_DICT_OBJ_NAME |
Object DDL,GRANT/REVOKE |
The name of the DDL target object. |
ORA_DICT_OBJ_TYPE |
Object DDL,GRANT/REVOKE |
The type of the DDL target object.GRANT/REVOKEScenario responseOBJECT PRIVILEGE、SYSTEM PRIVILEGEorROLE PRIVILEGE. |
ORA_SQL_TXT(sql_text OUT ORA_NAME_LIST_T) |
All Events | Returns the SQL text of the triggering statement. Sensitive information such as passwords is masked, and some sensitive statements may be returned in their entirety.***. The returned text is split into segments of at most 63 bytes (ensuring that multibyte characters are fully represented) before being written to the file.sql_text, the function returns the number of shards. |
ORA_IS_ALTER_COLUMN(column_name) |
ALTER |
The specified column in thisALTER TABLEReturns when the value in the field is modified.TRUE, otherwise returnFALSE. |
ORA_IS_DROP_COLUMN(column_name) |
ALTER |
The specified column in thisALTER TABLEWhen deleted in the middle, returnTRUE, otherwise returnFALSE. |
ORA_IS_CREATING_NESTED_TABLE |
CREATE |
OceanBase Database does not support nested table columns in Oracle. This function is retained for compatibility and always returns a fixed value.FALSE. |
ORA_GRANTEE(user_list OUT ORA_NAME_LIST_T) |
GRANT |
Returns all authorized users for the current authorization. The function returns the number of users. |
ORA_REVOKEE(user_list OUT ORA_NAME_LIST_T) |
REVOKE |
Returns the number of users whose permissions were revoked in this operation. |
ORA_PRIVILEGE_LIST(privilege_list OUT ORA_NAME_LIST_T) |
GRANT/REVOKE |
Returns the names of the privileges or roles granted or revoked this time, along with the number of returns. Usage:ALLare expanded in the order of the OceanBase Database permission model. |
ORA_WITH_GRANT_OPTION |
GRANT |
Grants privileges on objects and is accompanied byWITH GRANT OPTIONreturnedTRUE;WITH ADMIN OPTIONReturnFALSE. |
ORA_DES_ENCRYPTED_PASSWORD |
CREATE/ALTER |
OceanBase Database does not have an equivalent DES encrypted value. This function is retained for compatibility and always returns a fixed value.NULL. |
Note
ORA_NAME_LIST_T is a collection type defined in the SYS.DBMS_STANDARD package, with elements of type VARCHAR2(261). The functions in the aforementioned DBMS_STANDARD can be called directly without adding a package prefix, for example, ORA_GRANTEE(user_list). When there is no DDL event context, context-dependent functions return NULL or FALSE.
Limitations
When creating and using DDL triggers, note the following limitations:
The matching rules for trigger scopes are as follows:
ON SCHEMAmatches by the current user. That is, when the current user executes DDL, it triggers DDL triggers on the user's own schema; it does not match by the owner of the DDL target object.ON DATABASEmatches by the current tenant. Whenever any user within the current tenant executes DDL, it will be triggered.
The execution order rules are as follows:
- When the same DDL statement matches both schema-level and database-level triggers, the schema-level trigger is executed first, followed by the database-level trigger.
- Within the same scope, you can use
FOLLOWSto specify the execution order of triggers. If not specified, the execution order of multiple triggers is uncertain. - Specifying
FOLLOWSacross scopes is not supported. The referenced trigger must also be a DDL trigger, and their trigger event sets must have an intersection.
Executing any DDL, DCL, or
ANALYZEstatements via SQL or PL's SPI interface is prohibited within the Trigger Body.Setting global variables and system variables is prohibited within the Trigger Body.
A regular DDL trigger cannot execute
COMMITorROLLBACK; otherwise, theORA-04092error is returned. If a trigger is declared as an autonomous transaction usingPRAGMA AUTONOMOUS_TRANSACTION, the commit in an autonomous transaction is independent of the batch transaction that triggered it.When the current trigger is the DDL target, it does not participate in its own triggering, for example, operations like
CREATE OR REPLACE TRIGGERorDROP TRIGGER.DDL initiated internally by the kernel or on a standby tenant does not trigger triggers; when the same DDL is automatically retried, previously committed triggers are not re-executed.
Transaction description
DDL triggers and subsequent DDL statements are not executed within the same transaction. The specific behavior is as follows:
- All DDL triggers matched by a single DDL statement are executed sequentially within the same batch transaction. During execution, the session's automatic commit is temporarily disabled.
- After all triggers are successfully executed, the batch transaction is committed once, and then the actual DDL statement is executed or a DDL request is sent to RootService.
- If any trigger fails to execute, the entire batch transaction is rolled back, and the DDL is aborted without performing the actual DDL operation.
- After the trigger batch transaction is committed, if the subsequent DDL execution fails, times out, or is canceled, the modifications already committed by the trigger will not be rolled back.
Notice
Because triggers and DDL belong to two separate transactions, the logs recorded by the trigger or the data written by it still exist if the DDL fails. Business implementations must allow for this inconsistency. If you need to strictly ensure that trigger modifications succeed or fail together with the DDL, perform only validation or provide prompts within the trigger, and do not rely on the data written by the trigger to determine whether the DDL succeeded.
Privilege requirements
- To create a DDL trigger in your own schema, you must have the
CREATE TRIGGERorCREATE ANY TRIGGERsystem privilege. - To create a DDL trigger across schemas, or to listen for other users' schemas using
ON schema.SCHEMA, you must have theCREATE ANY TRIGGERsystem privilege. - To create a database-level DDL trigger (
ON DATABASE), in addition to the above creation privileges, you must also have theADMINISTER DATABASE TRIGGERsystem privilege.
Example
Create a DDL log table to record DDL events.
CREATE TABLE ddl_log (
event_name VARCHAR2(50),
obj_type VARCHAR2(50),
obj_name VARCHAR2(128),
login_user VARCHAR2(128),
ddl_time DATE
);
Create a schema-level BEFORE CREATE trigger to record the object information of CREATE statements.
CREATE OR REPLACE TRIGGER trg_before_create
BEFORE CREATE ON SCHEMA
BEGIN
INSERT INTO ddl_log
VALUES (ORA_SYSEVENT, ORA_DICT_OBJ_TYPE, ORA_DICT_OBJ_NAME, ORA_LOGIN_USER, SYSDATE);
END;
/
Execute a CREATE TABLE statement to verify that the trigger takes effect.
CREATE TABLE t_ddl_trigger_demo (id INT);
Query the log table to view the record for this CREATE event.
SELECT * FROM ddl_log;
Create a database-level BEFORE DDL trigger to record all DDL events within the current tenant. The user executing this example must have the ADMINISTER DATABASE TRIGGER system privilege in addition to basic creation privileges.
CREATE OR REPLACE TRIGGER trg_before_ddl
BEFORE DDL ON DATABASE
BEGIN
INSERT INTO ddl_log
VALUES (ORA_SYSEVENT, ORA_DICT_OBJ_TYPE, ORA_DICT_OBJ_NAME, ORA_LOGIN_USER, SYSDATE);
END;
/
Create a BEFORE DROP trigger to block DROP TABLE operations by throwing an exception when a table is dropped.
CREATE OR REPLACE TRIGGER trg_before_drop
BEFORE DROP ON SCHEMA
BEGIN
IF ORA_DICT_OBJ_TYPE = 'TABLE' THEN
RAISE_APPLICATION_ERROR(-20001, 'DROP TABLE is not allowed');
END IF;
END;
/
After use, drop the triggers and tables created in the examples.
DROP TRIGGER trg_before_create;
DROP TRIGGER trg_before_ddl;
DROP TRIGGER trg_before_drop;
DROP TABLE t_ddl_trigger_demo;
DROP TABLE ddl_log;