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

:wave:

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)

ibarch

ibarch

In order to freely use both schema and schemaless queries and don’t bother yourself manually updating timestamps, you must move autoupdating logic from timestamps macro to the database layer. In PostgreSQL you can use the built-in moddatetime extension and its function with a trigger. Take a look at my examples.

axelson

axelson

Scenic Core Team

True! And also true for Repo.insert :slight_smile:

Where Next?

Popular in Questions Top

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
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement