# Plangora Ash Expressions

Reusable custom expressions for [Ash Framework](https://hexdocs.pm/ash).
Version 0.1.0 provides `at_zone/2` for Ash Simple, ETS, and AshPostgres.

## Installation

Once 0.1.0 is available on Hex, add it to your application's dependencies.

```elixir
{:plangora_ash_expressions, "~> 0.1.0"}
```

Register the expression at compile time in your application's `config/config.exs`.

```elixir
config :ash, :custom_expressions, [PlangoraAshExpressions.AtZone]
```

If you already have a `:custom_expressions` entry, add
`PlangoraAshExpressions.AtZone` to that same list alongside your existing modules.
If Ash was already compiled, run `mix deps.compile ash --force` to pick up the
updated configuration.

For evaluation in Elixir, add an IANA time zone database such as `{:tz, "~> 0.28"}`
to your application's dependencies and configure it.

```elixir
config :elixir, :time_zone_database, Tz.TimeZoneDatabase
```

## HawkSang events by venue-local date

HawkSang can store an event's `starts_at` as a UTC instant and use the related
venue's IANA zone to find events on a local calendar date. In the event resource,
define the calculation inside `calculations do ... end`.

```elixir
calculate :venue_date, :date, expr(type(at_zone(starts_at, venue.time_zone), :date))
```

```elixir
require Ash.Query

Event
|> Ash.Query.filter(venue_date == ~D[2024-01-02])
|> Ash.read!()
```

With a Hong Kong venue, `2024-01-01 18:30:00.123456Z` becomes
`~N[2024-01-02 02:30:00.123456]` before conversion to the local date.

`at_zone(starts_at, venue.time_zone)` returns a `NaiveDateTime` and preserves
fractional seconds. Ash's built-in `:naive_datetime` calculation type loads at
second precision, so fractional seconds are lost if you declare that result type.
Keep the original instant for comparisons across time zones. Either input being
nil yields nil.

## PostgreSQL timestamp types

The HawkSang example works directly with a UTC-valued `timestamp without time
zone`. If `starts_at` is a native `timestamptz` and the repo enables
`use_timestamptz?/0`, Ash can cast a generic `:datetime` attribute to a
session-local `timestamp` before `at_zone/2` sees it. That can change the venue's
calendar date. Use one of these approaches for a native column.

**Declare the native type on the attribute.** The calculation above then uses
the native instant directly.

```elixir
attribute :starts_at, AshPostgres.TimestamptzUsec
```

**Type the input in the expression.** Use this when the attribute declaration
stays generic and the underlying column is a native `timestamptz`.

```elixir
calculate :venue_date, :date,
  expr(type(at_zone(type(starts_at, AshPostgres.TimestamptzUsec), venue.time_zone), :date))
```

Casting a UTC-naive column directly to `timestamptz` interprets it in the
session's zone. For a UTC-valued `timestamp`, `at_zone/2` first attaches UTC
with `AT TIME ZONE 'UTC'` and then converts to the requested zone. For a
`timestamptz`, it converts the instant directly. Both produce a `timestamp
without time zone` as local wall-clock time.

Released AshPostgres binds `now()` as an Elixir `DateTime`. The expression types
it and directly bound `DateTime` values as UTC `timestamp` parameters. An
explicitly typed `AshPostgres.TimestamptzUsec` parameter uses `timestamptz`.

Give ambiguous values, such as parameters inside fragments, an explicit type at
the point where PostgreSQL needs it. For a UTC-naive value use
`at_zone(type(fragment("?", ^instant), :utc_datetime_usec), venue.time_zone)`.
For an expression representing a native instant, use
`AshPostgres.TimestamptzUsec` as the type.

## Comparing local timestamps with microseconds

Ash 3.38.1 can truncate an untyped bound `NaiveDateTime` to seconds in a filter.
For exact equality, define an Ash type backed by Ecto's `:naive_datetime_usec`
in your app and use it to type the bound value. Use that type when loading a
calculation that needs to retain fractional seconds as well.

```elixir
defmodule MyApp.LocalTimestamp do
  use Ash.Type

  def storage_type(_constraints), do: :naive_datetime_usec
  def cast_input(value, _constraints), do: Ecto.Type.cast(:naive_datetime_usec, value)
  def cast_stored(value, _constraints), do: Ecto.Type.load(:naive_datetime_usec, value)
  def dump_to_native(value, _constraints), do: Ecto.Type.dump(:naive_datetime_usec, value)
  def matches_type?(value, _constraints), do: is_struct(value, NaiveDateTime)
end
```

```elixir
require Ash.Query
alias MyApp.LocalTimestamp

local = ~N[2024-01-02 02:30:00.123456]

Event
|> Ash.Query.filter(at_zone(starts_at, venue.time_zone) == type(^local, LocalTimestamp))
|> Ash.read!()
```

Inside the resource's `calculations` block, declare the same type for a
microsecond-precision calculation.

```elixir
calculate :venue_local_start, MyApp.LocalTimestamp, expr(at_zone(starts_at, venue.time_zone))
```

## Current local time

```elixir
import Ash.Expr

eval!(expr(at_zone(now(), "Asia/Hong_Kong")))
```

Use `expr(at_zone(now(), "Asia/Hong_Kong"))` in an Ash calculation as well.
Historical `as_of` behavior for current-time and relative-time expressions is
outside the 0.1.0 compatibility scope.

## Time zone validation

Validate IANA names when accepting input and persist canonical names such as
`Asia/Hong_Kong`. Elixir raises an `ArgumentError` when its configured time zone
database rejects the name. PostgreSQL rejects unrecognized names with a query
error, and one bad row can fail the entire read. PostgreSQL also accepts some
abbreviations, offsets, and capitalization variants that Elixir's IANA database
may reject or interpret differently. Keep the application's and PostgreSQL's
time zone data current for consistent DST rules.

## Compatibility and tests

The package requires Elixir 1.20 or later in the 1.x series and Ash
`~> 3.38.1`. Ash is the only direct runtime dependency.
Release verification used Ash 3.38.1, AshPostgres 2.16.0, and PostgreSQL 18.7.
AshPostgres and the Elixir time zone provider are test dependencies here and
are configured by the consuming application when needed. Other data layers
are outside the 0.1.0 compatibility scope.

Run the suite with a PostgreSQL database that allows temporary tables. Each SQL
test uses a temporary table and sets the connection's time zone to
`America/Los_Angeles` inside its transaction.

```sh
mix deps.get
ASH_EXPRESSIONS_TEST_DATABASE_URL=ecto://postgres:postgres@localhost/plangora_ash_expressions_test mix test
mix format --check-formatted
mix docs
mix hex.build
```

## Usage rules

Plangora Ash Expressions ships [usage rules](usage-rules.md) for the Elixir
UsageRules tool. They cover `at_zone/2` registration, local-date calculations
and filters, PostgreSQL timestamp types, and microsecond precision.

If you already use UsageRules, add `:plangora_ash_expressions` to your existing
`usage_rules` package list in `mix.exs`, then run `mix usage_rules.sync` to
import the rules into your configured file, such as `AGENTS.md`.
UsageRules is optional for consumers and adds no dependency to this library.
See the [UsageRules docs](https://hexdocs.pm/usage_rules/readme.html) for configuration details.

## Publishing releases

Set `HEX_API_KEY` in the GitHub repository’s Actions secrets using a Hex key
with `api:read` and `publish:plangora_ash_expressions` permissions.
When the release is approved, push a version tag such as `v0.1.0` or `0.1.0`
on the commit with the matching version in `mix.exs`. GitHub Actions checks the
version, formatting, PostgreSQL tests, documentation, and Hex package before
submitting the release and its docs. New public packages default to staged
publishing, so approve the staged release on Hex.pm to make it public.
See the [Hex publishing docs](https://hex.pm/docs/publish) for key setup and staged releases.

## Credit

The `at_zone/2` interface and in-memory approach follow the proposal by
[bitwalker in the Ash review for PR #3134](https://github.com/ash-project/ash/pull/3134#pullrequestreview-6062010046).
