サンプル
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
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
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
コントラクト
- 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
ファイル
- NOTES.md
- csx.json
- lib/account.ex
- mix.exs
- mix.lock
- test/contract_test.exs
- test/test_helper.exs
ソース
# 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.
{"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"}
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
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
%{
"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"},
}
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
ExUnit.start()