Class: Sequel::SQL::EscapedLikeExpression

Inherits:
Expression show all
Includes:
AliasMethods, BooleanMethods, CastMethods, OrderMethods
Defined in:
lib/sequel/extensions/escaped_like.rb

Overview

Represents an pattern match SQL expression, where the pattern can depend upon interpolated values in a database-dependent manner.

Instance Method Summary collapse

Methods included from OrderMethods

#asc, #desc

Methods included from CastMethods

#cast, #cast_numeric, #cast_string

Methods included from BooleanMethods

#~

Methods included from AliasMethods

#as

Methods inherited from Expression

#==, attr_reader, #clone, #eql?, #hash, inherited, #inspect

Constructor Details

#initialize(expr, case_sensitive, placeholder_pattern, placeholder_values) ⇒ EscapedLikeExpression

Initialize the expression. Arguments:

expr

Right hand site of LIKE/ILIKE operator, what you are matching against the pattern

case_insensitive

Whether the match is case sensitive

placeholder_pattern

The pattern to match against, with ? for the placeholders

placeholder_values

The string values for each ? in the placeholder pattern. Should be an array of strings, though it can be a single string if there is only a single placeholder.



37
38
39
40
41
42
43
44
45
46
# File 'lib/sequel/extensions/escaped_like.rb', line 37

def initialize(expr, case_sensitive, placeholder_pattern, placeholder_values)
  @expr = expr
  @method = case_sensitive ? :like : :ilike
  @pattern = placeholder_pattern
  unless placeholder_values.is_a?(Array)
    placeholder_values = [placeholder_values].freeze
  end
  @values = placeholder_values
  freeze
end

Instance Method Details

#to_s_append(ds, sql) ⇒ Object

Interpolate the pattern values into the placeholder pattern to get the final pattern, now that we have access to the dataset. Use the expression and final pattern and add an appropriate LIKE/ILIKE expression to the SQL being built.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/sequel/extensions/escaped_like.rb', line 51

def to_s_append(ds, sql)
  i = -1
  match_len = @values.length - 1
  like_pattern = String.new
  pattern = @pattern
  while true
    previous, q, pattern = pattern.partition('?')
    like_pattern << previous

    unless q.empty?
      if i == match_len
        raise Error, "Mismatched number of placeholders (#{i+1}) and placeholder arguments (#{@values.length}) for escaped like expression: #{@pattern.inspect}"
      end
      like_pattern << ds.escape_like(@values.at(i+=1))
    end

    if pattern.empty?
      unless i == match_len
        raise Error, "Mismatched number of placeholders (#{i+1}) and placeholder arguments (#{@values.length}) for escaped like expression: #{@pattern.inspect}"
      end
      break
    end
  end
  ds.literal_append(sql, Sequel.send(@method, @expr, like_pattern))
end