From e05a8b324f6ffcc54b69ade23a624d328ba30bbe Mon Sep 17 00:00:00 2001 From: Jacob Swanner Date: Sat, 1 Mar 2025 11:38:16 -0800 Subject: [PATCH] Load virtual into schema struct References: - https://github.com/elixir-ecto/ecto/issues/4398 --- lib/ecto/schema.ex | 1 + test/ecto/embedded_test.exs | 4 ++++ test/ecto/repo_test.exs | 5 +++++ 3 files changed, 10 insertions(+) diff --git a/lib/ecto/schema.ex b/lib/ecto/schema.ex index c8768f1471..855237c670 100644 --- a/lib/ecto/schema.ex +++ b/lib/ecto/schema.ex @@ -2344,6 +2344,7 @@ defmodule Ecto.Schema do {name, type} end end + |> Keyword.merge(virtual_fields) dump = for {name, {type, writable}} <- fields do diff --git a/test/ecto/embedded_test.exs b/test/ecto/embedded_test.exs index 162107b6c2..a92dda8668 100644 --- a/test/ecto/embedded_test.exs +++ b/test/ecto/embedded_test.exs @@ -39,6 +39,7 @@ defmodule Ecto.EmbeddedTest do embedded_schema do field :dark_mode, :boolean, default: false + field :n, :integer, virtual: true embeds_one :default_post, Post, defaults_to_struct: true end end @@ -78,6 +79,9 @@ defmodule Ecto.EmbeddedTest do assert %Settings{dark_mode: false, default_post: nil} = Ecto.embedded_load(Settings, %{"default_post" => nil}, :json) + assert %Settings{n: 1} = + Ecto.embedded_load(Settings, %{"n" => 1}, :json) + assert_raise ArgumentError, ~s[cannot load `"ABC"` as type Ecto.UUID for field `uuid` in schema Ecto.EmbeddedTest.UUIDSchema], fn -> diff --git a/test/ecto/repo_test.exs b/test/ecto/repo_test.exs index 56fd4be402..d15d9d0f1f 100644 --- a/test/ecto/repo_test.exs +++ b/test/ecto/repo_test.exs @@ -66,6 +66,7 @@ defmodule Ecto.RepoTest do field :y, :binary, source: :yyy field :z, :string, default: "z" field :w, :string, virtual: true + field :n, :integer, virtual: true field :array, {:array, :string} field :map, {:map, :string} has_many :children, MySchemaChild @@ -230,6 +231,10 @@ defmodule Ecto.RepoTest do assert %MySchema{map: %{"color" => "red"}} = TestRepo.load(MySchema, %{map: %{"color" => "red"}}) + # virtual field + assert %MySchema{n: 1} = + TestRepo.load(MySchema, %{n: 1}) + # nil assert %MySchema{x: nil} = TestRepo.load(MySchema, %{x: nil})