Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion schemainspect/pg/obj.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
33 changes: 31 additions & 2 deletions tests/test_triggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()