Class: SqlBeautifier::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/sql_beautifier/formatter.rb

Constant Summary collapse

LEADING_SENTINEL_PATTERN =
%r{\A#{CommentParser::SENTINEL_PATTERN}[[:space:]]*}
LEADING_SENTINEL_CAPTURE =
%r{\A(#{CommentParser::SENTINEL_PATTERN}[[:space:]]*)}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, depth: 0) ⇒ Formatter

Returns a new instance of Formatter.



12
13
14
15
# File 'lib/sql_beautifier/formatter.rb', line 12

def initialize(value, depth: 0)
  @value = value
  @depth = depth
end

Class Method Details

.call ⇒ Object



8
9
10
# File 'lib/sql_beautifier/formatter.rb', line 8

def self.call(...)
  new(...).call
end

Instance Method Details

#call ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/sql_beautifier/formatter.rb', line 17

def call
  return unless @value.present?

  @normalized_value = Normalizer.call(@value)
  return unless @normalized_value.present?

  @leading_sentinels = extract_leading_sentinels!
  return unless @normalized_value.present?

  drop_table_result = DropTable.parse(@normalized_value)&.render
  return prepend_sentinels(drop_table_result) if drop_table_result

  cte_result = CteQuery.parse(@normalized_value, depth: @depth)&.render
  return prepend_sentinels(cte_result) if cte_result

  create_table_as_result = CreateTableAs.parse(@normalized_value, depth: @depth)&.render
  return prepend_sentinels(create_table_as_result) if create_table_as_result

  create_table_result = CreateTable.parse(@normalized_value)&.render
  return prepend_sentinels(create_table_result) if create_table_result

  compound_result = CompoundQuery.parse(@normalized_value, depth: @depth)&.render
  return prepend_sentinels(compound_result) if compound_result

  insert_result = InsertQuery.parse(@normalized_value, depth: @depth)&.render
  return prepend_sentinels(insert_result) if insert_result

  update_result = UpdateQuery.parse(@normalized_value, depth: @depth)&.render
  return prepend_sentinels(update_result) if update_result

  delete_result = DeleteQuery.parse(@normalized_value, depth: @depth)&.render
  return prepend_sentinels(delete_result) if delete_result

  first_clause_position = Tokenizer.first_clause_position(@normalized_value)
  return prepend_sentinels("#{@normalized_value}\n") if first_clause_position.nil? || first_clause_position.positive?

  query = Query.parse(@normalized_value, depth: @depth)
  result = query.render
  return prepend_sentinels("#{@normalized_value}\n") unless result

  prepend_sentinels(result)
end