CodeSampleX

샘플

ecto 3.14.1: Inspect Ecto parameterized type representation, normalize Ecto.Enum mapped inputs, and distinguish scalar from composite cast failure shapes

검증된 샘플 — hex ecto 3.14.1: Inspect Ecto parameterized type representation, normalize Ecto.Enum mapped inputs, and distinguish scalar from composite cast…

sha256:6c6fb613f0a59efec76da1c4c4b630f16524102c374f9718430edeb1abd1742e

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 elixir 1 linux x64 elixir 1 elixir mix

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
Inspect Ecto parameterized type representation, normalize Ecto.Enum mapped inputs, and distinguish scalar from composite cast failure shapes
패키지
심벌
  • Ecto.ParameterizedType
  • Ecto.Type.parameterized?
  • Ecto.Type.type
  • Ecto.Type.cast!
  • Ecto.Type.cast
  • Ecto.Type.dump
  • Ecto.Type.load
  • Ecto.Enum.values
  • Ecto.Enum.dump_values
  • Ecto.Enum.mappings
  • Ecto.Changeset.cast
  • Ecto.CastError
환경
elixir 1
생성일
2026-08-17T04:43:50Z

컨트랙트

  1. assert schema type for an Ecto.Enum is a 2-element tuple {:parameterized, {Ecto.Enum, info}} rather than a 3-element tuple, Ecto.Type.parameterized? identifies it, and Ecto.Type.type returns the underlying primitive storage type
  2. assert casting an Ecto.Enum with mapped values accepts atom keys, string names, and raw mapped integers, while rejecting stringified integers with inclusion metadata
  3. assert Ecto.Enum reflections distinguish between Elixir value atoms, database dump values, and key-value mappings
  4. assert Ecto.Type.cast! returns normalized scalar values and raises Ecto.CastError on failure, while invalid composite arrays collapse to :error and changesets omit the failing element index

파일

  • NOTES.md
  • csx.json
  • lib/account.ex
  • mix.exs
  • mix.lock
  • test/contract_test.exs
  • test/test_helper.exs

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Ecto Parameterized Types, Enum Mapped Values, and Type Casting Traps

## Search Result
`search_known_solution` returned related embedded-schema samples, but none covered this exact current contract. This sample explores the two-element representation of parameterized types, `Ecto.Type.parameterized?/2`, mapped `Ecto.Enum` input normalization, `Ecto.Type.cast!/2` exceptions, and the deliberately coarse error shape of composite array casts.

## What a Model Would Have Written Instead
A model may still pattern match parameterized types as `{:parameterized, module, params}`, call the nonexistent `Ecto.Type.parameterized?/1`, reject mapped integer inputs that current Ecto normalizes, expect `Ecto.Type.cast!` to return ok/error tuples, or promise a failing array element index that the public cast result does not contain.

## How the Wrong Version Fails
Those assumptions either call an undefined arity, take a fallback branch on the two-element tuple, reject valid mapped inputs, or overstate composite diagnostics: invalid arrays return `:error`, and their changeset error has no element index.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"Parameterized types in Ecto schemas are represented as three-element tuples of {:parameterized, module, params}, and casting an Ecto.Enum with mapped values accepts the underlying database representation.","caseId":"case:sha256:8ea51dc7265761d2c7da202c61638fa8e942ef1829d0cb63af224ce1b170798e","contract":["assert schema type for an Ecto.Enum is a 2-element tuple {:parameterized, {Ecto.Enum, info}} rather than a 3-element tuple, Ecto.Type.parameterized? identifies it, and Ecto.Type.type returns the underlying primitive storage type","assert casting an Ecto.Enum with mapped values accepts atom keys, string names, and raw mapped integers, while rejecting stringified integers with inclusion metadata","assert Ecto.Enum reflections distinguish between Elixir value atoms, database dump values, and key-value mappings","assert Ecto.Type.cast! returns normalized scalar values and raises Ecto.CastError on failure, while invalid composite arrays collapse to :error and changesets omit the failing element index"],"goal":"Inspect Ecto parameterized type representation, normalize Ecto.Enum mapped inputs, and distinguish scalar from composite cast failure shapes","kind":"HOW","packages":["pkg:hex/ecto@3.14.1"],"schemaVersion":1,"symbols":["Ecto.ParameterizedType","Ecto.Type.parameterized?","Ecto.Type.type","Ecto.Type.cast!","Ecto.Type.cast","Ecto.Type.dump","Ecto.Type.load","Ecto.Enum.values","Ecto.Enum.dump_values","Ecto.Enum.mappings","Ecto.Changeset.cast","Ecto.CastError"]},"contractCommand":["mix","test","--no-deps-check"],"environment":{"arch":"x64","ecosystem":"hex","executionContext":"elixir","language":"elixir","os":"linux","packageManager":"mix","runtime":"elixir","runtimeVersion":"1","schemaVersion":1},"license":"MIT-0","packages":["pkg:hex/ecto@3.14.1"],"schemaVersion":1,"symbols":["Ecto.ParameterizedType","Ecto.Type.parameterized?","Ecto.Type.type","Ecto.Type.cast!","Ecto.Type.cast","Ecto.Type.dump","Ecto.Type.load","Ecto.Enum.values","Ecto.Enum.dump_values","Ecto.Enum.mappings","Ecto.Changeset.cast","Ecto.CastError"],"verifierAdapter":"hex@1"}
lib/account.ex
defmodule CsxEctoTypes.Account do
  @moduledoc """
  Schema demonstrating Ecto.ParameterizedType, Ecto.Enum with mapped database values,
  writable schema fields, and composite types.
  """
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key false
  embedded_schema do
    field :username, :string
    field :role, Ecto.Enum, values: [:admin, :moderator, :member]
    field :status, Ecto.Enum, values: [active: 1, pending: 2, suspended: 3]
    field :scores, {:array, :integer}
  end

  @permitted [:username, :role, :status, :scores]

  def changeset(account, params) do
    account
    |> cast(params, @permitted)
    |> validate_required([:username, :role])
  end
end
mix.exs
defmodule CsxEctoTypes.MixProject do
  use Mix.Project

  def project do
    [
      app: :csx_ecto_types,
      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_test.exs
defmodule CsxEctoTypes.ContractTest do
  use ExUnit.Case

  alias CsxEctoTypes.Account

  test "parameterized types are 2-element tuples in Ecto 3.12+ and reflect base types" do
    # Prior to Ecto 3.12, parameterized types were represented internally as
    # 3-element tuples: {:parameterized, module, params}.
    # Starting in Ecto 3.12, they are represented as 2-element tuples:
    # {:parameterized, {module, params}}.
    # Pattern matching on the old 3-element tuple silently fails to match.
    role_type = Account.__schema__(:type, :role)

    assert match?({:parameterized, {Ecto.Enum, _}}, role_type)
    assert tuple_size(role_type) == 2

    # parameterized?/2 checks both the representation and the implementing module.
    assert Ecto.Type.parameterized?(role_type, Ecto.Enum)
    refute Ecto.Type.parameterized?(:string, Ecto.Enum)
    refute Ecto.Type.parameterized?({:array, :integer}, Ecto.Enum)

    # Ecto.Type.type/1 resolves the underlying primitive storage type
    assert Ecto.Type.type(role_type) == :string

    status_type = Account.__schema__(:type, :status)
    assert match?({:parameterized, {Ecto.Enum, _}}, status_type)
    assert Ecto.Type.type(status_type) == :integer
  end

  test "Ecto.Enum with mapped values accepts raw database values but rejects mismatched representations" do
    # For field :status, Ecto.Enum, values: [active: 1, pending: 2, suspended: 3]
    # Current Ecto accepts the integer database representation as well as declared keys,
    # but a stringified integer is outside both accepted sets.

    good_atom = Account.changeset(%Account{}, %{"username" => "ada", "role" => "admin", "status" => :active})
    assert good_atom.valid?
    assert good_atom.changes.status == :active

    good_string = Account.changeset(%Account{}, %{"username" => "ada", "role" => "admin", "status" => "active"})
    assert good_string.valid?
    assert good_string.changes.status == :active

    mapped_int = Account.changeset(%Account{}, %{"username" => "ada", "role" => "admin", "status" => 1})
    assert mapped_int.valid?
    assert mapped_int.changes.status == :active

    bad_string = Account.changeset(%Account{}, %{"username" => "ada", "role" => "admin", "status" => "1"})
    refute bad_string.valid?
    refute Map.has_key?(bad_string.changes, :status)
    assert {msg, opts} = bad_string.errors[:status]
    assert msg == "is invalid"
    assert opts[:validation] == :inclusion

    # Ecto.Type confirms the lifecycle split:
    # cast converts user/external input to Elixir terms, dump converts to DB, load converts DB to Elixir
    status_type = Account.__schema__(:type, :status)
    assert Ecto.Type.cast(status_type, "active") == {:ok, :active}
    assert Ecto.Type.cast(status_type, 1) == {:ok, :active}
    assert match?({:error, _}, Ecto.Type.cast(status_type, "1"))
    assert Ecto.Type.dump(status_type, :active) == {:ok, 1}
    assert Ecto.Type.load(status_type, 1) == {:ok, :active}
  end

  test "Ecto.Enum reflections differentiate Elixir values, dump values, and key-value mappings" do
    # Ecto.Enum provides reflection helpers to inspect the defined enum metadata.
    # values/2 returns the Elixir atoms, dump_values/2 returns the storage terms,
    # and mappings/2 returns the keyword pairing.
    assert Ecto.Enum.values(Account, :status) == [:active, :pending, :suspended]
    assert Ecto.Enum.dump_values(Account, :status) == [1, 2, 3]
    assert Ecto.Enum.mappings(Account, :status) == [active: 1, pending: 2, suspended: 3]

    # For string-backed enums (values: [:admin, :moderator, :member])
    assert Ecto.Enum.values(Account, :role) == [:admin, :moderator, :member]
    assert Ecto.Enum.dump_values(Account, :role) == ["admin", "moderator", "member"]
    assert Ecto.Enum.mappings(Account, :role) == [admin: "admin", moderator: "moderator", member: "member"]
  end

  test "Ecto.Type.cast! unwraps or raises while composite array failures collapse to :error" do
    status_type = Account.__schema__(:type, :status)

    # Ecto.Type.cast!/2 returns the unwrapped cast value directly
    assert Ecto.Type.cast!(:integer, "42") == 42
    assert Ecto.Type.cast!(status_type, "pending") == :pending

    # On invalid input, cast!/2 raises Ecto.CastError (not ArgumentError)
    assert_raise Ecto.CastError, fn ->
      Ecto.Type.cast!(:integer, "not_an_int")
    end

    assert Ecto.Type.cast!(status_type, 2) == :pending

    assert_raise Ecto.CastError, fn ->
      Ecto.Type.cast!(status_type, "2")
    end

    # Composite array casting reports only :error; it does not expose the failing index.
    assert Ecto.Type.cast({:array, :integer}, ["10", "invalid", "30"]) == :error

    bad_changeset = Account.changeset(%Account{}, %{"username" => "ada", "role" => "admin", "scores" => ["10", "bad"]})
    refute bad_changeset.valid?
    assert bad_changeset.errors[:scores] ==
             {"is invalid", [type: {:array, :integer}, validation: :cast]}
  end

end
test/test_helper.exs
ExUnit.start()

오리진 시더

csx-seed