Class: StructuredDataToSql::XmlConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/structured_data_to_sql/xml_converter.rb

Constant Summary collapse

UNESCAPED_AMP =
/&(?!(?:amp|lt|gt|quot|apos|#\d+|#x[0-9a-fA-F]+);)/
XML_CHUNK_SIZE =
64 * 1024
XML_SANITIZER_TAIL =
128
DEFAULT_PROGRESS_INTERVAL =
5
ZERO_PROGRESS_WARNING_BYTES =
64 * 1024 * 1024

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(batch_size: 1000, include_tables: nil, exclude_tables: nil, include_files: nil, exclude_files: nil, schema_only: false, scrub_invalid_xml_chars: true, invalid_xml_report_path: nil, zero_progress_warning_bytes: ZERO_PROGRESS_WARNING_BYTES, verbose: false, input_gzip: false, output_gzip: nil, diagnostic_io: nil, diagnostics_report: nil, **unknown) ⇒ XmlConverter

Returns a new instance of XmlConverter.



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
# File 'lib/structured_data_to_sql/xml_converter.rb', line 35

def initialize(
  batch_size: 1000,
  include_tables: nil,
  exclude_tables: nil,
  include_files: nil,
  exclude_files: nil,
  schema_only: false,
  scrub_invalid_xml_chars: true,
  invalid_xml_report_path: nil,
  zero_progress_warning_bytes: ZERO_PROGRESS_WARNING_BYTES,
  verbose: false,
  input_gzip: false,
  output_gzip: nil,
  diagnostic_io: nil,
  diagnostics_report: nil,
  **unknown
)
  if unknown.any?
    raise ConfigurationError,
          "Unknown XML options: #{unknown.keys.join(", ")}"
  end
  XmlOptions.new(batch_size:, verbose:, input_gzip:, output_gzip:)
  unless batch_size.to_i.positive?
    raise UsageError, "XML batch size must be greater than 0"
  end

  @batch_size = batch_size
  @include_tables = include_tables&.to_set
  @exclude_tables = Array(exclude_tables).to_set
  @include_files = include_files&.to_set
  @exclude_files = Array(exclude_files).to_set
  @schema_only = schema_only
  @verbose = verbose
  @scrub_invalid_xml_chars = scrub_invalid_xml_chars
  @invalid_xml_report_path = invalid_xml_report_path
  @zero_progress_warning_bytes = zero_progress_warning_bytes
  @input_gzip = input_gzip
  @output_gzip = output_gzip
  @diagnostic_io = diagnostic_io
  @diagnostics_report = diagnostics_report
  @sql_emitter = MysqlDumpXml::SqlEmitter.new
  reset_stats
rescue StructuredDataToSql::ConfigurationError => e
  raise MysqlDumpXml::ConfigurationError, e.message
end

Instance Attribute Details

#statsObject (readonly)

Returns the value of attribute stats.



27
28
29
# File 'lib/structured_data_to_sql/xml_converter.rb', line 27

def stats
  @stats
end

Instance Method Details

#convert(*arguments, source: nil, output: nil, file_pattern: "*.xml", progress_callback: nil, on_progress: nil, atomic: true, progress_interval: DEFAULT_PROGRESS_INTERVAL, input_gzip: @input_gzip, output_gzip: @output_gzip) ⇒ Object



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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/structured_data_to_sql/xml_converter.rb', line 81

def convert(
  *arguments,
  source: nil,
  output: nil,
  file_pattern: "*.xml",
  progress_callback: nil,
  on_progress: nil,
  atomic: true,
  progress_interval: DEFAULT_PROGRESS_INTERVAL,
  input_gzip: @input_gzip,
  output_gzip: @output_gzip
)
  source ||= arguments[0]
  output ||= arguments[1]
  raise ConfigurationError, "source is required" if source.nil?
  raise ConfigurationError, "output is required" if output.nil?
  IOSupport.validate_output_target!(output)

  reset_stats
  @progress_callback = progress_callback
  @on_progress = on_progress
  @progress_interval = progress_interval
  @last_progress_at = nil
  @current_file_progress = nil
  @current_xml_table = nil
  @current_xml_table_included = nil
  @conversion_started_at = Time.now
  @total_input_bytes = 0
  @invalid_xml_report = nil
  @invalid_xml_report_finalized = false
  source_label =
    (
      if IOSupport.readable_io?(source)
        "(IO)"
      else
        Array(source).map(&:to_s).join(", ")
      end
    )
  @source_path = source_label
  @zero_progress_warning_emitted = false
  output_path = IOSupport.writable_io?(output) ? output : Pathname(output)
  unless IOSupport.writable_io?(output)
    prepare_invalid_xml_report(source_label, output_path)
  end
  files, temporary_inputs =
    IOSupport.discover(
      source,
      patterns: [file_pattern, "#{file_pattern}.gz"].uniq,
      stream_extension: ".xml",
      input_gzip:
    )
  raise UsageError, "No XML files found in #{source}" if files.empty?

  files_to_process, skipped = files.partition { |file| process_file?(file) }
  @stats[:files_skipped] += skipped.length
  if files_to_process.empty?
    raise UsageError,
          "No XML files to process after filtering. All #{files.length} files were excluded."
  end

  log "\n#{"=" * 60}\nXML TO SQL CONVERTER\n#{"=" * 60}"
  log "\nSource: #{source_label}"
  log "Output: #{output_path}"
  log "Files found: #{files.length}"
  log "Files to skip: #{skipped.length}" if skipped.any?
  log "Files to process: #{files_to_process.length}"
  @total_input_bytes =
    files_to_process.sum do |file|
      begin
        file.size
      rescue StandardError
        0
      end
    end
  report_progress(
    :start,
    file_count: files_to_process.length,
    total_input_bytes: @total_input_bytes,
    output_path: output_path.to_s,
    force: true
  )

  gzip_output =
    (
      if output_gzip.nil?
        (!IOSupport.writable_io?(output) && output.to_s.end_with?(".gz"))
      else
        output_gzip
      end
    )
  written_bytes =
    IOSupport.with_output(output, gzip: gzip_output, atomic:) do |out|
      @sql_emitter.write_header(out, source_label: source_label)
      files_to_process.each_with_index do |file, index|
        convert_file(
          file,
          out,
          index: index + 1,
          count: files_to_process.length
        )
      end
      @sql_emitter.write_footer(out)
    end
  @stats[:bytes_written] = written_bytes
  write_diagnostics_report(source_label, output_path)
  report_progress(
    :complete,
    bytes_written: @stats[:bytes_written],
    diagnostics_report: @stats[:diagnostics_report],
    force: true
  )
  finalize_invalid_xml_report(success: true)
  log "\n#{"=" * 60}\nCONVERSION COMPLETE\n#{"=" * 60}"
  log "\nFiles processed:  #{@stats[:files_processed]}"
  if @stats[:files_skipped].positive?
    log "Files skipped:    #{@stats[:files_skipped]}"
  end
  log "Tables converted: #{@stats[:tables_processed]}"
  if @stats[:tables_skipped].positive?
    log "Tables skipped:   #{@stats[:tables_skipped]}"
  end
  log "Rows converted:   #{@stats[:rows_processed]}"
  if @stats[:invalid_xml_chars_removed].positive?
    log "Invalid XML chars removed: #{@stats[:invalid_xml_chars_removed]}"
    log "Invalid XML audit: #{@invalid_xml_report.summary_path}"
  end
  log "Output size:      #{Format.format_size(@stats[:bytes_written])}"
  log "\nOutput written to: #{output_path}"
  ConversionResult.new(format: :xml, metrics: @stats)
rescue StructuredDataToSql::InputError => e
  raise MysqlDumpXml::InputError, e.message
rescue StructuredDataToSql::OutputError => e
  raise MysqlDumpXml::OutputError, e.message
rescue Nokogiri::XML::SyntaxError => e
  raise MysqlDumpXml::ParseError, e.message
rescue SystemCallError, IOError, Zlib::Error => e
  raise InputError, e.message
ensure
  finalize_invalid_xml_report(success: false)
  temporary_inputs&.each(&:unlink)
  @progress_callback = nil
  @on_progress = nil
  @current_file_progress = nil
  @current_xml_table = nil
  @current_xml_table_included = nil
  @invalid_xml_report = nil
end

#convert_file(xml_path, output, index: 1, count: 1) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/structured_data_to_sql/xml_converter.rb', line 229

def convert_file(xml_path, output, index: 1, count: 1)
  log "\nProcessing: #{File.basename(xml_path)}"
  file_size =
    begin
      xml_path.size
    rescue StandardError
      0
    end
  file_started_at = Time.now
  rows_before = @stats[:rows_processed]
  @current_file_progress = {
    path: xml_path.to_s,
    name: File.basename(xml_path),
    index: index,
    count: count,
    size: file_size,
    bytes_read: 0,
    pass: 1,
    passes: 1
  }
  report_progress(:file_start, force: true)
  structures = {}
  current_rows = []
  current_table = nil
  current_column_formats = []

  parse_xml_file(xml_path) do |event_type, table, data|
    case event_type
    when :structure
      set_current_xml_table(table)
      @stats[:tables_observed] += 1
      unless process_table?(table)
        @stats[:tables_skipped] += 1
        next
      end

      if current_rows.any?
        @sql_emitter.write_rows_batch(
          output,
          current_table,
          current_rows,
          column_formats: current_column_formats
        )
        current_rows = []
      end
      structures[table] = data
      output.write("\n-- Table: #{table}\n")
      output.write(data.to_create_table_sql)
      output.write("\n")
      @stats[:tables_processed] += 1
      report_progress(
        :table,
        current_table: table,
        force: @stats[:tables_processed] == 1
      )
    when :row
      @stats[:rows_observed] += 1
      next unless process_table?(table)
      next if @schema_only

      if current_table != table
        if current_rows.any?
          @sql_emitter.write_rows_batch(
            output,
            current_table,
            current_rows,
            column_formats: current_column_formats
          )
        end
        current_table = table
        current_rows = []
        current_column_formats =
          @sql_emitter.column_formats_for(structures[table], data)
      end

      current_rows << data
      @stats[:rows_processed] += 1
      report_progress(
        :rows,
        current_table: table,
        force: @stats[:rows_processed] == 1
      )
      if current_rows.length >= @batch_size
        @sql_emitter.write_rows_batch(
          output,
          current_table,
          current_rows,
          column_formats: current_column_formats
        )
        current_rows = []
      end
    end
  end

  if current_rows.any?
    @sql_emitter.write_rows_batch(
      output,
      current_table,
      current_rows,
      column_formats: current_column_formats
    )
  end
  @stats[:files_processed] += 1
  ledger_entry = {
    name: File.basename(xml_path),
    size: file_size,
    rows: @stats[:rows_processed] - rows_before,
    child_rows: 0,
    elapsed: Time.now - file_started_at
  }
  @ledger << ledger_entry
  report_progress(
    :file_complete,
    file_rows: ledger_entry[:rows],
    file_elapsed: ledger_entry[:elapsed],
    force: true
  )
  @current_file_progress = nil
end