Class: SQLResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/etl/transform/foreign_key_lookup_transform.rb

Instance Method Summary collapse

Constructor Details

#initialize(table, field, connection = nil) ⇒ SQLResolver

Initialize the SQL resolver. Use the given table and field name to search for the appropriate foreign key. The field should be the name of a natural key that is used to locate the surrogate key for the record.

The connection argument is optional. If specified it can be either a symbol referencing a connection defined in the ETL database.yml file or an actual ActiveRecord connection instance. If the connection is not specified then the ActiveRecord::Base.connection will be used.



90
91
92
93
94
95
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 90

def initialize(table, field, connection=nil)
  @table = table
  @field = field
  @connection = (connection.respond_to?(:quote) ? connection : ETL::Engine.connection(connection)) if connection
  @connection ||= ActiveRecord::Base.connection
end

Instance Method Details

#cacheObject



108
109
110
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 108

def cache
  @cache ||= {}
end

#load_cacheObject



111
112
113
114
115
116
117
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 111

def load_cache
  @use_cache = true
  q = "SELECT id, #{@field} FROM #{table_name}"
  @connection.select_all(q).each do |record|
    cache[record[@field]] = record['id']
  end
end

#resolve(value) ⇒ Object



96
97
98
99
100
101
102
103
104
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 96

def resolve(value)
  if @use_cache
    cache[value]
  else
    q = "SELECT id FROM #{table_name} WHERE #{@field} = #{@connection.quote(value)}"
    ETL::Engine.logger.debug("Executing query: #{q}")
    @connection.select_value(q)
  end
end

#table_nameObject



105
106
107
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 105

def table_name
  ETL::Engine.table(@table, @connection)
end