Gigitsu
Hi everyone ![]()
I’m trying to improve the typespecs in my application contexts, but I’m running into dialyzer errors when dealing with schemas that have fields that can be nil.
Here’s an example:
defmodule MyApp.User do
use Ecto.Schema
import Ecto.Changeset
@type t :: %__MODULE__{
id: integer(),
email: String.t(),
age: non_neg_integer()
}
schema "users" do
field :email, :string
field :age, :integer
end
def changeset(user, attrs) do
user |> cast(attrs, [:email, :age]) |> validate_required(:email)
end
end
defmodule MyApp.UsersContext do
alias MyApp.User
@spec change_user(user :: User.t(), attrs :: map()) :: Ecto.Changeset.t()
def change_user(%User{} = user, attrs \\ %{}) do
User.changeset(user, attrs)
end
end
defmodule MyApp.FakeController do
alias MyApp.User
def index() do
MyApp.UsersContext.change_user(%User{}, %{})
:ok
end
end
In this schema, there are no default values so %User{} will generate a struct where every field is nil.
Using this setup, dialyzer complains with:
The function call will not succeed.
MyApp.UsersContext.change_user(
%MyApp.User{
:__meta__ => %Ecto.Schema.Metadata{
:context => nil,
:prefix => nil,
:schema => MyApp.User,
:source => <<117, 115, 101, 114, 115>>,
:state => :built
},
:age => nil,
:email => nil,
:id => nil
},
%{}
)
breaks the contract
(user :: MyApp.User.t(), attrs :: map()) :: Ecto.Changeset.t()
To fix this error I have to explicitly put | nil in MyApp.User.t() type:
@type t :: %__MODULE__{
id: integer() | nil,
email: String.t() | nil,
age: non_neg_integer() | nil
}
But here are some things I’m unsure about:
- Is it idiomatic to be so explicit with
| nilfor every nullable field? - Is there a better or preferred way to declare the schema type (
@type t) that keeps it maintainable and readable, especially in large schemas?
Another possible solution I’ve found is to declare, somewhere in the codebase, a generic schema typespec:
@type schema_t(schema) :: %{
optional(atom) => any,
__struct__: schema,
__meta__: Ecto.Schema.Metadata.t(schema)
}
and use it in my specs:
@spec change_user(user :: schema_t(User), attrs :: map()) :: Ecto.Changeset.t()
Curious how others approach this.
Thanks!
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m aware of 2 such projects, are there others?
git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
Hi everyone.
My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
Hello folks!
So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
How Can I Optimise Compile Time Dependencies
I have been building an elixir application for about 2 years now. Many modules and files ha...
New
Other Trending Topics
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with.
But I don’t use it anymore.
Serverless was the promis...
New
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #ai
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #performance










Showing Posts 1 to 6- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
benwilson512
The short answer is yes.
integer()is simply different frominteger() | nil. Your code is using%User{}which absolutely does not have anidvalue yet, it hasn’t been saved to the DB, so it isn’t valid to claim it has an integer id in all cases.If you had code which did
user.id + 10that’s going to raise an exception, and you WANT dialyzer to give you heads up about such things.billylanchantin
There’s also the
TypedEctoSchemalibrary:It auto-generates the typespec boiler plate for your Ecto schemas. It has sensible defaults, and you can use
::inline to override the typespec for a specific fields.Gigitsu
@benwilson512 so being explicit is the only option here. I was hoping there’d be a shortcut for defining nullable fields. Thanks!
@billylanchantin thank you for the answer. I’ve seen some libraries (like the one you provided) used to help with this, but I’m trying to keep things vanilla Ecto if possible.
dogweather
TypedEctoSchema and TypedStruct are life-savers. They eliminate unnecessary verbosity and make schema definitions readable.
zorn
In some of my recent projects, I’ve preferred to model the schema type to be a description of a
repo-sourced value, thus allowing me to type things likeinserted_at: DateTime.t()instead ofinserted_at: DateTime.t() | nil.To allow for some functions which expected a non-repo-sourced value I would make a
@type struct_t() :: %__MODULE__{}.https://github.com/zorn/dustoff/blob/c0b45d8db2fceb36eeeff65e874e3ff95e6655ad/lib/dustoff/accounts/user_token.ex#L23-L41
I can’t say I observe many other Elixir codebases doing this, and my quick round-the-room check with some other devs says this nuance was not on their radar.
Gigitsu
I like this approach, and your
struct_tresembles my idea of aschema_ttype, though with less enforcement. Thank you.I agree. I once wrote a
typed_schemamacro myself, but it started to feel like it was adding unnecessary complexity and non-standard conventions on top of Ecto, so I went back to manually crafted typespecs.