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,189 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "source/reusable_io"
4
+ require_relative "source/csv_reader"
5
+ require_relative "column_value_analyzer"
6
+ require_relative "header_analyzer"
7
+ require_relative "target_schema"
8
+ require_relative "mapped_columns"
9
+ require_relative "run_processor"
10
+
11
+ module Pipeforge
12
+ # One migration of one source file into one target model, and the entry point of Pipeforge. It runs
13
+ # the stages on them: header analysis ({#analyze_headers}), column values analysis
14
+ # ({#analyze_column_values}) and the run ({#run}). The stages do not depend on each other. Building
15
+ # a migration reads the header of the source and the schema of the target, once.
16
+ #
17
+ # @example
18
+ # migration = Pipeforge::Migration.new(source_io: File.open("data/users.csv"), target_model_name: "User")
19
+ # header_analysis = migration.analyze_headers
20
+ # value_analysis = migration.analyze_column_values(
21
+ # mapped_columns: {email: {source_column_name: "Mail", value_mapping: {"N/A" => nil}}}
22
+ # )
23
+ # totals = migration.run(mode: :dry_run, mapped_columns: {email: {source_column_name: "Mail"}})
24
+ #
25
+ # A migration reaches the target through the target class of an adapter, installed ({.install_target})
26
+ # when the gem is required; each migration builds one target from it for its target model. The core
27
+ # names no database library. A target answers +schema+ (the {TargetSchema} of the model's table),
28
+ # +cast_value(column_name:, value:)+ (a {CastResult}: whether the model can cast a value and what it
29
+ # would load, in Ruby and in JSON types), +build_record(attributes:)+ (the target's record of one
30
+ # row), +preload_parents(records:)+ (loads the parents a chunk needs) and
31
+ # +transaction(rollback_at_end:)+ (runs a block inside one transaction of the target database,
32
+ # rolled back when the block ends if +rollback_at_end+ is true). A record answers +valid?+,
33
+ # +errors+ (a Hash, target column name => its {ErrorCatalog::ColumnError}), +add_error(error:)+, +attributes+,
34
+ # +json_attributes+ and +load+ (see {RunProcessor::ChunkProcessor}).
35
+ class Migration
36
+ # The values +mode+ of {#run} can have.
37
+ RUN_MODES = %i[dry_run run].freeze
38
+
39
+ class << self
40
+ # Gives the migrations the target class of an adapter. The gem calls it once, when it is required, with the
41
+ # class of the adapter the settings name. Every migration builds its own target from this class, for one
42
+ # target model, so the class keeps no state of its own. The last class installed is used.
43
+ #
44
+ # @api private
45
+ # @param target_class [Class] follows the target contract above and is built with
46
+ # +new(target_model_name:)+
47
+ # @return [void]
48
+ def install_target(target_class:)
49
+ @target_class = target_class
50
+ end
51
+
52
+ # @api private
53
+ # @return [Class, nil] the class given to {.install_target}; nil before it is called
54
+ attr_reader :target_class
55
+ end
56
+
57
+ # @param source_io [IO] the CSV source, for example +File.open("data/users.csv")+. It must
58
+ # respond to +read+, +rewind+ and +seek+; it is wrapped in a {Source::ReusableIO}, so it
59
+ # can be read again.
60
+ # @param target_model_name [String] the name of the model the data will be loaded through,
61
+ # for example +"User"+
62
+ #
63
+ # @raise [ArgumentError] the source is missing a method a migration needs (+read+, +rewind+ or +seek+)
64
+ # @raise [Source::Error] the source has no header row, or a header cell is blank or a name appears twice; or the
65
+ # first data row, which is read with the header, cannot be parsed or has more cells than the header
66
+ # @raise [TargetSchemaError] the table or its model cannot be found
67
+ def initialize(source_io:, target_model_name:)
68
+ @source_reader = Source::CsvReader.new(source_io: Source::ReusableIO.new(io: source_io))
69
+ # The header is read before the target is built, so an unusable file stops before the database is asked anything.
70
+ @source_headers = @source_reader.headers
71
+ @target = self.class.target_class.new(target_model_name: target_model_name)
72
+ @target_schema = @target.schema
73
+ end
74
+
75
+ # Matches the columns of the source to the columns of the target table by name only, and
76
+ # returns the best matches, in table order, with the metadata of each target column,
77
+ # and the columns left unmatched. Only the header of the source and the schema of the target
78
+ # are read, never any value or row.
79
+ #
80
+ # @return [HeaderAnalyzer::Result]
81
+ def analyze_headers
82
+ HeaderAnalyzer.call(
83
+ source_headers: @source_headers,
84
+ target_schema: @target_schema
85
+ )
86
+ end
87
+
88
+ # Measures the mapped columns of the source file: how many values are empty, how many fit
89
+ # the type of the target column, and which distinct values do and do not fit. The type, size
90
+ # and precision of each target column come from the schema of the target table.
91
+ #
92
+ # With a value mapping, each value is measured as the value it maps to, so the counts show
93
+ # what would be loaded, and the mapping comes back in the result. The rows are read again on
94
+ # every call, so an edited mapping can be measured again.
95
+ #
96
+ # @param mapped_columns [Hash{Symbol, String => Hash}] target column name => {source_column_name:,
97
+ # value_mapping: {value in the file => value to load}}, a plain Hash the caller builds (the header result is
98
+ # not passed in). The keys are Symbols; a String key is read as the Symbol. A source column may be given to
99
+ # several target columns. Every required target column (see {TargetColumn}) needs an entry. +value_mapping+ is
100
+ # optional (leave the key out, or give nil, for none), its keys are turned into text, and a
101
+ # value that maps to nil or a blank is loaded as empty. The caller's Hash is not changed (see
102
+ # {ResolvedMappedColumn}); the type and the limits of each target column come from the schema of the table.
103
+ # @return [ColumnValueAnalyzer::Result]
104
+ # @raise [Source::Error] a row cannot be parsed, or has more cells than the header
105
+ # @raise [ArgumentError] the mapped columns are not a Hash (alone), or an entry is not a Hash, an entry has a key
106
+ # other than +source_column_name+ and +value_mapping+, or a value mapping is not a Hash. Every such mistake is in
107
+ # the message.
108
+ # @raise [InvalidMappedColumnsError] a target column is not in the schema; an entry has no source column or one
109
+ # that is not in the file; or a required target column has no entry. Every such mistake is listed.
110
+ def analyze_column_values(mapped_columns:)
111
+ resolved_mapped_columns = resolved_mapped_columns_of(mapped_columns: mapped_columns)
112
+
113
+ ColumnValueAnalyzer.call(
114
+ source_reader: @source_reader, resolved_mapped_columns: resolved_mapped_columns, target: @target
115
+ )
116
+ end
117
+
118
+ # Validates every row of the source against the target and writes the ones that pass, one row at
119
+ # a time, and counts the rows written and the rows that failed. The rows are read in chunks, and
120
+ # each chunk's result, with its failed rows, is yielded to the block as soon as the chunk is done.
121
+ #
122
+ # A +:run+ keeps what it writes, each row in its own transaction. A +:dry_run+ writes the same
123
+ # rows inside one transaction that is rolled back at the end, so the target is unchanged and the
124
+ # failed rows are the same; the block is called inside that transaction, so it must not write to
125
+ # the target database.
126
+ #
127
+ # @param mode [Symbol] +:dry_run+ or +:run+
128
+ # @param mapped_columns [Hash{Symbol, String => Hash}] as in {#analyze_column_values}; the caller's Hash is not
129
+ # changed
130
+ # @param offset [Integer] rows to skip before the first one processed; the +row_number+ of the last
131
+ # row of an earlier run continues that run
132
+ # @param chunk_size [Integer] rows read, processed and yielded at a time; the +execution.chunk_size+
133
+ # setting when not given
134
+ # @yieldparam chunk_result [RunProcessor::ChunkResult] the outcome of one chunk; the block is optional
135
+ # @return [RunProcessor::RunResult]
136
+ # @raise [ArgumentError] +mode+ is not +:dry_run+ or +:run+, +offset+ is not a whole number of at least 0,
137
+ # or +chunk_size+ is not a whole number of at least 1; every bad one is in the message
138
+ # @raise [InvalidMappedColumnsError] as in {#analyze_column_values}; so is the +ArgumentError+ for the shape of
139
+ # the mapped columns
140
+ # @raise [Source::Error] a row cannot be parsed, or has more cells than the header
141
+ def run(mode:, mapped_columns:, offset: 0, chunk_size: Configuration.execution.chunk_size, &on_chunk)
142
+ check_run_arguments(mode: mode, offset: offset, chunk_size: chunk_size)
143
+ resolved_mapped_columns = resolved_mapped_columns_of(mapped_columns: mapped_columns)
144
+
145
+ RunProcessor.call(
146
+ source_reader: @source_reader, resolved_mapped_columns: resolved_mapped_columns,
147
+ offset: offset, chunk_size: chunk_size, mode: mode, target: @target, &on_chunk
148
+ )
149
+ end
150
+
151
+ private
152
+
153
+ # Stops with an ArgumentError that lists every argument of {#run} that cannot be used, or does nothing.
154
+ #
155
+ # @raise [ArgumentError] +mode+ is not +:dry_run+ or +:run+, +offset+ is not a whole number of at least
156
+ # 0, or +chunk_size+ is not a whole number of at least 1
157
+ def check_run_arguments(mode:, offset:, chunk_size:)
158
+ messages = []
159
+
160
+ unless RUN_MODES.include?(mode)
161
+ messages << ArgumentMessages::MESSAGES.fetch(:mode_not_allowed).call(mode: mode)
162
+ end
163
+
164
+ unless Utilities.non_negative_whole_number?(value: offset)
165
+ messages << ArgumentMessages::MESSAGES.fetch(:value_not_whole_number_at_least_0).call(name: "offset", value: offset)
166
+ end
167
+
168
+ unless Utilities.positive_whole_number?(value: chunk_size)
169
+ messages << ArgumentMessages::MESSAGES.fetch(:value_not_whole_number_at_least_1).call(name: "chunk_size", value: chunk_size)
170
+ end
171
+
172
+ raise ArgumentError, messages.join("; ") unless messages.empty?
173
+ end
174
+
175
+ # Checks the consumer's mapped columns against the header of the source and the columns of the target table, and gives
176
+ # them resolved for the column values stage and the run.
177
+ #
178
+ # @param mapped_columns [Object] what the caller gave
179
+ # @return [Hash{String => ResolvedMappedColumn}]
180
+ # @raise [ArgumentError] the shape of the mapped columns is wrong (see {MappedColumns#initialize})
181
+ # @raise [InvalidMappedColumnsError] the mapped columns do not fit the file or the table; every mistake is listed
182
+ def resolved_mapped_columns_of(mapped_columns:)
183
+ MappedColumns.new(
184
+ mapped_columns: mapped_columns, source_header_names: @source_headers,
185
+ target_columns: @target_schema.columns
186
+ ).resolved_mapped_columns!
187
+ end
188
+ end
189
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pipeforge
4
+ # One of the consumer's mapped columns (an entry of the +mapped_columns+ Hash) after the migration has checked it and
5
+ # looked up its target column in the schema. The column values stage takes these and not the consumer's Hash: they
6
+ # say which source column feeds a target column, how the values of the file are changed on the way, and the column
7
+ # of the target table it fills. {MappedColumns} makes them from the consumer's Hash.
8
+ # source_column_name String the source column the values are read from
9
+ # value_mapping Hash{String => Object} the value in the file (a text) => the value to load; empty when there is
10
+ # none
11
+ # target_column TargetColumn the column of the target table, which gives its type and limits
12
+ ResolvedMappedColumn = Data.define(:source_column_name, :value_mapping, :target_column)
13
+ end
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pipeforge
4
+ module RunProcessor
5
+ # The outcome of one chunk of rows, as the run hands it to the consumer.
6
+ # first_row_number, last_row_number absolute 1-based data record numbers of the first and the last
7
+ # row of the chunk (the header is not counted)
8
+ # processed_rows_count rows in the chunk
9
+ # valid_rows_count rows that passed the validation and were written
10
+ # failed_rows_count rows that did not
11
+ # failed_rows a {FailedRow} for each failed row, in file order
12
+ ChunkResult = Data.define(
13
+ :first_row_number, :last_row_number, :processed_rows_count, :valid_rows_count, :failed_rows_count,
14
+ :failed_rows
15
+ ) do
16
+ # @return [Hash] the chunk result as plain JSON types, ready to store or send: its failed rows are the Hashes
17
+ # {FailedRow#to_h} gives
18
+ def to_h
19
+ failed_row_hashes = []
20
+ failed_rows.each { |failed_row| failed_row_hashes << failed_row.to_h }
21
+
22
+ {
23
+ first_row_number: first_row_number,
24
+ last_row_number: last_row_number,
25
+ processed_rows_count: processed_rows_count,
26
+ valid_rows_count: valid_rows_count,
27
+ failed_rows_count: failed_rows_count,
28
+ failed_rows: failed_row_hashes
29
+ }
30
+ end
31
+ end
32
+
33
+ # One row that failed, as the consumer sees it.
34
+ # row_number absolute 1-based data record number (the header is not counted)
35
+ # attributes what the model record held when the row failed, as plain JSON types: column => value for every
36
+ # column of the record, cast to the type of the column and after the model's callbacks. It is never
37
+ # the raw source row.
38
+ # errors one error for each mistake, as an {ErrorCatalog} error object with the fields +origin+, +code+,
39
+ # +kind+, +target_column_name+, +message+, +details+ and +value+. +origin+ is where it was found:
40
+ # +:schema+ (the core's checks of the target schema), +:model+ (the application model's
41
+ # validations and callbacks) or +:database+ (the database refused the row).
42
+ FailedRow = Data.define(:row_number, :attributes, :errors) do
43
+ # @return [Hash] the failed row as plain JSON types, ready to store or send: its errors are the Hashes of their
44
+ # seven fields
45
+ def to_h
46
+ error_hashes = []
47
+
48
+ errors.each { |error| error_hashes << error.to_h }
49
+
50
+ {row_number: row_number, attributes: attributes, errors: error_hashes}
51
+ end
52
+ end
53
+
54
+ # Processes one chunk of rows: each row gets a model record, which is validated on two levels, the
55
+ # model's and the schema's, and, when valid, written before the next row is looked at. A row that is not
56
+ # valid, or that the database refuses, becomes a {FailedRow}.
57
+ module ChunkProcessor
58
+ class << self
59
+ # Validates and writes one chunk of rows.
60
+ #
61
+ # @param rows [Array<Hash{String => String, nil}>] one chunk, as the reader yields it
62
+ # @param first_row_number [Integer] absolute 1-based data record number of the first row
63
+ # @param transformer [RowTransformer]
64
+ # @param schema_checker [SchemaChecker]
65
+ # @param target [#build_record, #preload_parents] the target of the target model; the
66
+ # record it builds is written with +load+
67
+ # @return [ChunkResult]
68
+ def call(rows:, first_row_number:, transformer:, schema_checker:, target:)
69
+ model_records = build_model_records(rows: rows, transformer: transformer, target: target)
70
+
71
+ # One query for each association for the whole chunk, so the model's validation does not query the
72
+ # parent of each row.
73
+ target.preload_parents(records: model_records)
74
+
75
+ failed_rows = validate_and_load(
76
+ model_records: model_records, first_row_number: first_row_number, schema_checker: schema_checker
77
+ )
78
+
79
+ ChunkResult.new(
80
+ first_row_number: first_row_number,
81
+ last_row_number: first_row_number + rows.size - 1,
82
+ processed_rows_count: rows.size,
83
+ valid_rows_count: rows.size - failed_rows.size,
84
+ failed_rows_count: failed_rows.size,
85
+ failed_rows: failed_rows
86
+ )
87
+ end
88
+
89
+ private
90
+
91
+ # The model record of each row, in file order.
92
+ def build_model_records(rows:, transformer:, target:)
93
+ model_records = []
94
+
95
+ rows.each do |row|
96
+ model_records << target.build_record(attributes: transformer.result_of_row(row: row))
97
+ end
98
+
99
+ model_records
100
+ end
101
+
102
+ # Takes the model records one at a time, in row order: validates a record and, when it has no error,
103
+ # loads it before the next record is looked at. Returns the failed rows of the chunk.
104
+ def validate_and_load(model_records:, first_row_number:, schema_checker:)
105
+ failed_rows = []
106
+
107
+ model_records.each_with_index do |model_record, position|
108
+ add_errors(model_record: model_record, schema_checker: schema_checker)
109
+
110
+ # One row at a time: a later row is validated after the earlier ones are in the table, so the
111
+ # model's own uniqueness check also finds two rows of the file with the same value.
112
+ next if model_record.errors.empty? && model_record.load
113
+
114
+ # Every column of the record is shown, also one the consumer did not map (a column a callback filled, the
115
+ # primary key), because an error can be about it. After a refused write the record's errors are the
116
+ # database's.
117
+ failed_rows << FailedRow.new(
118
+ row_number: first_row_number + position,
119
+ attributes: model_record.json_attributes,
120
+ errors: model_record.errors.values
121
+ )
122
+ end
123
+
124
+ failed_rows
125
+ end
126
+
127
+ # Adds the errors of the two levels to the record, one for each column: the record keeps the first error
128
+ # of a column, so the ones it found itself come before the schema's.
129
+ def add_errors(model_record:, schema_checker:)
130
+ model_record.valid?
131
+
132
+ # The schema is checked on what the model record holds after its validation, because the model's
133
+ # callbacks can change a value.
134
+ schema_checker.call(attributes: model_record.attributes).each do |error|
135
+ model_record.add_error(error: error)
136
+ end
137
+ end
138
+ end
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pipeforge
4
+ module RunProcessor
5
+ # Applies the consumer's column mapping to one source row. It does the header mapping (which source
6
+ # column feeds each target column) and the value mapping, and nothing else. A blank result is not a
7
+ # value: the column is left out, so the target decides what an empty cell becomes.
8
+ class RowTransformer
9
+ # @param resolved_mapped_columns [Hash{String => ResolvedMappedColumn}] target column name => its resolved
10
+ # mapped column, whose value mapping has text keys
11
+ def initialize(resolved_mapped_columns:)
12
+ @resolved_mapped_columns = resolved_mapped_columns
13
+ end
14
+
15
+ # @param row [Hash{String => String, nil}] a row as the reader yields it
16
+ # @return [Hash{String => Object}] target column => the value to load: the value mapping applied. A
17
+ # column whose result is blank is not in the Hash
18
+ def result_of_row(row:)
19
+ values = {}
20
+
21
+ @resolved_mapped_columns.each do |target_column_name, resolved_mapped_column|
22
+ source_value = row[resolved_mapped_column.source_column_name]
23
+ value = resolved_mapped_column.value_mapping.fetch(source_value, source_value)
24
+
25
+ # Left out so the column's default fills it; a column with no default is empty without it.
26
+ next if Utilities.blank?(value: value)
27
+
28
+ values[target_column_name] = value
29
+ end
30
+
31
+ values
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../column_limits_checker"
4
+
5
+ module Pipeforge
6
+ module RunProcessor
7
+ # The checks the core can make on one record from the columns the consumer mapped, without reading any row.
8
+ # A column of the table that no entry fills is not checked: the model and the database check it.
9
+ # - a required column left empty: +value_missing+
10
+ # - a value outside the limits of its column, as {ColumnLimitsChecker} finds it:
11
+ # a string or text longer than +max_length+: +value_too_long+
12
+ # an integer outside the size from +limit+
13
+ # (from 0 for an unsigned column), a decimal with
14
+ # more digits before the point than +precision -
15
+ # scale+ once rounded to the scale, or a float
16
+ # that is infinite or larger than the column
17
+ # holds: +value_out_of_range+
18
+ # a value that is not a label
19
+ # of an enum column: +value_not_allowed+
20
+ # Whether a value fits the type of its column is not checked: a value that does not look like the
21
+ # type (+abc+ in an integer column) is left to the cast of the framework.
22
+ #
23
+ # The values are the ones the model record holds, already cast to the type of their column (an Integer, a Float
24
+ # or a decimal number for a number).
25
+ class SchemaChecker
26
+ # @param resolved_mapped_columns [Hash{String => ResolvedMappedColumn}] target column name => its resolved
27
+ # mapped column; the checks are made on the target column of each
28
+ def initialize(resolved_mapped_columns:)
29
+ @target_columns = []
30
+ resolved_mapped_columns.each_value { |resolved_mapped_column| @target_columns << resolved_mapped_column.target_column }
31
+
32
+ @limits_by_column_name = {}
33
+
34
+ @target_columns.each do |target_column|
35
+ @limits_by_column_name[target_column.name] = ColumnLimitsChecker.for(target_column: target_column)
36
+ end
37
+ end
38
+
39
+ # @param attributes [Hash{String => Object}] target column => value to load
40
+ # @return [Array<ErrorCatalog::ColumnError>] one error for each mistake, as the {ErrorCatalog} builds it, with +origin: :schema+
41
+ # (its +value+ is the value that failed, nil for an empty required value); empty when the record passes
42
+ def call(attributes:)
43
+ errors = []
44
+
45
+ @target_columns.each do |target_column|
46
+ value = attributes[target_column.name]
47
+
48
+ if value.nil?
49
+ errors << missing_error(target_column: target_column) if target_column.required
50
+ next
51
+ end
52
+
53
+ violation = @limits_by_column_name.fetch(target_column.name).violation_of(value: value)
54
+ errors << violation unless violation.nil?
55
+ end
56
+
57
+ errors
58
+ end
59
+
60
+ private
61
+
62
+ def missing_error(target_column:)
63
+ ErrorCatalog::ERRORS.fetch(:value_missing).call(origin: :schema, target_column_name: target_column.name, value: nil)
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "run_processor/row_transformer"
4
+ require_relative "run_processor/schema_checker"
5
+ require_relative "run_processor/chunk_processor"
6
+
7
+ module Pipeforge
8
+ # Runs a migration over the whole source: it reads the rows in chunks, gives each chunk to
9
+ # {ChunkProcessor}, which validates and writes the rows, and adds up the counts.
10
+ module RunProcessor
11
+ # The totals of a run, over every chunk.
12
+ # processed_rows_count rows read
13
+ # valid_rows_count rows that passed the validation and were written
14
+ # failed_rows_count rows that did not
15
+ RunResult = Data.define(:processed_rows_count, :valid_rows_count, :failed_rows_count)
16
+
17
+ class << self
18
+ # Writes every row of the source and yields each chunk's result to the block as the chunk is done.
19
+ #
20
+ # A +:run+ writes each row in its own transaction and keeps it. A +:dry_run+ writes the same rows inside
21
+ # one transaction that is rolled back when the last chunk is done, so nothing is kept; the block is
22
+ # called inside that transaction, so it must not write to the target database.
23
+ #
24
+ # @param source_reader [Source::CsvReader] the reader of the source
25
+ # @param resolved_mapped_columns [Hash{String => ResolvedMappedColumn}] target column name => its source column,
26
+ # value mapping and target column; only these columns are read and checked
27
+ # @param offset [Integer] rows to skip before the first one processed
28
+ # @param chunk_size [Integer] rows read, processed and yielded at a time
29
+ # @param mode [Symbol] +:dry_run+ or +:run+
30
+ # @param target [#build_record, #preload_parents, #transaction] the target of the target model
31
+ # (see {Migration})
32
+ # @yieldparam chunk_result [ChunkResult] the outcome of one chunk
33
+ # @return [RunResult]
34
+ def call(source_reader:, resolved_mapped_columns:, offset:, chunk_size:, mode:, target:, &on_chunk)
35
+ if mode == :dry_run
36
+ target.transaction(rollback_at_end: true) do
37
+ read_and_process_chunks(
38
+ source_reader: source_reader, resolved_mapped_columns: resolved_mapped_columns,
39
+ offset: offset, chunk_size: chunk_size, target: target, &on_chunk
40
+ )
41
+ end
42
+ else
43
+ read_and_process_chunks(
44
+ source_reader: source_reader, resolved_mapped_columns: resolved_mapped_columns,
45
+ offset: offset, chunk_size: chunk_size, target: target, &on_chunk
46
+ )
47
+ end
48
+ end
49
+
50
+ private
51
+
52
+ # Reads the source in chunks, gives each to {ChunkProcessor}, yields each result to the block and
53
+ # adds up the counts.
54
+ def read_and_process_chunks(source_reader:, resolved_mapped_columns:, offset:, chunk_size:, target:)
55
+ transformer = RowTransformer.new(resolved_mapped_columns: resolved_mapped_columns)
56
+ schema_checker = SchemaChecker.new(resolved_mapped_columns: resolved_mapped_columns)
57
+ processed_rows_count = 0
58
+ valid_rows_count = 0
59
+ failed_rows_count = 0
60
+ first_row_number = offset + 1
61
+
62
+ # The reader gives only the columns the mapping uses, so a chunk holds no unused cells.
63
+ source_reader.each_chunk(
64
+ offset: offset, chunk_size: chunk_size,
65
+ columns: source_column_names_of(resolved_mapped_columns: resolved_mapped_columns)
66
+ ) do |rows|
67
+ chunk_result = ChunkProcessor.call(
68
+ rows: rows, first_row_number: first_row_number, transformer: transformer,
69
+ schema_checker: schema_checker, target: target
70
+ )
71
+ yield chunk_result if block_given?
72
+
73
+ processed_rows_count += chunk_result.processed_rows_count
74
+ valid_rows_count += chunk_result.valid_rows_count
75
+ failed_rows_count += chunk_result.failed_rows_count
76
+ first_row_number = chunk_result.last_row_number + 1
77
+ end
78
+
79
+ RunResult.new(
80
+ processed_rows_count: processed_rows_count,
81
+ valid_rows_count: valid_rows_count,
82
+ failed_rows_count: failed_rows_count
83
+ )
84
+ end
85
+
86
+ # The source columns that the mapped columns read, each once.
87
+ def source_column_names_of(resolved_mapped_columns:)
88
+ source_column_names = []
89
+
90
+ resolved_mapped_columns.each_value do |resolved_mapped_column|
91
+ source_column_name = resolved_mapped_column.source_column_name
92
+ source_column_names << source_column_name unless source_column_names.include?(source_column_name)
93
+ end
94
+
95
+ source_column_names
96
+ end
97
+ end
98
+ end
99
+ end