Class: I_Dig_Sql

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/i_dig_sql.rb

Defined Under Namespace

Classes: H

Constant Summary collapse

Duplicate =
Class.new RuntimeError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ I_Dig_Sql

Returns a new instance of I_Dig_Sql.



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/i_dig_sql.rb', line 38

def initialize *args
  @digs = args.select { |a|
    a.is_a? I_Dig_Sql
  }

  @sqls = H.new
  @vars = H.new

  @sqls.merge_these *(@digs.map(&:sqls))
  @vars.merge_these *(@digs.map(&:vars))

  @string = args.select { |s| s.is_a? String }.join("\n")
end

Instance Attribute Details

#sqlsObject (readonly)

class H



37
38
39
# File 'lib/i_dig_sql.rb', line 37

def sqls
  @sqls
end

#varsObject (readonly)

class H



37
38
39
# File 'lib/i_dig_sql.rb', line 37

def vars
  @vars
end

Instance Method Details

#<<(str) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'lib/i_dig_sql.rb', line 68

def << str
  @string << (
    if @string.empty?
      str
    else
      "\n" << str
    end
  )
end

#[](name) ⇒ Object



52
53
54
# File 'lib/i_dig_sql.rb', line 52

def [] name
  @sqls[name]
end

#[]=(name, val) ⇒ Object



56
57
58
# File 'lib/i_dig_sql.rb', line 56

def []= name, val
  @sqls[name] = val
end

#eachObject



60
61
62
63
64
65
66
# File 'lib/i_dig_sql.rb', line 60

def each
  if block_given?
    @sqls.each { |k, v| yield k, v }
  else
    @sqls.each
  end
end

#to_pairObject



78
79
80
# File 'lib/i_dig_sql.rb', line 78

def to_pair
  [to_sql, vars]
end

#to_sqlObject



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/i_dig_sql.rb', line 82

def to_sql
  s    = @string.dup
  ctes = []

  s.gsub!(/\{\{\s?(\!|\*)?\s?([a-zA-Z0-9\_]+)\s?\}\}/) do |match|
    key = $2.to_sym
    case $1
    when "!"
      self[key]
    when "*"
      ctes << key
      "SELECT * FROM #{key}"
    else
      ctes << key
      key
    end
  end

  return s if ctes.empty?

  %^
    WITH
    #{ctes.map { |k| "#{k} AS (
      #{self[k]}
    )" }.join "
    ,
    "}
    #{s}
  ^
end