Class: Dexter::ColumnResolver

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/dexter/column_resolver.rb

Constant Summary

Constants included from Logging

Logging::COLOR_CODES

Instance Method Summary collapse

Methods included from Logging

#colorize, #log, #output

Constructor Details

#initialize(connection, queries, log_level:) ⇒ ColumnResolver

Returns a new instance of ColumnResolver.



5
6
7
8
9
# File 'lib/dexter/column_resolver.rb', line 5

def initialize(connection, queries, log_level:)
  @connection = connection
  @queries = queries
  @log_level = log_level
end

Instance Method Details

#performObject



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
# File 'lib/dexter/column_resolver.rb', line 11

def perform
  tables = Set.new(@queries.flat_map(&:candidate_tables))
  columns = tables.any? ? self.columns(tables) : []
  columns_by_table = columns.group_by { |c| c[:table] }.transform_values { |v| v.to_h { |c| [c[:column], c] } }
  columns_by_table.default = {}

  @queries.each do |query|
    log "Finding columns: #{query.statement}" if @log_level == "debug3"
    columns = Set.new
    begin
      find_columns(query.tree).each do |col|
        last_col = col["fields"].last
        if last_col["String"]
          columns << last_col["String"]["sval"]
        end
      end
    rescue JSON::NestingError
      if @log_level.start_with?("debug")
        log colorize("ERROR: Cannot get columns", :red)
      end
    end

    possible_columns = []
    columns.each do |column|
      query.candidate_tables.each do |table|
        resolved = columns_by_table.dig(table, column)
        possible_columns << resolved if resolved
      end
    end
    # use all columns in tables from views (not ideal)
    (query.tables_from_views & query.candidate_tables).each do |table|
      possible_columns.concat(columns_by_table[table].values)
    end
    query.columns = possible_columns.uniq
  end
end