【问题标题】:Get value of atomic counter (increment) with Rails and Postgres使用 Rails 和 Postgres 获取原子计数器的值(增量)
【发布时间】:2015-05-06 17:39:39
【问题描述】:

我需要自动递增模型计数器并使用其新值(由 Sidekiq 作业处理)。

目前,我使用

Group.increment_counter :tasks_count, @task.id

在我的模型中以原子方式递增计数器。

但是我还需要它的新值来发送通知,如果计数器有例如值50。有任何想法吗?锁定表/行还是有更简单的方法?

编辑/解决方案

基于mu is too short的回答和Rails的update_counters方法,我实现了一个实例方法(用PostgreSQL测试)。

def self.increment_counter_and_return_value(counter_name, id)
  quoted_column = connection.quote_column_name(counter_name)
  quoted_table = connection.quote_table_name(table_name)
  quoted_primary_key = connection.quote_column_name(primary_key)
  quoted_primary_key_value = connection.quote(id)

  sql = "UPDATE #{quoted_table} SET #{quoted_column} = COALESCE(#{quoted_column}, 0) + 1 WHERE #{quoted_table}.#{quoted_primary_key} = #{quoted_primary_key_value} RETURNING #{quoted_column}"
  connection.select_value(sql).to_i
end

像这样使用它:

Group.increment_counter_and_return_value(:tasks_count, @task.id)

它使用RETURNING 在同一查询中获取新值。

【问题讨论】:

    标签: ruby-on-rails postgresql rails-activerecord atomic sidekiq


    【解决方案1】:

    您的Group.increment_counter 调用将这样的 SQL 发送到数据库:

    update groups
    set tasks_count = coalesce(tasks_counter, 0) + 1
    where id = X
    

    其中X@task.id。获取新的tasks_counter 值的 SQL 方法是包含一个 RETURNING 子句:

    update groups
    set tasks_count = coalesce(tasks_counter, 0) + 1
    where id = X
    returning tasks_count
    

    不过,我不知道有任何方便的 Railsy 方法可以将该 SQL 导入数据库。通常的 Rails 方法是执行一堆锁定并重新加载 @task 或跳过锁定并希望最好:

    Group.increment_counter :tasks_count, @task.id
    @task.reload
    # and now look at @task.tasks_count to get the new value
    

    您可以像这样使用 RETURNING:

    new_count = Group.connection.execute(%Q{
        update groups
        set tasks_count = coalesce(tasks_counter, 0) + 1
        where id = #{Group.connection.quote(@task.id)}
        returning tasks_count
    }).first['tasks_count'].to_i
    

    您可能想在 Group 上的方法后面隐藏混乱,这样您就可以说:

    n = Group.increment_tasks_count_for(@task)
    # or
    n = @task.increment_tasks_count
    

    【讨论】:

    • 感谢您向我指出这一点。我根据您的回答用实例方法更新了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    相关资源
    最近更新 更多