1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
# frozen_string_literal: true
module Database
class MarkMigrationService
def initialize(connection:, version:)
@connection = connection
@version = version
end
def execute
return error(reason: :not_found) unless migration.present?
return error(reason: :invalid) if all_versions.include?(migration.version)
if create_version(version)
ServiceResponse.success
else
error(reason: :invalid)
end
end
private
attr_reader :connection, :version
def migration
@migration ||= connection
.migration_context
.migrations
.find { |migration| migration.version == version }
end
def all_versions
all_executed_migrations.map(&:to_i)
end
def all_executed_migrations
sm = Arel::SelectManager.new(arel_table)
sm.project(arel_table[:version])
sm.order(arel_table[:version].asc) # rubocop: disable CodeReuse/ActiveRecord
connection.select_values(sm, "#{self.class} Load")
end
def create_version(version)
im = Arel::InsertManager.new
im.into(arel_table)
im.insert(arel_table[:version] => version)
connection.insert(im, "#{self.class} Create", :version, version)
end
def arel_table
@arel_table ||= Arel::Table.new(:schema_migrations)
end
def error(reason:)
ServiceResponse.error(message: 'error', reason: reason)
end
end
end
|