11807: Migrate old records in jobs table from YAML to JSON.
[arvados.git] / services / api / lib / migrate_yaml_to_json.rb
1 module MigrateYAMLToJSON
2   def self.migrate(table, column)
3     conn = ActiveRecord::Base.connection
4     n = conn.update(
5       "UPDATE #{table} SET #{column}=$1 WHERE #{column}=$2",
6       "#{table}.#{column} convert YAML to JSON",
7       [[nil, "{}"], [nil, "--- {}\n"]])
8     Rails.logger.info("#{table}.#{column}: #{n} rows updated using empty hash")
9     finished = false
10     while !finished
11       n = 0
12       conn.exec_query(
13         "SELECT id, #{column} FROM #{table} WHERE #{column} LIKE $1 LIMIT 100",
14         "#{table}.#{column} check for YAML",
15         [[nil, '---%']],
16       ).rows.map do |id, yaml|
17         n += 1
18         json = SafeJSON.dump(YAML.load(yaml))
19         conn.exec_query(
20           "UPDATE #{table} SET #{column}=$1 WHERE id=$2 AND #{column}=$3",
21           "#{table}.#{column} convert YAML to JSON",
22           [[nil, json], [nil, id], [nil, yaml]])
23       end
24       Rails.logger.info("#{table}.#{column}: #{n} rows updated")
25       finished = (n == 0)
26     end
27   end
28 end