Skip to content

Instantly share code, notes, and snippets.

@janpaul123
Created November 23, 2017 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janpaul123/543065906ef764cf08ae36840cb098cf to your computer and use it in GitHub Desktop.
Save janpaul123/543065906ef764cf08ae36840cb098cf to your computer and use it in GitHub Desktop.
Apply diffs in Postgres
module Interactors
module ApplyDiffsToMapDocumentData
def self.call(map_id:, diffs:)
return if diffs.empty?
sql = <<-SQL
UPDATE maps SET document_data =
#{diffs.count.times.map { 'jsonb_set(' }.join('')}
document_data
#{diffs.each_with_index.map { |diff, i| ", '{#{diff[:path].join(',')}}', :value_#{i})" }.join('')}
WHERE maps.id = :map_id
SQL
sql_data = { map_id: map_id }
diffs.each_with_index do |diff, index|
sql_data["value_#{index}".to_sym] = diff[:value]
end
query = ActiveRecord::Base.send(:sanitize_sql_array, [sql, sql_data])
ActiveRecord::Base.connection.execute(query)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment