Class: MiniSql::InlineParamEncoder

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conn, array_encoder = nil) ⇒ InlineParamEncoder

Returns a new instance of InlineParamEncoder.



7
8
9
10
# File 'lib/mini_sql/inline_param_encoder.rb', line 7

def initialize(conn, array_encoder = nil)
  @conn = conn
  @array_encoder = array_encoder
end

Instance Attribute Details

#array_encoderObject (readonly)

Returns the value of attribute array_encoder.



5
6
7
# File 'lib/mini_sql/inline_param_encoder.rb', line 5

def array_encoder
  @array_encoder
end

#connObject (readonly)

Returns the value of attribute conn.



5
6
7
# File 'lib/mini_sql/inline_param_encoder.rb', line 5

def conn
  @conn
end

Instance Method Details

#encode(sql, *params) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/mini_sql/inline_param_encoder.rb', line 12

def encode(sql, *params)
  if Hash === (hash = params[0])
    raise ArgumentError, "Only one hash param is allowed, multiple were sent" if params.length > 1
    encode_hash(sql, hash)
  else
    encode_array(sql, params)
  end
end

#encode_array(sql, array) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/mini_sql/inline_param_encoder.rb', line 42

def encode_array(sql, array)
  i = -1
  sql.gsub("?") do
    i += 1
    quote_val(array[i])
  end
end

#encode_hash(sql, hash) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/mini_sql/inline_param_encoder.rb', line 21

def encode_hash(sql, hash)
  sql = sql.dup

  # longest key first for gsub to work
  # in an expected way
  hash.sort do |(k, _), (k1, _)|
    k1.to_s.length <=> k.to_s.length
  end.each do |k, v|
    sql.gsub!(":#{k}") do
      # ignore ::int and stuff like that
      # $` is previous to match
      if $` && $`[-1] != ":"
        quote_val(v)
      else
        ":#{k}"
      end
    end
  end
  sql
end

#quote_val(value) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/mini_sql/inline_param_encoder.rb', line 54

def quote_val(value)
  case value
  when String     then "'#{conn.escape_string(value.to_s)}'"
  when Numeric    then value.to_s
  when BigDecimal then value.to_s("F")
  when Time       then "'#{quoted_time(value)}'"
  when Date       then "'#{value.to_s}'"
  when Symbol     then "'#{conn.escape_string(value.to_s)}'"
  when true       then "true"
  when false      then "false"
  when nil        then "NULL"
  when []         then "NULL"
  when Array      then array_encoder ? "'#{array_encoder.encode(value)}'" : value.map { |v| quote_val(v) }.join(', ')
  else raise TypeError, "can't quote #{value.class.name}"
  end
end

#quoted_time(value) ⇒ Object



50
51
52
# File 'lib/mini_sql/inline_param_encoder.rb', line 50

def quoted_time(value)
  value.utc.iso8601
end