Defining Ecto Schemas (PostGres) to use NOT NULL in column definitions

I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Consider the following schema:

schema "addresses" do
    field :name, :string, size: 100
    field :company, :string, size: 100
    field :street1, :string, size: 250
    field :street2, :string, size: 250
    field :city, :string, size: 100
    field :state, :string, size: 2
    field :zip, :string, size: 32
    field :zip4, :string, size: 4  # NOT NULL?
    timestamps()
  end

I would prefer that the zip4 column can never be null… is there a way to do this? I don’t see it referenced on https://hexdocs.pm/ecto/Ecto.Schema.html

Thanks!

1 Like

You don’t specify if a column can be null or not in the schema, you do it in the migration (by setting , null: false). :slight_smile:

Remember, Ecto does not duplicate checks that the database already does (as many are just impossible to know ahead of time, although this one could be, it’s good to keep consistency).

7 Likes

This is correct but it is possible to enforce this constraint in your changeset function, which will yield a nice Changeset error rather than an exception.You can use validate_required in your changeset function. I’d still set null: false in the migration.

7 Likes

It ‘should’ already be doing this if the changeset is set up right?

What is the full message of this exception (and your changeset code)? o.O

So far as I know, the “right” way to setup the changeset to make a field be required is to use the Changeset function validate_required. That is how we do it. If I take the validate_required function out of my Changeset and leave the field blank, I end up with a Postgrex exception along the lines:

** (exit) an exception was raised:
    ** (Postgrex.Error) ERROR 23502 (not_null_violation): null value in column "title" violates not-null constraint

    table: listings
    column: title

I don’t have any code I can share at the moment.

1 Like