Class: PgSqlTriggers::Testing::DryRun

Inherits:
Object
  • Object
show all
Defined in:
lib/pg_sql_triggers/testing/dry_run.rb

Instance Method Summary collapse

Constructor Details

#initialize(trigger_registry) ⇒ DryRun

Returns a new instance of DryRun.



6
7
8
# File 'lib/pg_sql_triggers/testing/dry_run.rb', line 6

def initialize(trigger_registry)
  @trigger = trigger_registry
end

Instance Method Details

#estimate_impactObject

Show what tables/functions would be affected



51
52
53
54
55
56
57
58
# File 'lib/pg_sql_triggers/testing/dry_run.rb', line 51

def estimate_impact
  definition = JSON.parse(@trigger.definition)
  {
    tables_affected: [@trigger.table_name],
    functions_created: [definition["function_name"]],
    triggers_created: [@trigger.trigger_name]
  }
end

#explainObject

Explain the execution plan (does not execute trigger)



61
62
63
64
65
66
67
68
69
# File 'lib/pg_sql_triggers/testing/dry_run.rb', line 61

def explain
  sql = generate_sql[:sql_parts].pluck(:sql).join("\n\n")

  {
    success: true,
    sql: sql,
    note: "This is a preview only. No changes will be made to the database."
  }
end

#generate_sqlObject

Generate SQL that WOULD be executed (but don’t execute)



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
45
46
47
48
# File 'lib/pg_sql_triggers/testing/dry_run.rb', line 11

def generate_sql
  definition = JSON.parse(@trigger.definition)
  events = definition["events"].map(&:upcase).join(" OR ")

  sql_parts = []

  # 1. Function creation SQL
  if @trigger.function_body.present?
    sql_parts << {
      type: "CREATE FUNCTION",
      sql: @trigger.function_body,
      description: "Creates the trigger function '#{definition['function_name']}'"
    }
  end

  # 2. Trigger creation SQL
  trigger_timing = "BEFORE" # Could be configurable
  trigger_level = "ROW"     # Could be configurable

  trigger_sql = "CREATE TRIGGER #{@trigger.trigger_name} " \
                "#{trigger_timing} #{events} ON #{@trigger.table_name} " \
                "FOR EACH #{trigger_level}"

  trigger_sql += " WHEN (#{@trigger.condition})" if @trigger.condition.present?
  trigger_sql += " EXECUTE FUNCTION #{definition['function_name']}();"

  sql_parts << {
    type: "CREATE TRIGGER",
    sql: trigger_sql,
    description: "Creates the trigger '#{@trigger.trigger_name}' on table '#{@trigger.table_name}'"
  }

  {
    success: true,
    sql_parts: sql_parts,
    estimated_impact: estimate_impact
  }
end