53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
# File 'lib/constant_table_saver.rb', line 53
def find_by_sql(sql, binds = [])
@find_by_sql ||= {}
@find_by_sql[:all] ||= all.to_sql
@find_by_sql[:id] ||= relation.where(relation.table[primary_key].eq(connection.substitute_at(columns_hash[primary_key], 1))).limit(1).to_sql
@find_by_sql[:oldid] ||= relation.where(relation.table[primary_key].eq(connection.substitute_at(columns_hash[primary_key], 1))).
order(relation.table[primary_key].asc).limit(1).to_sql
@find_by_sql[:first] ||= relation.order(relation.table[primary_key].asc).limit(1).to_sql
@find_by_sql[:last] ||= relation.order(relation.table[primary_key].desc).limit(1).to_sql
_sql = sanitize_sql(sql)
_sql = _sql.to_sql if sql.respond_to?(:to_sql)
if binds.empty?
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 (_sql == @find_by_sql[:id] || _sql == @find_by_sql[:oldid]) &&
binds.length == 1 &&
binds.first.first.is_a?(ActiveRecord::ConnectionAdapters::Column) &&
binds.first.first.name == primary_key
@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
|