Sha256: cbd977af41be4d623e332602a03b5fe3613fe180bad5070223155ba0ad872cf0

Contents?: true

Size: 1.11 KB

Versions: 4

Compression:

Stored size: 1.11 KB

Contents

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

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

        option :original, type: Hash, reader: true

        alias_method :to, :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

4 entries across 4 versions & 1 rubygems

Version Path
rom-sql-0.4.0 lib/rom/sql/commands/update.rb
rom-sql-0.4.0.rc1 lib/rom/sql/commands/update.rb
rom-sql-0.4.0.beta2 lib/rom/sql/commands/update.rb
rom-sql-0.4.0.beta1 lib/rom/sql/commands/update.rb