diff --git a/schemainspect/pg/obj.py b/schemainspect/pg/obj.py index 0b60c8c..8c73b47 100644 --- a/schemainspect/pg/obj.py +++ b/schemainspect/pg/obj.py @@ -365,7 +365,20 @@ def drop_statement(self): @property def create_statement(self): - return self.full_definition + ";" + status_sql = { + 'O': 'ENABLE TRIGGER', + 'D': 'DISABLE TRIGGER', + 'R': 'ENABLE REPLICA TRIGGER', + 'A': 'ENABLE ALWAYS TRIGGER' + } + schema = quoted_identifier(self.schema) + table = quoted_identifier(self.table_name) + trigger_name = quoted_identifier(self.name) + if self.enabled in ('D', 'R', 'A'): + table_alter = f'ALTER TABLE {schema}.{table} {status_sql[self.enabled]} {trigger_name}' + return self.full_definition + ";\n" + table_alter + ";" + else: + return self.full_definition + ";" def __eq__(self, other): """ diff --git a/tests/test_triggers.py b/tests/test_triggers.py index 0a60b7a..d44a94e 100644 --- a/tests/test_triggers.py +++ b/tests/test_triggers.py @@ -31,9 +31,38 @@ """ -def test_triggers(db): +def test_view_trigger(db): with S(db) as s: s.execute(BASE) i = get_inspector(s) - i.triggers['"public"."view_on_table"."trigger_on_view"'] + trigger = i.triggers['"public"."view_on_table"."trigger_on_view"'] + + # Triggers on views should not include the ALTER TABLE part of the create statement + assert 'ALTER TABLE' not in trigger.create_statement() + + +def test_replica_trigger(db): + with S(db) as s: + s.execute(BASE) + function = ''' + CREATE OR REPLACE FUNCTION table_trigger_function() + RETURNS trigger + LANGUAGE plpgsql + AS $function$ + BEGIN + RETURN NEW; + END; + $function$ + ; + ''' + s.execute(function) + s.execute('CREATE TRIGGER table_trigger AFTER INSERT ON my_table FOR EACH ROW EXECUTE PROCEDURE table_trigger_function();') + s.execute('ALTER TABLLE my_table ENABLE REPLICA TRIGGER table_trigger;') + + i = get_inspector(s) + + trigger = i.triggers['"public"."my_table"."table_trigger"'] + + # Replica trigger needs the ALTER TABLE statement as well as the trigger definition + assert 'ALTER TABLE' in trigger.create_statement()