|
| 1 | +class UpdateAfterAndBeforeSchoolCareCategory < ActiveRecord::Migration[6.1] |
| 2 | + def up |
| 3 | + ActiveRecord::Base.transaction do |
| 4 | + # Set this to true to enable assertions |
| 5 | + @assertions_enabled = true |
| 6 | + |
| 7 | + rename_category from: 'After & Before School Care', to: 'After & Before School' |
| 8 | + |
| 9 | + create_subcategory_relationship('Arts, Culture & Identity', 'After & Before School') |
| 10 | + create_subcategory_relationship("Education", 'After & Before School') |
| 11 | + create_subcategory_relationship("Sports & Recreation", 'After & Before School') |
| 12 | + create_subcategory_relationship("Youth Workforce & Life Skills", 'After & Before School') |
| 13 | + end |
| 14 | + end |
| 15 | + |
| 16 | + def down |
| 17 | + raise ActiveRecord::IrreversibleMigration |
| 18 | + end |
| 19 | + |
| 20 | + private |
| 21 | + |
| 22 | + def rename_category(from:, to:) |
| 23 | + assert_category_exists from |
| 24 | + assert_category_does_not_exist to |
| 25 | + |
| 26 | + exec_query <<-SQL, "rename category from #{from} to #{to}", [to, from] |
| 27 | + UPDATE categories |
| 28 | + SET name = $1 |
| 29 | + WHERE name = $2; |
| 30 | + SQL |
| 31 | + end |
| 32 | + |
| 33 | + def assert_category_exists(name) |
| 34 | + return unless @assertions_enabled |
| 35 | + |
| 36 | + count = select_value("SELECT COUNT(*) FROM categories WHERE name = $1", "count category #{name}", [name]) |
| 37 | + raise "Expected category #{name} to exist, got #{count} results" unless count == 1 |
| 38 | + end |
| 39 | + |
| 40 | + def assert_category_does_not_exist(name) |
| 41 | + return unless @assertions_enabled |
| 42 | + |
| 43 | + count = select_value("SELECT COUNT(*) FROM categories WHERE name = $1", "count category #{name}", [name]) |
| 44 | + raise "Expected category #{name} to not exist, got #{count} results" unless count == 0 |
| 45 | + end |
| 46 | + |
| 47 | + def category_id(name) |
| 48 | + id = select_value("SELECT id FROM categories WHERE name = $1", "get category id #{name}", [name]) |
| 49 | + raise "Category #{name} does not exist" if id.nil? |
| 50 | + id |
| 51 | + end |
| 52 | + |
| 53 | + def create_subcategory_relationship(top_category, subcategory) |
| 54 | + top_category_id = category_id(top_category) |
| 55 | + subcategory_id = category_id(subcategory) |
| 56 | + exec_query <<-SQL, "create subcategory relationship #{top_category} -> #{subcategory}", [top_category_id, subcategory_id] |
| 57 | + INSERT INTO category_relationships (parent_id, child_id) |
| 58 | + VALUES ($1, $2); |
| 59 | + SQL |
| 60 | + end |
| 61 | +end |
0 commit comments