class Clear::Model::CollectionBase(T)
- Clear::Model::CollectionBase(T)
- Reference
- Object
Overview
CollectionBase(T)
is the base class for collection of model.
Collection of model are a SQL SELECT
query mapping & building system. They are Enumerable and are
Clear::SQL::SelectBuilder
behavior; therefore, they can be used array-like and are working with low-level SQL
Building.
The CollectionBase(T)
is extended by each model. For example, generating the model MyModel
will generate the
class MyModel::Collection
which inherits from CollectionBase(MyModel)
Collection are instantiated using Model.query
method.
Included Modules
- Clear::SQL::SelectBuilder
- Enumerable(T)
Direct Known Subclasses
Defined in:
clear/model/collection.crClass Method Summary
-
.item_class
Return the model class for this collection
Instance Method Summary
-
#<<(item : T)
Add an item to the current collection.
-
#[](off, fetch_columns = false) : T
Basically a fancy way to write
OFFSET x LIMIT 1
-
#[](range : Range(Number, Number), fetch_columns = false) : Array(T)
Get a range of models
-
#[]?(off, fetch_columns = false) : T?
Basically a fancy way to write
OFFSET x LIMIT 1
-
#add(item : T)
Alias for
Collection#<<
-
#any?
Check whether the query return any row.
-
#build(x : NamedTuple) : T
Build a new collection; if the collection comes from a has_many relation (e.g.
-
#build : T
Build a new collection; if the collection comes from a has_many relation (e.g.
-
#count(type : X.class = Int64) forall X
Use SQL
COUNT
over your query, and return this number as a Int64 -
#delete_all : self
Delete all the rows which would have been returned by this collection.
-
#dup
Duplicate the current request.
-
#each(fetch_columns = false, &block : T -> )
Build the SQL, send the query then iterate through each models gathered by the request.
-
#each_with_cursor(batch = 1000, fetch_columns = false, &block : T -> )
Build the SQL, send the query then iterate through each models gathered by the request.
-
#empty?
Inverse of
#any?
, return true if the request return no rows. -
#find(x) : T?
Returns a model using primary key equality Returns
nil
if not found. -
#find(fetch_columns = false, &) : T?
A convenient way to write
where{ condition }.first
-
#find(tuple : NamedTuple, fetch_columns = false) : T?
A convenient way to write
where({any_column: "any_value"}).first
-
#find!(x) : T
Returns a model using primary key equality.
-
#find!(fetch_columns = false, &) : T
A convenient way to write
where({any_column: "any_value"}).first!
-
#find!(tuple : NamedTuple, fetch_columns = false) : T
A convenient way to write
where{ condition }.first!
- #find_or_build(**tuple) : T
-
#find_or_build(**tuple, &block : T -> Nil) : T
Try to fetch a row.
-
#find_or_create(**tuple) : T
Try to fetch a row.
-
#find_or_create(**tuple, &block : T -> Nil) : T
Try to fetch a row.
-
#first(fetch_columns = false) : T?
Get the first row from the collection query.
-
#first!(fetch_columns = false) : T
Get the first row from the collection query.
-
#item_class
Return the model class for this collection
-
#last(fetch_columns = false) : T?
Get the last row from the collection query.
-
#last!(fetch_columns = false) : T
Get the last row from the collection query.
-
#map(fetch_columns = false, &block : T -> X) : Array(X) forall X
Build the SQL, send the query then build and array by applying the block transformation over it.
- #tags
-
#to_a(fetch_columns = false) : Array(T)
Create an array from the query.
-
#unlink(item : T)
Unlink the model currently referenced through a relation
has_many through
Instance methods inherited from module Clear::SQL::SelectBuilder
before_query(&block : -> Nil)
before_query,
columns : Array(SQL::Column)
columns,
default_wildcard_table
default_wildcard_table,
dup : self
dup,
havings : Array(Clear::Expression::Node)
havings,
is_distinct?
is_distinct?,
joins : Array(SQL::Join)
joins,
limit : Int64?
limit,
lock : String?
lock,
offset : Int64?
offset,
order_bys : Array(Clear::SQL::Query::OrderBy::Record)
order_bys,
to_delete
to_delete,
to_sql : String
to_sql,
to_update
to_update,
total_entries : Int64?
total_entries,
total_entries=(total_entries : Int64?)
total_entries=,
wheres : Array(Clear::Expression::Node)
wheres
Constructor methods inherited from module Clear::SQL::SelectBuilder
new(distinct_value = nil, cte = {} of String => Clear::SQL::Query::CTE::Record, columns = [] of SQL::Column, forced_columns = [] of SQL::Column, froms = [] of SQL::From, joins = [] of SQL::Join, wheres = [] of Clear::Expression::Node, havings = [] of Clear::Expression::Node, windows = [] of ::Tuple(String, String), group_bys = [] of Symbolic, order_bys = [] of Clear::SQL::Query::OrderBy::Record, limit = nil, offset = nil, lock = nil, before_query_triggers = [] of (-> Nil))
new
Instance methods inherited from module Clear::SQL::Query::WithPagination
current_page
current_page,
first_page?
first_page?,
last_page?
last_page?,
next_page
next_page,
out_of_bounds?
out_of_bounds?,
paginate(page : Int32 = DEFAULT_PAGE, per_page : Int32 = DEFAULT_LIMIT)
paginate,
per_page
per_page,
previous_page
previous_page,
total_pages
total_pages
Instance methods inherited from module Clear::SQL::Query::Change
change! : self
change!
Instance methods inherited from module Clear::SQL::Query::Connection
connection_name : String
connection_name,
use_connection(connection_name : String)
use_connection
Instance methods inherited from module Clear::SQL::Query::Pluck
pluck(fields : Tuple(*T)) forall Tpluck(*fields)
pluck(**fields : **T) forall T pluck, pluck_col(field : Clear::SQL::Symbolic, type : T.class) forall T
pluck_col(field : Clear::SQL::Symbolic) pluck_col
Instance methods inherited from module Clear::SQL::Query::Fetch
fetch(fetch_all = false, &block : Hash(String, Clear::SQL::Any) -> Nil)
fetch,
fetch_first
fetch_first,
fetch_first!
fetch_first!,
fetch_with_cursor(count = 1000, &block : Hash(String, Clear::SQL::Any) -> Nil)
fetch_with_cursor,
first
first,
first!
first!,
scalar(type : T.class) forall T
scalar,
to_a : Array(Hash(String, Clear::SQL::Any))
to_a
Instance methods inherited from module Clear::SQL::Query::Execute
execute(connection_name : String? = nil)
execute
Instance methods inherited from module Clear::SQL::Query::Lock
clear_lock
clear_lock,
with_lock(str : String = "FOR UPDATE")
with_lock
Instance methods inherited from module Clear::SQL::Query::Window
clear_windows
clear_windows,
print_windows
print_windows,
window(name, value)window(windows : NamedTuple) window, windows : Array(WindowDeclaration) windows
Instance methods inherited from module Clear::SQL::Query::CTE
cte : Hash(String, Clear::SQL::Query::CTE::Record)
cte,
with_cte(name, request : CTEAuthorized, recursive = false)with_cte(tuple : NamedTuple) with_cte, with_recursive_cte(tuple : NamedTuple) with_recursive_cte
Instance methods inherited from module Clear::SQL::Query::Aggregate
agg(field, x : X.class) forall X
agg,
avg(field, x : X.class) forall X
avg,
count(type : X.class = Int64) forall X
count,
max(field, x : X.class) forall X
max,
min(field, x : X.class) forall X
min,
sum(field, x : X.class) forall Xsum(field) : Float64 sum
Instance methods inherited from module Clear::SQL::Query::OffsetLimit
clear_limit
clear_limit,
clear_offset
clear_offset,
limit(x : Int?)
limit,
offset(x : Int?)
offset
Instance methods inherited from module Clear::SQL::Query::GroupBy
clear_group_bys
clear_group_bys,
group_by(*column_list)
group_by,
group_bys : Array(Symbolic)
group_bys
Instance methods inherited from module Clear::SQL::Query::OrderBy
clear_order_bys
clear_order_bys,
order_by(__tuple : NamedTuple)order_by(expression : Symbol, direction : Symbol = :asc, nulls : Symbol? = nil)
order_by(expression : String, direction : Symbol = :asc, nulls : Symbol? = nil)
order_by(**tuple) order_by, reverse_order_by reverse_order_by
Instance methods inherited from module Clear::SQL::Query::Having
clear_havings
clear_havings,
having(node : Clear::Expression::Node)having(&)
having(__conditions : NamedTuple | Hash(String, Clear::SQL::Any))
having(__template : String, *__args)
having(__template : String, **__tuple)
having(**tuple) having, or_having(node : Clear::Expression::Node)
or_having(__template : String, *__args)
or_having(__template : String, **__named_tuple)
or_having(&) or_having
Instance methods inherited from module Clear::SQL::Query::Where
clear_wheres
clear_wheres,
or_where(node : Clear::Expression::Node)or_where(__template : String, *__args)
or_where(__template : String, **__named_tuple)
or_where(&) or_where, where(node : Clear::Expression::Node)
where(&)
where(__conditions : NamedTuple | Hash(String, Clear::SQL::Any))
where(__template : String, *__args)
where(__template : String, **__tuple)
where(**tuple) where
Instance methods inherited from module Clear::SQL::Query::Join
cross_join(name : Selectable, lateral = false)
cross_join,
full_outer_join(name : Selectable, lateral = false, &)full_outer_join(name : Selectable, condition : String = "true", lateral = false) full_outer_join, inner_join(name : Selectable, lateral = false, &)
inner_join(name : Selectable, condition : String = "true", lateral = false) inner_join, join(name : Selectable, type = :inner, lateral = false, &)
join(name : Selectable, type = :inner, condition : String = "true", lateral = false)
join(name : Selectable, type = :inner, lateral = false) join, left_join(name : Selectable, lateral = false, &)
left_join(name : Selectable, condition : String = "true", lateral = false) left_join, right_join(name : Selectable, lateral = false, &)
right_join(name : Selectable, condition : String = "true", lateral = false) right_join
Instance methods inherited from module Clear::SQL::Query::From
clear_from
clear_from,
from(*__args)from(**__named_tuple) from, froms : Array(SQL::From) froms
Instance methods inherited from module Clear::SQL::Query::Select
clear_distinct
clear_distinct,
clear_force_select
clear_force_select,
clear_select
clear_select,
distinct(on : String? = "")
distinct,
distinct_value : String?
distinct_value,
force_select(c : Column)force_select(*__args)
force_select(**__tuple) force_select, select(*__args)
select(**__tuple) select, set_default_table_wildcard(table : String? = nil) set_default_table_wildcard
Class Method Detail
Instance Method Detail
Add an item to the current collection.
If the current collection is not originated from a has_many
or has_many through:
relation, calling #<<
over
the collection will raise a Clear::SQL::OperationNotPermittedError
Returns self
and therefore can be chained
Build a new collection; if the collection comes from a has_many relation
(e.g. my_model.associations.build
), the foreign column which store
the primary key of my_model
will be setup by default, preventing you
to forget it.
You can pass extra parameters using a named tuple:
`my_model.associations.build({a_column: "value"}) `
Build a new collection; if the collection comes from a has_many relation
(e.g. my_model.associations.build
), the foreign column which store
the primary key of my_model
will be setup by default, preventing you
to forget it.
Use SQL COUNT
over your query, and return this number as a Int64
Delete all the rows which would have been returned by this collection.
Is equivalent to collection.to_delete.execute
Duplicate the current request. Select query are mutable objects, and many of the methods will change the state of the collection:
collection = User.query # SELECT * FROM users;
collection.select("id") # SELECT id FROM users;
collection.select("id") # SELECT id, id FROM users;
Therefore, you may want to use #dup
to duplicate the current state of the collection.
Build the SQL, send the query then iterate through each models gathered by the request.
Build the SQL, send the query then iterate through each models gathered by the request. Use a postgres cursor to avoid memory bloating. Useful to fetch millions of rows at once.
A convenient way to write where({any_column: "any_value"}).first
Returns a model using primary key equality. Raises error if the model is not found.
A convenient way to write where({any_column: "any_value"}).first!
A convenient way to write where{ condition }.first!
Try to fetch a row. If not found, build a new object and setup the fields like setup in the condition tuple.
Try to fetch a row. If not found, build a new object and setup the fields like setup in the condition tuple. Just after building, save the object.
Try to fetch a row. If not found, build a new object and setup the fields like setup in the condition tuple. Just after building, save the object.
Get the first row from the collection query.
if not found, return nil
Get the first row from the collection query. if not found, throw an error
Get the last row from the collection query.
if not found, return nil
Get the last row from the collection query. if not found, throw an error
Build the SQL, send the query then build and array by applying the block transformation over it.
Unlink the model currently referenced through a relation has_many through
If the current colleciton doesn't come from a has_many through
relation,
this method will throw Clear::SQL::OperationNotPermittedError
Returns true
if unlinking is successful (e.g. one or more rows have been updated), or false
otherwise