【问题标题】:How to ensure sqlite isn't caching specific select queries?如何确保 sqlite 不缓存特定的选择查询?
【发布时间】:2009-08-21 18:12:36
【问题描述】:

我的情况是,我将 sqlite 与 ActiveRecord 和 Rails 一起使用(另外,这是 JRuby,所以我实际上正在使用 jdbcsqlite 适配器,以防万一)。现在,我试图在表 attention_seekers 中插入一行,但前提是没有其他现有的类似行。因此,

unless AttentionSeeker.find(:first, :conditions => {:key_id => key.id, :locale_id => l.id})
  item = AttentionSeeker.new(:key_id => key.id, :locale_id => l.id)
  item.save
end

这是日志中生成的输出:

CACHE (0.0ms)   SELECT * FROM attention_seekers WHERE (attention_seekers.key_id = 318 AND attention_seekers.locale_id = 20) 
AttentionSeeker Create (1.0ms)   INSERT INTO attention_seekers (key_id, locale_id) VALUES(318, 20)
CACHE (0.0ms)   SELECT * FROM attention_seekers WHERE (attention_seekers.key_id = 318 AND attention_seekers.locale_id = 20) 
AttentionSeeker Create (2.0ms)   INSERT INTO attention_seekers (key_id, locale_id) VALUES(318, 20)

如您所见,由于某种原因,该查找被缓存,即使我插入了影响它的元素。我做错了什么/如何阻止这种行为?

【问题讨论】:

    标签: ruby-on-rails sqlite activerecord


    【解决方案1】:

    我进行了一些挖掘并遇到了this helpful blog post,并提供了更多信息here。我的解决方案(使用 Mike Buckbee 建议的验证 - 谢谢!):

    AttentionSeeker.uncached do
      item = AttentionSeeker.new(:key_id => key.id, :locale_id => l.id)
      item.save
    end
    

    【讨论】:

    • 真棒乔希,很高兴你明白了。
    【解决方案2】:

    不要将此代码放入您的控制器(我猜它在哪里),您可能需要考虑使用验证,我认为这可以解决问题:

    class AttentionSeeker < ActiveRecord::Base
        validates_uniqueness_of :key_id, :scope => :locale_id
    end
    

    请注意验证规则中的“范围”选项。

    如果您无法尝试将查询包装在 Transaction

    如果做不到这一点,这看起来非常笨拙,您可以向查询本身添加缓存拦截器。类似的东西

    buster = rand(Time.now)
    attention_seeker = AttentionSeeker.find(:first, :conditions => ["#{buster} = #{buster}"])
    

    每次循环都应该给你一个独特的查询。

    【讨论】:

    • 我很高兴尝试这个,但我看到的行为完全相同。
    • 您是否尝试将其包装在事务中? (我的第二个建议)
    • 我将上面的 sn-p 包裹在一个事务中,但没有任何变化。
    【解决方案3】:

    架构级别的唯一索引比 validates_uniqueness_of 更安全。

    http://railswarts.blogspot.com/2007/11/validatesuniquenessof-is-broken-and.html

    斯蒂芬

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2018-01-18
      • 2011-04-13
      • 1970-01-01
      • 2018-06-18
      • 2021-12-13
      • 1970-01-01
      相关资源
      最近更新 更多