Sha256: cb7c8dd0ebafb5882f85307fbfd8065d00705a420a988a913974423620c73b66

Contents?: true

Size: 1.43 KB

Versions: 1

Compression:

Stored size: 1.43 KB

Contents

module ROM
  module SQL
    module Commands
      ERRORS = [
        Sequel::UniqueConstraintViolation,
        Sequel::NotNullConstraintViolation
      ].freeze

      module TupleCount
        # TODO: we need an interface for "target_count" here
        def assert_tuple_count
          if result == :one && target.count > 1
            raise TupleCountMismatchError, "#{inspect} expects one tuple"
          end
        end
      end

      class Create < ROM::Commands::Create
        include TupleCount

        def execute(tuples)
          pks = Array([tuples]).flatten.map do |tuple|
            attributes = input[tuple]
            validator.call(attributes)
            relation.insert(attributes.to_h)
          end

          relation.where(relation.model.primary_key => pks)
        rescue *ERRORS => e
          raise ConstraintError, e.message
        end
      end

      class Update < ROM::Commands::Update
        include TupleCount

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

          pks = relation.map { |t| t[relation.model.primary_key] }

          relation.update(attributes.to_h)
          relation.unfiltered.where(relation.model.primary_key => pks)
        end
      end

      class Delete < ROM::Commands::Delete
        include TupleCount

        def execute
          deleted = target.to_a
          target.delete
          deleted
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rom-sql-0.3.2 lib/rom/sql/commands.rb