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,202 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pipeforge
4
+ # One unsaved ActiveRecord record, wrapped for the run. It answers what the core asks of a model
5
+ # record (see {RunProcessor::ChunkProcessor}): the errors of the model's own validations, and the write.
6
+ class ActiveRecordModelRecord
7
+ # @return [ActiveRecord::Base] the unsaved record
8
+ attr_reader :record
9
+
10
+ # The mistakes of the record, one for each column, with the shared codes: +value_missing+, +value_too_long+,
11
+ # +value_not_unique+, +parent_missing+, +value_not_accepted+ (the target could not give the record the value),
12
+ # +value_not_allowed+ and, for any other validation, +value_invalid+. After {#load} was refused by the
13
+ # database they are its error instead, with +origin: :database+, the same codes, +value_out_of_range+ and
14
+ # +database_error+; a callback that stopped the save is +value_invalid+ with +origin: :model+.
15
+ #
16
+ # @return [Hash{String, nil => ErrorCatalog::ColumnError}] target column name => its error, in the order the errors
17
+ # were added; the key nil is the record as a whole. Empty when there is none
18
+ attr_reader :errors
19
+
20
+ # @param record [ActiveRecord::Base] the unsaved record
21
+ def initialize(record:)
22
+ @record = record
23
+ @errors = {}
24
+ end
25
+
26
+ # Adds an error to the record, unless its column already has one: the first error found for a column is the
27
+ # one kept.
28
+ #
29
+ # @param error [ErrorCatalog::ColumnError] an error built by the {ErrorCatalog}
30
+ # @raise [ArgumentError] the object was not built by the {ErrorCatalog}
31
+ # @return [void]
32
+ def add_error(error:)
33
+ unless ErrorCatalog.error?(candidate: error)
34
+ raise ArgumentError, ArgumentMessages::MESSAGES.fetch(:error_not_from_error_catalog).call(given_class: error.class)
35
+ end
36
+
37
+ return if @errors.key?(error.target_column_name)
38
+
39
+ @errors[error.target_column_name] = error
40
+ end
41
+
42
+ # Runs the model's validations on the record and adds what they report, so a column that already has an
43
+ # error (one the target added when it built the record, for example) is not reported again. It does not
44
+ # clear the errors.
45
+ #
46
+ # @return [Boolean] true when the record has no error
47
+ def valid?
48
+ add_model_errors unless @record.valid?
49
+
50
+ @errors.empty?
51
+ end
52
+
53
+ # Writes the record to its table in its own transaction (a savepoint when a transaction is
54
+ # already open). The model's validations are not run again. A mistake from the database is kept
55
+ # in {#errors} with +origin: :database+ and nothing of this row is kept. A callback of the model that
56
+ # stops the save is kept with +origin: :model+.
57
+ #
58
+ # @return [Boolean] true when the row was written
59
+ def load
60
+ @errors = {}
61
+
62
+ # requires_new makes a real transaction when none is open and a savepoint inside the dry run's,
63
+ # so only this row is undone when the database refuses it.
64
+ @record.class.transaction(requires_new: true) { @record.save!(validate: false) }
65
+
66
+ true
67
+ rescue ActiveRecord::StatementInvalid => database_error
68
+ add_error(error: database_error_for(database_error: database_error))
69
+
70
+ false
71
+ rescue ActiveRecord::RecordNotSaved => not_saved_error
72
+ # A callback of the model stopped the save.
73
+ add_error(
74
+ error: ErrorCatalog::ERRORS.fetch(:value_invalid_save_stopped)
75
+ .call(origin: :model, target_column_name: nil, value: nil, native_message: not_saved_error.message)
76
+ )
77
+
78
+ false
79
+ end
80
+
81
+ # The values the record holds now: cast to the types of the columns, and after the model's validation
82
+ # has run, so after its callbacks. They are what would be loaded. A column that was not given holds its
83
+ # default, or nil.
84
+ #
85
+ # @return [Hash{String => Object}] column => value
86
+ def attributes
87
+ @record.attributes
88
+ end
89
+
90
+ # The values of {#attributes} as plain JSON types, which is what a failed row shows: a date is its ISO
91
+ # text and a decimal a text.
92
+ #
93
+ # @return [Hash{String => Object}] column => value
94
+ def json_attributes
95
+ attributes.as_json
96
+ end
97
+
98
+ private
99
+
100
+ # The error of the {ErrorCatalog} for one database exception, as the database found it (no column, no value),
101
+ # with the text of the database as +native_message+.
102
+ def database_error_for(database_error:)
103
+ ErrorCatalog::ERRORS.fetch(database_key_of(database_error: database_error))
104
+ # The column is not worked out from the message: the wording differs between databases.
105
+ .call(origin: :database, target_column_name: nil, value: nil, native_message: database_error.message)
106
+ end
107
+
108
+ # The key of {ErrorCatalog::ERRORS} for a database exception: RecordNotUnique -> value_not_unique,
109
+ # InvalidForeignKey -> parent_missing, NotNullViolation -> value_missing, ValueTooLong -> value_too_long,
110
+ # RangeError -> value_out_of_range, anything else -> database_error.
111
+ def database_key_of(database_error:)
112
+ case database_error
113
+ when ActiveRecord::RecordNotUnique then :value_not_unique
114
+ when ActiveRecord::InvalidForeignKey then :parent_missing
115
+ when ActiveRecord::NotNullViolation then :value_missing
116
+ when ActiveRecord::ValueTooLong then :value_too_long
117
+ when ActiveRecord::RangeError then :value_out_of_range
118
+ else :database_error
119
+ end
120
+ end
121
+
122
+ def add_model_errors
123
+ @record.errors.each do |model_error|
124
+ add_error(error: model_error_for(model_error: model_error))
125
+ end
126
+ end
127
+
128
+ # The error of the {ErrorCatalog} for one error of the model's validations, with the value the record holds for
129
+ # the column.
130
+ def model_error_for(model_error:)
131
+ key = key_of(model_error: model_error)
132
+ target_column_name = target_column_name_of(model_error: model_error)
133
+ failed_value = value_of(target_column_name: target_column_name)
134
+
135
+ ErrorCatalog::ERRORS.fetch(key)
136
+ .call(
137
+ origin: :model, target_column_name: target_column_name, value: failed_value.as_json,
138
+ **facts_of(model_error: model_error, key: key, failed_value: failed_value)
139
+ )
140
+ end
141
+
142
+ # The value the record holds for a column; nil for the record as a whole and for an attribute that is not a column.
143
+ def value_of(target_column_name:)
144
+ return nil if target_column_name.nil? || !@record.has_attribute?(target_column_name)
145
+
146
+ @record[target_column_name]
147
+ end
148
+
149
+ # The facts of the error: the text of the model as +native_message+, for every error of the model, and the facts
150
+ # that its sentence uses.
151
+ def facts_of(model_error:, key:, failed_value:)
152
+ case key
153
+ when :value_too_long
154
+ {
155
+ native_message: model_error.message, max_length: model_error.options[:count],
156
+ length: failed_value.to_s.length
157
+ }.compact
158
+ when :value_invalid then {native_message: model_error.message, error_type: model_error.type}
159
+ else {native_message: model_error.message}
160
+ end
161
+ end
162
+
163
+ # The key of {ErrorCatalog::ERRORS} for an error of the model.
164
+ def key_of(model_error:)
165
+ case model_error.type
166
+ when :blank then blank_key_of(model_error: model_error)
167
+ when :too_long then :value_too_long
168
+ when :taken then :value_not_unique
169
+ else :value_invalid
170
+ end
171
+ end
172
+
173
+ # The key of a blank error: +parent_missing+ for a +belongs_to+ association whose foreign key holds
174
+ # a value, and +value_missing+ otherwise.
175
+ def blank_key_of(model_error:)
176
+ parent_reflection = parent_association_of(model_error: model_error)
177
+ return :value_missing if parent_reflection.nil? || @record[parent_reflection.foreign_key].nil?
178
+
179
+ :parent_missing
180
+ end
181
+
182
+ # The column the error is about: nil for an error on the record as a whole (+:base+), the foreign key column for
183
+ # an error on a +belongs_to+ association, and the name of the attribute for any other error.
184
+ def target_column_name_of(model_error:)
185
+ return nil if model_error.attribute == :base
186
+
187
+ parent_reflection = parent_association_of(model_error: model_error)
188
+ return parent_reflection.foreign_key unless parent_reflection.nil?
189
+
190
+ model_error.attribute.to_s
191
+ end
192
+
193
+ # The +belongs_to+ association that the error is on, with a single foreign key column; nil when it
194
+ # is on anything else.
195
+ def parent_association_of(model_error:)
196
+ reflection = @record.class.reflect_on_association(model_error.attribute)
197
+ return nil unless reflection&.belongs_to? && reflection.foreign_key.is_a?(String)
198
+
199
+ reflection
200
+ end
201
+ end
202
+ end
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pipeforge
4
+ # Reads the structure of one ActiveRecord model's table and of the application model itself, and
5
+ # nothing else: no row of the table is read.
6
+ #
7
+ # Only the columns that can be given a source column are in the schema. The primary key (filled
8
+ # by the database), the columns the model ignores, the generated columns and the array columns
9
+ # are left out, so the rest of Pipeforge never hears of them.
10
+ #
11
+ # @example
12
+ # schema = Pipeforge::ActiveRecordSchemaReader.new(
13
+ # model: User, enum_labels_by_column_name: {}, polymorphic_columns_by_column_name: {}
14
+ # ).call
15
+ # schema.columns.map(&:name) # => ["email", "company_id"]
16
+ class ActiveRecordSchemaReader
17
+ # The column types whose size is a number of characters; for the others it is a number of bytes.
18
+ TEXT_TYPES = %w[string text].freeze
19
+
20
+ # @param model [Class] the ActiveRecord model of the target table
21
+ # @param enum_labels_by_column_name [Hash{String => Array<String>}] column name => the labels of its enum, for the enum
22
+ # columns of the model
23
+ # @param polymorphic_columns_by_column_name [Hash{String => PolymorphicColumn}] column name => the polymorphic association it
24
+ # belongs to, for the id column and the type column of each polymorphic association of the model
25
+ def initialize(model:, enum_labels_by_column_name:, polymorphic_columns_by_column_name:)
26
+ @model = model
27
+ @enum_labels_by_column_name = enum_labels_by_column_name
28
+ @polymorphic_columns_by_column_name = polymorphic_columns_by_column_name
29
+ end
30
+
31
+ # @return [TargetSchema] the table name, the model name and the columns that can be given a source column
32
+ def call
33
+ TargetSchema.new(table_name: @model.table_name, model_name: @model.name, columns: build_columns)
34
+ end
35
+
36
+ private
37
+
38
+ def build_columns
39
+ foreign_keys = foreign_keys_by_column_name
40
+ primary_keys = Array(@model.primary_key)
41
+ target_columns = []
42
+
43
+ @model.columns_hash.each_value do |model_column|
44
+ next unless writable?(model_column: model_column, primary_keys: primary_keys)
45
+
46
+ target_columns << build_column(
47
+ model_column: model_column, foreign_key: foreign_keys[model_column.name],
48
+ polymorphic: @polymorphic_columns_by_column_name[model_column.name]
49
+ )
50
+ end
51
+
52
+ target_columns
53
+ end
54
+
55
+ # Whether the column can be given a source column: it is not the primary key, not a generated
56
+ # column and not an array column. The columns the model ignores are not in its column list at all.
57
+ def writable?(model_column:, primary_keys:)
58
+ return false if primary_keys.include?(model_column.name)
59
+ return false if model_column.virtual?
60
+
61
+ !array_column?(model_column: model_column)
62
+ end
63
+
64
+ # Whether each cell of the column holds a list of values. Only some databases have such columns
65
+ # (PostgreSQL), so the question is asked only of a column that can answer it.
66
+ def array_column?(model_column:)
67
+ model_column.respond_to?(:array?) && model_column.array?
68
+ end
69
+
70
+ # Whether a row cannot be loaded without a source column for the column: the column refuses
71
+ # an empty value (+null+ is false) and has no default, neither in the table (a value or a
72
+ # function) nor in the model. The timestamps the model fills itself count as a default.
73
+ def required?(model_column:)
74
+ return false if model_column.null
75
+ return false if model_column.has_default?
76
+ return false if timestamp_filled_by_model?(column_name: model_column.name)
77
+
78
+ @model.column_defaults[model_column.name].nil?
79
+ end
80
+
81
+ # Whether the model sets the column when it saves a record: a timestamp of a model that
82
+ # records timestamps (+created_at+, +updated_at+ and the like).
83
+ def timestamp_filled_by_model?(column_name:)
84
+ return false unless @model.record_timestamps
85
+
86
+ @model.all_timestamp_attributes_in_model.include?(column_name)
87
+ end
88
+
89
+ # Builds the target column from the model's view of the column: its attribute type and
90
+ # +column_defaults+. For an enum column the labels are in +enum_labels+, and an integer column
91
+ # is not signed when its attribute type is ActiveRecord's unsigned integer.
92
+ def build_column(model_column:, foreign_key:, polymorphic:)
93
+ attribute_type = @model.type_for_attribute(model_column.name)
94
+ type = attribute_type.type.to_s
95
+ text_type = TEXT_TYPES.include?(type)
96
+
97
+ TargetColumn.new(
98
+ name: model_column.name,
99
+ type: type,
100
+ sql_type: model_column.sql_type,
101
+ # For a column that is not text: the size in bytes of an integer, the significand bits of a float.
102
+ limit: text_type ? nil : attribute_type.limit,
103
+ is_signed: is_signed_of(attribute_type: attribute_type),
104
+ max_length: text_type ? attribute_type.limit : nil,
105
+ precision: attribute_type.precision,
106
+ scale: attribute_type.scale,
107
+ default: @model.column_defaults[model_column.name],
108
+ enum_labels: @enum_labels_by_column_name[model_column.name],
109
+ required: required?(model_column: model_column),
110
+ foreign_key: foreign_key,
111
+ polymorphic: polymorphic
112
+ )
113
+ end
114
+
115
+ # Whether an integer column holds negative numbers; nil for a column that is not an integer.
116
+ def is_signed_of(attribute_type:)
117
+ return false if attribute_type.is_a?(ActiveRecord::Type::UnsignedInteger)
118
+ return true if attribute_type.type == :integer
119
+
120
+ nil
121
+ end
122
+
123
+ # The foreign key columns of the model, by column name, from its +belongs_to+ associations.
124
+ # A polymorphic association has no one parent table, and a composite key is not one column, so
125
+ # neither is described as a foreign key (a polymorphic one is described by +polymorphic+ on its id and type columns).
126
+ def foreign_keys_by_column_name
127
+ foreign_keys = {}
128
+
129
+ @model.reflect_on_all_associations(:belongs_to).each do |reflection|
130
+ next if reflection.polymorphic?
131
+ next unless reflection.foreign_key.is_a?(String)
132
+
133
+ foreign_keys[reflection.foreign_key] = ForeignKey.new(
134
+ association_name: reflection.name.to_s,
135
+ parent_table_name: reflection.klass.table_name
136
+ )
137
+ end
138
+
139
+ foreign_keys
140
+ end
141
+ end
142
+ end
@@ -0,0 +1,277 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "model_record"
4
+ require_relative "schema_reader"
5
+
6
+ module Pipeforge
7
+ # The ActiveRecord target for one target model: it reads the structure of the model's table, casts
8
+ # values as the model would, builds the model's records, preloads their parents and runs a block in
9
+ # a transaction. It reads no row of the target except the parent rows the model's own validation
10
+ # needs. What is asked of one record (checking it, writing it) is answered by the
11
+ # {ActiveRecordModelRecord} it returns.
12
+ #
13
+ # The target is named by its model class (+"User"+). The target finds the class among the models
14
+ # that are loaded; it never loads any itself. The table is the model's own table.
15
+ #
16
+ # @example
17
+ # target = Pipeforge::ActiveRecordTarget.new(target_model_name: "User")
18
+ # target.schema.columns.map(&:name) # => ["email", "company_id"]
19
+ class ActiveRecordTarget
20
+ # @param target_model_name [String] the name of a loaded model
21
+ # @raise [TargetSchemaError] no loaded model has that name (+model_not_found+), or
22
+ # the table of the model does not exist (+target_table_not_found+)
23
+ def initialize(target_model_name:)
24
+ @model = find_model(target_model_name: target_model_name)
25
+ reject_missing_table
26
+ @enum_labels_by_column_name = read_enum_labels_by_column_name
27
+ @polymorphic_columns_by_column_name = read_polymorphic_columns_by_column_name
28
+ end
29
+
30
+ # The labels of the model's enum for a column.
31
+ #
32
+ # @param column_name [String] a column of the table
33
+ # @return [Array<String>, nil] the labels as text; nil when the model declares no enum for the column
34
+ def enum_labels(column_name:)
35
+ @enum_labels_by_column_name[column_name]
36
+ end
37
+
38
+ # The structure of the model's table: its columns that can be given a source column.
39
+ #
40
+ # @return [TargetSchema]
41
+ def schema
42
+ ActiveRecordSchemaReader.new(
43
+ model: @model, enum_labels_by_column_name: @enum_labels_by_column_name,
44
+ polymorphic_columns_by_column_name: @polymorphic_columns_by_column_name
45
+ ).call
46
+ end
47
+
48
+ # Builds the model's unsaved record from the attributes. Each value is cast as {#cast_value} casts it, and
49
+ # the record is given the cast value. A value the record cannot be given is not given
50
+ # to it, and the record has an error for that column instead, with the value that failed: a value the column's type cannot cast (a text that
51
+ # is not JSON, a day that is not in the calendar), a value that is not a label of the column's enum (ActiveRecord raises on a label it does not know), and a type
52
+ # of a polymorphic association that names no model. An empty value is always given, the model's own validation
53
+ # decides what it means.
54
+ #
55
+ # @param attributes [Hash{String => Object}] target column => value to load
56
+ # @return [ActiveRecordModelRecord] the unsaved record, wrapped
57
+ def build_record(attributes:)
58
+ assigned_values = {}
59
+ rejections_by_column_name = {}
60
+
61
+ attributes.each do |column_name, value|
62
+ if value.nil?
63
+ assigned_values[column_name] = nil
64
+ next
65
+ end
66
+
67
+ cast_result = cast_value(column_name: column_name, value: value)
68
+ casted_value = cast_result.cast_value
69
+
70
+ if !cast_result.castable
71
+ # There is no cast value, so the error shows the value as it was given.
72
+ rejections_by_column_name[column_name] = {key: :value_not_accepted_not_castable, value: value.as_json}
73
+ elsif not_an_enum_label?(column_name: column_name, casted_value: casted_value)
74
+ rejections_by_column_name[column_name] = {key: :value_not_accepted_enum_label, value: casted_value.as_json}
75
+ elsif polymorphic_type_unknown?(column_name: column_name, casted_value: casted_value)
76
+ rejections_by_column_name[column_name] = {key: :value_not_accepted_polymorphic_type, value: casted_value.as_json}
77
+ else
78
+ assigned_values[column_name] = casted_value
79
+ end
80
+ end
81
+
82
+ model_record = ActiveRecordModelRecord.new(record: @model.new(assigned_values))
83
+
84
+ rejections_by_column_name.each do |column_name, rejection|
85
+ model_record.add_error(
86
+ error: ErrorCatalog::ERRORS.fetch(rejection[:key])
87
+ .call(origin: :model, target_column_name: column_name, value: rejection[:value])
88
+ )
89
+ end
90
+
91
+ model_record
92
+ end
93
+
94
+ # Reads a value as the column's type would: what the model would load (the cast value, a Ruby object) and
95
+ # the same data in plain JSON types (the json value). It reads no row and writes nothing. The value of an
96
+ # enum column is given back as it is.
97
+ #
98
+ # @param column_name [String] a column of the table
99
+ # @param value [String, Hash, Array, Object] a value from the file (a non-empty text) or from a value
100
+ # mapping, as it is
101
+ # @return [CastResult] the cast value and the json value of a value the type can cast (both are nil for the
102
+ # JSON null), or {CastResult::NOT_CASTABLE} for a value it cannot cast; for an enum column, the value as
103
+ # it is
104
+ def cast_value(column_name:, value:)
105
+ # The cast of an enum type turns a value the database stores for a label into that label (1 into
106
+ # "placed") and leaves its text ("1") alone, which would show the same value in two ways.
107
+ unless enum_labels(column_name: column_name).nil?
108
+ return castable_cast_result(cast_value: value)
109
+ end
110
+
111
+ cast_by_attribute_type(attribute_type: @model.type_for_attribute(column_name), value: value)
112
+ end
113
+
114
+ # Runs the block in one transaction on the connection of the table's model; with +rollback_at_end+
115
+ # the transaction is undone when the block ends, so nothing the block wrote is kept.
116
+ #
117
+ # @param rollback_at_end [Boolean] undo everything the block wrote when it ends
118
+ # @yield the work to do inside the transaction
119
+ # @return [Object] the block's result
120
+ def transaction(rollback_at_end:, &block)
121
+ result = nil
122
+
123
+ # The model's own connection, so a model kept in another database is written to that database.
124
+ # requires_new: inside a transaction that the consumer already opened, the block would only join it, and
125
+ # ActiveRecord swallows the Rollback without undoing anything; a savepoint makes the undo real.
126
+ @model.transaction(requires_new: true) do
127
+ result = block.call
128
+ raise ActiveRecord::Rollback if rollback_at_end
129
+ end
130
+
131
+ # Kept in a variable because a rolled-back transaction returns nil.
132
+ result
133
+ end
134
+
135
+ # Loads the parents that the records need, with one query for each +belongs_to+ association (for each
136
+ # parent class of a polymorphic one).
137
+ #
138
+ # @param records [Array<ActiveRecordModelRecord>] the records built for one chunk
139
+ # @return [void]
140
+ def preload_parents(records:)
141
+ unsaved_records = []
142
+ records.each { |model_record| unsaved_records << model_record.record }
143
+
144
+ @model.reflect_on_all_associations(:belongs_to).each do |reflection|
145
+ # One query for each association, so the model's validation does not query the parent of each record.
146
+ ActiveRecord::Associations::Preloader.new(records: unsaved_records, associations: reflection.name).call
147
+ end
148
+ end
149
+
150
+ private
151
+
152
+ # The labels of every enum the model declares, by column name. The model's enums do not change, so they are
153
+ # read once.
154
+ def read_enum_labels_by_column_name
155
+ labels_by_column_name = {}
156
+
157
+ @model.defined_enums.each do |column_name, enum_mapping|
158
+ # A label is text; one that ActiveRecord keeps as a number is read as its text.
159
+ labels_by_column_name[column_name] = enum_mapping.keys.map(&:to_s)
160
+ end
161
+
162
+ labels_by_column_name
163
+ end
164
+
165
+ # The id column and the type column of each polymorphic +belongs_to+ association of the model, by column
166
+ # name. The associations of the model do not change, so they are read once.
167
+ def read_polymorphic_columns_by_column_name
168
+ polymorphic_columns = {}
169
+
170
+ @model.reflect_on_all_associations(:belongs_to).each do |reflection|
171
+ next unless reflection.polymorphic?
172
+
173
+ association_name = reflection.name.to_s
174
+ polymorphic_columns[reflection.foreign_key] = PolymorphicColumn.new(association_name: association_name, role: "id")
175
+ polymorphic_columns[reflection.foreign_type] = PolymorphicColumn.new(association_name: association_name, role: "type")
176
+ end
177
+
178
+ polymorphic_columns
179
+ end
180
+
181
+ # Whether the column has an enum and the cast value is not one of its labels.
182
+ def not_an_enum_label?(column_name:, casted_value:)
183
+ labels = enum_labels(column_name: column_name)
184
+
185
+ !labels.nil? && !labels.include?(casted_value.to_s)
186
+ end
187
+
188
+ # Whether the column is the type column of a polymorphic association and the cast value names no model.
189
+ # ActiveRecord raises NameError when it reads the parent of such a type.
190
+ def polymorphic_type_unknown?(column_name:, casted_value:)
191
+ polymorphic_column = @polymorphic_columns_by_column_name[column_name]
192
+ return false if polymorphic_column.nil? || polymorphic_column.role != "type"
193
+
194
+ !model_named?(name: casted_value.to_s)
195
+ end
196
+
197
+ # Whether the text names a model, as ActiveRecord reads the type of a polymorphic association: a constant that
198
+ # is a class below ActiveRecord::Base. A model that is not loaded yet is found by the autoload. An abstract class
199
+ # has no table to hold a parent, so it is not a model.
200
+ def model_named?(name:)
201
+ model_class = name.safe_constantize
202
+
203
+ model_class.is_a?(Class) && model_class < ActiveRecord::Base && !model_class.abstract_class?
204
+ end
205
+
206
+ # The loaded model with that name. An abstract class is not a model of a table, so it is not found.
207
+ def find_model(target_model_name:)
208
+ model = ActiveRecord::Base.descendants.find do |candidate|
209
+ candidate.name == target_model_name && !candidate.abstract_class?
210
+ end
211
+ return model unless model.nil?
212
+
213
+ raise TargetSchemaError.single(
214
+ **TargetSchemaError::ENTRIES.fetch(:model_not_found).call(target_model_name: target_model_name)
215
+ )
216
+ end
217
+
218
+ def reject_missing_table
219
+ # The connection of the model, because a model can use another database than ActiveRecord::Base.
220
+ table_exists = @model.with_connection do |connection|
221
+ connection.data_source_exists?(@model.table_name)
222
+ end
223
+ return if table_exists
224
+
225
+ raise TargetSchemaError.single(
226
+ **TargetSchemaError::ENTRIES.fetch(:target_table_not_found).call(
227
+ table_name: @model.table_name, model_name: @model.name
228
+ )
229
+ )
230
+ end
231
+
232
+ # Casts a value with the attribute type of a column; the text of a json or jsonb column is decoded as JSON.
233
+ #
234
+ # @return [CastResult] the answer of {#cast_value}: {CastResult::NOT_CASTABLE} for a value the type cannot
235
+ # cast or a text that is not JSON
236
+ def cast_by_attribute_type(attribute_type:, value:)
237
+ if json_text?(attribute_type: attribute_type, value: value)
238
+ cast_json_text(text: value)
239
+ else
240
+ cast_with_attribute_type(attribute_type: attribute_type, value: value)
241
+ end
242
+ end
243
+
244
+ # A json or jsonb text is decoded as JSON; a text that is not JSON cannot be cast.
245
+ def cast_json_text(text:)
246
+ # decode, not deserialize: deserialize turns a parse error into nil, the same as the text null. cast
247
+ # would keep the String, which the column then stores as a JSON string.
248
+ castable_cast_result(cast_value: ActiveSupport::JSON.decode(text))
249
+ rescue JSON::ParserError
250
+ CastResult::NOT_CASTABLE
251
+ end
252
+
253
+ # Casts a value that is not the text of a json or jsonb column.
254
+ def cast_with_attribute_type(attribute_type:, value:)
255
+ # The cast is lenient: abc in an integer column is 0.
256
+ loaded_value = attribute_type.cast(value)
257
+
258
+ # ActiveRecord answers nil for a text it cannot read, such as a day that is not in the calendar.
259
+ return CastResult::NOT_CASTABLE if loaded_value.nil?
260
+
261
+ castable_cast_result(cast_value: loaded_value)
262
+ end
263
+
264
+ def castable_cast_result(cast_value:)
265
+ CastResult.new(castable: true, cast_value: cast_value, json_value: cast_value.as_json)
266
+ end
267
+
268
+ # Whether a value is the text of a json or jsonb column, which is read as JSON.
269
+ def json_text?(attribute_type:, value:)
270
+ json_column?(attribute_type: attribute_type) && value.is_a?(String)
271
+ end
272
+
273
+ def json_column?(attribute_type:)
274
+ [:json, :jsonb].include?(attribute_type.type)
275
+ end
276
+ end
277
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pipeforge
4
+ # What a target answers when it is asked to cast one value: whether the value can be cast and, when it can,
5
+ # the value in its two representations. The two values mean something only when +castable+ is true.
6
+ # castable whether the adapter can cast the value
7
+ # cast_value what the model would load, a Ruby object; nil for the JSON null and when the value cannot be cast
8
+ # json_value the cast value in plain JSON types; nil for the JSON null and when the value cannot be cast
9
+ CastResult = Data.define(:castable, :cast_value, :json_value)
10
+
11
+ # The answer for a text that cannot be cast.
12
+ CastResult::NOT_CASTABLE = CastResult.new(castable: false, cast_value: nil, json_value: nil)
13
+ end