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

Serves `POST /<table>`: single and bulk inserts and upserts, on the pipeline in
`PgRest.Write`.

`Prefer: resolution=merge-duplicates|ignore-duplicates` makes it an upsert on the
`on_conflict=` columns (default: the primary key). `merge` updates only the payload
columns of a conflicting row and needs `:update` as well as `:create`. The status follows
PostgREST: `merge` is 200 when no row was inserted (`SQL.Write` counts them) and 201
otherwise; `ignore` is always 201. `Preference-Applied` echoes `resolution` unless the
table has no primary key and the request names no `on_conflict`.

A `PUT` (`PgRest.Write.Put`) arrives here as a one row `merge` on the primary key, and is answered
by `PgRest.Responder.put/6`. Over a non-identity scope the conflicting row must be in scope (`PgRest.SQL.Write` guards
the update with a correlated `EXISTS`); a `merge` that skips a row because of it is a 42501
and rolls back.

The order is `PgRest.Write`'s: authorize, then plan the target (and its representation) and
read `column_defaults/3` when `missing=default`, then validate the payload
(`PgRest.Write.Payload`: row count, key shape, unknown and non-writable columns, a custom
changeset), and `PgRest.SQL.Write.insert/3` builds the statement. A request the hook denies
or whose `select=` is invalid never runs a user changeset.

# `run`

```elixir
@spec run(
  Plug.Conn.t(),
  map(),
  map(),
  PgRest.Request.t(),
  map(),
  [{String.t(), String.t()}] | nil
) ::
  Plug.Conn.t()
```

Runs the insert and sends the response. `key` is a `PUT`'s URL key (`PgRest.Write.Put`): see
`PgRest.SQL.Write.insert/3`.

---

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