Created
November 23, 2017 00:20
-
-
Save janpaul123/543065906ef764cf08ae36840cb098cf to your computer and use it in GitHub Desktop.
Apply diffs in Postgres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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