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



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

def cache
  @cache ||= {}
end

#load_cacheObject



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

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

#resolve(value) ⇒ Object



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

def resolve(value)
  if @use_cache
    cache[cache_key(value)]
  else
    q = "SELECT id FROM #{table_name} WHERE #{wheres(value)}"
    @connection.select_value(q)
  end
end

#table_nameObject



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

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