Rules for working with Plangora Ash Expressions
Copy MarkdownRegister the expression
- Add
PlangoraAshExpressions.AtZoneto the existing:custom_expressionslist in the application's compile-time Ash config.
config :ash, :custom_expressions, [PlangoraAshExpressions.AtZone]- Run
mix deps.compile ash --forceif Ash was compiled before the config change. - Configure an IANA time zone database for evaluation in Elixir. For example, add
tzto the consuming application and setconfig :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 asnow(). The zone can be a literal, an attribute, or a related attribute. - Validate and store canonical IANA names such as
Asia/Hong_Kongwhen accepting input. An invalid zone stored on a row can fail a PostgreSQL read. - The result is a local
NaiveDateTimewith 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
venuerelationship and useAsh.Query.filter(venue_date == ^date)to query it.
calculate :venue_date, :date, expr(type(at_zone(starts_at, venue.time_zone), :date))- Historical
as_ofbehavior 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 zoneor an explicitly nativetimestamptz. For a native column, declare the attribute asAshPostgres.TimestamptzUsecor wrap a generic:datetimeattribute intype(starts_at, AshPostgres.TimestamptzUsec)insideat_zone/2. This prevents Ash from interpreting the instant in the session's time zone. - Ash's built-in
:naive_datetimecan drop fractional seconds when loading calculations or casting filter values. For microsecond precision, use an Ash type backed by Ecto's:naive_datetime_usecfor 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.