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

The pipeline shared by every write: insert, upsert, update and delete.

    authorize -> plan the target (and catalog) -> payload -> execute -> respond

Every write plans before building the payload, so a request the hook or `allow:` denies (or
whose `select=` is invalid) never runs a user changeset.

A write supplies its statement builder; this module owns what is the same for all of them:

  * `authorize/6`: the write's own operation, plus `:read` on the root when the response
    shows rows, a `Location` or a count, or the request filters (filters, counts and
    `RETURNING` are a read channel), all through `PgRest.Authorization.check/5` (`allow:`,
    then the hook). A `Location` also needs a readable primary key. Representation embeds
    are authorized by the planner.
  * `plan_mutation/4`: the same for `PATCH` and `DELETE`, keeping the root filters on the plan
    (`PgRest.Write.Modify`). `execute/5` takes `job.check` (`:with_check`, the default, or
    `:none` for a delete) and `job.locate?` (`false` when there is no `Location`).
  * `plan/4`: the target planned through `PgRest.Planner`, which yields the scoped source
    and column types. A representation plans the request's `select=`, `order=` and embedded
    parameters; root filters and paging do not apply to written rows. Anything else plans
    `select=*` without the planner's `:read` walk (the `authorize?: false` planner option),
    since `authorize/6` already decided what the write needs. The target table, its
    catalog and the `search_path` follow the scope's effective schema prefix
    (`PgRest.SQL.ScopedSource.effective_prefix/2`), as reads do.
  * `execute/5`: the transaction: the statement, the single-object check and the write
    check (the scope as a row-level security `WITH CHECK`). A failure rolls back.
  * `key_columns/4` (with a `locate?` flag) and `location/3`: the written keys and the
    `Location` header.

The write check **fails closed**: a non-identity scope on a resource without a key
cannot be checked, so the write is refused before any SQL (`PgRest.Registry` already
rejects such a resource at start).

## Differences from PostgREST

Strict max-affected counts rows actually written, including when aggregate
representations collapse them. PostgREST counts the response rows instead.
A hidden on_conflict column returns 42703, like a nonexistent conflict column.

Hook permission caps bound response counts as well as representations. Transactional
checks and single-row Location decisions still use the uncapped written rows; a cap
cannot make a bulk write singular. PostgREST has no application permission cap.

# `job`

```elixir
@type job() :: %{
  :plan =&gt; PgRest.Plan.Read.t(),
  :media =&gt; PgRest.MediaType.t(),
  :write_path =&gt; atom(),
  optional(atom()) =&gt; term()
}
```

A planned write: the read plan of the target and the negotiated media type.

# `authorize`

```elixir
@spec authorize(
  Plug.Conn.t(),
  map(),
  atom() | [atom()],
  PgRest.Request.t(),
  map(),
  keyword()
) ::
  {:ok, PgRest.Authorization.State.t()} | {:error, PgRest.Error.t()}
```

Authorizes each of `operations` on the target, and `:read` on the root when the response needs it
(`headers-only`, a `count=` or a representation). Returns an explicit authorization
state for the request; user context is never used to store grants.

Options: `:filters?` (default `false`) says the request filters rows, which is a read
channel and needs `:read` too; `:location?` (default `true`) says `headers-only` sends a
`Location`, which `PATCH` and `DELETE` never do. A `Location` shows the primary key, so it
also needs every key column to be readable (`readable:`), else `42501`, as Postgres needs
`SELECT` on the columns a `RETURNING` reads.

# `columns`

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

Parses `columns=a,b` into source column names, or `nil` when absent.

# `defaults`

```elixir
@spec defaults(module(), PgRest.Plan.Read.t(), atom() | nil) :: {:ok, map()}
```

The column defaults for `missing=default`, else none. Read from the target's effective
schema (`PgRest.SQL.ScopedSource.effective_schema/2`).

# `ensure_conflict_columns`

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

`:ok` when every `on_conflict=` name is a readable column of the resource; otherwise the
`42703` Postgres reports for an unknown column, so the parameter is no oracle for hidden
columns or index names.

# `execute`

```elixir
@spec execute(map(), map(), PgRest.Request.t(), job(), ([String.t()] | nil -&gt;
                                                    {String.t(), [term()]})) ::
  {:ok, map() | String.t()} | {:error, PgRest.Error.t()}
```

Runs the write in one transaction. `build` receives the key fields (strings) the
statement must return as `pgrst_keys`, or `nil`, and returns `{sql, params}`.

Returns `{:ok, result}` (`body`, `page_total`, `keys`; the plan text of a plan media type) or
`{:error, error}`.

# `filters?`

```elixir
@spec filters?(PgRest.Request.t()) :: boolean()
```

Whether the request names a row filter (or something that may be one: an embedded
parameter). Computed from the query string, before any planning, so `:read` can be
authorized first. For this `:read` check, declared `custom_params` count:
`handle_param/4` narrows the rows a `PATCH` or `DELETE` touches, so it is a read
channel like any filter. They do not satisfy `require_filters_for_mutations`, which
needs a column filter.

# `key_columns`

```elixir
@spec key_columns(map(), boolean(), PgRest.Request.t(), boolean()) ::
  [String.t()] | nil
```

The key fields (strings, in field order) a statement returns as `pgrst_keys`: the scope
key when the write is checked, plus the primary key for `return=headers-only`.

# `key_pairs`

```elixir
@spec key_pairs(map(), [atom()]) :: [{String.t(), String.t()}]
```

`{field name, source column}` for each of `fields` (atoms), in the resource's field order.

# `location`

```elixir
@spec location(map(), PgRest.Request.t(), map()) :: String.t() | nil
```

The `Location` of a single written row, `/<table>?<pk>=eq.<value>` joined with `&`
(`is.null` for a null), or `nil`. Values are encoded like PostgREST's query strings and
keep their text (`1.50`).

# `on_conflict`

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

Parses `on_conflict=a,b` into column names, or `nil` when absent. Same grammar and
errors as `columns=`.

# `plan`

```elixir
@spec plan(PgRest.Request.t(), map(), map(), boolean()) ::
  {:ok, PgRest.Plan.Read.t()} | {:error, PgRest.Error.t()}
```

Plans the target of a write (see the moduledoc). Catalog lookups happen here, before the
transaction opens.

# `plan_mutation`

```elixir
@spec plan_mutation(PgRest.Request.t(), map(), map(), boolean()) ::
  {:ok,
   %{
     plan: PgRest.Plan.Read.t(),
     returning: PgRest.Plan.Read.t() | nil,
     authorization_state: PgRest.Authorization.State.t()
   }}
  | {:error, PgRest.Error.t()}
```

Plans a `PATCH` or `DELETE`: `{:ok, %{plan:, returning:}}`.

`plan` selects the rows: the root filters and logic trees stay on it (`plan.where`) for the
statement to compile on the mutation target. It is planned against `select=*`, as upstream
does, so an embedded parameter that names no embed (`?clients.id=eq.1`) is `PGRST108` before
any SQL, and `embed=is.null` is a column filter (`42703`), never silently dropped.
`limit`, `offset`, `columns` and `on_conflict` do not select rows and are dropped.

`returning` is the plan of the representation (`select=`, `order=`, embedded parameters, the
hook's `:read`), without filters, or `nil` for any other `return=`.

`check_source` carries the base scope intersected with the write-operation policy. Custom
params select rows like filters do, so, like filters, they never constrain the new row.

# `representation?`

```elixir
@spec representation?(PgRest.Request.t()) :: boolean()
```

Whether the request asks for `return=representation`.

# `scrub_details?`

```elixir
@spec scrub_details?(map(), boolean()) :: boolean()
```

Whether constraint details are hidden from the client (S-H5): when the effective source is
not the identity scope (`scoped?`) or a column allowlist narrows the resource, as Postgres
does under row-level security.

# `source_columns`

```elixir
@spec source_columns(map(), [atom()]) :: [String.t()]
```

The source columns of `fields` (atoms), in the resource's field order.

---

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