Class: StructuredDataToSql::Json::NameRegistry

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

Overview

Allocates deterministic, collision-free table and column names. Built during the inference pass and reused verbatim during the emit pass so both passes agree on every name.

Constant Summary collapse

MAX_NAME_LENGTH =
64

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeNameRegistry

Returns a new instance of NameRegistry.



26
27
28
29
30
31
32
# File 'lib/structured_data_to_sql/json/shredder.rb', line 26

def initialize
  @columns = {}
  @column_owner = Hash.new { |hash, key| hash[key] = {} }
  @children = {}
  @child_owner = Hash.new { |hash, key| hash[key] = {} }
  @collisions = 0
end

Instance Attribute Details

#collisionsObject (readonly)

Returns the value of attribute collisions.



24
25
26
# File 'lib/structured_data_to_sql/json/shredder.rb', line 24

def collisions
  @collisions
end

Class Method Details

.sanitize(name) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/structured_data_to_sql/json/shredder.rb', line 50

def self.sanitize(name)
  sanitized =
    name
      .to_s
      .gsub(/([a-z0-9])([A-Z])/, '\1_\2')
      .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
      .downcase
      .gsub(/[^a-z0-9_]+/, "_")
      .squeeze("_")
      .gsub(/\A_+|_+\z/, "")
  sanitized = "t_#{sanitized}" if sanitized.match?(/\A\d/)
  sanitized.empty? ? "unnamed" : sanitized
end

.truncate(name) ⇒ Object



64
65
66
67
68
# File 'lib/structured_data_to_sql/json/shredder.rb', line 64

def self.truncate(name)
  return name if name.length <= MAX_NAME_LENGTH

  "#{name[0, MAX_NAME_LENGTH - 9]}_#{Digest::SHA1.hexdigest(name)[0, 8]}"
end

Instance Method Details

#child_rel(table_rel, raw_path) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/structured_data_to_sql/json/shredder.rb', line 42

def child_rel(table_rel, raw_path)
  key = [table_rel, raw_path.join("\0")]
  @children[key] ||= allocate(@child_owner[:tables], key) do
    rel = sanitize_path(raw_path)
    table_rel.empty? ? rel : "#{table_rel}_#{rel}"
  end
end

#column_name(table_rel, raw_path, representation) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/structured_data_to_sql/json/shredder.rb', line 34

def column_name(table_rel, raw_path, representation)
  key = [table_rel, representation, raw_path.join("\0")]
  @columns[key] ||= allocate(@column_owner[table_rel], key) do
    base = sanitize_path(raw_path)
    representation == :json ? "#{base}_json" : base
  end
end