Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Uniq column error #385

Closed
Adzz opened this issue Jun 23, 2020 · 2 comments
Closed

Uniq column error #385

Adzz opened this issue Jun 23, 2020 · 2 comments

Comments

@Adzz
Copy link

Adzz commented Jun 23, 2020

I have this factory:

def thing_factory() do
  %Thing{name: Ecto.UUID.generate()}
end

name is a column with a unique index.

When I do this:

for _ <- 1..5 do
  thing = build(:thing)
  insert_list(4, :other_thing, thing: thing)
end

I get:

 ** (Ecto.ConstraintError) constraint error when attempting to insert struct:
 * thing_name_index (unique_constraint)

essentially saying the name is not uniq. If I change it to this it works:

for _ <- 1..5 do
  thing = insert(:thing)
  insert_list(4, :other_thing, thing: thing)
end

Am I doing something wrong?

@germsvel
Copy link
Collaborator

Hi @Adzz, I'm not a 100% sure, but I think this is what's happening.

First, I think the for comprehension is irrelevant to the problem. So think doing this will still trigger the error:

thing = build(:thing)
insert_list(4, :other_thing, thing: thing)

build(:thing) just creates a struct with the auto-generated UUID. You're then trying to insert 4 :other_thing, each of which has an associated (but not inserted) thing with the same name.

# insert :other_thing_1 (and insert :thing with auto generated UUID) => succeeds
# insert :other_thing_2 (and attempt to insert :thing with same UUID) => fails b/c that UUID is already in the database. 
# :other_thing 3 and 4 aren't even attempted

If you insert(:thing) instead of just build(:thing) to begin with, insert_list(:other_thing) will not attempt to insert thing when it's recursively inserting those 4 records.

Does that make sense? I hope this helps!

@germsvel
Copy link
Collaborator

germsvel commented Dec 8, 2020

Opened up a PR that I think fixes this issue. Let me know what you think -> #406

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants