lib/rom/sql/migration/migrator.rb in rom-sql-2.0.0.beta2 vs lib/rom/sql/migration/migrator.rb in rom-sql-2.0.0.beta3

- old
+ new

@@ -1,26 +1,31 @@ require 'pathname' require 'rom/types' require 'rom/initializer' require 'rom/sql/migration' +require 'rom/sql/migration/runner' require 'rom/sql/migration/inline_runner' +require 'rom/sql/migration/writer' module ROM module SQL module Migration # @api private class Migrator extend Initializer DEFAULT_PATH = 'db/migrate'.freeze VERSION_FORMAT = '%Y%m%d%H%M%S'.freeze + DEFAULT_INFERRER = Schema::Inferrer.new.suppress_errors.freeze param :connection option :path, type: ROM::Types.Definition(Pathname), default: -> { DEFAULT_PATH } + option :inferrer, default: -> { DEFAULT_INFERRER } + # @api private def run(options = {}) Sequel::Migrator.run(connection, path.to_s, options) end @@ -33,17 +38,20 @@ def migration(&block) Sequel.migration(&block) end # @api private - def create_file(name, version = generate_version) - filename = "#{version}_#{name}.rb" + def create_file(name, version = generate_version, **options) + sequence = options[:sequence] ? '%03d' % options[:sequence] : nil + filename = "#{ version }#{ sequence }_#{ name }.rb" + content = options[:content] || migration_file_content + path = options[:path] || self.path dirname = Pathname(path) fullpath = dirname.join(filename) FileUtils.mkdir_p(dirname) - File.write(fullpath, migration_file_content) + File.write(fullpath, content) fullpath end # @api private @@ -55,21 +63,36 @@ def migration_file_content File.read(Pathname(__FILE__).dirname.join('template.rb').realpath) end # @api private - def diff(gateway, inferrer, target) - empty = SQL::Schema.define(target.name) - current = target.with(inferrer.(empty, gateway)) + def auto_migrate!(gateway, schemas, options = EMPTY_HASH, &block) + diff_finder = SchemaDiff.new(gateway.database_type) - SchemaDiff.new.(current, target) - end + changes = schemas.map { |target| + empty = SQL::Schema.define(target.name) + current = target.with(inferrer.(empty, gateway)) - def auto_migrate!(gateway, schemas) - runner = InlineRunner.new(gateway) - inferrer = ROM::SQL::Schema::Inferrer.new.suppress_errors - changes = schemas.map { |schema| diff(gateway, inferrer, schema) }.reject(&:empty?) + diff_finder.(current, target) + }.reject(&:empty?) + + runner = migration_runner(options) runner.(changes) + end + + # @api private + def migration_runner(options) + if options[:inline] + Runner.new(InlineRunner.new(connection)) + else + counter = 0 + writer = Writer.new do |name, content| + create_file(name, **options, content: content, sequence: counter) + counter += 1 + end + + Runner.new(writer) + end end end end end end