# `PgRest.Write.Payload`
[🔗](https://github.com/agoodway/pgrest/blob/v0.2.0/lib/pg_rest/write/payload.ex#L1)

Validates and prepares the body of a write for `PgRest.SQL.Write`.

Payload keys are database column names. The union of keys is checked once against the
resource's fields (an unknown one is `PGRST204`) and its effective writable set (a column
outside it is `42501`, as a missing column privilege would be).

Without `columns=` every row must have the same keys, as in PostgREST (`PGRST102`).
With `columns=` only those columns are written and other keys are ignored.

## Fast path

A resource without a custom `changeset/3` or explicitly writable virtual fields skips
per-row changesets: the original request
bytes (`raw_body`, or one `Jason.encode!/1` of the decoded body) are bound as is, and
Postgres reports bad values (`22P02`) as PostgREST does.

## Changeset path

Each row passes through `changeset(struct(resource), row, context)`; the context carries
`operation: :create | :upsert | :update`. An invalid changeset is a 400 whose `details` are
`traverse_errors` flattened to one string (`field: message; ...`).

**The final changes express write intent.** The changeset runs **once per row** (keep it
pure), on `struct(resource)`. The fields written are the keys of `changeset.changes` that
are persisted columns (and in `columns=`, when given), each with its `get_field/2` value.
The writable set gates only client-supplied keys (a `42501` before the changeset runs), so a
change the callback generates (`put_change/3`) is written even for a non-writable or
`redact: true` field. The changeset sees `struct(resource)`, also for `PATCH`, not the stored
row: a `put_change` derived from struct fields uses their defaults. 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.

Ecto's `cast/4` leaves a value equal to the struct default (often `nil`, `0`, `false`,
`""` through `empty_values`, `[]`) out of the changes, so to write it, cast with
`force_changes: true` before validating (the default `changeset/3` does). Ecto does not
force embeds: a `cast_embed/3` that clears an embed to a struct default that is the same
(`nil` for `embeds_one`, `[]` for `embeds_many`) is not in the changes and is omitted.

Values are dumped with `Ecto.Type.embedded_dump/3` as `:json` (uuid and similar types
become strings); `:binary` values (and `{:array, :binary}` elements) become `\x<hex>`
text, the `bytea` input form, so any bytes round-trip. Absent keys stay absent and follow
`missing=`.

# `built`

```elixir
@type built() :: %{
  input: PgRest.SQL.Write.input(),
  columns: [String.t()],
  write_path: :fast | :changeset,
  count: non_neg_integer()
}
```

# `build`

```elixir
@spec build(
  map(),
  PgRest.Request.t(),
  [String.t()] | nil,
  map(),
  pos_integer(),
  :create | :upsert
) ::
  {:ok, built()} | {:error, PgRest.Error.t()}
```

Builds the statement input of a write. `columns` is the parsed `columns=` list or `nil`;
`operation` (`:create` or `:upsert`) is what a custom `changeset/3` sees in its context.
`built.columns` are the source columns the statement writes.

# `build_update`

```elixir
@spec build_update(
  map(),
  PgRest.Request.t(),
  [String.t()] | nil,
  map(),
  pos_integer()
) ::
  {:ok, built()} | {:error, PgRest.Error.t()}
```

Builds the statement input of a `PATCH`: at most one object (an array of one is unwrapped;
`[]`, `{}` and a scalar write nothing; several objects are a 400 `PGRST102`, a documented
difference from PostgREST, which applies one of them arbitrarily). The columns to `SET` are
the supplied payload keys, or `columns=`; they come back in `built.columns`.

A custom `changeset/3` sees `operation: :update`. `:required` errors are dropped for fields
the payload does not supply (a partial update), any other error is a 400. The columns set
are the changeset's final changes, as described in the moduledoc.

# `uniform_keys`

```elixir
@spec uniform_keys(list(), [String.t()] | nil) ::
  {:ok, [String.t()]} | {:error, PgRest.Error.t()}
```

The keys of a JSON payload's `rows` (a list of decoded elements): `columns` when given (the
`columns=` list), else the keys every row shares. Every row must be an object (`PGRST102`,
or Postgres' own `22023` when `columns=` lets a non-object through) and, without `columns=`,
have the same keys (`PGRST102`).

---

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