Class: RailsAiBridge::Introspectors::DatabaseStatsIntrospector

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_ai_bridge/introspectors/database_stats_introspector.rb

Overview

Collects approximate row counts from PostgreSQL's pg_stat_user_tables. Only activates for PostgreSQL adapter; returns { skipped: true } otherwise.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ DatabaseStatsIntrospector

Returns a new instance of DatabaseStatsIntrospector.



10
11
12
# File 'lib/rails_ai_bridge/introspectors/database_stats_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_bridge/introspectors/database_stats_introspector.rb', line 8

def app
  @app
end

Instance Method Details

#callObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/rails_ai_bridge/introspectors/database_stats_introspector.rb', line 14

def call
  return { skipped: true, reason: 'ActiveRecord not available' } unless defined?(ActiveRecord::Base)

  adapter = ActiveRecord::Base.connection.adapter_name.downcase
  return { skipped: true, reason: "Only available for PostgreSQL (current: #{adapter})" } unless adapter.include?('postgresql')

  rows = ActiveRecord::Base.connection.select_all(<<~SQL.squish)
    SELECT relname AS table_name,
           n_live_tup AS approximate_row_count
    FROM pg_stat_user_tables
    ORDER BY n_live_tup DESC
  SQL

  tables = rows.map do |row|
    { table: row['table_name'], approximate_rows: row['approximate_row_count'].to_i }
  end

  { adapter: 'postgresql', tables: tables, total_tables: tables.size }
rescue StandardError => error
  { error: error.message }
end