Rules for working with Plangora Ash Expressions

Copy Markdown

Register the expression

config :ash, :custom_expressions, [PlangoraAshExpressions.AtZone]
  • Run mix deps.compile ash --force if Ash was compiled before the config change.
  • Configure an IANA time zone database for evaluation in Elixir. For example, add tz to the consuming application and set config :elixir, :time_zone_database, Tz.TimeZoneDatabase.

Convert instants inside Ash expressions

  • Use at_zone(instant, zone) on Ash Simple, ETS, and AshPostgres. Pass a UTC datetime attribute or an instant expression such as now(). The zone can be a literal, an attribute, or a related attribute.
  • Validate and store canonical IANA names such as Asia/Hong_Kong when accepting input. An invalid zone stored on a row can fail a PostgreSQL read.
  • The result is a local NaiveDateTime with fractional seconds preserved. A nil instant or zone yields nil. Keep the original instant for chronological comparisons across zones.
  • Convert to the target zone before extracting a local date. For example, define this calculation on an event with a venue relationship and use Ash.Query.filter(venue_date == ^date) to query it.
calculate :venue_date, :date, expr(type(at_zone(starts_at, venue.time_zone), :date))
  • Historical as_of behavior for current-time and relative-time expressions is outside the 0.1.0 compatibility scope.

Preserve timestamp types and precision

  • On PostgreSQL, use a UTC-valued timestamp without time zone or an explicitly native timestamptz. For a native column, declare the attribute as AshPostgres.TimestamptzUsec or wrap a generic :datetime attribute in type(starts_at, AshPostgres.TimestamptzUsec) inside at_zone/2. This prevents Ash from interpreting the instant in the session's time zone.
  • Ash's built-in :naive_datetime can drop fractional seconds when loading calculations or casting filter values. For microsecond precision, use an Ash type backed by Ecto's :naive_datetime_usec for the calculation and explicitly type values in direct expression comparisons.
Ash.Query.filter(at_zone(starts_at, venue.time_zone) == type(^local, MyApp.LocalTimestamp))

See the package README for a complete LocalTimestamp type example.