fireproofsocks

fireproofsocks

Not_null_violation on seeding my database: timestamps() macro failing?

I’m able to create and migrate my database tables Ok. But when I try to seed it, I’m getting errors as soon as I encounter a table that uses the timestamps() macro in its migration definition:

** (Postgrex.Error) ERROR 23502 (not_null_violation) null value in column "inserted_at" violates not-null constraint

    table: tenants
    column: inserted_at

My migration looks like this:

defmodule Auth.Repo.Migrations.Tenants do
  use Ecto.Migration

  def change do
    create table(:tenants, primary_key: false) do
      add :id, :string, size: 16, null: false, primary_key: true # Slug
      add :status_id, references("tenants_statuses", type: :string), size: 10, null: false
      add :name, :string, size: 32, null: false, default: ""
      add :description, :text, null: false, default: ""
      timestamps()
    end
  end
end

And my seeds.exs like this:

alias Auth.Repo

Repo.insert_all(
  "tenants_statuses",
  [
    %{id: "on", name: "On", description: "Signups and logins for this tenant are enabled"},
    %{id: "off", name: "Off", description: "Signups and logins for this are disabled"},
  ]
)
Repo.insert_all(
  Auth.Schemas.Tenant,
  [
    %{
      id: "wholesale",
      name: "Wholesale",
      status_id: "on",
      description: "Deny Designs and the Wholesale channel",
    }
  ]
)

I’ve tried using both the string table name as the 1st argument or the schema module, but the error is the same. When I inspect the table inside PostGreSQL, I see that it has not defined a default value:

Column    |              Type              | Collation | Nullable |        Default        | Storage  | Stats target | Description 
-------------+--------------------------------+-----------+----------+-----------------------+----------+--------------+-------------
id          | character varying(16)          |           | not null |                       | extended |              | 
status_id   | character varying(10)          |           | not null |                       | extended |              | 
name        | character varying(32)          |           | not null | ''::character varying | extended |              | 
description | text                           |           | not null | ''::text              | extended |              | 
inserted_at | timestamp(0) without time zone |           | not null |                       | plain    |              | 
updated_at  | timestamp(0) without time zone |           | not null |                       | plain    |              | 

I thought that using timestamps() would set up a default value for both of those columns, but clearly I’m missing something. Can anyone point out what I’m missing? Thanks!

Most Liked

axelson

axelson

Scenic Core Team

Minor clarification, Repo.insert_all does use ecto schemas but does not autogenerate default values. From the docs for Repo.insert_all/3:

If the schema contains an autogenerated ID field, it will be handled either at the adapter or the storage layer. However any other autogenerated value, like timestamps, won’t be autogenerated when using insert_all/3 . This is by design as this function aims to be a more direct way to insert data into the database without the conveniences of insert/2 . This is also consistent with update_all/3 that does not handle timestamps as well.

idi527

idi527

:waving_hand:

The defaults come from your ecto schemas (if you use another timestamps() macro there), they are not generated in the database.

So since *_all functions like Repo.insert_all don’t use ecto schemas, there are no default timestamps being sent to the database thus violating the constraint.

fireproofsocks

fireproofsocks

Further clarification: Repo.insert_all MAY use Ecto Schemas (but it is not required to do so: you can simply pass the name of the table as a string). At various points I have tried removing my schema files altogether to avoid having my seeding operation dependent on them – it works fine (excepting the timestamps as discussed)

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New

We're in Beta

About us Mission Statement