@@ -13,6 +13,7 @@ class SequelManagement
1313 self . logger = Logger . new ( $stdout)
1414
1515 define_db_task!
16+ define_ch_task!
1617 end
1718
1819 private
@@ -23,6 +24,10 @@ class SequelManagement
2324 self . class ::MIGRATIONS_PATH
2425 end
2526
27+ def ch_migrations_path
28+ "db/migrate/clickhouse"
29+ end
30+
2631 def define_db_task!
2732 namespace :db do
2833 desc "Rollback all migrations, which doesn't exist in master branch"
@@ -47,6 +52,31 @@ class SequelManagement
4752 end
4853 end
4954
55+ def define_ch_task!
56+ namespace :ch do
57+ desc "Rollback all migrations, which doesn't exist in master branch"
58+ task rollback_new_migrations : :environment do
59+ abort "Shouldn't run in production mode!" if Rails . env . production?
60+
61+ logger . info "Begin rolling back new migrations"
62+
63+ git_command = "git ls-tree --name-only origin/master #{ ch_migrations_path } /"
64+ migration_files , error , status = Open3 . capture3 ( git_command )
65+ abort "Can't get list of migration files:\n #{ error } " unless status . success?
66+
67+ original_migrations = migration_files . split . map { |path | File . basename ( path ) }
68+ migrations_to_rollback = ( ch_migrator . applied_migrations - original_migrations ) . sort . reverse
69+
70+ next if migrations_to_rollback . empty?
71+
72+ logger . info "Rolling back migrations:"
73+ logger . info migrations_to_rollback . join ( "\n " )
74+
75+ ch_rollback! ( migrations_to_rollback )
76+ end
77+ end
78+ end
79+
5080 def git_command
5181 "git ls-tree --name-only origin/master #{ migrations_path } /"
5282 end
@@ -58,6 +88,14 @@ class SequelManagement
5888 end
5989 end
6090
91+ def ch_migrator
92+ @ch_migrator ||= begin
93+ full_path = Rails . root . join ( ch_migrations_path )
94+ Sequel ::TimestampMigrator . new ( DB , full_path , allow_missing_migration_files : true ,
95+ table : "clickhouse_migrations" )
96+ end
97+ end
98+
6199 def rollback! ( migrations )
62100 migrations . each do |migration |
63101 migrator . undo ( migration . to_i )
@@ -69,6 +107,18 @@ class SequelManagement
69107 end
70108 end
71109 end
110+
111+ def ch_rollback! ( migrations )
112+ migrations . each do |migration |
113+ ch_migrator . undo ( migration . to_i )
114+ rescue Sequel ::Migrator ::Error => error
115+ if error . message . include? ( "does not exist in the filesystem" )
116+ logger . info error . message
117+ else
118+ raise error
119+ end
120+ end
121+ end
72122end
73123
74124SequelManagement . new
0 commit comments