pipeforge 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +14 -0
  3. data/LICENSE +21 -0
  4. data/README.md +168 -0
  5. data/guides/matching-columns.md +126 -0
  6. data/guides/measuring-values.md +121 -0
  7. data/guides/running-the-migration.md +145 -0
  8. data/lib/pipeforge/adapter_registry.rb +37 -0
  9. data/lib/pipeforge/adapters/activerecord/adapter.rb +7 -0
  10. data/lib/pipeforge/adapters/activerecord/model_record.rb +202 -0
  11. data/lib/pipeforge/adapters/activerecord/schema_reader.rb +142 -0
  12. data/lib/pipeforge/adapters/activerecord/target.rb +277 -0
  13. data/lib/pipeforge/cast_result.rb +13 -0
  14. data/lib/pipeforge/column_limits_checker.rb +152 -0
  15. data/lib/pipeforge/column_value_analyzer/column_summary_builder.rb +163 -0
  16. data/lib/pipeforge/column_value_analyzer/distinct_values.rb +61 -0
  17. data/lib/pipeforge/column_value_analyzer/listed_values.rb +26 -0
  18. data/lib/pipeforge/column_value_analyzer.rb +96 -0
  19. data/lib/pipeforge/configuration.rb +209 -0
  20. data/lib/pipeforge/error_catalog.rb +184 -0
  21. data/lib/pipeforge/errors.rb +229 -0
  22. data/lib/pipeforge/header_analyzer/matcher.rb +170 -0
  23. data/lib/pipeforge/header_analyzer/pair_scorer.rb +116 -0
  24. data/lib/pipeforge/header_analyzer/tokenizer.rb +43 -0
  25. data/lib/pipeforge/header_analyzer.rb +129 -0
  26. data/lib/pipeforge/mapped_columns.rb +208 -0
  27. data/lib/pipeforge/migration.rb +189 -0
  28. data/lib/pipeforge/resolved_mapped_column.rb +13 -0
  29. data/lib/pipeforge/run_processor/chunk_processor.rb +141 -0
  30. data/lib/pipeforge/run_processor/row_transformer.rb +35 -0
  31. data/lib/pipeforge/run_processor/schema_checker.rb +67 -0
  32. data/lib/pipeforge/run_processor.rb +99 -0
  33. data/lib/pipeforge/source/csv_reader.rb +212 -0
  34. data/lib/pipeforge/source/reusable_io.rb +71 -0
  35. data/lib/pipeforge/target_schema.rb +47 -0
  36. data/lib/pipeforge/utilities.rb +58 -0
  37. data/lib/pipeforge/version.rb +5 -0
  38. data/lib/pipeforge.rb +22 -0
  39. metadata +97 -0
@@ -0,0 +1,170 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "tokenizer"
4
+ require_relative "pair_scorer"
5
+
6
+ module Pipeforge
7
+ module HeaderAnalyzer
8
+ # Matches source columns to target columns by name only. Values, types and constraints never
9
+ # change the result.
10
+ #
11
+ # Every target column is scored against every source column. A pair with a score below the
12
+ # inclusion threshold is never a candidate. The candidates are sorted by score, best first;
13
+ # pairs with the same score are put in the order of the target column name and then the
14
+ # source column name, so the result is the same on every run and does not depend on where the
15
+ # columns sit in the file or the table.
16
+ #
17
+ # The sorted candidates are walked from the top:
18
+ # - a target column that already has a match is skipped;
19
+ # - a source column that was matched with a different score is skipped (the target with the
20
+ # better score for it keeps it);
21
+ # - any other pair is a match. A source column matched with the same score by an earlier pair
22
+ # is shared, and the consumer chooses which target column to keep.
23
+ #
24
+ # A target column can have several source columns with the same score. The one whose name
25
+ # comes first is the match, and the others are listed in its +tied_source_column_names+, so the consumer can
26
+ # see the tie. A source column that was already matched with another score is not listed:
27
+ # it was not free to take the target.
28
+ #
29
+ # Every word of a name counts, a trailing +id+ included: +company_id+ matches +Company Id+
30
+ # fully and +Company+ less well.
31
+ #
32
+ # The target columns are given by name. They are only the columns that can be given a source
33
+ # column: the target leaves out the others (the primary key, ignored and generated
34
+ # columns).
35
+ #
36
+ # @example
37
+ # matcher = Pipeforge::HeaderAnalyzer::Matcher.new(
38
+ # inclusion_threshold: 55,
39
+ # pair_scorer: Pipeforge::HeaderAnalyzer::PairScorer.new(reorder_penalty: 10),
40
+ # tokenizer: Pipeforge::HeaderAnalyzer::Tokenizer.new
41
+ # )
42
+ # matcher.call(source_column_names: ["First Name"], target_column_names: ["first_name"]).matches
43
+ class Matcher
44
+ # A source column matched to a target column.
45
+ # tied_source_column_names the other source columns that had the same score for this target column and
46
+ # were free to take it, in name order; empty when nothing tied
47
+ Match = Data.define(:source_column_name, :target_column_name, :score, :tied_source_column_names)
48
+
49
+ # The outcome of one matching.
50
+ # matches the matched pairs, in target column order
51
+ # unmatched_source_column_names source columns in no match, in file order
52
+ # unmatched_target_column_names target columns without a match, in table order
53
+ Result = Data.define(:matches, :unmatched_source_column_names, :unmatched_target_column_names)
54
+
55
+ # A column name with its tokens, for a source column or a target column.
56
+ ColumnTokens = Data.define(:name, :tokens)
57
+
58
+ # A source column and a target column whose score reaches the inclusion threshold.
59
+ Candidate = Data.define(:source_column_name, :target_column_name, :score)
60
+
61
+ # @param inclusion_threshold [Numeric] the lowest score of a match, a number of at least 1
62
+ # @param pair_scorer [PairScorer] scores one target column against one source column
63
+ # @param tokenizer [Tokenizer] splits a column name into tokens
64
+ def initialize(inclusion_threshold:, pair_scorer:, tokenizer:)
65
+ @inclusion_threshold = inclusion_threshold
66
+ @pair_scorer = pair_scorer
67
+ @tokenizer = tokenizer
68
+ end
69
+
70
+ # @param source_column_names [Array<String>] the header names of the source, in file order
71
+ # @param target_column_names [Array<String>] the column names of the target table, in table order
72
+ # @return [Result]
73
+ def call(source_column_names:, target_column_names:)
74
+ tokenized_sources = tokenize_columns(column_names: source_column_names)
75
+ tokenized_targets = tokenize_columns(column_names: target_column_names)
76
+ candidates = build_candidates(tokenized_sources: tokenized_sources, tokenized_targets: tokenized_targets)
77
+ picked = pick_matches(ranked_candidates: rank(candidates: candidates))
78
+
79
+ Result.new(
80
+ matches: in_table_order(matches: picked[:matches], target_column_names: target_column_names),
81
+ unmatched_source_column_names: source_column_names - picked[:matched_source_columns],
82
+ unmatched_target_column_names: target_column_names - picked[:matched_target_column_names]
83
+ )
84
+ end
85
+
86
+ private
87
+
88
+ def tokenize_columns(column_names:)
89
+ tokenized_columns = []
90
+
91
+ column_names.each do |column_name|
92
+ tokenized_columns << ColumnTokens.new(name: column_name, tokens: @tokenizer.call(name: column_name))
93
+ end
94
+
95
+ tokenized_columns
96
+ end
97
+
98
+ # Every pair of a target column and a source column whose score reaches the inclusion
99
+ # threshold.
100
+ def build_candidates(tokenized_sources:, tokenized_targets:)
101
+ candidates = []
102
+
103
+ tokenized_targets.each do |tokenized_target|
104
+ tokenized_sources.each do |tokenized_source|
105
+ score = @pair_scorer.call(left_tokens: tokenized_target.tokens, right_tokens: tokenized_source.tokens)
106
+ next if score < @inclusion_threshold
107
+
108
+ candidates << Candidate.new(
109
+ source_column_name: tokenized_source.name, target_column_name: tokenized_target.name, score: score
110
+ )
111
+ end
112
+ end
113
+
114
+ candidates
115
+ end
116
+
117
+ # Best score first. The names only fix the order of pairs with the same score: a target
118
+ # column name and a source column name are each unique, so no two pairs have the same key.
119
+ def rank(candidates:)
120
+ candidates.sort_by { |candidate| [-candidate.score, candidate.target_column_name, candidate.source_column_name] }
121
+ end
122
+
123
+ # Walks the ranked candidates and picks the matches. Each match is built when it is picked,
124
+ # with an empty +tied_source_column_names+ list; a later candidate that ties with it (the same target
125
+ # column, the same score, an available source column) adds its source column to that list.
126
+ #
127
+ # @return [Hash] the +matches+ (in the order they were picked), and the names of the
128
+ # +matched_source_columns+ and +matched_target_column_names+ that have a match
129
+ def pick_matches(ranked_candidates:)
130
+ match_by_target_column_name = {}
131
+ match_score_by_source_column = {}
132
+
133
+ ranked_candidates.each do |candidate|
134
+ source_match_score = match_score_by_source_column[candidate.source_column_name]
135
+ source_available = source_match_score.nil? || source_match_score == candidate.score
136
+ next unless source_available
137
+
138
+ existing_match = match_by_target_column_name[candidate.target_column_name]
139
+ if existing_match
140
+ existing_match.tied_source_column_names << candidate.source_column_name if existing_match.score == candidate.score
141
+ next
142
+ end
143
+
144
+ match_by_target_column_name[candidate.target_column_name] = to_match(candidate: candidate)
145
+ match_score_by_source_column[candidate.source_column_name] = candidate.score if source_match_score.nil?
146
+ end
147
+
148
+ {
149
+ matches: match_by_target_column_name.values,
150
+ matched_source_columns: match_score_by_source_column.keys,
151
+ matched_target_column_names: match_by_target_column_name.keys
152
+ }
153
+ end
154
+
155
+ # Each target column has at most one match, so the positions are all different.
156
+ def in_table_order(matches:, target_column_names:)
157
+ matches.sort_by { |match| target_column_names.index(match.target_column_name) }
158
+ end
159
+
160
+ def to_match(candidate:)
161
+ Match.new(
162
+ source_column_name: candidate.source_column_name,
163
+ target_column_name: candidate.target_column_name,
164
+ score: candidate.score,
165
+ tied_source_column_names: []
166
+ )
167
+ end
168
+ end
169
+ end
170
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pipeforge
4
+ module HeaderAnalyzer
5
+ # Scores how well the tokens of one target column (the left side) match the tokens of one
6
+ # source column (the right side). Only names are used, never values.
7
+ #
8
+ # Word points (0 to 1) compare two tokens: identical tokens score 1, a token that is a full
9
+ # prefix of the other scores shorter length / longer length, anything else scores 0
10
+ # (+first+ and +f+ score 0.2, +name+ and +username+ score 0).
11
+ #
12
+ # The score of the two columns is +2 x sum of word points / (left tokens + right tokens)+,
13
+ # as a percentage. Each token is used at most once. Tokens are paired best word points first.
14
+ #
15
+ # Each pair has the position of its left token (the left index) and the position of its right
16
+ # token (the right index). Going through the pairs by the left index, if the right index ever
17
+ # goes down, the paired tokens are in a different order on the two sides and a fixed penalty
18
+ # is subtracted once. A token without a pair is not part of this check.
19
+ #
20
+ # @example
21
+ # scorer = Pipeforge::HeaderAnalyzer::PairScorer.new(reorder_penalty: 10)
22
+ # scorer.call(left_tokens: %w[first name], right_tokens: %w[f name]) # => 60.0
23
+ class PairScorer
24
+ # One pairing of a token of the left side with a token of the right side, by position in
25
+ # each list.
26
+ TokenMatch = Data.define(:left_index, :right_index, :points)
27
+
28
+ # @param reorder_penalty [Numeric] points subtracted when the paired tokens are in a
29
+ # different order (0 to 100)
30
+ def initialize(reorder_penalty:)
31
+ @reorder_penalty = reorder_penalty
32
+ end
33
+
34
+ # @param left_tokens [Array<String>] the tokens of the target column
35
+ # @param right_tokens [Array<String>] the tokens of the source column
36
+ # @return [Float] the score, 0 to 100, rounded to two decimals
37
+ def call(left_tokens:, right_tokens:)
38
+ token_matches = pair_tokens(left_tokens: left_tokens, right_tokens: right_tokens)
39
+ token_count = left_tokens.size + right_tokens.size
40
+
41
+ percentage(
42
+ token_matches: token_matches,
43
+ token_count: token_count,
44
+ reordered: !in_order?(token_matches: token_matches)
45
+ )
46
+ end
47
+
48
+ private
49
+
50
+ # 0 to 1: how well two tokens match.
51
+ def word_points(left_token:, right_token:)
52
+ shorter, longer = [left_token, right_token].sort_by(&:length)
53
+ return Rational(0) unless longer.start_with?(shorter)
54
+
55
+ Rational(shorter.length, longer.length)
56
+ end
57
+
58
+ # Pairs each left token with at most one right token, and the other way round, best word
59
+ # points first. A tie is broken by the position of the left token and then of the right token.
60
+ def pair_tokens(left_tokens:, right_tokens:)
61
+ candidates = candidate_matches(left_tokens: left_tokens, right_tokens: right_tokens)
62
+ best_first = candidates.sort_by { |match| [-match.points, match.left_index, match.right_index] }
63
+ used_left_indexes = []
64
+ used_right_indexes = []
65
+ chosen_matches = []
66
+
67
+ best_first.each do |match|
68
+ next if used_left_indexes.include?(match.left_index)
69
+ next if used_right_indexes.include?(match.right_index)
70
+
71
+ used_left_indexes << match.left_index
72
+ used_right_indexes << match.right_index
73
+ chosen_matches << match
74
+ end
75
+
76
+ chosen_matches
77
+ end
78
+
79
+ # Every pair of tokens that match at all.
80
+ def candidate_matches(left_tokens:, right_tokens:)
81
+ candidates = []
82
+
83
+ left_tokens.each_with_index do |left_token, left_index|
84
+ right_tokens.each_with_index do |right_token, right_index|
85
+ points = word_points(left_token: left_token, right_token: right_token)
86
+ next if points.zero?
87
+
88
+ candidates << TokenMatch.new(left_index: left_index, right_index: right_index, points: points)
89
+ end
90
+ end
91
+
92
+ candidates
93
+ end
94
+
95
+ # True when the right index of the pairs keeps going up: going through the pairs by the left
96
+ # index, the right index never goes down.
97
+ def in_order?(token_matches:)
98
+ by_left_index = token_matches.sort_by(&:left_index)
99
+ right_indexes = by_left_index.map(&:right_index)
100
+
101
+ right_indexes == right_indexes.sort
102
+ end
103
+
104
+ # The score as a percentage, less the penalty when the order differs, never below 0.
105
+ def percentage(token_matches:, token_count:, reordered:)
106
+ return 0.0 if token_count.zero?
107
+
108
+ sum_of_points = token_matches.sum(&:points)
109
+ score = Rational(2) * sum_of_points / token_count * 100
110
+ score -= @reorder_penalty if reordered
111
+
112
+ [score, 0].max.to_f.round(2)
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pipeforge
4
+ module HeaderAnalyzer
5
+ # Splits a column name into lowercase word pieces, called tokens, so two column names can be
6
+ # compared word by word.
7
+ #
8
+ # A name is split on spaces and other non-alphanumeric characters, on camelCase and on
9
+ # acronym runs, and where letters meet digits. Each token is lowercased and otherwise kept as
10
+ # written: a plural is not turned into its singular.
11
+ #
12
+ # @example
13
+ # tokenizer = Pipeforge::HeaderAnalyzer::Tokenizer.new
14
+ # tokenizer.call(name: "HTTPServer2") # => ["http", "server", "2"]
15
+ # tokenizer.call(name: "user_email") # => ["user", "email"]
16
+ class Tokenizer
17
+ # @param name [String] a column name such as "FirstName", "first_name" or "First Name"
18
+ # @return [Array<String>] the tokens, in the order they appear in the name
19
+ def call(name:)
20
+ tokens_of(name: name)
21
+ end
22
+
23
+ private
24
+
25
+ def tokens_of(name:)
26
+ separated_text = separate_words(text: name)
27
+ pieces = separated_text.split(/[^\p{Alnum}]+/)
28
+ words = pieces.reject(&:empty?)
29
+
30
+ words.map(&:downcase)
31
+ end
32
+
33
+ # Puts a space where one word ends and the next begins without a separator.
34
+ def separate_words(text:)
35
+ after_camel_case = text.gsub(/(\p{Ll}|\p{N})(\p{Lu})/, '\1 \2')
36
+ after_acronym = after_camel_case.gsub(/(\p{Lu})(\p{Lu}\p{Ll})/, '\1 \2')
37
+ after_letter_digit = after_acronym.gsub(/(\p{L})(\p{N})/, '\1 \2')
38
+
39
+ after_letter_digit.gsub(/(\p{N})(\p{L})/, '\1 \2')
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,129 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "header_analyzer/matcher"
4
+
5
+ module Pipeforge
6
+ # The header stage: matches the columns of the source to the columns of the target table by
7
+ # name only, and gives the best matches with the metadata of each target column.
8
+ #
9
+ # It is a service: {.call} is given the header names of the source and the schema of the
10
+ # target, and reads nothing itself. It sees no value of the source and no row of the target,
11
+ # and it keeps nothing between calls. The migration reads the header (and checks it) and asks
12
+ # the target for the schema.
13
+ #
14
+ # @example
15
+ # result = Pipeforge::HeaderAnalyzer.call(
16
+ # source_headers: ["First Name", "Zip"], target_schema: schema
17
+ # )
18
+ # result.matches.first
19
+ # # => {target_column_name: "first_name", source_column_name: "First Name", score: 100.0, tied_source_column_names: [],
20
+ # # metadata: {...}}
21
+ module HeaderAnalyzer
22
+ # The outcome of the header stage.
23
+ # target_table_name, model_name the table and the model the adapter read it from (nil when
24
+ # the adapter has no model)
25
+ # matches [{target_column_name:, source_column_name:, score:, tied_source_column_names:,
26
+ # metadata:}], in table order: the pairs at or above the
27
+ # inclusion threshold. A source column can be in several
28
+ # entries when their scores are the same; the consumer chooses
29
+ # which target to keep. +tied_source_column_names+ lists the other source
30
+ # columns that had the same score for this target and were
31
+ # free to take it (empty when nothing tied).
32
+ # unmatched_source_column_names source columns in no match, in file order
33
+ # unmatched_target_columns [{target_column_name:, metadata:}] for the target columns without a match,
34
+ # in table order
35
+ #
36
+ # The metadata of a target column is its entry in the schema: type, sql_type, limit,
37
+ # max_length, precision, scale, default, enum_labels (nil, or the labels),
38
+ # required, foreign_key (nil, or {association_name:, parent_table_name:}) and polymorphic (nil, or
39
+ # {association_name:, role:} for the id column and the type column of a polymorphic association).
40
+ #
41
+ # Everything in it is a plain Hash, Array, String, number, boolean or nil, so +to_h+ gives the
42
+ # result as plain JSON types, ready to store or send.
43
+ Result = Data.define(
44
+ :target_table_name, :model_name, :matches, :unmatched_source_column_names, :unmatched_target_columns
45
+ )
46
+
47
+ class << self
48
+ # @param source_headers [Array<String>] the column names of the source, in file order,
49
+ # already checked (not blank, not repeated)
50
+ # @param target_schema [TargetSchema] the schema of the target table
51
+ # @return [Result]
52
+ def call(source_headers:, target_schema:)
53
+ target_column_names = target_schema.columns.map(&:name)
54
+ matcher_result = build_matcher.call(source_column_names: source_headers, target_column_names: target_column_names)
55
+
56
+ build_result(target_schema: target_schema, matcher_result: matcher_result)
57
+ end
58
+
59
+ private
60
+
61
+ def build_matcher
62
+ settings = Configuration.recommendation
63
+
64
+ Matcher.new(
65
+ inclusion_threshold: settings.inclusion_threshold,
66
+ pair_scorer: PairScorer.new(reorder_penalty: settings.reorder_penalty),
67
+ tokenizer: Tokenizer.new
68
+ )
69
+ end
70
+
71
+ def build_result(target_schema:, matcher_result:)
72
+ metadata_by_target_column_name = {}
73
+
74
+ target_schema.columns.each do |target_column|
75
+ metadata_by_target_column_name[target_column.name] = metadata_of(target_column: target_column)
76
+ end
77
+
78
+ Result.new(
79
+ target_table_name: target_schema.table_name,
80
+ model_name: target_schema.model_name,
81
+ matches: build_matches(matcher_result: matcher_result, metadata_by_target_column_name: metadata_by_target_column_name),
82
+ unmatched_source_column_names: matcher_result.unmatched_source_column_names,
83
+ unmatched_target_columns: build_unmatched_target_entries(
84
+ matcher_result: matcher_result, metadata_by_target_column_name: metadata_by_target_column_name
85
+ )
86
+ )
87
+ end
88
+
89
+ def build_matches(matcher_result:, metadata_by_target_column_name:)
90
+ matches = []
91
+
92
+ matcher_result.matches.each do |match|
93
+ matches << {
94
+ target_column_name: match.target_column_name,
95
+ source_column_name: match.source_column_name,
96
+ score: match.score,
97
+ tied_source_column_names: match.tied_source_column_names,
98
+ metadata: metadata_by_target_column_name.fetch(match.target_column_name)
99
+ }
100
+ end
101
+
102
+ matches
103
+ end
104
+
105
+ def build_unmatched_target_entries(matcher_result:, metadata_by_target_column_name:)
106
+ unmatched_target_entries = []
107
+
108
+ matcher_result.unmatched_target_column_names.each do |target_column_name|
109
+ unmatched_target_entries << {
110
+ target_column_name: target_column_name, metadata: metadata_by_target_column_name.fetch(target_column_name)
111
+ }
112
+ end
113
+
114
+ unmatched_target_entries
115
+ end
116
+
117
+ # The state of a target column as it is in the schema, as plain data: every field of the
118
+ # schema column except its name (the result already carries it), with the foreign key as a
119
+ # hash too, so the result converts to JSON.
120
+ def metadata_of(target_column:)
121
+ metadata = target_column.to_h.except(:name)
122
+ metadata[:foreign_key] = target_column.foreign_key&.to_h
123
+ metadata[:polymorphic] = target_column.polymorphic&.to_h
124
+
125
+ metadata
126
+ end
127
+ end
128
+ end
129
+ end
@@ -0,0 +1,208 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pipeforge
4
+ # The consumer's mapped columns, checked against the header of the source file and the columns of the target table,
5
+ # and resolved for the stages that take them. The consumer writes a Hash of target column name => entry, and an entry
6
+ # is {source_column_name: ..., value_mapping: ...} (the value mapping is optional). A key written as a String is read
7
+ # as the Symbol, and the caller's Hash is not changed.
8
+ #
9
+ # A mapping with the wrong shape is a mistake in the call: building the object raises an ArgumentError that lists
10
+ # every such mistake. A mapping with the right shape that does not fit the file or the table is a mistake about the
11
+ # data: {#resolved_mapped_columns!} raises one error that lists every one, so the caller can fix them in one round. A source column may feed several target
12
+ # columns: that is the consumer's choice and is not checked.
13
+ #
14
+ # @example
15
+ # checked_mapping = MappedColumns.new(
16
+ # mapped_columns: {email: {source_column_name: "Mail"}}, source_header_names: %w[Mail Age],
17
+ # target_columns: target_schema.columns
18
+ # )
19
+ # checked_mapping.resolved_mapped_columns! # => {"email" => #<data ResolvedMappedColumn ...>}
20
+ class MappedColumns
21
+ # The keys of an entry that Pipeforge reads.
22
+ ENTRY_KEYS = %i[source_column_name value_mapping].freeze
23
+ ENTRY_KEYS_TEXT = ENTRY_KEYS.map(&:inspect).join(" and ").freeze
24
+
25
+ # @param mapped_columns [Object] what the consumer gave: target column name (a Symbol or a String) => entry
26
+ # @param source_header_names [Array<String>] the column names of the source file, in file order
27
+ # @param target_columns [Array<TargetColumn>] the columns of the target table that can be loaded into
28
+ # @raise [ArgumentError] +mapped_columns+ is not a Hash (alone); otherwise every shape mistake in one message: a
29
+ # target column name that is neither a Symbol nor a String, an entry that is not a Hash, a key of an entry other
30
+ # than +source_column_name+ and +value_mapping+, or a +value_mapping+ that is neither a Hash nor nil
31
+ def initialize(mapped_columns:, source_header_names:, target_columns:)
32
+ reject_wrong_shape(mapped_columns: mapped_columns)
33
+
34
+ @source_header_names = source_header_names
35
+ @target_columns_by_name = {}
36
+ target_columns.each { |target_column| @target_columns_by_name[target_column.name] = target_column }
37
+ @entries_by_target_column_name = normalized_copy_of(mapped_columns: mapped_columns)
38
+ end
39
+
40
+ # Checks the mapped columns against the file and the table, and resolves them.
41
+ #
42
+ # @return [Hash{String => ResolvedMappedColumn}] the mapping resolved against the target columns (the target column
43
+ # names as Strings, in the order the consumer gave them)
44
+ # @raise [InvalidMappedColumnsError] one entry for each data mistake, in this order: each mapped column first
45
+ # (+target_column_not_in_schema+, then +column_missing_source_column+ or +mapped_column_not_in_file+), then the
46
+ # required columns that have no entry (+required_column_unmapped+)
47
+ def resolved_mapped_columns!
48
+ found_errors = data_errors
49
+ raise InvalidMappedColumnsError.new(errors: found_errors) unless found_errors.empty?
50
+
51
+ build_resolved_mapped_columns
52
+ end
53
+
54
+ private
55
+
56
+ # Stops with every shape mistake in one message. That the mapped columns are a Hash is checked first and reported
57
+ # alone, because without a Hash there is nothing else to read. The input is checked as it was given, so a name or a
58
+ # key may be a Symbol or a String.
59
+ def reject_wrong_shape(mapped_columns:)
60
+ unless mapped_columns.is_a?(Hash)
61
+ raise ArgumentError, ArgumentMessages::MESSAGES.fetch(:mapped_columns_not_a_hash).call(given_class: mapped_columns.class)
62
+ end
63
+
64
+ problems = []
65
+
66
+ mapped_columns.each do |target_column_name, entry|
67
+ problems.concat(shape_problems_of(target_column_name: target_column_name, entry: entry))
68
+ end
69
+
70
+ raise ArgumentError, problems.join("; ") unless problems.empty?
71
+ end
72
+
73
+ # The shape mistakes of one entry. The name and the entry are checked independently, so both are reported; the keys
74
+ # of the entry can be checked only when it is a Hash.
75
+ def shape_problems_of(target_column_name:, entry:)
76
+ problems = []
77
+
78
+ unless symbol_or_string?(value: target_column_name)
79
+ problems << ArgumentMessages::MESSAGES.fetch(:mapped_column_name_not_symbol_or_string).call(
80
+ target_column_name: target_column_name
81
+ )
82
+ end
83
+
84
+ if entry.is_a?(Hash)
85
+ problems.concat(key_problems_of(target_column_name: target_column_name, entry: entry))
86
+ else
87
+ problems << ArgumentMessages::MESSAGES.fetch(:mapped_column_entry_not_a_hash).call(
88
+ target_column_name: target_column_name, given_class: entry.class
89
+ )
90
+ end
91
+
92
+ problems
93
+ end
94
+
95
+ def key_problems_of(target_column_name:, entry:)
96
+ problems = []
97
+
98
+ entry.each do |key, value|
99
+ if entry_key?(key: key)
100
+ # A value mapping that is given must be a Hash, or nil for no mapping. What is inside the Hash is not checked,
101
+ # because a value may be mapped to anything, even nil or a blank.
102
+ if key.to_sym == :value_mapping && !value.nil? && !value.is_a?(Hash)
103
+ problems << ArgumentMessages::MESSAGES.fetch(:value_mapping_not_a_hash).call(
104
+ target_column_name: target_column_name, given_class: value.class
105
+ )
106
+ end
107
+ else
108
+ problems << ArgumentMessages::MESSAGES.fetch(:mapped_column_unknown_key).call(
109
+ target_column_name: target_column_name, key: key, entry_keys_text: ENTRY_KEYS_TEXT
110
+ )
111
+ end
112
+ end
113
+
114
+ problems
115
+ end
116
+
117
+ def entry_key?(key:)
118
+ symbol_or_string?(value: key) && ENTRY_KEYS.include?(key.to_sym)
119
+ end
120
+
121
+ def symbol_or_string?(value:)
122
+ value.is_a?(Symbol) || value.is_a?(String)
123
+ end
124
+
125
+ # A copy of the checked mapped columns with the target column names as Strings (the names of the table's columns
126
+ # are Strings), the keys of an entry as Symbols and the keys of a value mapping as text (the values of the file are
127
+ # text, so a key written as 1 has to match the text "1"). A value mapping that is nil or left out becomes an empty
128
+ # one. Of two keys that give the same text, the later one is kept.
129
+ def normalized_copy_of(mapped_columns:)
130
+ entries_by_target_column_name = {}
131
+
132
+ mapped_columns.each do |target_column_name, entry|
133
+ entries_by_target_column_name[target_column_name.to_s] = normalized_entry_of(entry: entry)
134
+ end
135
+
136
+ entries_by_target_column_name
137
+ end
138
+
139
+ def normalized_entry_of(entry:)
140
+ normalized_entry = entry.transform_keys(&:to_sym)
141
+ normalized_entry[:value_mapping] = Hash(normalized_entry[:value_mapping]).transform_keys(&:to_s)
142
+
143
+ normalized_entry
144
+ end
145
+
146
+ def data_errors
147
+ found_errors = []
148
+
149
+ @entries_by_target_column_name.each do |target_column_name, entry|
150
+ found_errors << target_column_error(target_column_name: target_column_name)
151
+ found_errors << source_column_error(target_column_name: target_column_name, entry: entry)
152
+ end
153
+ found_errors.concat(required_column_errors)
154
+
155
+ found_errors.compact
156
+ end
157
+
158
+ # The error of an entry whose target column is not a column of the table, or nil.
159
+ def target_column_error(target_column_name:)
160
+ return if @target_columns_by_name.key?(target_column_name)
161
+
162
+ InvalidMappedColumnsError::ENTRIES.fetch(:target_column_not_in_schema).call(target_column_name: target_column_name)
163
+ end
164
+
165
+ # The error of an entry that names no source column, or one that is not in the file, or nil.
166
+ def source_column_error(target_column_name:, entry:)
167
+ source_column_name = entry[:source_column_name]
168
+
169
+ if source_column_name.nil?
170
+ InvalidMappedColumnsError::ENTRIES.fetch(:column_missing_source_column).call(target_column_name: target_column_name)
171
+ elsif !@source_header_names.include?(source_column_name)
172
+ InvalidMappedColumnsError::ENTRIES.fetch(:mapped_column_not_in_file).call(
173
+ target_column_name: target_column_name, source_column_name: source_column_name
174
+ )
175
+ end
176
+ end
177
+
178
+ # A required target column that has no entry at all. An entry that exists but names no source column is already
179
+ # reported by +column_missing_source_column+.
180
+ def required_column_errors
181
+ found_errors = []
182
+
183
+ @target_columns_by_name.each_value do |target_column|
184
+ next unless target_column.required
185
+ next if @entries_by_target_column_name.key?(target_column.name)
186
+
187
+ found_errors << InvalidMappedColumnsError::ENTRIES.fetch(:required_column_unmapped).call(
188
+ target_column_name: target_column.name
189
+ )
190
+ end
191
+
192
+ found_errors
193
+ end
194
+
195
+ def build_resolved_mapped_columns
196
+ resolved_mapped_columns = {}
197
+
198
+ @entries_by_target_column_name.each do |target_column_name, entry|
199
+ resolved_mapped_columns[target_column_name] = ResolvedMappedColumn.new(
200
+ source_column_name: entry[:source_column_name], value_mapping: entry[:value_mapping],
201
+ target_column: @target_columns_by_name.fetch(target_column_name)
202
+ )
203
+ end
204
+
205
+ resolved_mapped_columns
206
+ end
207
+ end
208
+ end