Method: PgSync::Sync#in_parallel

Defined in:
lib/pgsync/sync.rb

#in_parallel(tables, first_schema:, &block) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/pgsync/sync.rb', line 158

def in_parallel(tables, first_schema:, &block)
  spinners = TTY::Spinner::Multi.new(format: :dots)
  item_spinners = {}

  start = lambda do |item, i|
    table, opts = item
    message = String.new(":spinner ")
    message << table.sub("#{first_schema}.", "")
    # maybe output later
    # message << " #{opts[:sql]}" if opts[:sql]
    spinner = spinners.register(message)
    spinner.auto_spin
    item_spinners[item] = spinner
  end

  failed_tables = []

  finish = lambda do |item, i, result|
    spinner = item_spinners[item]
    table_name = item.first.sub("#{first_schema}.", "")

    if result[:status] == "success"
      spinner.success(display_message(result))
    else
      # TODO add option to fail fast
      spinner.error(display_message(result))
      failed_tables << table_name
      fail_sync(failed_tables) if @options[:fail_fast]
    end

    unless spinner.send(:tty?)
      status = result[:status] == "success" ? "✔" : "✖"
      log [status, table_name, display_message(result)].compact.join(" ")
    end
  end

  options = {start: start, finish: finish}
  if @options[:debug] || @options[:in_batches]
    options[:in_processes] = 0
  else
    options[:in_threads] = 4 if windows?
  end

  # could try to use `raise Parallel::Kill` to fail faster with --fail-fast
  # see `fast_faster` branch
  # however, need to make sure connections are cleaned up properly
  Parallel.each(tables, **options, &block)

  fail_sync(failed_tables) if failed_tables.any?
end