class DB::Query
A mutable query builder.
Public Class Methods
Create a new query builder attached to the specified context. @parameter context [Context::Generic] the context which is used for escaping arguments.
# File lib/db/query.rb, line 31 def initialize(context, buffer = String.new) @context = context @connection = context.connection @buffer = +buffer end
Public Instance Methods
Send the query to the remote server to be executed. See {Context::Session#call} for more details. @returns [Enumerable] The resulting records.
# File lib/db/query.rb, line 101 def call(&block) # Console.debug(self, "Executing query...", buffer: @buffer) @context.call(@buffer, &block) end
Append a raw textual clause to the query buffer. @parameter value [String] A raw SQL string, e.g. ‘WHERE x > 10`. @returns [Query] The mutable query itself.
# File lib/db/query.rb, line 40 def clause(value) @buffer << " " unless @buffer.end_with?(" ") || @buffer.empty? @buffer << value return self end
Append an identifier value to the query buffer. Escapes the field according to the requirements of the underlying connection. @parameter value [String | Symbol | DB::Identifier
] Passed to the underlying database connection for conversion to a string representation. @returns [Query] The mutable query itself.
# File lib/db/query.rb, line 64 def identifier(value) @buffer << " " unless @buffer.end_with?(" ") @connection.append_identifier(value, @buffer) return self end
# File lib/db/query.rb, line 110 def inspect "\#<#{self.class} #{@buffer.inspect}>" end
Interpolate a query fragment with the specified parameters. The parameters are escaped before being appended.
@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.
# 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
# File lib/db/query.rb, line 93 def key_column(*arguments, **options) @buffer << @connection.key_column(*arguments, **options) return self end
Append a literal value to the query buffer. Escapes the field according to the requirements of the underlying connection. @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.
# File lib/db/query.rb, line 52 def literal(value) @buffer << " " unless @buffer.end_with?(" ") @connection.append_literal(value, @buffer) return self end
# File lib/db/query.rb, line 106 def to_s @buffer end