CodeSampleX

Exemple

ecto 3.14.1: Navigate default foreign key types in Ecto associations and handle :id type defaults when schemas use binary_id primary keys

Échantillon vérifié pour hex ecto 3.14.1: Navigate default foreign key types in Ecto associations and handle :id type defaults when schemas use binary_id…

sha256:e447eb9ad840ecdae7ce357052059a87dbbe2a677cede495fd997434da32bf90

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré elixir linux x64 elixir elixir mix

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
elixir 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-17
elixir 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-18

Cas

HOW
Objectif
Navigate default foreign key types in Ecto associations and handle :id type defaults when schemas use binary_id primary keys
Paquets
Symboles
  • Ecto.Schema.belongs_to
  • Ecto.Schema.has_many
  • Ecto.Schema.has_one
  • Ecto.Schema
  • Ecto.Changeset.cast
Environnement
elixir
Créé
2026-08-17T04:43:50Z

Contrat

  1. assert belongs_to defaults the foreign key field type to :id integer even when @primary_key is configured as :binary_id, causing binary UUID string parameters to fail with a cast validation error
  2. assert casting integer values into default belongs_to foreign key fields succeeds because the unconfigured foreign key type defaults to :id
  3. assert configuring @foreign_key_type :binary_id sets the default association foreign key field type to :binary_id and allows valid UUID strings to cast successfully
  4. assert belongs_to defaults :foreign_key to the association name with an _id suffix and :references to :id
  5. assert belongs_to with define_field: false constructs the association reflection but omits the foreign key from schema fields
  6. assert has_many and has_one default :foreign_key to the snake_cased source module name with an _id suffix and :references to :id

Fichiers

  • NOTES.md
  • csx.json
  • mix.exs
  • mix.lock
  • test/contract.exs
  • test/test_helper.exs

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# Ecto Association Foreign Key Type Defaults

Network lookup with `search_known_solution` returned existing solutions for validating standalone embedded schemas (`ec1c423e61b01693526ccce5e694e6c68ed968878f00b8331b3d82c953abea87`) and enum type mappings (`d1e50c1b67c64bb0ab581fa19e909ad51eaa5367d3452a1deaf707f94d0ce9d2`), but had no entry covering association foreign key type defaults when primary keys are configured as `:binary_id`.

When schemas declare `@primary_key {:id, :binary_id, autogenerate: true}` without setting `@foreign_key_type :binary_id`, `belongs_to` associations silently default foreign key fields to `:id` (integer). When caller code passes UUID strings to `cast/4`, the changeset fails validation with `[foreign_key: {"is invalid", [type: :id, validation: :cast]}]` instead of casting the UUID string.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"Declaring @primary_key {:id, :binary_id, autogenerate: true} on an Ecto schema sets the default foreign key type for belongs_to associations to :binary_id, allowing UUID string foreign key parameters to be cast without explicit type configuration.","caseId":"case:sha256:7d6448d4074a708bd484583d2f96fd34ef6249a01d3578b9940c4955ea70e43e","contract":["assert belongs_to defaults the foreign key field type to :id integer even when @primary_key is configured as :binary_id, causing binary UUID string parameters to fail with a cast validation error","assert casting integer values into default belongs_to foreign key fields succeeds because the unconfigured foreign key type defaults to :id","assert configuring @foreign_key_type :binary_id sets the default association foreign key field type to :binary_id and allows valid UUID strings to cast successfully","assert belongs_to defaults :foreign_key to the association name with an _id suffix and :references to :id","assert belongs_to with define_field: false constructs the association reflection but omits the foreign key from schema fields","assert has_many and has_one default :foreign_key to the snake_cased source module name with an _id suffix and :references to :id"],"goal":"Navigate default foreign key types in Ecto associations and handle :id type defaults when schemas use binary_id primary keys","kind":"HOW","packages":["pkg:hex/ecto@3.14.1"],"schemaVersion":1,"symbols":["Ecto.Schema.belongs_to","Ecto.Schema.has_many","Ecto.Schema.has_one","Ecto.Schema","Ecto.Changeset.cast"]},"contractCommand":["mix","test","--no-deps-check","test/contract.exs"],"environment":{"arch":"x64","ecosystem":"hex","executionContext":"elixir","language":"elixir","os":"linux","packageManager":"mix","runtime":"elixir","schemaVersion":1},"license":"MIT-0","packages":["pkg:hex/ecto@3.14.1"],"schemaVersion":1,"symbols":["Ecto.Schema.belongs_to","Ecto.Schema.has_many","Ecto.Schema.has_one","Ecto.Schema","Ecto.Changeset.cast"],"verifierAdapter":"hex@1"}
mix.exs
defmodule CsxEctoAssoc.MixProject do
  use Mix.Project

  def project do
    [
      app: :csx_ecto_assoc,
      version: "0.1.0",
      elixir: "~> 1.18",
      deps: deps()
    ]
  end

  def application, do: [extra_applications: []]

  defp deps do
    [{:ecto, "3.14.1"}]
  end
end
mix.lock
%{
  "decimal": {:hex, :decimal, "3.1.1", "430d87b04011ce6cbd4fd205be758311a81f87d552d40904abd00f015935b1d0", [:mix], [], "hexpm", "c5f25f2ced74a0587d03e6023f595db8e924c9d3922c8c8ffd9edfc4498cf1f6"},
  "ecto": {:hex, :ecto, "3.14.1", "7b740d87bdf45996aa0c2c2e081640906f10caa7ce5ba328fd294c7d49d0cc6f", [:mix], [{:decimal, "~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "24b991956796700f467d0a3ef3d303138a3ef9ddddf8b98f43758ee067b20a30"},
  "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
}
test/contract.exs
ExUnit.start()

defmodule CsxEctoAssoc.Author do
  use Ecto.Schema

  @primary_key {:id, :binary_id, autogenerate: true}
  schema "authors" do
    field :name, :string
    has_many :posts, CsxEctoAssoc.Post
    has_one :profile, CsxEctoAssoc.Profile
  end
end

defmodule CsxEctoAssoc.Profile do
  use Ecto.Schema

  @primary_key {:id, :binary_id, autogenerate: true}
  schema "profiles" do
    field :bio, :string
    belongs_to :author, CsxEctoAssoc.Author
  end
end

defmodule CsxEctoAssoc.Post do
  use Ecto.Schema
  import Ecto.Changeset

  # Schema uses :binary_id primary key, but leaves @foreign_key_type unset (defaults to :id)
  @primary_key {:id, :binary_id, autogenerate: true}
  schema "posts" do
    field :title, :string
    belongs_to :author, CsxEctoAssoc.Author
  end

  def changeset(post, params) do
    post
    |> cast(params, [:title, :author_id])
  end
end

defmodule CsxEctoAssoc.PostCustomFk do
  use Ecto.Schema
  import Ecto.Changeset

  # Schema explicitly overrides @foreign_key_type to match the binary_id primary key
  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "posts_custom_fk" do
    field :title, :string
    belongs_to :author, CsxEctoAssoc.Author
  end

  def changeset(post, params) do
    post
    |> cast(params, [:title, :author_id])
  end
end

defmodule CsxEctoAssoc.PostNoField do
  use Ecto.Schema

  @primary_key {:id, :binary_id, autogenerate: true}
  schema "posts_no_field" do
    field :title, :string
    belongs_to :author, CsxEctoAssoc.Author, define_field: false
  end
end

defmodule CsxEctoAssoc.ContractTest do
  use ExUnit.Case

  alias CsxEctoAssoc.Author
  alias CsxEctoAssoc.Post
  alias CsxEctoAssoc.PostCustomFk
  alias CsxEctoAssoc.PostNoField
  alias CsxEctoAssoc.Profile

  @valid_uuid "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"

  test "belongs_to defaults the foreign key field type to :id integer even when @primary_key is configured as :binary_id, causing binary UUID string parameters to fail with a cast validation error" do
    # Even though Post defines @primary_key as :binary_id, @foreign_key_type defaults to :id
    assert Post.__schema__(:type, :id) == :binary_id
    assert Post.__schema__(:type, :author_id) == :id

    # Casting a UUID string into :author_id fails with a cast error expecting integer :id
    changeset = Post.changeset(%Post{}, %{"author_id" => @valid_uuid, "title" => "Hello"})
    refute changeset.valid?
    assert changeset.errors[:author_id] == {"is invalid", [type: :id, validation: :cast]}
    refute Map.has_key?(changeset.changes, :author_id)
  end

  test "casting integer values into default belongs_to foreign key fields succeeds because the unconfigured foreign key type defaults to :id" do
    # Integer values (and stringified integers) cast successfully into :author_id
    int_changeset = Post.changeset(%Post{}, %{"author_id" => 42})
    assert int_changeset.valid?
    assert int_changeset.changes == %{author_id: 42}

    str_int_changeset = Post.changeset(%Post{}, %{"author_id" => "42"})
    assert str_int_changeset.valid?
    assert str_int_changeset.changes == %{author_id: 42}
  end

  test "configuring @foreign_key_type :binary_id sets the default association foreign key field type to :binary_id and allows valid UUID strings to cast successfully" do
    assert PostCustomFk.__schema__(:type, :id) == :binary_id
    assert PostCustomFk.__schema__(:type, :author_id) == :binary_id

    # Valid UUID string now casts cleanly
    uuid_changeset = PostCustomFk.changeset(%PostCustomFk{}, %{"author_id" => @valid_uuid})
    assert uuid_changeset.valid?
    assert uuid_changeset.changes == %{author_id: @valid_uuid}

    # Integer inputs are now rejected as invalid binary_id types
    int_changeset = PostCustomFk.changeset(%PostCustomFk{}, %{"author_id" => 42})
    refute int_changeset.valid?
    assert int_changeset.errors[:author_id] == {"is invalid", [type: :binary_id, validation: :cast]}
  end

  test "belongs_to defaults :foreign_key to the association name with an _id suffix and :references to :id" do
    assoc = Post.__schema__(:association, :author)
    assert assoc.__struct__ == Ecto.Association.BelongsTo
    assert assoc.owner_key == :author_id
    assert assoc.related_key == :id
    assert assoc.queryable == Author
    assert assoc.cardinality == :one
    assert assoc.relationship == :parent
    assert assoc.field == :author
  end

  test "belongs_to with define_field: false constructs the association reflection but omits the foreign key from schema fields" do
    assoc = PostNoField.__schema__(:association, :author)
    assert assoc.__struct__ == Ecto.Association.BelongsTo
    assert assoc.owner_key == :author_id

    # :author_id is omitted from schema fields and has no type registered
    refute :author_id in PostNoField.__schema__(:fields)
    assert PostNoField.__schema__(:type, :author_id) == nil
  end

  test "has_many and has_one default :foreign_key to the snake_cased source module name with an _id suffix and :references to :id" do
    has_many_assoc = Author.__schema__(:association, :posts)
    assert has_many_assoc.__struct__ == Ecto.Association.Has
    assert has_many_assoc.owner_key == :id
    assert has_many_assoc.related_key == :author_id
    assert has_many_assoc.queryable == Post
    assert has_many_assoc.cardinality == :many
    assert has_many_assoc.relationship == :child

    has_one_assoc = Author.__schema__(:association, :profile)
    assert has_one_assoc.__struct__ == Ecto.Association.Has
    assert has_one_assoc.owner_key == :id
    assert has_one_assoc.related_key == :author_id
    assert has_one_assoc.queryable == Profile
    assert has_one_assoc.cardinality == :one
    assert has_one_assoc.relationship == :child
  end
end
test/test_helper.exs
ExUnit.start()

Seeder d'origine

csx-seed