class

Marten::DB::Query::Set(M)

Inherits Marten::Template::Object / Marten::Template::CanDefineTemplateAttributes / Marten::DB::Query::Set::Any / Enumerable / Reference / Object

The main query set class.

A query set is an object that matches a collection of records in the database. Those objects are matched through the use of optional filters that allow to explicitly query the database based on specific parameters. Query sets also allow to configure how these objects should be returned (for example in which order).

The most important characteristic of a query set is that it is lazily evaluated: unless the code that resulted in the creation of the query set explicitly asks for the underlying objects, no actual query is made to the considered database. Querying the database is always deferred to the last possible moment: that is, when the actual records are requested.

Constructors

new(query : Marten::DB::Query::SQL::Query(M) = SQL::Query(M).new, prefetched_relations : Array(String) = [] of String, custom_query_sets : Hash(String, Marten::DB::Query::Set::Any) = {} of String => Any)
Source

Instance methods

&(other : self)

Combines the current query set with another one using the AND operator.

This method returns a new query set that is the result of combining the current query set with another one using the AND operator. For example:

query_set_1 = Post.all.filter(title: "Test")
query_set_2 = Post.all.filter(is_published: true)

combined_query_set = query_set_1 & query_set_2
Source
[](index : Int)

Returns the record at the given index.

If no record can be found at the given index, then an IndexError exception is raised.

Source
[](range : Range)

Returns the records corresponding to the passed range.

If no records match the passed range, an IndexError exception is raised. If the current query set was already "consumed" (records were retrieved from the database), an array of records will be returned. Otherwise, another sliced query set will be returned.

Source
[]?(index : Int)

Returns the record at the given index.

nil is returned if no record can be found at the given index.

Source
[]?(range : Range)

Returns the records corresponding to the passed range.

nil is returned if no records match the passed range. If the current query set was already "consumed" (records were retrieved from the database), an array of records will be returned. Otherwise, another sliced query set will be returned.

Source
^(other : self)

Combines the current query set with another one using the XOR operator.

This method returns a new query set that is the result of combining the current query set with another one using the XOR operator. For example:

query_set_1 = Post.all.filter(title: "Test")
query_set_2 = Post.all.filter(is_published: true)

combined_query_set = query_set_1 ^ query_set_2
Source
|(other : self)

Combines the current query set with another one using the OR operator.

This method returns a new query set that is the result of combining the current query set with another one using the OR operator. For example:

query_set_1 = Post.all.filter(title: "Test")
query_set_2 = Post.all.filter(is_published: true)

combined_query_set = query_set_1 | query_set_2
Source
all

Returns a cloned version of the current query set matching all records.

Source
annotate

Returns a new query set with the specified annotations.

This method returns a new query set with the specified annotations. The annotations are specified using a block where each annotation has to be wrapped using the annotate method. For example:

query_set = Book.all.annotate { count(:authors) }
other_query_set = Book.all.annotate do
  count(:authors, alias_name: :author_count)
  sum(:pages, alias_name: :total_pages)
end

Each of the specified annotations is then available for further use in the query set (in order to filter or order the records). The annotations are also available in retrieved model records via the #annotations method, which returns a hash containing the annotations as keys and their values as values.

Source
annotate(expression : Expression::Annotate)

Returns a new query set with the specified annotations.

This method returns a new query set with the specified annotations. The annotations are specified as a Marten::DB::Query::Expression::Annotate object.

Source
any?

Returns true if the query set matches at least one record, or false otherwise. Alias for #exists?.

Source
average(field : String | Symbol)

Returns the average of a field for the current query set.

This method calculates the average value of the specified field for the considered query set. For example:

query_set = Product.all
query_set.average(:price) # => 25.0

This will return the average price of all products in the database.

Source
build

Initializes a new model instance.

The new model instance is initialized by using the attributes defined in the kwargs double splat argument.

new_post = Post.all.build(title: "My blog post")
Source
build

Initializes a new model instance.

This method provides the exact same behaviour as #build with the ability to define a block that is executed for the new object. This block can be used to directly initialize the new model instance.

new_post = Post.all.build(title: "My blog post") do |p|
  p.complex_attribute = compute_complex_attribute
end
Source
bulk_create(objects : Array(M), batch_size : Int32 | Nil = nil)

Bulk inserts the passed model instances into the database.

This method allows to insert multiple model instances into the database in a single query. This can be useful when dealing with large amounts of data that need to be inserted into the database. For example:

query_set = Post.all
query_set.bulk_create(
  [
    Post.new(title: "First post"),
    Post.new(title: "Second post"),
    Post.new(title: "Third post"),
  ]
)

An optional batch_size argument can be passed to this method in order to specify the number of records that should be inserted in a single query. By default, all records are inserted in a single query (except for SQLite databases where the limit of variables in a single query is 999). For example:

query_set = Post.all
query_set.bulk_create(
  [
    Post.new(title: "First post"),
    Post.new(title: "Second post"),
    Post.new(title: "Third post"),
  ],
  batch_size: 2
)
Source
count(field : String | Symbol | Nil = nil)

Returns the number of records that are targeted by the current query set.

Source
create

Creates a model instance and saves it to the database if it is valid.

The new model instance is initialized by using the attributes defined in the kwargs double splat argument. Regardless of whether it is valid or not (and thus persisted to the database or not), the initialized model instance is returned by this method:

query_set = Post.all
query_set.create(title: "My blog post")
Source
create

Creates a model instance and saves it to the database if it is valid.

This method provides the exact same behaviour as create with the ability to define a block that is executed for the new object. This block can be used to directly initialize the object before it is persisted to the database:

query_set = Post.all
query_set.create(title: "My blog post") do |post|
  post.complex_attribute = compute_complex_attribute
end
Source
create!

Creates a model instance and saves it to the database if it is valid.

The model instance is initialized using the attributes defined in the kwargs double splat argument. If the model instance is valid, it is persisted to the database ; otherwise a Marten::DB::Errors::InvalidRecord exception is raised.

query_set = Post.all
query_set.create!(title: "My blog post")
Source
create!

Creates a model instance and saves it to the database if it is valid.

This method provides the exact same behaviour as create! with the ability to define a block that is executed for the new object. This block can be used to directly initialize the object before it is persisted to the database:

query_set = Post.all
query_set.create!(title: "My blog post") do |post|
  post.complex_attribute = compute_complex_attribute
end
Source
delete(raw : Bool = false) : Int64

Deletes the records corresponding to the current query set and returns the number of deleted records.

By default, related objects will be deleted by following the deletion strategy defined in each foreign key field if applicable, unless the raw argument is set to true.

When the raw argument is set to true, a raw SQL delete statement will be used to delete all the records matching the currently applied filters. Note that using this option could cause errors if the underlying database enforces referential integrity.

Moreover, it is important to note that using raw: true won't delete parent records if considered query set is targeting model records that make use of multi table inheritance.

Source
distinct

Returns a new query set that will use SELECT DISTINCT in its query.

By doing so it is possible to eliminate any duplicated row in the query set results:

query_set = Post.all.distinct
Source
distinct(*fields : String | Symbol)

Returns a new query set that will use SELECT DISTINCT ON in its query

By doing so it is possible to eliminate any duplicated row based on the specified fields:

query_set = Post.all.distinct(:title)

It should be noted that it is also possible to follow associations of direct related models too by using the double underscores notation(__). For example the following query will select distinct records based on a joined "author" attribute:

query_set = Post.all.distinct(:author__name)
Source
each

Allows to iterate over the records that are targeted by the current query set.

This method can be used to define a block that iterates over the records that are targeted by a query set:

Post.all.each do |post|
  # Do something
end
Source
exclude(query_node : Node)

Returns a query set whose records do not match the given query node object.

Source
exclude

Returns a query set whose records do not match the given set of filters.

This method returns a Marten::DB::Query::Set object. The filters passed to this method method must be specified using the predicate format:

query_set = Post.all
query_set.exclude(title: "Test")
query_set.exclude(title__startswith: "A")

If multiple filters are specified, they will be joined using an AND operator at the SQL level.

Source
exclude

Returns a query set whose records do not match the given set of advanced filters.

This method returns a Marten::DB::Query::Set object and allows to define complex database queries involving AND and OR operators. It yields a block where each filter has to be wrapped using a q(...) expression. These expressions can then be used to build complex queries such as:

query_set = Post.all
query_set.exclude { (q(name: "Foo") | q(name: "Bar")) & q(is_published: True) }
Source
exists?(query_node : Node)

Returns true if the a query set filtered with the given query node object matches at least one record.

query_set = Post.all
query_set.exists?(Marten::DB::Query::Node.new(name__startswith: "Fr"))
Source
exists?

Returns true if the current query set matches at least one record, or false otherwise.

Source
exists?

Returns true if the query set corresponding to the specified filters matches at least one record.

This method returns true if the filters passed to this method match at least one record. These filters must be specified using the predicate format:

query_set = Post.all
query_set.exists?(title: "Test")
query_set.exists?(title__startswith: "A")

If multiple filters are specified, they will be joined using an AND operator at the SQL level.

Source
exists?

Returns true if the query set corresponding to the specified advanced filters matches at least one record.

This method returns a Bool object and allows to define complex database queries involving AND and OR operators. It yields a block where each filter has to be wrapped using a q(...) expression. These expressions can then be used to build complex queries such as:

query_set = Post.all
query_set.exists? { (q(name: "Foo") | q(name: "Bar")) & q(is_published: true) }
Source
filter(raw_predicate : String, params : Array)

Returns a query set whose records match the given raw predicate and named parameters.

This method enables filtering based on raw SQL predicates, offering greater flexibility than standard field predicates. It returns a modified Marten::DB::Query::Set.

For example:

query_set = Post.all
query_set.filter("is_published = ?", [true])
Source
filter(raw_predicate : String, params : Hash | NamedTuple)

Returns a query set whose records match the given raw predicate and named parameters.

This method enables filtering based on raw SQL predicates, offering greater flexibility than standard field predicates. It returns a modified Marten::DB::Query::Set.

For example:

query_set = Post.all
query_set.filter("is_published = :published", {published: true})
Source
filter(raw_predicate : String)

Returns a query set whose records match the given raw predicate and named parameters.

This method enables filtering based on raw SQL predicates, offering greater flexibility than standard field predicates. It returns a modified Marten::DB::Query::Set.

For example:

query_set = Post.all
query_set.filter("is_published = true")
Source
filter(query_node : Node)

Returns a query set whose records match the given query node.

Source
filter(raw_predicate : String, *args)

Returns a query set whose records match the given raw predicate and named parameters.

This method enables filtering based on raw SQL predicates, offering greater flexibility than standard field predicates. It returns a modified Marten::DB::Query::Set.

For example:

query_set = Post.all
query_set.filter("is_published = ?", true)
Source
filter(raw_predicate : String, **kwargs)

Returns a query set whose records match the given raw predicate and named parameters.

This method enables filtering based on raw SQL predicates, offering greater flexibility than standard field predicates. It returns a modified Marten::DB::Query::Set.

For example:

query_set = Post.all
query_set.filter("is_published = :published", published: true)
Source
filter

Returns a query set matching a specific set of filters.

This method returns a Marten::DB::Query::Set object. The filters passed to this method method must be specified using the predicate format:

query_set = Post.all
query_set.filter(title: "Test")
query_set.filter(title__startswith: "A")

If multiple filters are specified, they will be joined using an AND operator at the SQL level.

Source
filter

Returns a query set matching a specific set of advanced filters.

This method returns a Marten::DB::Query::Set object and allows to define complex database queries involving AND and OR operators. It yields a block where each filter has to be wrapped using a q(...) expression. These expressions can then be used to build complex queries such as:

query_set = Post.all
query_set.filter { (q(name: "Foo") | q(name: "Bar")) & q(is_published: true) }
Source
first

Returns the first record that is matched by the query set, or nil if no records are found.

Source
first!

Returns the first record that is matched by the query set, or raises a NilAssertionError error otherwise.

Source
get(raw_predicate : String, params : Array)

Returns the model instance matching the given raw SQL predicate with positional parameters.

This method allows retrieving a record based on a custom SQL predicate using an array of parameters. It returns nil if no record matches the predicate.

For example:

tag = Tag.all.get("name=? AND is_active=?", ["crystal", true])
Source
get(raw_predicate : String, params : Hash | NamedTuple)

Returns the model instance matching the given raw SQL predicate with a named parameters hash.

This method allows retrieving a record based on a custom SQL predicate using a hash of named parameters. It returns nil if no record matches the predicate.

For example:

tag = Tag.all.get("name=:name", {name: "crystal"})
Source
get(raw_predicate : String)

Returns the model instance matching the given raw SQL predicate.

This method allows retrieving a record based on a custom SQL predicate without parameters. It returns nil if no record matches the predicate.

For example:

tag = Tag.all.get("is_active = true")
Source
get(query_node : Node)

Returns the model instance matching a specific query node object, or nil if no record is found.

Source
get(raw_predicate : String, *args)

Returns the model instance matching the given raw SQL predicate with positional arguments.

This method allows retrieving a record based on a custom SQL predicate with positional arguments. It returns nil if no record matches the predicate.

For example:

tag = Tag.all.get("name=?", "crystal")
Source
get(raw_predicate : String, **kwargs)

Returns the model instance matching the given raw SQL predicate with named parameters.

This method allows retrieving a record based on a custom SQL predicate using named parameters. It returns nil if no record matches the predicate.

For example:

tag = Tag.all.get("name=:name AND is_active=:active", name: "crystal", active: true)
Source
get

Returns the model instance matching the given set of filters.

Model fields such as primary keys or fields with a unique constraint should be used here in order to retrieve a specific record:

query_set = Post.all
post_1 = query_set.get(id: 123)
post_2 = query_set.get(id: 456, is_published: false)

If the specified set of filters doesn't match any records, the returned value will be nil.

In order to ensure data consistency, this method will raise a Marten::DB::Errors::MultipleRecordsFound exception if multiple records match the specified set of filters.

Source
get

Returns the model instance matching a specific set of advanced filters.

Model fields such as primary keys or fields with a unique constraint should be used here in order to retrieve a specific record:

query_set = Post.all
post_1 = query_set.get { q(id: 123) }
post_2 = query_set.get { q(id: 456, is_published: false) }

If the specified set of filters doesn't match any records, the returned value will be nil.

In order to ensure data consistency, this method will raise a Marten::DB::Errors::MultipleRecordsFound exception if multiple records match the specified set of filters.

Source
get!(raw_predicate : String, params : Array)

Returns the model instance matching the given raw SQL predicate with positional parameters, raising an error if not found.

This method allows retrieving a record based on a custom SQL predicate using an array of parameters. If no record matches the predicate, a RecordNotFound exception is raised.

For example:

tag = Tag.all.get!("name=? AND is_active=?", ["crystal", true])
Source
get!(raw_predicate : String, params : Hash | NamedTuple)

Returns the model instance matching the given raw SQL predicate with a named parameters hash, raising an error if not found.

This method allows retrieving a record based on a custom SQL predicate using a hash of named parameters. If no record matches the predicate, a RecordNotFound exception is raised.

For example:

tag = Tag.all.get!("name=:name", {name: "crystal"})
Source
get!(raw_predicate : String)

Returns the model instance matching the given raw SQL predicate, raising an error if not found.

This method allows retrieving a record based on a custom SQL predicate without parameters. If no record matches the predicate, a RecordNotFound exception is raised.

For example:

tag = Tag.all.get!("is_active = true")
Source
get!(query_node : Node)

Returns the model instance matching a specific query node object, or raise an error otherwise.

Source
get!(raw_predicate : String, *args)

Returns the model instance matching the given raw SQL predicate with positional arguments, raising an error if not found.

This method allows retrieving a record based on a custom SQL predicate with positional arguments. If no record matches the predicate, a RecordNotFound exception is raised.

For example:

tag = Tag.all.get!("name=?", "crystal")
Source
get!(raw_predicate : String, **kwargs)

Returns the model instance matching the given raw SQL predicate with named parameters, raising an error if not found.

This method allows retrieving a record based on a custom SQL predicate using named parameters. If no record matches the predicate, a RecordNotFound exception is raised.

For example:

tag = Tag.all.get!("name=:name AND is_active=:active", name: "crystal", active: true)
Source
get!

Returns the model instance matching the given set of filters.

Model fields such as primary keys or fields with a unique constraint should be used here in order to retrieve a specific record:

query_set = Post.all
post_1 = query_set.get!(id: 123)
post_2 = query_set.get!(id: 456, is_published: false)

If the specified set of filters doesn't match any records, a Marten::DB::Errors::RecordNotFound exception will be raised.

In order to ensure data consistency, this method will also raise a Marten::DB::Errors::MultipleRecordsFound exception if multiple records match the specified set of filters.

Source
get!

Returns the model instance matching a specific set of advanced filters.

Model fields such as primary keys or fields with a unique constraint should be used here in order to retrieve a specific record:

query_set = Post.all
post_1 = query_set.get! { q(id: 123) }
post_2 = query_set.get! { q(id: 456, is_published: false) }

If the specified set of filters doesn't match any records, a Marten::DB::Errors::RecordNotFound exception will be raised.

In order to ensure data consistency, this method will raise a Marten::DB::Errors::MultipleRecordsFound exception if multiple records match the specified set of filters.

Source
get_or_create

Returns the model record matching the given set of filters or create a new one if no one is found.

Model fields that uniquely identify a record should be used here. For example:

tag = Tag.all.get_or_create(label: "crystal")

When no record is found, the new model instance is initialized by using the attributes defined in the kwargs double splat argument. Regardless of whether it is valid or not (and thus persisted to the database or not), the initialized model instance is returned by this method.

In order to ensure data consistency, this method will raise a Marten::DB::Errors::MultipleRecordsFound exception if multiple records match the specified set of filters.

Source
get_or_create

Returns the model record matching the given set of filters or create a new one if no one is found.

Model fields that uniquely identify a record should be used here. The provided block can be used to initialize the model instance to create (in case no record is found). For example:

tag = Tag.all.get_or_create(label: "crystal") do |new_tag|
  new_tag.active = false
end

When no record is found, the new model instance is initialized by using the attributes defined in the kwargs double splat argument. Regardless of whether it is valid or not (and thus persisted to the database or not), the initialized model instance is returned by this method.

In order to ensure data consistency, this method will raise a Marten::DB::Errors::MultipleRecordsFound exception if multiple records match the specified set of filters.

Source
get_or_create!

Returns the model record matching the given set of filters or create a new one if no one is found.

Model fields that uniquely identify a record should be used here. For example:

tag = Tag.all.get_or_create!(label: "crystal")

When no record is found, the new model instance is initialized by using the attributes defined in the kwargs double splat argument. If the new model instance is valid, it is persisted to the database ; otherwise a Marten::DB::Errors::InvalidRecord exception is raised.

In order to ensure data consistency, this method will raise a Marten::DB::Errors::MultipleRecordsFound exception if multiple records match the specified set of filters.

Source
get_or_create!

Returns the model record matching the given set of filters or create a new one if no one is found.

Model fields that uniquely identify a record should be used here. The provided block can be used to initialize the model instance to create (in case no record is found). For example:

tag = Tag.all.get_or_create!(label: "crystal") do |new_tag|
  new_tag.active = false
end

When no record is found, the new model instance is initialized by using the attributes defined in the kwargs double splat argument. If the new model instance is valid, it is persisted to the database ; otherwise a Marten::DB::Errors::InvalidRecord exception is raised.

In order to ensure data consistency, this method will raise a Marten::DB::Errors::MultipleRecordsFound exception if multiple records match the specified set of filters.

Source
includes?(value : M)

Returns true if a specific model record is included in the query set.

Source
inspect(io)

Appends a string representation of the query set to the passed io.

Source
join(*relations : String | Symbol)

Returns a queryset whose specified relations are "followed" and joined to each result.

When using #join, the specified relationships will be followed and each record returned by the queryset will have the corresponding related objects already selected and populated. Using #join can result in performance improvements since it can help reduce the number of SQL queries, as illustrated by the following example:

query_set = Post.all

p1 = query_set.get(id: 1)
puts p1.author # hits the database to retrieve the related "author"

p2 = query_set.join(:author).get(id: 1)
puts p2.author # doesn't hit the database since the related "author" was already selected

It should be noted that it is also possible to follow foreign keys of direct related models too by using the double underscores notation(__). For example the following query will select the joined "author" and its associated "profile":

query_set = Post.all
query_set.join(:author__profile)
Source
last

Returns the last record that is matched by the query set, or nil if no records are found.

Source
last!

Returns the last record that is matched by the query set, or raises a NilAssertionError error otherwise.

Source
maximum(field : String | Symbol)

Returns the maximum value of a field for the current query set.

Finds the smallest value within the specified field for the records targeted by the query set. For example:

products = Product.where(category: "Electronics")
lowest_price = products.maximum(:price)

This would identify the highest-priced product within the "Electronics" category.

Source
minimum(field : String | Symbol)

Returns the minimum value of a field for the current query set.

Finds the smallest value within the specified field for the records targeted by the query set. For example:

products = Product.where(category: "Electronics")
lowest_price = products.minimum(:price)

This would identify the lowest-priced product within the "Electronics" category.

Source
model

Returns the model class associated with the query set.

Source
none

Returns a queryset that will always return an empty array of record, without querying the database.

Once this method is used, any subsequent method call (such as extra filters) will continue returning an empty array of records.

Source
order(fields : Array(String | Symbol))

Allows to specify the ordering in which records should be returned when evaluating the query set.

Multiple fields can be specified in order to define the final ordering. For example:

query_set = Post.all
query_set.order(["-published_at", "title"])

In the above example, records would be ordered by descending publication date, and then by title (ascending).

Source
order(*fields : String | Symbol)

Allows to specify the ordering in which records should be returned when evaluating the query set.

Multiple fields can be specified in order to define the final ordering. For example:

query_set = Post.all
query_set.order("-published_at", "title")

In the above example, records would be ordered by descending publication date, and then by title (ascending).

Source
paginator(page_size : Int)

Returns a paginator that can be used to paginate the current query set.

This method returns a Marten::DB::Query::Paginator object, which can then be used to retrieve specific pages.

Source
pick(fields : Array(String | Symbol)) : Array(Field::Any) | Nil

Returns specific column values for a single record without actually loading it.

This method allows to easily select specific column values for a single record from the current query set. This allows retrieving specific column values without actually loading the entire record, and as such this is most useful for query sets that have been narrowed down to match a single record. The method returns an array containing the requested column values, or nil if no record was matched by the current query set. For example:

Post.filter(pk: 1).pick(["title", "published"])
# => ["First article", true]
Source
pick(*fields : String | Symbol) : Array(Field::Any) | Nil

Returns specific column values for a single record without actually loading it.

This method allows to easily select specific column values for a single record from the current query set. This allows retrieving specific column values without actually loading the entire record, and as such this is most useful for query sets that have been narrowed down to match a single record. The method returns an array containing the requested column values, or nil if no record was matched by the current query set. For example:

Post.filter(pk: 1).pick("title", "published")
# => ["First article", true]
Source
pick!(fields : Array(String | Symbol)) : Array(Field::Any)

Returns specific column values for a single record without actually loading it.

This method allows to easily select specific column values for a single record from the current query set. This allows retrieving specific column values without actually loading the entire record, and as such this is most useful for query sets that have been narrowed down to match a single record. The method returns an array containing the requested column values, or raises NilAssertionError if no record was matched by the current query set. For example:

Post.filter(pk: 1).pick!(["title", "published"])
# => ["First article", true]
Source
pick!(*fields : String | Symbol) : Array(Field::Any)

Returns specific column values for a single record without actually loading it.

This method allows to easily select specific column values for a single record from the current query set. This allows retrieving specific column values without actually loading the entire record, and as such this is most useful for query sets that have been narrowed down to match a single record. The method returns an array containing the requested column values, or raises NilAssertionError if no record was matched by the current query set. For example:

Post.filter(pk: 1).pick!("title", "published")
# => ["First article", true]
Source
pks

Returns the primary key values of the considered model records targeted by the current query set.

This method returns an array containing the primary key values of the model records that are targeted by the current query set. For example:

Post.all.pks # => [1, 2, 3]
Source
pluck(fields : Array(String | Symbol)) : Array(Array(Field::Any))

Returns specific column values without loading entire record objects.

This method allows to easily select specific column values from the current query set. This allows retrieving specific column values without actually loading entire records. The method returns an array containing one array with the actual column values for each record targeted by the query set. For example:

Post.all.pluck(["title", "published"])
# => [["First article", true], ["Upcoming article", false]]
Source
pluck(*fields : String | Symbol) : Array(Array(Field::Any))

Returns specific column values without loading entire record objects.

This method allows to easily select specific column values from the current query set. This allows retrieving specific column values without actually loading entire records. The method returns an array containing one array with the actual column values for each record targeted by the query set. For example:

Post.all.pluck("title", "published")
# => [["First article", true], ["Upcoming article", false]]
Source
prefetch(relation_name : String | Symbol, query_set : Any)

Returns a queryset that will automatically prefetch in a single batch the records for the specified relation, with a custom queryset to control how the related records are queried. The prefetched records will be populated on the returned queryset. Using this method can result in performance improvements by reducing the number of SQL queries, as illustrated by the following example:

# Prefetching with a custom queryset
posts = Post.all.prefetch(:tags, query_set: Tag.order(:name)).to_a
puts posts[0].tags # Prefetched with custom ordering

It should be noted that this method enforces type-checking for the custom queryset to ensure its model matches the relation being prefetched. If a type mismatch is detected, a Marten::DB::Errors::UnmetQuerySetCondition exception will be raised. For example:

# Valid usage
posts = Post.all.prefetch(:tags, query_set: Tag.order(:name))

# Invalid usage: Type mismatch
posts = Post.all.prefetch(:tags, query_set: Comment.order(:created_at))
# Raises Marten::DB::Errors::UnmetQuerySetCondition:
# "Can't prefetch :tags using Comment query set."
Source
prefetch(*relations : String | Symbol)

Returns a queryset that will automatically prefetch in a single batch the records for the specified relations.

When using #prefetch, the records corresponding to the specified relationships will be prefetched in single batches and each record returned by the queryset will have the corresponding related objects already selected and populated. Using #prefetch can result in performance improvements since it can help reduce the number of SQL queries, as illustrated by the following example:

posts_1 = Post.all.to_a
puts posts_1[0].tags.to_a # hits the database to retrieve the related "tags" (many-to-many relation)

posts_2 = Post.all.prefetch(:tags).to_a
puts posts_2[0].tags # doesn't hit the database since the related "tags" relation was already prefetched

It should be noted that it is also possible to follow relations and reverse relations too by using the double underscores notation(__). For example the following query will prefetch the "author" relation and then the "favorite tags" relation of the author records:

query_set = Post.all
query_set.prefetch(:author__favorite_tags)

Finally, it is worth mentioning that multiple relations can be specified to #prefetch. For example:

Author.all.prefetch(:books__genres, :publisher)
Source
raw(query : String, params : Array)

Returns a raw query set for the passed SQL query and positional parameters.

This method returns a Marten::DB::Query::RawSet object, which allows to iterate over the model records matched by the passed SQL query and associated positional parameters. For example:

Article.all.raw("SELECT * FROM articles WHERE title = ? and created_at > ?", ["Hello World!", "2022-10-30"])
Source
raw(query : String, params : Hash | NamedTuple)

Returns a raw query set for the passed SQL query and named parameters.

This method returns a Marten::DB::Query::RawSet object, which allows to iterate over the model records matched by the passed SQL query and associated named parameters. For example:

Article.all.raw(
  "SELECT * FROM articles WHERE title = :title and created_at > :created_at",
  {
    title:      "Hello World!",
    created_at: "2022-10-30",
  }
)
Source
raw(query : String, *args)

Returns a raw query set for the passed SQL query and optional positional parameters.

This method returns a Marten::DB::Query::RawSet object, which allows to iterate over the model records matched by the passed SQL query. For example:

Article.all.raw("SELECT * FROM articles")

Additional positional parameters can also be specified if the query needs to be parameterized. For example:

Article.all.raw("SELECT * FROM articles WHERE title = ? and created_at > ?", "Hello World!", "2022-10-30")
Source
raw(query : String, **kwargs)

Returns a raw query set for the passed SQL query and optional named parameters.

This method returns a Marten::DB::Query::RawSet object, which allows to iterate over the model records matched by the passed SQL query. For example:

Article.all.raw("SELECT * FROM articles")

Additional named parameters can also be specified if the query needs to be parameterized. For example:

Article.all.raw(
  "SELECT * FROM articles WHERE title = :title and created_at > :created_at",
  title: "Hello World!",
  created_at: "2022-10-30"
)
Source
reverse

Allows to reverse the order of the current query set.

Source
size

Returns the number of records that are targeted by the current query set.

Source
sum(field : String | Symbol)

Returns the sum of a field for the current query set.

Calculates the total sum of values within the specified field for the records included in the query set. For example:

order_items = OrderItem.filter(order_id: 123)
total_price = order_items.sum(:price)

This would calculate the total cost of all items within order number 123.

Source
to_s(io)

Appends a string representation of the query set to the passed io.

Source
to_sql

Returns the SQL representation of the current query set.

Source
update(values : Hash | NamedTuple)

Updates all the records matched by the current query set with the passed values.

This method allows to update all the records that are matched by the current query set with a hash or a named tuple of values. It returns the number of records that were updated:

query_set = Post.all
query_set.update({"title" => "Updated"})

It should be noted that this methods results in a regular UPDATE SQL statement. As such, the records that are updated through the use of this method won't be validated, and no callbacks will be executed for them either.

Source
update

Updates all the records matched by the current query set with the passed values.

This method allows to update all the records that are matched by the current query set with the values defined in the kwargs double splat argument. It returns the number of records that were updated:

query_set = Post.all
query_set.update(title: "Updated")

It should be noted that this methods results in a regular UPDATE SQL statement. As such, the records that are updated through the use of this method won't be validated, and no callbacks will be executed for them either.

Source
using(db : Nil | String | Symbol)

Allows to define which database alias should be used when evaluating the query set.

Source