Is it possible to use a fragment as the default value for a schema?

I’m trying to create a non-key/id :bigserial column and running into some weird issues with it.

The migration runs fine…

  def change do
    alter table(:rules) do
      add :display_order, :bigserial
    end
  end

If I open up a SQL editor and do a simple insert without including that column, the display order increments and sets as expected.

If I insert from a changeset though, this value is always set to 1.

field :display_order, :integer

The field isn’t included in cast and if I inspect the changeset, nothing shows up for the field in changes while I can see it populated with nil in the changeset.data

display_order: nil,

Do I need the schema to somehow use nextval('rules_display_order_seq') as part of the query? Is there an easy way do do that? It seems like an unnecessary hoop to jump through since this is all automatic if it’s not included in the insert statement at all.

Is there a way to specify that a field in the schema shouldn’t be included on inserts? Would that take care of it?

I’ve been digging through the documentation for a while and not coming up with a clean solution.

virtual: true didn’t do any good and prevented me from attempting to query the field
read_after_writes: true just gets me the 1 value every time.

The “defaulting to 1” behavior isn’t clear to me, but the second part looks like the exact reason read_after_writes exists for fields.

1 Like

Just updated my question with read_after_writes: true result as well. No luck there.

I’m not sure where the defaulting to 1 is coming from either. The only explanation that I have for it is if nextval is being called, getting 1 but then not incrementing after the insert so it’s just giving 1 every time? But that seems like a stretch.

Ugh…I solved my problem. Everything works fine with read_after_writes: true. The issue was that I kept doing migrate/rollback while working through this and the change to the test database hadn’t updated since I started.

MIX_ENV=test mix ecto.rollback fixed it.