Ash.Sort (ash v1.37.0) View Source

Utilities and types for sorting.

Link to this section Summary

Functions

A utility for parsing sorts provided from external input. Only allows sorting on public attributes and aggregates.

A utility for sorting a list of records at runtime.

Link to this section Types

Specs

sort_order() ::
  :asc
  | :desc
  | :asc_nils_first
  | :asc_nils_last
  | :desc_nils_first
  | :desc_nils_last

Specs

t() :: [atom() | {atom(), sort_order()}]

Link to this section Functions

Link to this function

parse_input(resource, sort)

View Source

Specs

parse_input(
  Ash.Resource.t(),
  String.t()
  | [atom() | String.t() | {atom(), sort_order()} | [String.t()]]
  | nil
) :: t() | nil

A utility for parsing sorts provided from external input. Only allows sorting on public attributes and aggregates.

The supported formats are:

Sort Strings

A comma separated list of fields to sort on, each with an optional prefix.

The prefixes are:

  • "+" - Same as no prefix. Sorts :asc.
  • "++" - Sorts :asc_nils_first
  • "-" - Sorts :desc
  • "--" - Sorts :desc_nils_last

For example

"foo,-bar,++baz,--buz"

A list of sort strings

Same prefix rules as above, but provided as a list.

For example:

["foo", "-bar", "++baz", "--buz"]

A standard Ash sort

Link to this function

parse_sort(resource, field)

View Source
Link to this function

runtime_sort(results, sort)

View Source

A utility for sorting a list of records at runtime.

For example:

Ash.Sort.runtime_sort([record1, record2, record3], name: :asc, type: :desc_nils_last)

Keep in mind that it is unrealistic to expect this runtime sort to always be exactly the same as a sort that may have been applied by your data layer. This is especially true for strings. For example, Postgres strings have a collation that affects their sorting, making it unpredictable from the perspective of a tool using the database: https://www.postgresql.org/docs/current/collation.html