class Atomically::QueryService

Constants

DEFAULT_CONFLICT_TARGETS

Public Class Methods

new(klass, relation: nil, model: nil) click to toggle source
# File lib/atomically/query_service.rb, line 15
def initialize(klass, relation: nil, model: nil)
  @klass = klass
  @relation = relation || @klass
  @model = model
end

Public Instance Methods

create_or_plus(columns, data, update_columns, conflict_target: DEFAULT_CONFLICT_TARGETS) click to toggle source
# File lib/atomically/query_service.rb, line 21
def create_or_plus(columns, data, update_columns, conflict_target: DEFAULT_CONFLICT_TARGETS)
  @klass.import(columns, data, on_duplicate_key_update: on_duplicate_key_plus_sql(update_columns, conflict_target))
end
decrement_unsigned_counters(counters) click to toggle source

Parameters

  • counters - A Hash containing the names of the fields to update as keys and the amount to update the field by as values.

# File lib/atomically/query_service.rb, line 69
def decrement_unsigned_counters(counters)
  result = open_update_all_scope do
    counters.each do |field, amount|
      where("#{field} >= ?", amount).update("#{field} = #{field} - ?", amount) if amount > 0
    end
  end
  return (result == 1)
end
pay_all(hash, update_columns, primary_key: :id) click to toggle source
# File lib/atomically/query_service.rb, line 25
def pay_all(hash, update_columns, primary_key: :id) # { id => pay_count }
  return 0 if hash.blank?

  update_columns = update_columns.map(&method(:quote_column))

  query = hash.inject(@klass.none) do |relation, (id, pay_count)|
    condition = @relation.where(primary_key => id)
    update_columns.each{|s| condition = condition.where("#{s} >= ?", pay_count) }
    next relation.or(condition)
  end

  raw_when_sql = hash.map{|id, pay_count| "WHEN #{sanitize(id)} THEN #{sanitize(-pay_count)}" }.join("\n")
  no_var_in_sql = true if update_columns.size == 1 or adapter_check_service.pg?
  update_sqls = update_columns.map.with_index do |column, idx|
    if no_var_in_sql
      value = "(\nCASE #{quote_column(primary_key)}\n#{raw_when_sql}\nEND)"
    else
      value = idx == 0 ? "(@change := \nCASE #{quote_column(primary_key)}\n#{raw_when_sql}\nEND)" : '@change'
    end
    next "#{column} = #{column} + #{value}"
  end

  return where_all_can_be_updated(query, hash.size).update_all(update_sqls.join(', '))
end
update(attrs, from: :not_set) click to toggle source
# File lib/atomically/query_service.rb, line 54
def update(attrs, from: :not_set)
  success = update_and_return_number_of_updated_rows(attrs, from) == 1

  if success
    assign_without_changes(attrs)
    @model.send(:clear_attribute_changes, @model.changes.keys)
  end

  return success
end
update_all(expected_size, *args) click to toggle source
# File lib/atomically/query_service.rb, line 50
def update_all(expected_size, *args)
  where_all_can_be_updated(@relation, expected_size).update_all(*args)
end
update_all_and_get_ids(*args) click to toggle source
# File lib/atomically/query_service.rb, line 78
def update_all_and_get_ids(*args)
  if adapter_check_service.pg?
    scope = UpdateAllScope::UpdateAllScope.new(model: @model, relation: @relation.where(''))
    scope.update(*args)
    return @klass.connection.execute("#{scope.to_sql} RETURNING id", "#{@klass} Update All").map{|s| s['id'].to_i }
  end

  ids = nil
  id_column = quote_column_with_table(:id)
  @klass.transaction do
    @relation.connection.execute('SET @ids := NULL')
    @relation.where("(SELECT @ids := CONCAT_WS(',', #{id_column}, @ids))").update_all(*args) # 撈出有真的被更新的 id,用逗號串在一起
    ids = @klass.from(nil).pluck(Arel.sql('@ids')).first
  end
  return ids.try{|s| s.split(',').map(&:to_i).uniq.sort } || [] # 將 id 從字串取出來 @id 的格式範例: '1,4,12'
end

Private Instance Methods

adapter_check_service() click to toggle source
# File lib/atomically/query_service.rb, line 97
def adapter_check_service
  @adapter_check_service ||= Atomically::AdapterCheckService.new(@klass)
end
assign_without_changes(attributes) click to toggle source
# File lib/atomically/query_service.rb, line 149
def assign_without_changes(attributes)
  @model.assign_attributes(attributes)
  @model.send(:clear_attribute_changes, attributes.keys)
end
on_duplicate_key_plus_sql(columns, conflict_target) click to toggle source
# File lib/atomically/query_service.rb, line 101
def on_duplicate_key_plus_sql(columns, conflict_target)
  service = Atomically::OnDuplicateSqlService.new(@klass, columns)
  return service.mysql_quote_columns_for_plus.join(', ') if adapter_check_service.mysql?
  return {
    conflict_target: conflict_target,
    columns: service.pg_quote_columns_for_plus.join(', '),
  }
end
open_update_all_scope(&block) click to toggle source
# File lib/atomically/query_service.rb, line 142
def open_update_all_scope(&block)
  return 0 if @model == nil
  scope = UpdateAllScope::UpdateAllScope.new(model: @model)
  scope.instance_exec(&block)
  return scope.do_query!
end
quote_column(column) click to toggle source
# File lib/atomically/query_service.rb, line 114
def quote_column(column)
  @klass.connection.quote_column_name(column)
end
quote_column_with_table(column) click to toggle source
# File lib/atomically/query_service.rb, line 110
def quote_column_with_table(column)
  "#{@klass.quoted_table_name}.#{quote_column(column)}"
end
sanitize(value) click to toggle source
# File lib/atomically/query_service.rb, line 118
def sanitize(value)
  @klass.connection.quote(value)
end
update_and_return_number_of_updated_rows(attrs, from_value) click to toggle source
# File lib/atomically/query_service.rb, line 126
def update_and_return_number_of_updated_rows(attrs, from_value)
  model = @model
  return open_update_all_scope do
    update(updated_at: Time.now)

    model.changes.each do |column, (_old_value, new_value)|
      update(column => new_value)
    end

    attrs.each do |column, value|
      old_value = (from_value == :not_set ? model[column] : from_value)
      where(column => old_value).update(column => value) if old_value != value
    end
  end
end
where_all_can_be_updated(query, expected_size) click to toggle source
# File lib/atomically/query_service.rb, line 122
def where_all_can_be_updated(query, expected_size)
  query.where("(#{@klass.from(query.where('')).select('COUNT(*)').to_sql}) = ?", expected_size)
end