Class: SqlBeautifier::Expression

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.find_top_level_as(text) ⇒ Object



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
# File 'lib/sql_beautifier/expression.rb', line 21

def self.find_top_level_as(text)
  scanner = Scanner.new(text)

  until scanner.finished?
    consumed = scanner.scan_quoted_or_sentinel!
    next if consumed

    if scanner.current_char == Constants::OPEN_PARENTHESIS
      scanner.increment_depth!
      scanner.advance!
      next
    end

    if scanner.current_char == Constants::CLOSE_PARENTHESIS
      scanner.decrement_depth!
      scanner.advance!
      next
    end

    return scanner.position if scanner.top_level? && scanner.keyword_at?("as")

    scanner.advance!
  end

  nil
end

.parse(text) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/sql_beautifier/expression.rb', line 8

def self.parse(text)
  stripped = text.strip
  alias_position = find_top_level_as(stripped)

  if alias_position
    definition = stripped[0...alias_position].strip
    alias_name = stripped[(alias_position + 3)..].strip
    new(definition: definition, alias_name: alias_name)
  else
    new(definition: stripped)
  end
end

Instance Method Details

#render ⇒ Object



48
49
50
51
52
# File 'lib/sql_beautifier/expression.rb', line 48

def render
  return @definition unless @alias_name

  "#{@definition} as #{@alias_name}"
end