summaryrefslogtreecommitdiff
path: root/lib/humble/mapping_configuration.rb
blob: 3b57f04a5d3cf1e2d886c768357d435a73f51f8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
module Humble
  class MappingConfiguration
    def initialize(table, configuration)
      @table = table
      @configuration = configuration
    end

    def find_all_using(session)
      ResultSet.new(session.create_connection[@table.name], mapper_for(session))
    end

    def save_using(session, entity)
      connection = session.create_connection[@table.name]
      if primary_key.has_default_value?(entity)
        result = connection.insert(@table.prepare_statement_for(entity))
        primary_key.apply(result, entity, session)
      else
        connection.update(@table.prepare_statement_for(entity))
      end
    end

    def delete_using(session, entity)
      primary_key.destroy(session.create_connection[@table.name], entity)
    end

    def matches?(item)
      @table.type == item || item.is_a?(@table.type)
    end

    private

    def mapper_for(session)
      DefaultMapper.new(@table, session)
    end

    def primary_key
      @primary_key ||= @table.find do |column|
        column.primary_key?
      end
    end

    class DefaultMapper
      def initialize(table, session)
        @table = table
        @session = session
      end

      def map_from(row)
        @table.type.new.tap do |entity|
          row.each do |key, value|
            @table.column_for(key).apply(value, entity, @session)
          end
        end
      end
    end
  end
end