Bylaw.Db.Adapters.Postgres.Checks.EctoChangesetUniqueConstraints (bylaw_postgres v0.1.0-alpha.1)

Copy Markdown View Source

Validates Ecto.Changeset.unique_constraint/3 annotations for Postgres indexes.

Examples

With a unique index on users.email, before:

def changeset(user, attrs) do
  user
  |> Ecto.Changeset.cast(attrs, [:email])
  |> Ecto.Changeset.validate_required([:email])
end

The database protects uniqueness, but an insert conflict can bubble up as a database error instead of a changeset error attached to :email.

After, annotate the changeset with the matching constraint:

def changeset(user, attrs) do
  user
  |> Ecto.Changeset.cast(attrs, [:email])
  |> Ecto.Changeset.validate_required([:email])
  |> Ecto.Changeset.unique_constraint(:email)
end

Ecto can translate the database constraint violation into a normal changeset error for callers.

Notes

The check skips dynamic cast or change field lists, expression indexes, partial indexes, primary keys, and unique indexes 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 unique_constraint/3 when a candidate casts all fields covered by a unique Postgres index. Dynamic cast/change field lists are skipped for v1.

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

{Bylaw.Db.Adapters.Postgres.Checks.EctoChangesetUniqueConstraints,
 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:

{Bylaw.Db.Adapters.Postgres.Checks.EctoChangesetUniqueConstraints,
 paths: ["lib/my_app/accounts"],
 schema_modules: [MyApp.Accounts.User, MyApp.Accounts.Organization]}

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

{Bylaw.Db.Adapters.Postgres.Checks.EctoChangesetUniqueConstraints,
 paths: ["lib/my_app"],
 rules: [
   [
     only: [schema: "public"],
     except: [[table: "legacy_users", constraint: "legacy_users_email_index"]]
   ]
 ]}

Usage

Add this module to the checks passed to Bylaw.Db.Adapters.Postgres.validate/2. See the README usage section for the full ExUnit setup.

Summary

Functions

Implements the Bylaw.Db.Check validation callback.

Types

check_opt()

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

check_opts()

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

Functions

validate(target, opts)

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

Implements the Bylaw.Db.Check validation callback.