Migration scripts must thoroughly validate data conditions and handle edge cases to ensure reliable data transformation. Always check for data existence before applying operations, properly handle duplicate records, and avoid migrating calculated or derived fields.

Key practices:

Example of proper duplicate handling:

duplicate = DB.query_single(<<~SQL, name: name).first
  SELECT id from ai_personas where name = :name
SQL

if duplicate.present?
  duplicate  # Return existing record to continue migration
else
  # Create new record
end

This approach prevents migration failures and ensures data integrity across different migration scenarios and schema versions.