Module: Json2sql::Sanitizer

Defined in:
lib/json2sql/sanitizer.rb

Constant Summary collapse

KEYWORD_DANGEROUS =

Characters stripped from SQL identifiers (table/column names).

/[ `;"'\\]/

Class Method Summary collapse

Class Method Details

.keyword(input) ⇒ Object

Removes dangerous characters from an identifier string.



9
10
11
12
# File 'lib/json2sql/sanitizer.rb', line 9

def self.keyword(input)

  input.to_s.gsub(KEYWORD_DANGEROUS, "")
end

.keyword_wrap(input, wrap = "`") ⇒ Object

Wraps an identifier in the given quote character (default: backtick). Dangerous characters inside the identifier are stripped.



23
24
25
26
# File 'lib/json2sql/sanitizer.rb', line 23

def self.keyword_wrap(input, wrap = "`")

  "#{wrap}#{keyword(input)}#{wrap}"
end

.reference(input) ⇒ Object

Converts a JSON path reference (e.g. “$.users.id”) into a backtick-quoted SQL reference (e.g. “‘users`.`id`”). Strips the leading “$.” and splits on “.”.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/json2sql/sanitizer.rb', line 38

def self.reference(input)
  
  str = input.to_s[2..] # strip leading "$."
  result = +"`"
  str.each_char do |c|
    case c
    when "."
      result << "`.`"
    when " ", "`", ";", '"', "'", "\\"
      # skip dangerous characters
    else
      result << c
    end
  end
  result << "`"
  result
end

.value(input) ⇒ Object

Escapes a value string for safe embedding between SQL quotes. ‘ → ” and \ → \



16
17
18
19
# File 'lib/json2sql/sanitizer.rb', line 16

def self.value(input)

  input.to_s.gsub("\\", "\\\\\\\\").gsub("'", "''")
end

.value_wrap(input, wrap = "'") ⇒ Object

Wraps a value in the given quote character (default: single-quote). Single quotes and backslashes inside the value are escaped.



30
31
32
33
# File 'lib/json2sql/sanitizer.rb', line 30

def self.value_wrap(input, wrap = "'")

  "#{wrap}#{value(input)}#{wrap}"
end