Class: ProjectUnification::Migrator

Inherits:
Object
  • Object
show all
Defined in:
lib/project_unification/migrator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_project_id:, target_project_id:, options: {}) ⇒ Migrator

Returns a new instance of Migrator.



30
31
32
33
34
35
# File 'lib/project_unification/migrator.rb', line 30

def initialize(source_project_id:, target_project_id:, options: {})
  @source_project_id = source_project_id
  @target_project_id = target_project_id
  @options = options
  @on_model_migrated = options[:on_model_migrated]
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



28
29
30
# File 'lib/project_unification/migrator.rb', line 28

def options
  @options
end

#source_project_idObject (readonly)

Returns the value of attribute source_project_id.



28
29
30
# File 'lib/project_unification/migrator.rb', line 28

def source_project_id
  @source_project_id
end

#target_project_idObject (readonly)

Returns the value of attribute target_project_id.



28
29
30
# File 'lib/project_unification/migrator.rb', line 28

def target_project_id
  @target_project_id
end

Instance Method Details

#apply_conflict_handler(record, stats) ⇒ Object (private)

Dispatch to handle_unify_conflict and update stats based on its return value.

handle_unify_conflict return convention:

nil / false  -> handler did not persist; caller should save! the record
true         -> handler persisted via update_columns; skip save!
:destroyed   -> handler destroyed the source record (merged into target); skip save!


225
226
227
228
229
230
231
232
233
234
# File 'lib/project_unification/migrator.rb', line 225

def apply_conflict_handler(record, stats)
  result = record.handle_unify_conflict(target_project_id)

  if result == :destroyed
    stats[:destroyed] += 1
  else
    record.save! unless result
    stats[:migrated] += 1
  end
end

#conflict_fields(record) ⇒ Object (private)



240
241
242
243
244
# File 'lib/project_unification/migrator.rb', line 240

def conflict_fields(record)
  record.errors.details
    .select { |_, details| details.any? { |d| d[:error] == :taken } }
    .keys
end

#migrate_allHash

Migrate all models from source to target project.

Returns:

  • (Hash)

    Migration results with statistics and errors



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/project_unification/migrator.rb', line 39

def migrate_all
  results = {
    statistics: {
      models_processed: 0,
      records_migrated: 0,
      fast_track_count: 0,
      slow_track_count: 0,
      special_track_count: 0,
      errors_encountered: 0
    },
    details_by_model: {},
    conflicts: [],
    errors: [],
    merge_registry: []
  }

  # MANIFEST is ordered for deletion: FK children appear before FK parents so
  # children can be deleted without violating FK constraints. For migration we
  # need the opposite — parents must arrive in the target project before their
  # children, so that when a child calls valid? with project_id = target_project_id
  # any same-project validator on its FK will find the parent already there.
  # Reversing MANIFEST gives us that order cheaply.
  Project::MANIFEST.reverse.each do |model_name|
    klass = model_name.safe_constantize
    next unless klass
    next unless klass.column_names.include?('project_id')
    next unless ProjectUnification::ModelClassifier.should_migrate?(klass)

    track = ProjectUnification::ModelClassifier.track_for(klass)

    model_started_at = Time.now
    model_result = case track
                   when :fast
                     process_fast_track(klass)
                   when :slow
                     process_slow_track(klass)
                   when :cached
                     process_cached_table(klass)
                   when :special
                     process_special_handling(klass)
                   else
                     raise NotImplementedError, "Unknown track #{track.inspect} for #{klass.name}"
                   end

    if model_result
      model_result[:duration] = (Time.now - model_started_at).round(1)
      @on_model_migrated&.call(model_name, track, model_result)

      results[:details_by_model][model_name] = model_result
      results[:statistics][:models_processed] += 1
      results[:statistics][:records_migrated] += model_result[:migrated] || 0

      track_key = "#{track}_track_count".to_sym
      results[:statistics][track_key] ||= 0
      results[:statistics][track_key] += model_result[:migrated] || 0

      results[:statistics][:errors_encountered] += model_result[:errors]&.length || 0
      results[:conflicts].concat(model_result[:conflicts] || [])
      results[:errors].concat(model_result[:errors] || [])
      results[:merge_registry].concat(model_result[:merge_registry] || [])
    end
  end

  results
end

#process_cached_table(klass) ⇒ Object (private)

Process cached tables with direct SQL update.



192
193
194
195
196
197
198
199
# File 'lib/project_unification/migrator.rb', line 192

def process_cached_table(klass)
  handler = ProjectUnification::SpecialHandlers::CachedTablesHandler.new(
    source_project_id:,
    target_project_id:,
    klass:
  )
  handler.migrate
end

#process_fast_track(klass) ⇒ Object (private)

Fast track: Bulk SQL UPDATE for simple cases.



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/project_unification/migrator.rb', line 108

def process_fast_track(klass)
  return nil unless klass.where(project_id: source_project_id).exists?

  sql = ActiveRecord::Base.sanitize_sql_array([
    "UPDATE #{klass.table_name} SET project_id = ? WHERE project_id = ?",
    target_project_id,
    source_project_id
  ])

  rows_affected = ActiveRecord::Base.connection.execute(sql).cmd_tuples

  {
    track: :fast,
    migrated: rows_affected,
    method: :bulk_sql,
    errors: []
  }
rescue => e
  {
    track: :fast,
    migrated: 0,
    errors: [{
      error: e.message,
      model: klass.name
    }]
  }
end

#process_slow_track(klass) ⇒ Object (private)

Slow track: validate each project reassignment, fail on conflict.



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/project_unification/migrator.rb', line 137

def process_slow_track(klass)
  stats = { track: :slow, migrated: 0, destroyed: 0, conflicts: [], errors: [] }

  records = klass.where(project_id: source_project_id)
  return nil unless records.exists?

  records.find_in_batches do |batch|
    safe_ids = []
    conflict_records = []

    batch.each do |record|
      record.no_cached = true if record.respond_to?(:no_cached=)
      record.project_id = target_project_id

      if record.valid?
        safe_ids << record.id
      elsif uniqueness_error?(record)
        conflict_records << record
      else
        stats[:errors] << {
          id: record.id,
          model: klass.name,
          error: record.errors.full_messages.join('; ')
        }
      end
    rescue => e
      stats[:errors] << { id: record.id, model: klass.name, error: e.message }
    end

    if safe_ids.any?
      stats[:migrated] += klass
        .where(id: safe_ids)
        .update_all(project_id: target_project_id)
    end

    conflict_records.each do |record|
      if record.respond_to?(:handle_unify_conflict)
        apply_conflict_handler(record, stats)
      else
        stats[:conflicts] << {
          id: record.id,
          model: klass.name,
          conflict_fields: conflict_fields(record),
          errors: record.errors.full_messages
        }
      end
    rescue => e
      stats[:errors] << { id: record.id, model: klass.name, error: e.message }
    end
  end

  stats
end

#process_special_handling(klass) ⇒ Object (private)

Special handling for models that need custom logic.



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/project_unification/migrator.rb', line 202

def process_special_handling(klass)
  handler_class = case klass.name
  when 'TaxonName' then ProjectUnification::TaxonNameHandler
  when 'CollectingEvent' then ProjectUnification::SpecialHandlers::CollectingEventHandler
  when 'ProjectSource' then ProjectUnification::SpecialHandlers::ProjectSourceHandler
  when 'RangedLotCategory' then ProjectUnification::SpecialHandlers::RangedLotCategoryHandler
  when 'OtuPageLayout' then ProjectUnification::SpecialHandlers::OtuPageLayoutHandler
  when 'Image' then ProjectUnification::SpecialHandlers::ImageHandler
  when 'Document' then ProjectUnification::SpecialHandlers::DocumentHandler
  when 'ControlledVocabularyTerm' then ProjectUnification::SpecialHandlers::ControlledVocabularyTermHandler
  else raise NotImplementedError, "No special handler defined for #{klass.name}"
  end

  handler_class.new(source_project_id:, target_project_id:, options:).migrate
end

#uniqueness_error?(record) ⇒ Boolean (private)

Returns:

  • (Boolean)


236
237
238
# File 'lib/project_unification/migrator.rb', line 236

def uniqueness_error?(record)
  record.errors.details.values.flatten.any? { |e| e[:error] == :taken }
end