120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
|
# File 'lib/constant_table_saver.rb', line 120
def find_by_sql(sql, binds = [])
@find_by_sql ||= {
:all => relation.to_sql,
:id => relation.where(relation.table[primary_key].eq(connection.substitute_at(columns_hash[primary_key], 0))).limit(1).
tap {|r| r.bind_values += [[columns_hash[primary_key], :undefined]]}. arel,
:first => relation.order(relation.table[primary_key].asc).limit(1).to_sql,
:last => relation.order(relation.table[primary_key].desc).limit(1).to_sql,
}
if binds.empty?
_sql = _to_sql_with_binds(sql, binds)
if _sql == @find_by_sql[:all]
return @cached_records ||= super(relation.to_sql).each(&:freeze)
elsif _sql == @find_by_sql[:first]
return [relation.to_a.first].compact
elsif _sql == @find_by_sql[:last]
return [relation.to_a.last].compact
end
elsif binds.length == 1 &&
binds.first.first.is_a?(ActiveRecord::ConnectionAdapters::Column) &&
binds.first.first.name == primary_key &&
_to_sql_with_binds(sql, binds) == _to_sql_with_binds(@find_by_sql[:id], binds) @cached_records_by_id ||= relation.to_a.index_by {|record| record.id.to_param}
return [@cached_records_by_id[binds.first.last.to_param]].compact
end
super
end
|