class Query
A mutable query builder.
Definitions
def initialize(context, buffer = String.new)
Create a new query builder attached to the specified context.
Signature
-
parameter
context
Context::Generic
the context which is used for escaping arguments.
Implementation
def initialize(context, buffer = String.new)
@context = context
@connection = context.connection
@buffer = +buffer
end
def clause(value)
Append a raw textual clause to the query buffer.
Signature
-
parameter
value
String
A raw SQL string, e.g.
WHERE x > 10
.-
returns
Query
The mutable query itself.
Implementation
def clause(value)
@buffer << " " unless @buffer.end_with?(" ") || @buffer.empty?
@buffer << value
return self
end
def literal(value)
Append a literal value to the query buffer. Escapes the field according to the requirements of the underlying connection.
Signature
-
parameter
value
Object
Any kind of object, passed to the underlying database connection for conversion to a string representation.
-
returns
Query
The mutable query itself.
Implementation
def literal(value)
@buffer << " " unless @buffer.end_with?(" ")
@connection.append_literal(value, @buffer)
return self
end
def identifier(value)
Append an identifier value to the query buffer. Escapes the field according to the requirements of the underlying connection.
Signature
-
parameter
value
String | Symbol | DB::Identifier
Passed to the underlying database connection for conversion to a string representation.
-
returns
Query
The mutable query itself.
Implementation
def identifier(value)
@buffer << " " unless @buffer.end_with?(" ")
@connection.append_identifier(value, @buffer)
return self
end
def interpolate(fragment, **parameters)
Interpolate a query fragment with the specified parameters. The parameters are escaped before being appended.
Signature
-
parameter
fragment
String
A fragment of SQL including placeholders, e.g.
WHERE x > %{column}
.-
parameter
parameters
Hash
The substitution parameters.
-
returns
Query
The mutable query itself.
Implementation
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
def call(&block)
Send the query to the remote server to be executed. See DB::Context::Session#call
for more details.
Signature
-
returns
Enumerable
The resulting records.
Implementation
def call(&block)
# Console.debug(self, "Executing query...", buffer: @buffer)
@context.call(@buffer, &block)
end