class Jennifer::QueryBuilder::Query

Included Modules

Direct Known Subclasses

Defined in:

jennifer/query_builder/query.cr

Constructors

Class Method Summary

Instance Method Summary

Instance methods inherited from module Jennifer::QueryBuilder::Executables

db_results : Array(Hash(String, DBAny)) db_results, decrement(fields : Hash(Symbol, _))
decrement(**fields)
decrement
, delete delete, each(&) each, each_result_set(&) each_result_set, exists? : Bool exists?, explain : String explain, find_each(primary_key : String, batch_size : Int32 = 1000, start = nil, direction : String | Symbol = "asc", &)
find_each(primary_key : Criteria, batch_size : Int32 = 1000, start = nil, direction : String | Symbol = "asc", &)
find_each(primary_key : Nil, batch_size : Int32 = 1000, start : Int32 = 0, direction : String | Symbol = "asc", &)
find_each(batch_size : Int32 = 1000, start : Int32 = 0, direction : String | Symbol = "asc", &)
find_each
, find_in_batches(primary_key : String, batch_size : Int32 = 1000, start : Int32? = nil, direction : String | Symbol = "asc", &)
find_in_batches(batch_size : Int32 = 1000, start : Int32 = 0, &)
find_in_batches(primary_key : Criteria, batch_size : Int32 = 1000, start = nil, direction : String | Symbol = "asc", &)
find_in_batches(primary_key : Nil, batch_size : Int32 = 1000, start : Int32 = 0, &)
find_in_batches
, find_records_by_sql(query : String, args : Array(DBAny) = [] of DBAny) find_records_by_sql, first first, first! first!, ids ids, increment(fields : Hash(Symbol, _))
increment(**fields)
increment
, insert(fields : Array(String), values : Array(Array(DBAny)))
insert(options : Hash(String | Symbol, DBAny) | NamedTuple)
insert
, last last, last! last!, pluck(fields : Array) : Array(Array(DBAny))
pluck(field : String | Symbol) : Array(DBAny)
pluck(*fields : String | Symbol) : Array(Array(DBAny))
pluck(**types : **T) forall T
pluck
, results : Array(Record) results, to_a to_a, update(&)
update(options : Hash)
update(**options)
update
, upsert(fields : Array(String), values : Array(Array(DBAny)), unique_fields : Array = [] of String)
upsert(fields : Array(String), values : Array(Array(DBAny)), unique_fields : Array, &)
upsert

Instance methods inherited from module Jennifer::QueryBuilder::Joining

join(source : Class, table_alias : String? = nil, type = :inner, relation : String? = nil, &)
join(source : String, table_alias : String? = nil, type = :inner, relation : String? = nil, &)
join(source : Query, table_alias : String, type = :inner, &)
join
, lateral_join(source : Query, table_alias : String, type = :inner, &) lateral_join, left_join(source : Class, table_alias : String? = nil, &)
left_join(source : String, table_alias : String? = nil, &)
left_join
, right_join(source : Class, table_alias : String? = nil, &)
right_join(source : String, table_alias : String? = nil, &)
right_join

Instance methods inherited from module Jennifer::QueryBuilder::Ordering

order(opts : Hash(String, String | Symbol))
order(opts : Hash(Symbol, String | Symbol))
order(opt : OrderExpression)
order(opts : Array(OrderExpression))
order(opts : Hash(String | Symbol, String | Symbol))
order(**opts)
order(&)
order
, ordered? ordered?, reorder(opts : Hash(String, String | Symbol))
reorder(opts : Hash(Symbol, String | Symbol))
reorder(opt : OrderExpression)
reorder(opts : Array(OrderExpression))
reorder(opts : Hash(String | Symbol, String | Symbol))
reorder(**opts)
reorder(&)
reorder

Instance methods inherited from module Jennifer::QueryBuilder::Aggregations

avg(field, klass : T.class) : T forall T avg, count : Int32 count, group_avg(field, klass : T.class) : Array(T) forall T group_avg, group_count(field) group_count, group_max(field, klass : T.class) : Array(T) forall T group_max, group_min(field, klass : T.class) : Array(T) forall T group_min, group_sum(field, klass : T.class) : Array(T) forall T group_sum, max(field, klass : T.class) : T forall T max, min(field, klass : T.class) : T forall T min, sum(field, klass : T.class) : T forall T sum

Instance methods inherited from module Jennifer::QueryBuilder::Statement

as_sql(sql_generator) as_sql, filterable? filterable?, sql_args : Array(DBAny) sql_args

Constructor Detail

def self.new(table, adapter = Adapter.default_adapter) #

[View source]
def self.new #

[View source]

Class Method Detail

def self.[](*args) #

Alias for .build.

Jennifer::Query["contacts"].where { _name == "Jack London" }

[View source]
def self.build(*args) #

Builds query with related expression builder.

Should be used instead of .new.

Jennifer::Query.build("contacts").where { _name == "Jack London" }

[View source]
def self.null(table = "") #

Alias for new(table).none.


[View source]

Instance Method Detail

def _select_fields : Array(Criteria) #

Returns array of Criteria for SELECT query statement.


[View source]
def adapter : Adapter::Base #

[View source]
def as_sql(generator) #
Description copied from module Jennifer::QueryBuilder::Statement

Converts node to SQL using sql_generator SQLGenerator.


[View source]
def as_sql #

[View source]
def clone #

Creates a clone of the query.

query = Jennifer::Query["contacts"].where { _city == "Kyiv" }
query.clone.where { _name.like("John%") }
query.clone.where { _name.like("Peter%") }

[View source]
def distinct #

Specifies whether the records should be unique or not.


[View source]
def do_nothing? : Bool #

Returns whether query should be executed.


[View source]
def empty? #

[View source]
def eql?(other : Query) #

Compare current object with given comparing generated SQL query and parameters.

Is used for testing.


[View source]
def eql?(other : Statement | LogicOperator) #

[View source]
def except(parts : Array(String)) #

Creates a clone of the query without specified parts.

Allowed values for parts:

  • select
  • raw_select
  • from
  • where
  • having
  • limit
  • offset
  • lock
  • distinct
  • order
  • join
  • union
  • group
  • none
  • cte

Any eager loading isn't copied to a new query.

Jennifer::Query["contacts"].where { _city == "Paris" }.except(["where"])

[View source]
def exec(&) #

Allows executing a block in the query context.

Jennifer::Query["contacts"].exec { where { _name == "Jack London" } }

[View source]
def expression_builder : Jennifer::QueryBuilder::ExpressionBuilder #

Returns current query expression builder.


[View source]
def filterable? #
Description copied from module Jennifer::QueryBuilder::Statement

Returns whether node has an argument to be added to SQL statement arguments.


[View source]
def from(from : String | Query) #

Specifies table from which the records will be fetched.

Can accept other query.

# FROM contacts
Jennifer::Query[""].from("contacts") # FROM contacts
# FROM (SELECT users.* WHERE users.active)
Jennifer::Query["contacts"].from(Jennifer::Query["users"].where { _active })

[View source]
def group(column : String) #

Groups by given column realizes it as is.

Jennifer::Query["contacts"].group("first_name || last_name")

[View source]
def group(column : Symbol) #

Groups by given column realizing it as a current table's field.

Jennifer::Query["contacts"].group(:name)

[View source]
def group(column : Criteria) #

[View source]
def group(*columns : String) #

Groups by given columns realizes them as are


[View source]
def group(*columns : Symbol) #

Groups by given columns realizes them as current table's ones


[View source]
def group(&) #

[View source]
def having(&) #

Allows to specify a HAVING clause.

Note that you can’t use HAVING without also specifying a GROUP clause.


[View source]
def limit(count : Int32) #

Specifies a limit for the number of records to retrieve.

Jennifer::Query["contacts"].limit(10)

[View source]
def lock(type : String | Bool = true) #

Specifies locking settings.

true is default value. Also string declaration can be provide.

Also SKIP LOCKED construction can be used with manual mode:

Queue.all.where do
  _id == g(Queue.all.limit(1).lock("FOR UPDATE SKIP LOCKED"))
end.delete

[View source]
def merge(other : self) #

Merges other query into current one.

This method merges the following query components:

  • JOINs
  • GROUP BYs
  • ORDERs
  • CTEs
  • HAVINGs
  • WHEREs
  • do nothing
# returns contacts that have main address
addresses_condition = Jennifer::Query["addresses"].where { _main }
Jennifer::Query["contacts"].join("addresses") { _contact_id == _contacts__id }
  .merge(addresses_condition)

This method provides mechanism to reuse some predefined queries for involved tables. It makes real sense when is used in the scope of ModelQuery and models.

Contacts.all.relation(:addresses).merge(Address.all.main)

[View source]
def none #

Returns a chainable query with zero records.

Jennifer::Query["contacts"].where { _name == "Jack London" }.none

[View source]
def offset(count : Int32) #

Specifies the number of rows to skip before returning rows.

Jennifer::Query["contacts"].offset(10)

[View source]
def select(raw_sql : String) #

Specifies raw SELECT clause value.

Jennifer::Query["contacts"].select("name as first_name, age as count").results

[View source]
def select(field : Criteria) #

Specifies criterion to be used in SELECT clause.

Jennifer::Query["contacts"].exec { select(expression._name.alias("first_name")) }.results

[View source]
def select(fields : Array(Criteria)) #

[View source]
def select(*fields : Symbol) #

Specifies column names to be used in SELECT clause.


[View source]
def select(&) #

[View source]
def set_tree(other : LogicOperator | Condition) #

Joins given other condition statement to the main condition tree.


[View source]
def set_tree(other : Query) #

Joins given other condition statement to the main condition tree.


[View source]
def set_tree(other : SQLNode) #

Joins given other condition statement to the main condition tree.


[View source]
def set_tree(other : Nil) #

Joins given other condition statement to the main condition tree.


[View source]
def sql_args : Array(DBAny) #
Description copied from module Jennifer::QueryBuilder::Statement

Returns array of SQL query arguments.


[View source]
def table : String #

Table name to be specified in FROM clause.


[View source]
def to_json(only : Array(String)? = nil, except : Array(String)? = nil, &) #

Returns a JSON string representing collection of retrieved entities.

For more details see Resource#to_json

Jennifer::Query["user"].to_json
# => [{"id": 1, "name": "John Smith"}]

[View source]
def to_json(json : JSON::Builder) #

[View source]
def to_json(json : JSON::Builder, only : Array(String)? = nil, except : Array(String)? = nil, &) #

[View source]
def to_json(only : Array(String)? = nil, except : Array(String)? = nil) #

[View source]
def to_s(io : IO) #
Description copied from class Reference

Appends a short String representation of this object which includes its class name and its object address.

class Person
  def initialize(@name : String, @age : Int32)
  end
end

Person.new("John", 32).to_s # => #<Person:0x10a199f20>

[View source]
def tree : Condition | LogicOperator | Nil #

Query filter to be rendered in WHERE clause.


[View source]
def tree=(tree : Condition | LogicOperator | Nil) #

Query filter to be rendered in WHERE clause.


[View source]
def union(query, all : Bool = false) #

Adds query to UNION.

To use UNION ALL pass true as a second argument.

Jennifer::Query["contacts"].union(Jennifer::Query["users"])
Jennifer::Query["contacts"].union(Jennifer::Query["users"], true)

[View source]
def where(&) #

Mutates query applying all modification returned from the block.

Yields the expression builder and block is also executed with expression builder context.

User.where { _email == "example@test.com" }

[View source]
def where(conditions : Hash(Symbol, _)) #

Mutates query by given conditions.

All key-value pairs are treated as a sequence of equal conditions

Jennifer::Query["contacts"].where({:name => "test", :age => 23})
# SELECT contacts.* FROM contacts WHERE (contacts.name = 'test' AND contacts.age = 23)

[View source]
def with(name : String | Symbol, query : Query, recursive : Bool = false) #

Adds CTE (common table expression) to the query.

You can define multiple CTE for one query.

# WITH RECURSIVE test AS (SELECT users.* FROM users )
Jennifer::Query["contacts"].with("test", Jennifer::Query["users"])

# WITH RECURSIVE test AS (SELECT users.* FROM users )
Jennifer::Query["contacts"].with("test", Jennifer::Query["users"], true)

[View source]