Class: Exwiw::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/exwiw/runner.rb

Instance Method Summary collapse

Constructor Details

#initialize(connection_config:, output_dir:, config_dir:, dump_target:, logger:, output_format: 'insert', insert_only: false, after_insert_hook_path: nil, cli_options: {}) ⇒ Runner

Returns a new instance of Runner.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/exwiw/runner.rb', line 7

def initialize(
  connection_config:,
  output_dir:,
  config_dir:,
  dump_target:,
  logger:,
  output_format: 'insert',
  insert_only: false,
  after_insert_hook_path: nil,
  cli_options: {}
)
  @connection_config = connection_config
  @output_dir = output_dir
  @config_dir = config_dir
  @dump_target = dump_target
  @output_format = output_format
  @insert_only = insert_only
  @after_insert_hook_path = after_insert_hook_path
  @cli_options = cli_options
  @logger = logger
end

Instance Method Details

#runObject



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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/exwiw/runner.rb', line 29

def run
  adapter = Adapter.build(@connection_config, @logger)
  configs = load_table_config(adapter.class.table_config_class)

  validate_ignored(configs)
  validate_rails_managed_target!(configs)

  table_by_name = configs.each_with_object({}) { |config, hash| hash[config.name] = config }

  target = table_by_name[@dump_target.table_name]
  adapter.validate_as_dump_target!(target) if target

  @logger.info("Determining table processing order...")
  ordered_table_names = DetermineTableProcessingOrder.run(configs.select { |c| adapter.dumpable?(c) })

  clean_output_dir!

  ordered_tables = ordered_table_names.map { |n| table_by_name.fetch(n) }
  schema_path = File.join(@output_dir, "insert-000-schema.#{adapter.schema_output_extension}")
  @logger.info("Writing schema to #{schema_path}...")
  adapter.dump_schema(ordered_tables, schema_path)

  total_size = ordered_table_names.size
  ordered_table_names.each_with_index do |table_name, idx|
    table = table_by_name.fetch(table_name)

    if table.ignore
      @logger.info("Skipping data extraction for '#{table_name}' (ignore:true)")
      next
    end

    @logger.info("Processing table '#{table_name}'... (#{idx + 1}/#{total_size})")

    query_ast = adapter.build_query(table, @dump_target, table_by_name)

    # Track which phase we are in so that, if an error is raised while
    # turning the fetched rows into SQL/JSONL, the rescue below can report
    # both the failing step and the exact extraction query that produced the
    # data being processed.
    phase = "executing extraction query"
    begin
      results = adapter.execute(query_ast)
      record_num = results.size

      if record_num.zero?
        @logger.info("  No records matched. skip this table.")
        next
      end
      insert_idx = (idx + 1).to_s.rjust(3, '0')

      if @output_format == 'copy'
        phase = "generating COPY statement"
        @logger.debug("  Generate COPY statement...")
        copy_sql = adapter.to_copy_from_stdin(results, table)
        @logger.info("  Generated COPY statement for #{record_num} records.")

        File.open(File.join(@output_dir, "insert-#{insert_idx}-#{table_name}.#{adapter.output_extension}"), 'w') do |file|
          file.puts(copy_sql)
          post = adapter.post_insert_sql(table)
          file.puts(post) if post
        end
      else
        phase = "generating INSERT statement"
        @logger.debug("  Generate INSERT statement...")
        chunk_size = table.bulk_insert_chunk_size
        chunks = chunk_size ? results.each_slice(chunk_size).to_a : [results]
        insert_sql = chunks.map { |chunk_rows| adapter.to_bulk_insert(chunk_rows, table) }.join("\n")

        @logger.info("  Generated INSERT statement for #{record_num} records (#{chunks.size} statement(s)).")
        File.open(File.join(@output_dir, "insert-#{insert_idx}-#{table_name}.#{adapter.output_extension}"), 'w') do |file|
          file.puts(insert_sql)
          post = adapter.post_insert_sql(table)
          file.puts(post) if post
        end
      end

      if adapter.supports_bulk_delete? && !@insert_only && !(table.respond_to?(:rails_managed?) && table.rails_managed?)
        phase = "generating DELETE statement"
        @logger.debug("  Generate DELETE statement...")
        delete_sql = adapter.to_bulk_delete(query_ast, table)
        if @logger.debug?
          @logger.debug("  Generated DELETE statement:\n#{delete_sql}")
        else
          @logger.info("  Generated DELETE statement.")
        end
        delete_idx = (total_size - idx).to_s.rjust(3, '0')
        File.open(File.join(@output_dir, "delete-#{delete_idx}-#{table_name}.#{adapter.output_extension}"), 'w') do |file|
          file.puts(delete_sql)
        end
      end
    rescue => e
      @logger.error("Error while #{phase} for table '#{table_name}' (#{idx + 1}/#{total_size}): #{e.class}: #{e.message}")
      @logger.error("  Extraction query that produced the data being processed:")
      @logger.error("    #{adapter.describe_query(query_ast)}")
      raise
    end
  end

  if @after_insert_hook_path
    @logger.info("Running after-insert hook: #{@after_insert_hook_path}")
    AfterInsertHook.run(
      path: @after_insert_hook_path,
      cli_options: @cli_options,
      output_dir: @output_dir,
      next_idx: total_size + 1,
      output_extension: adapter.output_extension,
      logger: @logger,
    )
  end
end