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

Compiles writes to one SQL statement, mirroring PostgREST's `mutatePlanToQuery`.

`insert/3` binds the whole payload as **one** JSON parameter (`$1::text::json`) however
many rows it holds, and expands it with `json_populate_recordset`:

    WITH pgrst_payload AS (SELECT $1::text::json AS j),
    pgrst_source AS (
      INSERT INTO t (<cols>) SELECT <cols> FROM json_populate_recordset(NULL::t, <array>) _
      RETURNING <every column> AS <its Ecto field name>)
    <read wrapper over pgrst_source>

A single object is wrapped into a one element array in SQL. `RETURNING` exposes the
columns under their Ecto field names, which is how `PgRest.SQL.Read` addresses a node.

`json_populate_recordset` yields `NULL` for an absent key. With `missing: :default` each
element is first merged over `jsonb_build_object(<column>, <default expression>, ...)`
(PostgREST's `fromJsonBodyF`), so an absent key takes the column default while an explicit
`null` stays `NULL`. The expressions come from `PgRest.Catalog.column_defaults/3`.

`update/5` and `delete/4` compile `PATCH` and `DELETE` (see their docs): one statement, the
payload one JSON parameter, filters compiled on the target or through a `FOR UPDATE`
semijoin over the scoped source.

The statement always returns `total`, `page_total`, `body`, `pgrst_keys`, `pgrst_inserted`,
`pgrst_written`, `pgrst_matched` and the two response GUC columns (`PgRest.ResponseGucs`). `pgrst_keys` is
the written primary keys as JSON text, `[{"<field>": value, ...}, ...]`, when the caller
asks for them (`:keys`); `check/4` binds that text back to verify the scope.

# `input`

```elixir
@type input() :: [map()] | {:raw, binary(), [String.t()]}
```

Rows as maps keyed by source column, or the original request bytes plus their keys.

# `check`

```elixir
@spec check(module(), PgRest.Plan.Read.t(), String.t(), [String.t()], module()) ::
  {String.t(), [term()]}
```

The write check, a statement in the same transaction as the write: how many of the
written `keys` (the text of `pgrst_keys`) the resource's scope does **not** see. `0` passes.

The keys are one JSON parameter; each is probed with a correlated `EXISTS`, never
`IN (subquery)`. `key_fields` are the primary key (or `unique_key`) fields in order and
`plan.column_types` supplies their catalog types.

# `delete`

```elixir
@spec delete(module(), PgRest.Plan.Read.t(), PgRest.Plan.Read.t() | nil, keyword()) ::
  {String.t(), [term()]}
```

Compiles a `DELETE` into `{sql, params}`, the same two shapes as `update/5`:
`DELETE FROM t AS pgrst_m WHERE ... RETURNING ...`.

# `insert`

```elixir
@spec insert(module(), input(), keyword()) :: {String.t(), [term()]}
```

Compiles an insert into `{sql, params}`.

## Options

  * `:repo` - the Ecto repo (required)
  * `:columns` - the source columns to write; default: the keys of the rows
  * `:missing` - `:default` applies column defaults for absent keys
  * `:defaults` - `%{column => default expression}` (from the catalog), used with `:missing`
  * `:on_conflict` - `nil`, or `%{target: [column], action: :merge | :ignore, guard: ...}`:
    `ON CONFLICT (<target>) DO UPDATE SET <payload columns> = EXCLUDED.<column>` or
    `DO NOTHING`. `merge` counts the inserted rows (`pgrst_inserted`); `guard` is
    `%{plan:, key: [{field, source_column}]}`, the scope probe of the existing row
  * `:returning_plan` - the read plan of the representation; `nil` returns no body
  * `:hook_limit` - caps response counts when there is no representation; written rows
    and keys used by transactional checks remain uncapped
  * `:media` - the `PgRest.MediaType` of the representation (default JSON): an object type
    unwraps a single row, `nulls=stripped` strips nulls, CSV renders text
  * `:keys` - `[field_name]`, the primary key fields to return as `pgrst_keys`
  * `:key` - `[{column, text}]`, a `PUT`'s URL key: only the payload element whose column equals
    the text (cast by Postgres to the column's type, as `json_populate_record` reads it) is
    written, and only when exactly one does; the count is returned as `pgrst_matched`. Every
    element is still decoded, so Postgres type-checks them all
  * `:source_query` - the target's scoped Ecto query (`plan.source_query`): the table is
    written in its effective schema prefix (`PgRest.SQL.ScopedSource.effective_prefix/2`);
    default: the resource's own prefix

# `update`

```elixir
@spec update(
  module(),
  input(),
  PgRest.Plan.Read.t(),
  PgRest.Plan.Read.t() | nil,
  keyword()
) ::
  {String.t(), [term()]}
```

Compiles a `PATCH` into `{sql, params}`. `input` is `{:raw, json, keys}` (one object, or an
array of one) and `opts` as for `insert/3` (`:repo`, `:columns`, `:missing`, `:defaults`,
`:media`, `:keys`).

The columns `SET` are `opts[:columns]` (default: the keys), taken from the payload by
`json_populate_recordset`, so every value arrives in its column's catalog type. With none
the statement selects no row (`WHERE false`), as PostgREST does.

`plan` is the target plan whose `where` selects the rows; `returning_plan` (the plan
without `where`) shapes the representation, `nil` for none. Two shapes, by the scope:

  * **Identity scope**, PostgREST's own: the filters are compiled on the target,
    `UPDATE t AS pgrst_m SET ... WHERE <filters>`. Tables without a primary key work.
  * **Any other scope**: the rows are chosen through the scope and locked,
    `WHERE (<key>) IN (SELECT <key> FROM (<scoped source>) s WHERE <filters> FOR UPDATE)`,
    so a concurrent change of ownership is waited for and re-checked (S-L1).

---

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