Sha256: 671ad15a405129e72d51f5e6bb7af7a4f5cb810c6ba4ea5be493f72a79475ac6

Contents?: true

Size: 1.54 KB

Versions: 9

Compression:

Stored size: 1.54 KB

Contents

# frozen_string_literal: true

module Sequel::Plugins::Upsert
  module ClassMethods
    # Returns an upsert dataset
    #
    # @param target [Symbol] target column
    # @example
    #   User.upsert_dataset.insert(name: "John", email: "jd@test.com")
    #
    # @return [Sequel::Dataset] dataset
    def upsert_dataset(target: primary_key)
      cols = columns - Array(primary_key)
      update_spec = cols.map { |x| [x, Sequel[:excluded][x]] }
      where_spec = cols.map { |x| [Sequel[table_name][x], Sequel[:excluded][x]] }

      dataset.insert_conflict(
        target: target,
        update: update_spec,
        update_where: Sequel.~(where_spec),
      )
    end

    # Executes the upsert request
    #
    # @param row [Hash] values
    # @param options [Hash] options
    #
    # @example
    #   User.upsert(name: "John", email: "jd@test.com", target: :email)
    # @return [Sequel::Model]
    def upsert(row, **options)
      upsert_dataset(**options).insert(sequel_values(row))
    end

    # Executes the upsert request for multiple rows
    # @see #upsert
    # @see #upsert_dataset
    def multi_upsert(rows, **options)
      rows = rows.map { |row| sequel_values(row) }
      upsert_dataset(options).multi_insert(rows)
    end

    # Returns formatted row values
    #
    # @param row [Hash]
    #
    # @return [Hash]
    def sequel_values(row)
      upsert_model.new(row).values
    end

    # Returns upsert model for current table
    #
    # @return [Sequel::Model]
    def upsert_model
      @upsert_model ||= Sequel::Model(table_name)
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
umbrellio-sequel-plugins-0.3.1.69 lib/sequel/plugins/upsert.rb
umbrellio-sequel-plugins-0.3.1.68 lib/sequel/plugins/upsert.rb
umbrellio-sequel-plugins-0.3.0.67 lib/sequel/plugins/upsert.rb
umbrellio-sequel-plugins-0.3.0.62 lib/sequel/plugins/upsert.rb
umbrellio-sequel-plugins-0.3.0 lib/sequel/plugins/upsert.rb
umbrellio-sequel-plugins-0.2.0 lib/sequel/plugins/upsert.rb
umbrellio-sequel-plugins-0.1.2 lib/sequel/plugins/upsert.rb
umbrellio-sequel-plugins-0.1.1 lib/sequel/plugins/upsert.rb
umbrellio-sequel-plugins-0.1.0 lib/sequel/plugins/upsert.rb