# `PgRest.Resource`
[🔗](https://github.com/agoodway/pgrest/blob/v0.2.0/lib/pg_rest/resource.ex#L1)

Behavior for defining PgRest API resources from Ecto schemas.

## Usage

    defmodule MyApp.Orders do
      use Ecto.Schema
      use PgRest.Resource

      schema "orders" do
        field :reference, :string
        field :status, :string
        timestamps()
      end

      import Ecto.Query

      @impl PgRest.Resource
      def scope(query, %{tenant_id: tid}) do
        where(query, [r], r.tenant_id == ^tid)
      end
    end

## Unsupported table names

A table whose name starts with `pgrst_` (`pgrst_source`, `pgrst_source_count`, ...)
collides with the CTE and alias names PgRest generates. Do not register one.

# `context`

```elixir
@type context() :: map()
```

A map of contextual information (repo, user, tenant, etc.) passed to callbacks.

# `after_load`

```elixir
@callback after_load(map(), context()) :: map()
```

Post-processes a row after loading from the database (needs `after_load: true`).

The body is decoded with plain `Jason`, so numbers arrive as integers (exact) or floats: a
non-integer number is re-encoded as a float (`1.50` becomes `1.5`, digits past double
precision are rounded). Select exact decimals as text (`amount::text`) on such resources.

Rows are string-keyed maps, also for embedded resources and for spread (`...rel(...)`)
targets: a spread's rows go through this callback before their columns merge into the
parent row. When an embed has no row (a null to-one, an empty to-many), the callback runs
once on a placeholder row whose planned columns are all `nil`, only to decide which
columns to emit: the ones it keeps appear as `nil` (to-one) or `[]` (to-many), including
keys it adds, and columns it removes stay hidden. If it raises on the placeholder, no
columns are emitted for that spread.

The keys are the response's output keys: a request alias (`select=secret_alias:secret`)
renames a column before this callback sees it. Do not use key-based redaction here as a
security control; hide columns with `readable:` / `writable:` instead.

This is a transformation hook, not a confidentiality control. It runs after the query
projected its columns, so filters, order, counts and `!inner` can still reveal values of
fields it removes, and it does not run on the implicit junction rows of many-to-many
embeds. Use `readable:` / `writable:` for columns and `scope/2` for rows.

Rows are processed children first, exactly once each: embedded rows (by the planned
output key) and merged spreads go through their callbacks before the row's own callback
runs, so a parent callback may rename or drop embed keys.

# `changeset`

```elixir
@callback changeset(Ecto.Schema.t(), map(), context()) :: Ecto.Changeset.t()
```

Builds the changeset of one written row (once per row; keep it pure). Its final changes
express write intent: only keys in `changeset.changes` are written. Cast with
`force_changes: true` to write (and validate) a value equal to the struct default.

# `handle_param`

```elixir
@callback handle_param(String.t(), String.t(), Ecto.Query.t(), context()) ::
  Ecto.Query.t()
```

Handles a custom query parameter not recognized by the standard parser.

# `scope`

```elixir
@callback scope(Ecto.Query.t(), context()) :: Ecto.Query.t() | {:error, PgRest.Error.t()}
```

Applies scoping to the base query (e.g. tenant isolation).

The scope is a predicate: it may add `where`, `join` and `distinct` only (anything else
raises `ArgumentError` naming the resource). Named bindings are fine: `from(q, as: :t)`,
`join(..., as: :j)` and `where([t: t, j: j], ...)` are compiled by Ecto itself and
spliced as-is, so the names are kept. A scope may return `{:error, %PgRest.Error{}}`
to reject the request.

# `__using__`
*macro* 

Injects PgRest resource behaviour, configuration, and default callback implementations.

## Options

  * `:allow` - `:all` (default) or a list of `:read | :create | :update | :delete`. An
    excluded operation is a `42501` on every resource a request touches (see
    `PgRest.Authorization.check/5`): without `:read` the resource cannot be embedded,
    spread or used as a junction, and its writes cannot read rows back
  * `:custom_params` - query parameter names routed to `handle_param/4` (default `[]`)
  * `:after_load` - `true` when `after_load/2` is overridden (default `false`)
  * `:unique_key` - fields forming a unique key for scoped mutations on tables
    without a primary key (default `nil`). It must be truly unique and its
    columns `NOT NULL`: the write check and the scope semijoin trust it (a NULL key is
    dropped by `IN`, a duplicate key matches more than one row)
  * `:relationships` - overrides and explicit relationship declarations, see
    `PgRest.SchemaGraph`
  * `:readable` / `:writable` - `:all` (default) or a list of field names exposed
    for reading / writing. Redact fields are hidden unless listed explicitly. The
    default `changeset/3` casts the effective writable set with `force_changes: true`.

## Writes through a custom `changeset/3`

A resource that defines `changeset/3` is written row by row (`operation: :create` is in
the context; `:upsert` for a `Prefer: resolution=` request; `:update` for `PATCH`, where
`:required` errors for fields the payload does not supply are dropped). The changeset runs
**once per row** (keep it pure) and **its final changes express write intent**: the
columns written are the keys of `changeset.changes` (persisted, and in `columns=` when
given), with their changeset values, including any change the callback adds
(`put_change/3`). `writable:` (and `redact: true`) gate only keys the client supplies (`42501`),
so a generated change is written even for a non-writable or redacted field. The changeset
receives `struct(resource)`, also for `PATCH`, not the stored row, so a `put_change`
derived from struct fields uses their defaults. Edges:

  * a supplied key the changeset does not put in its changes is not written: an insert
    gets the database default and an update leaves the column unchanged (cast every key
    you accept);
  * `cast/4` drops a value equal to the struct default (`nil`, `0`, `false`, `""` through
    `empty_values`, `[]`, ...), so it is not written either. To write it, cast with
    `force_changes: true` before your validations (they then see it too); the default
    `changeset/3` does;
  * Ecto does not force embeds: a `cast_embed/3` clearing an embed to a struct default
    that is the same (`nil` for `embeds_one`, `[]` for `embeds_many`) is omitted;
  * a change that only some rows get (a callback that adds a column conditionally, or a
    default-equal value dropped without `force_changes`) makes the rows non-uniform; the
    column is written `NULL` (or its default with `missing=default`) for the other rows. An
    upsert (`operation: :upsert`) refuses that with a 400 `PGRST102` ("All object keys must
    match"), so a merge never overwrites stored data with `NULL`.

Validation errors are a 400 `23514` whose `details` is `field: message; ...`.

## Scoped writes

`PATCH` and `DELETE` over a scope select their rows through a `FOR UPDATE` semijoin, so
a concurrent change of ownership is waited for and re-checked. When the scope joins or
uses `distinct`, the lock is taken on the table rows but the scope predicate (inside the
semijoin) is not re-evaluated after the wait: a `DELETE` has the weaker guarantee. A
`PATCH` is covered by the write check, which fails a row that left the scope with a
42501.

## Differences from PostgREST

Virtual fields explicitly listed in `writable:` are changeset-only inputs and are never
written to SQL. Unlisted virtual fields are unknown payload keys (PGRST204).
PostgREST accepts database columns only; this supports virtual password inputs whose
changeset generates a persisted hash.

`scope/2` and `changeset/3` have no definitions until the module is compiled: a
`@before_compile` hook injects the identity scope and the default changeset only
when the module does not define its own, and records that in the config as
`custom_scope?` / `custom_changeset?`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
