Class: AuditTables::BuildAuditTrigger

Inherits:
Object
  • Object
show all
Defined in:
lib/audit_tables/build_audit_trigger.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table_name) ⇒ BuildAuditTrigger

Returns a new instance of BuildAuditTrigger.



6
7
8
# File 'lib/audit_tables/build_audit_trigger.rb', line 6

def initialize(table_name)
  @table_name = table_name
end

Instance Attribute Details

#table_nameObject (readonly)

Returns the value of attribute table_name.



4
5
6
# File 'lib/audit_tables/build_audit_trigger.rb', line 4

def table_name
  @table_name
end

Instance Method Details

#buildObject

rubocop:disable Metrics/MethodLength:



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/audit_tables/build_audit_trigger.rb', line 11

def build
  sequence_name = "seq_audit_#{table_name}"

  execute %{
    DROP TRIGGER IF EXISTS trigger_audit_#{table_name} ON #{table_name};

    CREATE SEQUENCE IF NOT EXISTS #{sequence_name} START 1;

    CREATE OR REPLACE FUNCTION trigger_audit_#{table_name}_func() RETURNS TRIGGER AS $body$
    BEGIN
      IF (TG_OP = 'INSERT') THEN
        INSERT INTO audit_#{table_name}
        SELECT nextval('#{sequence_name}'), 'INSERT', NOW(), *
        FROM #{table_name}
        WHERE id = NEW.id;
      ELSIF (TG_OP = 'UPDATE') THEN
        INSERT INTO audit_#{table_name}
        SELECT nextval('#{sequence_name}'), 'UPDATE', NOW(), *
        FROM #{table_name}
        WHERE id = OLD.id;
      ELSIF (TG_OP = 'DELETE') THEN
        INSERT INTO audit_#{table_name}
        SELECT nextval('#{sequence_name}'), 'DELETE', NOW(), OLD.*;
      END IF;
      RETURN NULL;
    END;
    $body$
    LANGUAGE plpgsql
    SECURITY DEFINER;

    CREATE TRIGGER trigger_audit_#{table_name} AFTER INSERT OR UPDATE OR DELETE ON #{table_name}
    FOR EACH ROW EXECUTE PROCEDURE trigger_audit_#{table_name}_func();
  }
end