Module: ActiveVersion::Database::Triggers::PostgreSQL

Defined in:
lib/active_version/database/triggers/postgresql.rb

Overview

PostgreSQL trigger support for ActiveVersion

Class Method Summary collapse

Class Method Details

.drop_trigger(trigger_name, table_name) ⇒ String

Drop trigger

Parameters:

  • trigger_name (String)

    Name of the trigger

  • table_name (String)

    Name of the table

Returns:

  • (String)

    SQL for DROP TRIGGER statement



212
213
214
# File 'lib/active_version/database/triggers/postgresql.rb', line 212

def drop_trigger(trigger_name, table_name)
  "DROP TRIGGER IF EXISTS #{trigger_name} ON #{table_name} CASCADE;"
end

.drop_trigger_function(function_name) ⇒ String

Drop trigger function

Parameters:

  • function_name (String)

    Name of the function

Returns:

  • (String)

    SQL for DROP FUNCTION statement



204
205
206
# File 'lib/active_version/database/triggers/postgresql.rb', line 204

def drop_trigger_function(function_name)
  "DROP FUNCTION IF EXISTS #{function_name}() CASCADE;"
end

.generate_audit_trigger(table_name, options = {}) ⇒ String

Generate trigger for audits

Parameters:

  • table_name (String)

    Name of the table

  • options (Hash) (defaults to: {})

    Trigger options

Returns:

  • (String)

    SQL for CREATE TRIGGER statement



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/active_version/database/triggers/postgresql.rb', line 114

def generate_audit_trigger(table_name, options = {})
  function_name = "active_version_audit_#{table_name}"
  trigger_name = options[:trigger_name] || "active_version_audit_on_#{table_name}"
  events = options[:events] || [:insert, :update, :delete]

  event_clause = events.map(&:upcase).join(" OR ")

  <<~SQL
    CREATE TRIGGER #{trigger_name}
    AFTER #{event_clause} ON #{table_name}
    FOR EACH ROW
    WHEN (coalesce(current_setting('active_version.disabled', true), '') <> 'on')
    EXECUTE FUNCTION #{function_name}();
  SQL
end

.generate_audit_trigger_function(table_name, audit_table_name, options = {}) ⇒ String

Generate trigger function for audits

Parameters:

  • table_name (String)

    Name of the table to create trigger for

  • audit_table_name (String)

    Name of the audit table

  • options (Hash) (defaults to: {})

    Trigger options

Returns:

  • (String)

    SQL for trigger function



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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/active_version/database/triggers/postgresql.rb', line 12

def generate_audit_trigger_function(table_name, audit_table_name, options = {})
  function_name = "active_version_audit_#{table_name}"
  auditable_type = options[:auditable_type] || table_name.classify
  version_column = options[:version_column] || "version"
  changes_column = options[:changes_column] || "audited_changes"
  context_column = options[:context_column] || "audited_context"
  action_column = options[:action_column] || "action"

  <<~SQL
    CREATE OR REPLACE FUNCTION #{function_name}()
    RETURNS TRIGGER AS $$
    DECLARE
      new_version INTEGER;
      changes JSONB;
      context_data JSONB;
      action_type TEXT;
    BEGIN
      -- Determine action
      IF TG_OP = 'INSERT' THEN
        action_type := 'create';
        changes := to_jsonb(NEW.*);
      ELSIF TG_OP = 'UPDATE' THEN
        action_type := 'update';
        changes := jsonb_build_object(
          'old', to_jsonb(OLD.*),
          'new', to_jsonb(NEW.*)
        );
      ELSIF TG_OP = 'DELETE' THEN
        action_type := 'destroy';
        changes := to_jsonb(OLD.*);
      END IF;

      -- Get version number
      IF action_type = 'create' THEN
        new_version := 1;
      ELSE
        SELECT COALESCE(MAX(#{version_column}), 0) + 1
        INTO new_version
        FROM #{audit_table_name}
        WHERE #{audit_table_name}.auditable_id = COALESCE(NEW.id, OLD.id)
          AND #{audit_table_name}.auditable_type = '#{auditable_type}';
      END IF;

      -- Get context from session variables (if set)
      context_data := COALESCE(
        current_setting('active_version.context', true)::jsonb,
        '{}'::jsonb
      );

      -- Insert audit record
      IF TG_OP = 'DELETE' THEN
        INSERT INTO #{audit_table_name} (
          auditable_id,
          auditable_type,
          #{action_column},
          #{changes_column},
          #{version_column},
          #{context_column},
          created_at,
          updated_at
        ) VALUES (
          OLD.id,
          '#{auditable_type}',
          action_type,
          changes,
          new_version,
          context_data,
          NOW(),
          NOW()
        );
        RETURN OLD;
      ELSE
        INSERT INTO #{audit_table_name} (
          auditable_id,
          auditable_type,
          #{action_column},
          #{changes_column},
          #{version_column},
          #{context_column},
          created_at,
          updated_at
        ) VALUES (
          NEW.id,
          '#{auditable_type}',
          action_type,
          changes,
          new_version,
          context_data,
          NOW(),
          NOW()
        );
        RETURN NEW;
      END IF;
    END;
    $$ LANGUAGE plpgsql;
  SQL
end

.generate_revision_trigger(table_name, options = {}) ⇒ String

Generate trigger for revisions

Parameters:

  • table_name (String)

    Name of the table

  • options (Hash) (defaults to: {})

    Trigger options

Returns:

  • (String)

    SQL for CREATE TRIGGER statement



188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/active_version/database/triggers/postgresql.rb', line 188

def generate_revision_trigger(table_name, options = {})
  function_name = "active_version_revision_#{table_name}"
  trigger_name = options[:trigger_name] || "active_version_revision_on_#{table_name}"

  <<~SQL
    CREATE TRIGGER #{trigger_name}
    BEFORE UPDATE ON #{table_name}
    FOR EACH ROW
    WHEN (coalesce(current_setting('active_version.disabled', true), '') <> 'on')
    EXECUTE FUNCTION #{function_name}();
  SQL
end

.generate_revision_trigger_function(table_name, revision_table_name, options = {}) ⇒ String

Generate trigger function for revisions

Parameters:

  • table_name (String)

    Name of the table

  • revision_table_name (String)

    Name of the revision table

  • options (Hash) (defaults to: {})

    Trigger options

Returns:

  • (String)

    SQL for trigger function



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/active_version/database/triggers/postgresql.rb', line 135

def generate_revision_trigger_function(table_name, revision_table_name, options = {})
  function_name = "active_version_revision_#{table_name}"
  foreign_key = options[:foreign_key] || "#{table_name.singularize}_id"
  version_column = options[:version_column] || "version"

  <<~SQL
    CREATE OR REPLACE FUNCTION #{function_name}()
    RETURNS TRIGGER AS $$
    DECLARE
      new_version INTEGER;
      revision_data RECORD;
    BEGIN
      -- Only create revision on UPDATE
      IF TG_OP != 'UPDATE' THEN
        RETURN NEW;
      END IF;

      -- Skip if nothing changed
      IF NEW.* IS NOT DISTINCT FROM OLD.* THEN
        RETURN NEW;
      END IF;

      -- Get next version number
      SELECT COALESCE(MAX(#{version_column}), 0) + 1
      INTO new_version
      FROM #{revision_table_name}
      WHERE #{revision_table_name}.#{foreign_key} = NEW.id;

      -- Create revision with OLD values
      INSERT INTO #{revision_table_name} (
        #{foreign_key},
        #{version_column},
        #{build_revision_columns(table_name, options)},
        created_at,
        updated_at
      )
      SELECT
        NEW.id,
        new_version,
        #{build_revision_values("OLD", table_name, options)},
        NOW(),
        NOW();

      RETURN NEW;
    END;
    $$ LANGUAGE plpgsql;
  SQL
end