@@ -27,49 +27,43 @@ namespace :pg_migration do
27
27
end
28
28
29
29
data = JSON . parse ( File . read ( filepath ) )
30
- now = Time . current # Use the same timestamp for all imported records
31
30
32
- # Import in dependency order
33
- if data [ "trained_messages" ]
34
- puts "Importing #{ data [ "trained_messages" ] . length } TrainedMessage records..."
31
+ ActiveRecord ::Base . transaction do
32
+ # Import in dependency order
35
33
36
- # Prepare the data for bulk insert
37
- attributes = data [ "trained_messages" ] . map do |record |
38
- record . delete ( "id" )
39
- # Add timestamps if they don't exist in your JSON data
40
- record [ "created_at" ] ||= now
41
- record [ "updated_at" ] ||= now
42
- record
34
+ if data [ "trained_messages" ]
35
+ puts "Importinng TrainedMessage records.."
36
+ data [ "trained_messages" ] . each do |record |
37
+ record . delete ( "id" )
38
+ TrainedMessage . insert! ( record )
39
+ print "."
40
+ end
41
+ puts "\n Imported #{ data [ "trained_messages" ] . length } TrainedMessage records"
43
42
end
44
43
45
- # Perform the bulk insert
46
- TrainedMessage . insert_all! ( attributes )
47
- end
48
-
49
- # Repeat for BannedUser
50
- if data [ "banned_users" ]
51
- puts "Importing #{ data [ "banned_users" ] . length } BannedUser records..."
52
- attributes = data [ "banned_users" ] . map do |record |
53
- record . delete ( "id" )
54
- record [ "created_at" ] ||= now
55
- record [ "updated_at" ] ||= now
56
- record
44
+ if data [ "banned_users" ]
45
+ puts "Importing BannedUser records..."
46
+ data [ "banned_users" ] . each do |record |
47
+ record . delete ( "id" )
48
+ BannedUser . insert! ( record )
49
+ print "."
50
+ end
51
+ puts "\n Imported #{ data [ "banned_users" ] . length } BannedUser records"
57
52
end
58
- BannedUser . insert_all! ( attributes )
59
- end
60
53
61
- # Repeat for GroupClassifierState
62
- if data [ "group_classifier_states" ]
63
- puts "Importing #{ data [ "group_classifier_states" ] . length } GroupClassifierStates records..."
64
- attributes = data [ "group_classifier_states" ] . map do |record |
65
- record . delete ( "id" )
66
- record [ "created_at" ] ||= now
67
- record [ "updated_at" ] ||= now
68
- record
54
+ if data [ "group_classifier_states" ]
55
+ puts "Importing GroupClassifierStates records..."
56
+ data [ "group_classifier_states" ] . each do |record |
57
+ # Find the existing record by its unique group_id or prepare a new one
58
+ state = GroupClassifierState . find_or_initialize_by ( group_id : record [ "group_id" ] )
59
+
60
+ # Update its attributes with the data from the JSON file
61
+ state . update! ( record . except ( "id" ) )
62
+ print "."
63
+ end
64
+ puts "\n Imported #{ data [ "group_classifier_states" ] . length } GroupClassifierStates records"
69
65
end
70
- GroupClassifierState . insert_all! ( attributes )
71
66
end
72
-
73
67
puts "Migration complete!"
74
68
end
75
69
end
0 commit comments