Merge branch '11917-dont-clear-cache'
[arvados.git] / services / api / lib / migrate_yaml_to_json.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 module MigrateYAMLToJSON
6   def self.migrate(table, column)
7     conn = ActiveRecord::Base.connection
8     n = conn.update(
9       "UPDATE #{table} SET #{column}=$1 WHERE #{column}=$2",
10       "#{table}.#{column} convert YAML to JSON",
11       [[nil, "{}"], [nil, "--- {}\n"]])
12     Rails.logger.info("#{table}.#{column}: #{n} rows updated using empty hash")
13     finished = false
14     while !finished
15       n = 0
16       conn.exec_query(
17         "SELECT id, #{column} FROM #{table} WHERE #{column} LIKE $1 LIMIT 100",
18         "#{table}.#{column} check for YAML",
19         [[nil, '---%']],
20       ).rows.map do |id, yaml|
21         n += 1
22         json = SafeJSON.dump(YAML.load(yaml))
23         conn.exec_query(
24           "UPDATE #{table} SET #{column}=$1 WHERE id=$2 AND #{column}=$3",
25           "#{table}.#{column} convert YAML to JSON",
26           [[nil, json], [nil, id], [nil, yaml]])
27       end
28       Rails.logger.info("#{table}.#{column}: #{n} rows updated")
29       finished = (n == 0)
30     end
31   end
32 end