Class: RailsSimpleSearch::SqlHandler::SelectionGroup

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

Overview

this class is to represent a sql select statements, union of select statements, or intersect of select statements

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(item = nil) ⇒ SelectionGroup

Returns a new instance of SelectionGroup.



15
16
17
18
# File 'lib/selection_group.rb', line 15

def initialize(item = nil)
  @selection_item = item if item
  @children = []
end

Class Method Details

.union_alias_countObject



9
10
11
12
13
# File 'lib/selection_group.rb', line 9

def self.union_alias_count
  @union_alias_count ||= 0
  @union_alias_count += 1
  @union_alias_count
end

Instance Method Details

#add_child(condition_group) ⇒ Object



20
21
22
23
24
# File 'lib/selection_group.rb', line 20

def add_child(condition_group)
  raise "It's not allowed to add child into leaf node" if leaf?

  @children << condition_group if condition_group
end

#add_item(selection_item) ⇒ Object



26
27
28
29
30
# File 'lib/selection_group.rb', line 26

def add_item(selection_item)
  raise "It's not allowed to add item into non-leaf node" unless empty?

  @selection_item = selection_item
end

#empty?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/selection_group.rb', line 42

def empty?
  @children.empty? ? true : false
end

#leaf?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/selection_group.rb', line 38

def leaf?
  @selection_item ? true : false
end

#relation(and_or) ⇒ Object



32
33
34
35
36
# File 'lib/selection_group.rb', line 32

def relation(and_or)
  raise "It's no need to set relation for leaf node" if leaf?

  @relation = and_or
end

#to_sqlObject



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/selection_group.rb', line 46

def to_sql
  if leaf?
    @selection_item.to_sql
  elsif @relation == :or
    unioned_sql = @children.map(&:to_sql).join(' union ')
    "select * from ( #{unioned_sql} ) as #{union_alias}"
  elsif @relation == :and
    @children.map(&:to_sql).join(' intersect ')
  else
    raise "This should not happen"
  end
end

#union_aliasObject



59
60
61
# File 'lib/selection_group.rb', line 59

def union_alias
  "union_alias_#{self.class.union_alias_count}"
end