Skip to content

Commit 134a6b8

Browse files
Merge pull request #3245 from alphagov/change-linksets-pkey-3-populate-column
(ADR-009 PR 3) Populate link_set_content_id with rake task
2 parents 03da175 + 3bd5eb1 commit 134a6b8

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
desc "Add link_set_content_id to links"
2+
task :add_link_set_content_id_to_links, [:link_id] => [:environment] do |_t, args|
3+
batch_size = 1000
4+
link_id = args.fetch(:link_id, 0).to_i
5+
total_updated = 0
6+
link_set_links = Link.where.not(link_set_id: nil)
7+
total_count = link_set_links.where(id: link_id...).count
8+
9+
loop do
10+
max_link_id = link_set_links.where(id: link_id...)
11+
.order(id: :asc).limit(batch_size)
12+
.pluck(:id).last
13+
break if max_link_id.nil?
14+
15+
puts "Processing link ids from #{link_id} to #{max_link_id}"
16+
17+
sql = <<-SQL
18+
UPDATE links
19+
SET link_set_content_id = link_sets.content_id
20+
FROM link_sets
21+
WHERE links.link_set_id IS NOT NULL AND links.link_set_id = link_sets.id
22+
AND links.id BETWEEN ? AND ?
23+
SQL
24+
25+
ActiveRecord::Base.connection.execute(
26+
ActiveRecord::Base.sanitize_sql_array([sql, link_id, max_link_id]),
27+
)
28+
29+
link_id = max_link_id + 1
30+
total_updated += batch_size
31+
puts "Processed #{total_updated} of #{total_count} links so far (#{(total_updated.to_f / total_count * 100).round(1)}%)"
32+
sleep(0.1)
33+
end
34+
35+
puts "Finished processing links. Total updated: #{total_updated}"
36+
end

0 commit comments

Comments
 (0)