# `Bylaw.Db.Adapters.Postgres.Checks.EctoChangesetForeignKeyConstraints`
[🔗](https://github.com/ryanzidago/bylaw/blob/v0.1.0-alpha.1/lib/bylaw/db/adapters/postgres/checks/ecto_changeset_foreign_key_constraints.ex#L1)

Validates `Ecto.Changeset.foreign_key_constraint/3` annotations for Postgres FKs.

## Examples

With a foreign key on `orders.account_id`, before:

```elixir
def changeset(order, attrs) do
  order
  |> Ecto.Changeset.cast(attrs, [:account_id])
  |> Ecto.Changeset.validate_required([:account_id])
end
```

The database rejects missing accounts, but the caller may see a low-level
constraint error instead of an `:account_id` changeset error.

After, annotate the changeset with the matching constraint:

```elixir
def changeset(order, attrs) do
  order
  |> Ecto.Changeset.cast(attrs, [:account_id])
  |> Ecto.Changeset.validate_required([:account_id])
  |> Ecto.Changeset.foreign_key_constraint(:account_id)
end
```

Ecto can report the invalid relationship through the changeset API.

## Notes

The check skips dynamic `cast` or `change` field lists and foreign keys whose
columns cannot be mapped to Ecto schema fields.

## Options

The check discovers compiled Ecto schemas through reflection, parses source
files for conservative changeset candidates, and only requires
`foreign_key_constraint/3` when a candidate casts the local foreign-key field.
Dynamic cast/change field lists are skipped for v1.

Pass `paths: [...]` so Bylaw can parse source AST for user-defined changeset
functions:

```elixir
{Bylaw.Db.Adapters.Postgres.Checks.EctoChangesetForeignKeyConstraints,
 paths: ["lib/my_app"]}
```

When the repo can report `config()[:otp_app]`, schema module discovery is
derived from it. Use `schema_modules: [...]` when the check should inspect an
explicit set of schemas instead:

```elixir
{Bylaw.Db.Adapters.Postgres.Checks.EctoChangesetForeignKeyConstraints,
 paths: ["lib/my_app/billing"],
 schema_modules: [MyApp.Billing.Invoice, MyApp.Billing.Payment]}
```

Use `rules: [...]` to scope the Postgres constraints considered by the check:

```elixir
{Bylaw.Db.Adapters.Postgres.Checks.EctoChangesetForeignKeyConstraints,
 paths: ["lib/my_app"],
 rules: [
   [
     only: [schema: "public"],
     except: [[table: "events", column: "actor_id"]]
   ]
 ]}
```

## Usage

Add this module to the checks passed to
`Bylaw.Db.Adapters.Postgres.validate/2`. See the
[README usage section](readme.html#usage) for the full ExUnit setup.

# `check_opt`

```elixir
@type check_opt() ::
  {:validate, boolean()}
  | {:otp_app, atom()}
  | {:paths, [Path.t()]}
  | {:schema_modules, [module()]}
  | {:rules, [keyword()]}
```

# `check_opts`

```elixir
@type check_opts() :: [check_opt()]
```

# `validate`

```elixir
@spec validate(target :: Bylaw.Db.Target.t(), opts :: check_opts()) ::
  Bylaw.Db.Check.result()
```

Implements the `Bylaw.Db.Check` validation callback.

---

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