Sha256: c9eef18034e1d59bb1b939de87f30d39bf34a0ff3d839fd78bf19e2d870fca8c

Contents?: true

Size: 1.21 KB

Versions: 2

Compression:

Stored size: 1.21 KB

Contents

require 'rom/sql/commands'
require 'rom/sql/commands/error_wrapper'
require 'rom/sql/commands/transaction'

module ROM
  module SQL
    module Commands
      class Update < ROM::Commands::Update
        include Transaction
        include ErrorWrapper

        option :original, type: Hash, reader: true

        alias_method :to, :call
        alias_method :set, :call

        def execute(tuple)
          attributes = input[tuple]
          validator.call(attributes)

          changed = diff(attributes.to_h)

          if changed.any?
            update(changed)
          else
            []
          end
        end

        def change(original)
          self.class.new(relation, options.merge(original: original))
        end

        def update(tuple)
          pks = relation.map { |t| t[primary_key] }
          dataset = relation.dataset
          dataset.update(tuple)
          dataset.unfiltered.where(primary_key => pks).to_a
        end

        def primary_key
          relation.primary_key
        end

        private

        def diff(tuple)
          if original
            Hash[tuple.to_a - (tuple.to_a & original.to_a)]
          else
            tuple
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rom-sql-0.4.3 lib/rom/sql/commands/update.rb
rom-sql-0.4.1 lib/rom/sql/commands/update.rb