18676: remove script/get_anonymous_user_token.rb and update
[arvados.git] / services / api / lib / fix_collection_versions_timestamps.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'set'
6
7 include CurrentApiClient
8 include ArvadosModelUpdates
9
10 def fix_collection_versions_timestamps
11   act_as_system_user do
12     uuids = [].to_set
13     # Get UUIDs from collections with more than 1 version
14     Collection.where(version: 2).find_each(batch_size: 100) do |c|
15       uuids.add(c.current_version_uuid)
16     end
17     uuids.each do |uuid|
18       first_pair = true
19       # All versions of a particular collection get fixed together.
20       ActiveRecord::Base.transaction do
21         Collection.where(current_version_uuid: uuid).order(version: :desc).each_cons(2) do |c1, c2|
22           # Skip if the 2 newest versions' modified_at values are separate enough;
23           # this means that this collection doesn't require fixing, allowing for
24           # migration re-runs in case of transient problems.
25           break if first_pair && (c2.modified_at.to_f - c1.modified_at.to_f) > 1
26           first_pair = false
27           # Fix modified_at timestamps by assigning to N-1's value to N.
28           # Special case: the first version's modified_at will be == to created_at
29           leave_modified_by_user_alone do
30             leave_modified_at_alone do
31               c1.modified_at = c2.modified_at
32               c1.save!(validate: false)
33               if c2.version == 1
34                 c2.modified_at = c2.created_at
35                 c2.save!(validate: false)
36               end
37             end
38           end
39         end
40       end
41     end
42   end
43 end