Class: StructuredDataToSql::JsonConverter

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

Overview

Converts arbitrary JSON export files into a MySQL/MariaDB SQL dump using convention-based relational shredding. Counterpart to XmlConverter: same output framing, filters, gzip handling, atomic writes, and progress callback vocabulary. Each file is streamed twice: pass 1 infers the schema (CREATE TABLEs must precede INSERTs), pass 2 emits the rows.

Constant Summary collapse

DEFAULT_PROGRESS_INTERVAL =
5
DEFAULT_MAX_DEPTH =
5

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, records_path: nil, records_path_config: nil, table_name: nil, max_depth: DEFAULT_MAX_DEPTH, json_columns: nil, graphql_unwrap: true, raw_dates: false, schema_dir: nil, meta_table: true, recover_truncated: false, ndjson: :auto, input_mode: nil, verbose: false, input_gzip: false, output_gzip: nil, profile: nil, diagnostic_io: nil, diagnostics_report: nil) ⇒ JsonConverter

Returns a new instance of JsonConverter.



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

def initialize(
  batch_size: 1000,
  include_tables: nil,
  exclude_tables: nil,
  include_files: nil,
  exclude_files: nil,
  schema_only: false,
  records_path: nil,
  records_path_config: nil,
  table_name: nil,
  max_depth: DEFAULT_MAX_DEPTH,
  json_columns: nil,
  graphql_unwrap: true,
  raw_dates: false,
  schema_dir: nil,
  meta_table: true,
  recover_truncated: false,
  ndjson: :auto,
  input_mode: nil,
  verbose: false,
  input_gzip: false,
  output_gzip: nil,
  profile: nil,
  diagnostic_io: nil,
  diagnostics_report: nil
)
  ndjson = { json: false, ndjson: true, auto: :auto }.fetch(
    input_mode.to_sym
  ) if input_mode
  JsonOptions.new(
    batch_size:,
    max_depth:,
    ndjson:,
    verbose:,
    input_gzip:,
    output_gzip:
  )
  unless batch_size.to_i.positive?
    raise UsageError, "JSON batch size must be greater than 0"
  end
  unless max_depth.to_i.positive?
    raise UsageError, "JSON max depth must be greater than 0"
  end
  if schema_dir && !Dir.exist?(schema_dir)
    raise UsageError, "Schema directory not found: #{schema_dir}"
  end
  if records_path_config && !File.exist?(records_path_config)
    raise UsageError,
          "Records path config not found: #{records_path_config}"
  end

  @profile = normalize_profile(profile)
  if @profile && schema_only
    raise UsageError, "--profile cannot be used with schema-only output"
  end
  if @profile && (include_tables || Array(exclude_tables).any?)
    raise UsageError,
          "--profile cannot be combined with table include/exclude filters"
  end
  if @profile && (records_path || records_path_config || table_name)
    raise UsageError,
          "--profile cannot be combined with records-path options or a root table override"
  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
  @records_path = validate_records_path(records_path, "--records-path")
  @records_path_config =
    (
      if records_path_config
        load_records_path_config(records_path_config)
      else
        nil
      end
    )
  @table_name = table_name
  @max_depth = max_depth
  @json_columns = json_columns
  @graphql_unwrap = graphql_unwrap
  @raw_dates = raw_dates
  @schema_dir = schema_dir
  @meta_table = meta_table
  @recover_truncated = recover_truncated
  @ndjson = ndjson
  @verbose = verbose
  @input_gzip = input_gzip
  @output_gzip = output_gzip
  @diagnostic_io = diagnostic_io
  @diagnostics_report = diagnostics_report
  @emitter = Json::SqlEmitter.new
  reset_stats
rescue StructuredDataToSql::ConfigurationError => e
  raise Json::ConfigurationError, e.message
end

Instance Attribute Details

#statsObject (readonly)

Returns the value of attribute stats.



31
32
33
# File 'lib/structured_data_to_sql/json_converter.rb', line 31

def stats
  @stats
end

Instance Method Details

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



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
228
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
# File 'lib/structured_data_to_sql/json_converter.rb', line 135

def convert(
  *arguments,
  source: nil,
  output: nil,
  file_pattern: "*.json",
  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
  @conversion_started_at = Time.now
  @total_work_bytes = nil
  @total_input_bytes = nil
  @emitted_tables = {}
  @profile_tables = {}
  @profile_validator = profile_class::InputValidator.new if @profile
  @pii_meta = []
  @schema_used = false
  @io_source = IOSupport.readable_io?(source)
  source_label =
    (
      if IOSupport.readable_io?(source)
        "(IO)"
      else
        Array(source).map(&:to_s).join(", ")
      end
    )
  output_path = IOSupport.writable_io?(output) ? output : Pathname(output)
  patterns = [
    file_pattern,
    "#{file_pattern}.gz",
    "*.jsonl",
    "*.jsonl.gz",
    "*.ndjson",
    "*.ndjson.gz"
  ].uniq
  files, temporary_inputs =
    IOSupport.discover(
      source,
      patterns:,
      stream_extension: ".json",
      input_gzip:
    )
  raise UsageError, "No JSON 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 JSON files to process after filtering. All #{files.length} files were excluded."
  end
  validate_profile_files!(files_to_process) if @profile
  @manifest =
    Json::ExporterManifest.load(Json::ExporterManifest.locate(source))
  @source_paths = quality_signal_paths(files_to_process)
  if @profile_validator.respond_to?(:run_context=)
    @profile_validator.run_context = {
      manifest: @manifest,
      source_paths: @source_paths
    }
  end

  log "\n#{"=" * 60}\nJSON 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
  @total_input_bytes = total_input_bytes
  @total_work_bytes =
    files_to_process.sum do |file|
      IOSupport.estimated_input_bytes(file) * streaming_passes_for(file)
    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|
      @emitter.write_header(out, source_label)
      write_profile_preamble(out) if @profile
      files_to_process.each_with_index do |file, index|
        convert_file(
          file,
          out,
          index: index + 1,
          count: files_to_process.length
        )
      end
      if @schema_used && @meta_table
        @emitter.write_meta_table(out, @pii_meta)
      end
      write_profile(out) if @profile
      @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],
    bytes_read: @stats[:bytes_read],
    diagnostics_report: @stats[:diagnostics_report],
    force: 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]} (+#{@stats[:child_rows_processed]} child rows)"
  log "Output size:      #{Format.format_size(@stats[:bytes_written])}"
  log "\nOutput written to: #{output_path}"
  ConversionResult.new(format: :json, metrics: @stats)
rescue StructuredDataToSql::InputError => e
  raise Json::InputError, e.message
rescue StructuredDataToSql::OutputError => e
  raise Json::OutputError, e.message
rescue Oj::ParseError, EncodingError => e
  raise Json::ParseError, e.message
rescue SystemCallError, IOError, Zlib::Error => e
  raise InputError, e.message
ensure
  temporary_inputs&.each(&:unlink)
  @progress_callback = nil
  @on_progress = nil
  @io_source = nil
  @current_file_progress = nil
end