Class: ViewData::PG::PrimaryKey::GetColumns

Inherits:
Object
  • Object
show all
Includes:
Configure, Dependency
Defined in:
lib/view_data/pg/primary_key/get_columns.rb

Defined Under Namespace

Modules: Telemetry

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.build(session: nil) ⇒ Object



13
14
15
16
17
18
# File 'lib/view_data/pg/primary_key/get_columns.rb', line 13

def self.build(session: nil)
  instance = new
  Session.configure(instance, session: session)
  ::Telemetry.configure(instance)
  instance
end

.call(table) ⇒ Object



20
21
22
23
# File 'lib/view_data/pg/primary_key/get_columns.rb', line 20

def self.call(table)
  instance = build()
  instance.(table)
end

.register_telemetry_sink(instance) ⇒ Object



56
57
58
59
60
# File 'lib/view_data/pg/primary_key/get_columns.rb', line 56

def self.register_telemetry_sink(instance)
  sink = Telemetry::Sink.new
  instance.telemetry.register(sink)
  sink
end

Instance Method Details

#cacheObject



50
51
52
53
54
# File 'lib/view_data/pg/primary_key/get_columns.rb', line 50

def cache
  @cache ||= Hash.new do |hash, table|
    hash[table] = query(table)
  end
end

#call(table) ⇒ Object



25
26
27
# File 'lib/view_data/pg/primary_key/get_columns.rb', line 25

def call(table)
  cache[table]
end

#query(table) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/view_data/pg/primary_key/get_columns.rb', line 29

def query(table)
  result = session.execute(<<~SQL, [table])
    SELECT
      TEXT(attr.attname) AS column_name
    FROM pg_index AS index
    JOIN pg_attribute AS attr
      ON attr.attrelid = index.indrelid
      AND attr.attnum = ANY(index.indkey)
    WHERE index.indrelid = $1::regclass
    AND index.indisprimary
  SQL

  columns = result.to_a.map do |hash|
    hash['column_name']
  end

  telemetry.record(:columns_queried, Telemetry::Data.new(table, columns))

  columns
end