Gigitsu

Gigitsu

Hi everyone :waving_hand:

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 | nil for 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!

Showing Posts 1 to 6

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

The short answer is yes.

integer() is simply different from integer() | nil. Your code is using %User{} which absolutely does not have an id value 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 + 10 that’s going to raise an exception, and you WANT dialyzer to give you heads up about such things.

billylanchantin

billylanchantin

Curious how others approach this.

There’s also the TypedEctoSchema library:

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

Gigitsu OP

@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

dogweather

TypedEctoSchema and TypedStruct are life-savers. They eliminate unnecessary verbosity and make schema definitions readable.

zorn

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 like inserted_at: DateTime.t() instead of inserted_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

Gigitsu OP

I like this approach, and your struct_t resembles my idea of a schema_t type, though with less enforcement. Thank you.

I agree. I once wrote a typed_schema macro 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.

— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews