Sha256: 43f727ffe14b852885ace05f125869556a83d892c3f2f0bf70a9dc6ced47d22c

Contents?: true

Size: 1.6 KB

Versions: 5

Compression:

Stored size: 1.6 KB

Contents

require 'zlib'

class Upsert
  # @private
  class MergeFunction
    MAX_NAME_LENGTH = 62

    class << self
      def execute(controller, row)
        merge_function = lookup controller, row
        merge_function.execute row
      end

      def unique_name(table_name, selector_keys, setter_keys)
        parts = [
          'upsert',
          table_name,
          'SEL',
          selector_keys.join('_A_'),
          'SET',
          setter_keys.join('_A_')
        ].join('_')
        if parts.length > MAX_NAME_LENGTH
          # maybe i should md5 instead
          crc32 = Zlib.crc32(parts).to_s
          [ parts[0..MAX_NAME_LENGTH-10], crc32 ].join
        else
          parts
        end
      end

      def lookup(controller, row)
        @lookup ||= {}
        selector_keys = row.selector.keys
        setter_keys = row.setter.keys
        key = [controller.table_name, selector_keys, setter_keys]
        @lookup[key] ||= new(controller, selector_keys, setter_keys)
      end
    end

    attr_reader :controller
    attr_reader :selector_keys
    attr_reader :setter_keys

    def initialize(controller, selector_keys, setter_keys)
      @controller = controller
      @selector_keys = selector_keys
      @setter_keys = setter_keys
      create!
    end

    def name
      @name ||= MergeFunction.unique_name table_name, selector_keys, setter_keys
    end

    def connection
      controller.connection
    end

    def table_name
      controller.table_name
    end

    def quoted_table_name
      controller.quoted_table_name
    end

    def column_definitions
      controller.column_definitions
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
upsert-1.1.6 lib/upsert/merge_function.rb
upsert-1.1.5 lib/upsert/merge_function.rb
upsert-1.1.4 lib/upsert/merge_function.rb
upsert-1.1.3 lib/upsert/merge_function.rb
upsert-1.1.1 lib/upsert/merge_function.rb