Class: SQLResolver

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

Direct Known Subclasses

IncrementalCacheSQLResolver

Instance Method Summary (collapse)

Constructor Details

- (SQLResolver) initialize(atable, afield, connection = nil)

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.



94
95
96
97
98
99
100
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 94

def initialize(atable, afield, connection=nil)
  # puts "table: #{atable.inspect} field:#{afield.inspect}"
  @table = atable
  @field = afield
  @connection = (connection.respond_to?(:quote) ? connection : ETL::Engine.connection(connection)) if connection
  @connection ||= ActiveRecord::Base.connection
end

Instance Method Details

- (Object) cache



120
121
122
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 120

def cache
  @cache ||= {}
end

- (Object) load_cache



124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 124

def load_cache
  q = "SELECT id, #{field.join(', ')} FROM #{table_name}"
  # puts q
  @connection.select_all(q).each do |record|
    ck = @field.kind_of?(Array) ? record.values_at(*@field) : record[@field]
    # puts "load_cache key: #{ck.class.name}:#{ck.inspect}"
    # puts "  #{@field.class.name}:#{@field.inspect}"
    # puts "  #{record[@field].class.name}:#{record[@field].inspect}"
    cache[ck] = record['id']
  end
  @use_cache = true
end

- (Object) resolve(value)



102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 102

def resolve(value)
  return nil if value.nil?
  r = nil
  if @use_cache
    r = cache[value]
    # puts "resolve failed: #{value.class.name}:#{value.inspect} from: #{@table}.#{@field}" unless r
  else
    q = "SELECT id FROM #{table_name} WHERE #{wheres(value)}"
    # puts q
    r = @connection.select_value(q)
  end
  r
end

- (Object) table_name



116
117
118
# File 'lib/etl/transform/foreign_key_lookup_transform.rb', line 116

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