class
CQL::Query
- CQL::Query
- Reference
- Object
Overview
The Query
class is responsible for building SQL queries in a structured manner.
It holds various components like selected columns, tables, conditions, and more.
It provides methods to execute the query and return results.
Example Creating a new query
schema = CQL::Schema.new
CQL::Query.new(schema)
query.select(:name, :age).from(:users).where(name: "John").all(User)
=> [{"name" => "John", "age" => 30}]
Example Executing a query and iterating over results
schema = CQL::Schema.new
query = CQL::Query.new(schema)
query.select(:name, :age).from(:users).where(name: "John").each(User) do |user|
puts user.name
end
=> John
Defined in:
query.crConstructors
-
.new(schema : Schema)
Initializes the
Query
object with the provided schema.
Instance Method Summary
- #aggr_columns : Array(Expression::Aggregate)
-
#all(as as_kind)
Executes the query and returns all records.
-
#all!(as as_kind)
- @param as [Type] The type to cast the results to - @return [Array(Type)] The results of the query
-
#avg(column : Symbol)
Adds an AVG aggregate function to the query.
-
#build
Builds the final query expression.
- #columns : Array(CQL::BaseColumn)
-
#count(column : Symbol = :*)
Adds a COUNT aggregate function to the query.
-
#distinct
Sets the distinct flag to true.
- #distinct=(distinct : Bool)
- #distinct? : Bool
-
#each(as as_kind, &)
Iterates over each result and yields it to the provided block.
-
#first(as as_kind)
Executes the query and returns the first record.
-
#first!(as as_kind)
- @param as [Type] The type to cast the result to - @return [Type] The first result of the query
-
#from(*tbls_or_aliases : Symbol | Hash(Symbol, Symbol))
Specifies the tables to select from.
-
#from(**tables_with_aliases)
Accept keyword arguments for table/alias pairs
-
#get(as as_kind)
Executes the query and returns a scalar value.
-
#group(*columns : Symbol | String)
Specifies the columns to group by.
- #group_by : Array(CQL::BaseColumn)
- #having : Expression::Having | Nil
-
#having(&)
Adds a HAVING condition to the grouped results.
- #having=(having : Expression::Having | Nil)
-
#inner(table_or_alias : Symbol | Hash(Symbol, Symbol), on : Hash(CQL::BaseColumn, CQL::BaseColumn | DB::Any))
Adds an INNER JOIN to the query.
-
#inner(table_or_alias : Symbol | Hash(Symbol, Symbol), &)
Adds an INNER JOIN to the query using a block for the condition.
- #joins : Array(Expression::Join)
-
#joins(*tables_to_join : Symbol)
Accept single splat for table names (no explicit alias)
-
#joins(**tables_to_join)
Accept keyword arguments for table/alias pairs
-
#left(table_or_alias : Symbol | Hash(Symbol, Symbol), on : Hash(CQL::BaseColumn, CQL::BaseColumn | DB::Any))
Adds a LEFT JOIN to the query.
-
#left(table_or_alias : Symbol | Hash(Symbol, Symbol), &)
Adds a LEFT JOIN to the query using a block.
-
#left_joins(*tables_to_join : Symbol)
Accept single splat for table names (no explicit alias)
-
#left_joins(**tables_to_join)
Accept keyword arguments for table/alias pairs
-
#limit(value : Int32)
Sets the limit for the number of records to return.
- #limit : Int32 | Nil
- #limit=(limit : Int32 | Nil)
-
#max(column : Symbol)
Adds a MAX aggregate function to the query.
-
#merge(other_query : Query) : Query
Merges the properties of another Query object into this one.
-
#min(column : Symbol)
Adds a MIN aggregate function to the query.
-
#offset(value : Int32)
Sets the offset for the query.
- #offset : Int32 | Nil
- #offset=(offset : Int32 | Nil)
-
#order(*fields : Symbol | String)
Specifies the columns to order by.
-
#order(**fields)
Specifies the columns to order by with direction.
- #order_by : Hash(CQL::BaseColumn, Expression::OrderDirection)
- #query_tables : Hash(String, QueryTableInfo)
-
#right(table_or_alias : Symbol | Hash(Symbol, Symbol), on : Hash(CQL::BaseColumn, CQL::BaseColumn | DB::Any))
Adds a RIGHT JOIN to the query.
-
#right(table_or_alias : Symbol | Hash(Symbol, Symbol), &)
Adds a RIGHT JOIN to the query using a block.
-
#right_joins(*tables_to_join : Symbol)
Accept single splat for table names (no explicit alias)
-
#right_joins(**tables_to_join)
Accept keyword arguments for table/alias pairs
- #schema : Schema
-
#select(*columns : Symbol | String)
Specifies the columns to select.
-
#select(**fields : Hash(String | Symbol, Array(Symbol) | Symbol))
Specifies the columns to select.
- #select(**fields)
-
#select(*cols : Symbol | String, **fields : Hash(String | Symbol, Array(Symbol) | Symbol))
Allow mixing String/Symbol args and Hash
- #select(*cols, **columns)
-
#sum(column : Symbol)
Adds a SUM aggregate function to the query.
-
#to_sql(gen = @schema.gen)
Converts the query into an SQL string and its corresponding parameters.
-
#where(hash : Hash(String | Symbol, DB::Any))
Accept Hash(Symbol, DB::Any) for backward compatibility
- #where : Expression::Where | Nil
-
#where(&)
Correct implementation for where(&)
- #where(**fields)
- #where=(where : Expression::Where | Nil)
Constructor Detail
Initializes the Query
object with the provided schema.
- @param schema [Schema] The schema object to use for the query
- @return [Query] The query object
Example Creating a new query
schema = CQL::Schema.new
query = CQL::Query.new(schema)
=> #<CQL::Query:0x00007f8b1b0b3b00>
Instance Method Detail
Executes the query and returns all records.
- @param as [Type] The type to cast the results to
- @return [Array(Type)] The results of the query
Example
schema = CQL::Schema.new
query = CQL::Query.new(schema)
query.select(:name, :age).from(:users).all(User)
=> [<User:0x00007f8b1b0b3b00 @name="John", @age=30>, <User:0x00007f8b1b0b3b00 @name="Jane", @age=25>]
- @param as [Type] The type to cast the results to
- @return [Array(Type)] The results of the query
Example
schema = CQL::Schema.new
query = CQL::Query.new(schema)
query.select(:name, :age).from(:users).all!(User)
=> [<User:0x00007f8b1b0b3b00 @name="John", @age=30>, <User:0x00007f8b1b0b3b00 @name="Jane", @age=25>]
Adds an AVG aggregate function to the query.
- @param column [Symbol] The column to average
- @return [Query] The query object
Example
query.avg(:rating)
=> "SELECT AVG(rating) FROM users"
Builds the final query expression.
- @return [Expression::Query] The query expression
Example
query.build
=> #<Expression::Query:0x00007f8b1b0b3b00>
Adds a COUNT aggregate function to the query.
- @param column [Symbol] The column to count
- @return [Query] The query object
Example
query.count(:id)
=> "SELECT COUNT(id) FROM users"
Sets the distinct flag to true.
- @return [Query] The query object
Example
query.from(:users).distinct
=> "SELECT DISTINCT * FROM users"
Iterates over each result and yields it to the provided block. Example:
query.each(User) do |user|
puts user.name
end
=> John
Executes the query and returns the first record.
- @param as [Type] The type to cast the result to
- @return [Type] The first result of the query
Example
schema = CQL::Schema.new
query = CQL::Query.new(schema)
query.select(:name, :age).from(:users).first(User)
=> <User:0x00007f8b1b0b3b00 @name="John", @age=30>
- @param as [Type] The type to cast the result to
- @return [Type] The first result of the query
Example
schema = CQL::Schema.new
query = CQL::Query.new(schema)
query.select(:name, :age).from(:users).first!(User)
=> <User:0x00007f8b1b0b3b00 @name="John", @age=30>
Specifies the tables to select from.
- @param tbls [Symbol*] The tables to select from
- @return [Query] The query object
Example
query.from(:users, :orders)
=> "SELECT * FROM users, orders"
Executes the query and returns a scalar value.
- @param as [Type] The type to cast the result to
- @return [Type] The scalar result of the query
Example:
query.get(Int64)
schema = CQL::Schema.new
query = CQL::Query.new(schema)
query.select(:count).from(:users).get(Int64)
=> 10
Specifies the columns to group by. Handles qualified columns or aliases.
- @param columns [Symbol* | String*] The columns to group by
- @return [Query] The query object
Adds a HAVING condition to the grouped results. The block uses a HavingBuilder which needs alias awareness.
- @yield [HavingBuilder] Block to build the condition.
- @return [Query] The query object
Adds an INNER JOIN to the query.
- @param table [Symbol | Hash(Symbol,Symbol)] Table name or alias mapping (e.g., :orders or {orders: :o})
- @param on [Hash(CQL::BaseColumn, CQL::BaseColumn | DB::Any)] The join condition using BaseColumn objects.
- @return [Query] The query object
Example
query.from(:users).inner(:orders, on: { users.id => orders.user_id })
# OR with alias
query.from(users: :u).inner({orders: :o}, on: { u.id => o.user_id })
=> "SELECT * FROM users AS u INNER JOIN orders AS o ON u.id = o.user_id"
Adds an INNER JOIN to the query using a block for the condition.
- @param table [Symbol | Hash(Symbol,Symbol)] Table name or alias mapping.
- @yield [FilterBuilder] The block to build the ON condition.
- @return [Query] The query object
Example
query.from(:users).inner(:orders) { |join| join.on { |cond| cond.users.id == cond.orders.user_id } }
# OR with alias
query.from(users: :u).inner({orders: :o}) { |join| join.on { |cond| cond.u.id == cond.o.user_id } }
Adds a LEFT JOIN to the query.
(Parameters and examples similar to #inner
but using #left
and LEFT JOIN)
Adds a LEFT JOIN to the query using a block.
(Parameters and examples similar to #inner
block version but using #left
)
Sets the limit for the number of records to return.
- @param value [Int32] The limit value
- @return [Query] The query object
Example
query.from(:users).limit(10)
=> "SELECT * FROM users LIMIT 10"
Adds a MAX aggregate function to the query.
- @param column [Symbol] The column to find the maximum value of
- @return [Query] The query object
Example
query.from(:users).max(:price)
=> "SELECT MAX(price) FROM users"
Merges the properties of another Query object into this one. The current query is modified in place.
- @param other_query [Query] The query object to merge from.
- @return [Query] The current query object, modified.
Behavior:
- Schema: Must be the same for both queries.
- Distinct: Becomes
true
if either query is distinct. - Select Columns (
@columns
): Concatenated and uniqued by object identity. - Aggregate Columns (
@aggr_columns
): Concatenated and uniqued by object identity. - Query Tables (
@query_tables
): Merged. Conflicts on alias pointing to different tables raise an error. - Joins (
@joins
): Concatenated and uniqued by object identity. - Where (
@where
): Conditions are combined usingAND
. - Group By (
@group_by
): Concatenated and uniqued by object identity. - Having (
@having
): Conditions are combined usingAND
. - Order By (
@order_by
): Entries fromother_query
take precedence. - Limit (
@limit
): The minimum of the two limits is taken if both are set; otherwise, the set limit is used. - Offset (
@offset
): Theother_query
's offset takes precedence if set.
ameba/disable Metrics/CyclomaticComplexity
Adds a MIN aggregate function to the query.
- @param column [Symbol] The column to find the minimum value of
- @return [Query] The query object
Example
query.min(:price)
=> "SELECT MIN(price) FROM users"
Sets the offset for the query.
- @param value [Int32] The offset value
- @return [Query] The query object
Example
query.from(:users).limit(10).offset(20)
=> "SELECT * FROM users LIMIT 10 OFFSET 20"
Specifies the columns to order by.
Handles qualified columns like #order("users.name")
or aliases #order("u.name")
.
- @param fields [Symbol* | String*] The columns to order by (Symbol or "alias.column")
- @return [Query] The query object
Specifies the columns to order by with direction. Handles qualified columns or aliases in keys.
- @param fields [Hash(Symbol | String, Symbol)] Column => :asc/:desc
- @return [Query] The query object
Adds a RIGHT JOIN to the query.
(Parameters and examples similar to #inner
but using #right
and RIGHT JOIN)
Adds a RIGHT JOIN to the query using a block.
(Parameters and examples similar to #inner
block version but using #right
)
Specifies the columns to select.
- @param columns [Symbol*] The columns to select
- @return [Query] The query object
Example
query.select(:name, :age)
=> "SELECT name, age FROM users"
Specifies the columns to select.
- @param fields [Hash(Symbol, Array(Symbol) | Symbol)] The columns to select
- @return [Query] The query object
Example
query.from(:users, :address).select(users: [:name, :age], address: [:city, :state])
=> "SELECT users.name, users.age, address.city, address.state FROM users, address"
** Example with aggregates **
query.from(:users).select(count: :id)
=> "SELECT COUNT(id) FROM users"
** Example with aliases **
query.from(:users, :orders).select(users: [:name, :age], orders: [:total_amount, :status])
=> "SELECT users.name, users.age, orders.total_amount, orders.status FROM users, orders"
Allow mixing String/Symbol args and Hash
Adds a SUM aggregate function to the query.
- @param column [Symbol] The column to sum
- @return [Query] The query object
Example
query.sum(:total_amount)
=> "SELECT SUM(total_amount) FROM users"
Converts the query into an SQL string and its corresponding parameters.
- @param gen [Generator] The generator to use for converting the query
- @return [Tuple(String, Array(DB::Any))] The SQL query and its parameters
Example
query.to_sql
=> {"SELECT * FROM users WHERE name = ? AND age = ?", ["John", 30]}
Accept Hash(Symbol, DB::Any) for backward compatibility