Class: RailsAiContext::Introspectors::SchemaIntrospector

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_ai_context/introspectors/schema_introspector.rb

Overview

Extracts database schema information including tables, columns, indexes, and foreign keys from the Rails application.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ SchemaIntrospector

Returns a new instance of SchemaIntrospector.



10
11
12
# File 'lib/rails_ai_context/introspectors/schema_introspector.rb', line 10

def initialize(app)
  @app = app
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



8
9
10
# File 'lib/rails_ai_context/introspectors/schema_introspector.rb', line 8

def app
  @app
end

Instance Method Details

#callHash

Returns database schema context.

Returns:

  • (Hash)

    database schema context



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
# File 'lib/rails_ai_context/introspectors/schema_introspector.rb', line 15

def call
  return static_schema_parse unless active_record_connected?
  return static_schema_parse if table_names.empty?

  schema_content = File.exist?(schema_file_path) ? (RailsAiContext::SafeFile.read(schema_file_path, max_size: RailsAiContext.configuration.max_schema_file_size) || "") : ""

  check_constraints = []
  enum_types = []
  if File.exist?(schema_file_path) && defined?(Listeners::SchemaDslListener)
    ast_results = SourceIntrospector.walk(schema_file_path, { schema: -> { Listeners::SchemaDslListener.new } })
    schema_results = ast_results[:schema]

    current_table = nil
    schema_results.sort_by { |r| r[:location] }.each do |entry|
      case entry[:type]
      when :create_table then current_table = entry[:table]
      when :check_constraint
        check_constraints << { table: current_table, expression: entry[:expression] } if current_table
      when :add_check_constraint
        check_constraints << { table: entry[:table], expression: entry[:expression] }
      when :enum
        enum_types << { name: entry[:name], values: entry[:values] }
      end
    end
  end

  {
    adapter: adapter_name,
    tables: extract_tables,
    total_tables: table_names.size,
    schema_version: current_schema_version,
    check_constraints: check_constraints,
    enum_types: enum_types,
    generated_columns: parse_generated_columns(schema_content)
  }
end