Class: Dbwatcher::Services::DiagramAnalyzers::InferredRelationshipAnalyzer

Inherits:
BaseAnalyzer show all
Defined in:
lib/dbwatcher/services/diagram_analyzers/inferred_relationship_analyzer.rb

Overview

Analyzes relationships based on naming conventions and data patterns

This service infers relationships between tables when explicit foreign keys are not present, using naming conventions, column patterns, and junction table detection.

Examples:

analyzer = InferredRelationshipAnalyzer.new(session)
dataset = analyzer.call

Instance Method Summary collapse

Methods inherited from BaseAnalyzer

#call

Methods inherited from BaseService

call, #call

Methods included from Logging

#debug_enabled?, #log_debug, #log_error, #log_info, #log_warn

Constructor Details

#initialize(session = nil) ⇒ InferredRelationshipAnalyzer

Initialize with session



20
21
22
23
24
25
# File 'lib/dbwatcher/services/diagram_analyzers/inferred_relationship_analyzer.rb', line 20

def initialize(session = nil)
  @session = session
  @connection = ActiveRecord::Base.connection if defined?(ActiveRecord::Base)
  @session_tables = session ? extract_session_tables : []
  super()
end

Instance Method Details

#analyze(_context) ⇒ Array<Hash>

Analyze inferred relationships



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/dbwatcher/services/diagram_analyzers/inferred_relationship_analyzer.rb', line 31

def analyze(_context)
  return [] unless schema_available?

  Rails.logger.debug "InferredRelationshipAnalyzer: Starting analysis with #{tables_to_analyze.length} tables"
  relationships = []

  # Analyze naming convention relationships
  relationships.concat(analyze_naming_conventions)

  # Analyze junction tables
  relationships.concat(analyze_junction_tables)

  # Analyze column patterns
  relationships.concat(analyze_column_patterns)

  Rails.logger.info "InferredRelationshipAnalyzer: Found #{relationships.length} inferred relationships"
  relationships
end

#analyzer_typeString

Get analyzer type



125
126
127
# File 'lib/dbwatcher/services/diagram_analyzers/inferred_relationship_analyzer.rb', line 125

def analyzer_type
  "inferred_relationship"
end

#transform_to_dataset(raw_data) ⇒ DiagramData::Dataset

Transform raw relationship data to Dataset



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
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/dbwatcher/services/diagram_analyzers/inferred_relationship_analyzer.rb', line 54

def transform_to_dataset(raw_data)
  dataset = create_empty_dataset
  dataset..merge!({
                            total_relationships: raw_data.length,
                            tables_analyzed: tables_to_analyze.length,
                            inference_types: raw_data.map { |r| r[:inference_type] }.uniq
                          })

  # Create entities for each unique table
  table_entities = {}

  # First, collect all unique tables from the relationships
  tables = []
  raw_data.each do |relationship|
    tables << relationship[:from_table] if relationship[:from_table]
    tables << relationship[:to_table] if relationship[:to_table]
  end
  tables.uniq!

  # Create entities for all tables
  tables.each do |table_name|
    entity = create_entity(
      id: table_name,
      name: table_name,
      type: "table",
      metadata: {
        table_name: table_name,
        source: "inferred_analysis"
      }
    )
    dataset.add_entity(entity)
    table_entities[table_name] = entity
  end

  # Create relationships in a separate loop
  raw_data.each do |relationship|
    next unless relationship[:from_table] && relationship[:to_table]

    # Include self-referential relationships (source and target are the same)
    # but log them for debugging
    if relationship[:from_table] == relationship[:to_table]
      Rails.logger.info "InferredRelationshipAnalyzer: Including self-referential relationship for " \
                        "#{relationship[:from_table]} " \
                        "(#{relationship[:from_column]} -> #{relationship[:to_column]})"
    end

    relationship_obj = create_relationship({
                                             source_id: relationship[:from_table],
                                             target_id: relationship[:to_table],
                                             type: relationship[:type],
                                             label: relationship[:label],
                                             metadata: {
                                               inference_type: relationship[:inference_type],
                                               confidence: relationship[:confidence],
                                               from_column: relationship[:from_column],
                                               to_column: relationship[:to_column],
                                               original_type: relationship[:type],
                                               self_referential: relationship[:from_table] ==
                          relationship[:to_table]
                                             }
                                           })

    dataset.add_relationship(relationship_obj)
  end

  dataset
end