Class: DB::Query

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

Overview

A mutable query builder.

Instance Method Summary collapse

Constructor Details

#initialize(context, buffer = String.new) ⇒ Query

Create a new query builder attached to the specified context.



31
32
33
34
35
# File 'lib/db/query.rb', line 31

def initialize(context, buffer = String.new)
  @context = context
  @connection = context.connection
  @buffer = +buffer
end

Instance Method Details

#call(&block) ⇒ Object

Send the query to the remote server to be executed. See Context::Session#call for more details.



101
102
103
104
# File 'lib/db/query.rb', line 101

def call(&block)
  # Console.debug(self, "Executing query...", buffer: @buffer)
  @context.call(@buffer, &block)
end

#clause(value) ⇒ Object

Append a raw textual clause to the query buffer.



40
41
42
43
44
45
46
# File 'lib/db/query.rb', line 40

def clause(value)
  @buffer << ' ' unless @buffer.end_with?(' ') || @buffer.empty?
  
  @buffer << value
  
  return self
end

#identifier(value) ⇒ Object

Append an identifier value to the query buffer. Escapes the field according to the requirements of the underlying connection.



64
65
66
67
68
69
70
# File 'lib/db/query.rb', line 64

def identifier(value)
  @buffer << ' ' unless @buffer.end_with?(' ')
  
  @connection.append_identifier(value, @buffer)
  
  return self
end

#inspectObject



110
111
112
# File 'lib/db/query.rb', line 110

def inspect
  "\#<#{self.class} #{@buffer.inspect}>"
end

#interpolate(fragment, **parameters) ⇒ Object

Interpolate a query fragment with the specified parameters. The parameters are escaped before being appended.



78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/db/query.rb', line 78

def interpolate(fragment, **parameters)
  parameters.transform_values! do |value|
    case value
    when Symbol, Identifier
      @connection.append_identifier(value)
    else
      @connection.append_literal(value)
    end
  end
  
  @buffer << sprintf(fragment, parameters)
  
  return self
end

#key_column(*arguments, **options) ⇒ Object



93
94
95
96
97
# File 'lib/db/query.rb', line 93

def key_column(*arguments, **options)
  @buffer << @connection.key_column(*arguments, **options)
  
  return self
end

#literal(value) ⇒ Object

Append a literal value to the query buffer. Escapes the field according to the requirements of the underlying connection.



52
53
54
55
56
57
58
# File 'lib/db/query.rb', line 52

def literal(value)
  @buffer << ' ' unless @buffer.end_with?(' ')
  
  @connection.append_literal(value, @buffer)
  
  return self
end

#to_sObject



106
107
108
# File 'lib/db/query.rb', line 106

def to_s
  @buffer
end