ent / ent/ent

Constraint Failure Setting Required Edge for O2O Two Types When Upserting

Open
#4,089 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
17.2k
Forks
1k
PR merge metrics
No merged PRs in 30d

Description

- [x] The issue is present in the latest release.
- [x] I have searched the [issues](https://github.com/ent/ent/issues) of this repository and believe that this is not a duplicate.

## Current Behavior 😯

When setting an edge directly (i.e. `SetBarID()`) a constraint error is thrown when it is a required edge.

## Expected Behavior 🤔

**Problem statement**: Encountering constraint errors with required O2O edges in ent during upserts, seeking a more efficient solution than clearing and setting the edge

I am working through an interesting issue involving O2O edges with ent. When making the edge to bar required, whenever performing an upsert on the buzz entity will fail with a constraint error that Bar is already connected to a different Foo.

```
func (FooEntity) Edges() []ent.Edge {
return []ent.Edge{
edge.To("bar", BarEntity.Type).
Unique().
Required(), // breaks
}
}

func (BarEntity) Edges() []ent.Edge {
return []ent.Edge{
edge.From("FooEntity", FooEntity.Type).
Ref("buzz").
Field("foo_id").
Unique(), // one-to-one
}
}

// this throws a constraint error
client.fooentity.
Create().
... set fields....
SetBarID(foo.barID).
OnConflictColumns(barentity.FieldID).
UpdateNewValues()
```

To get around this, I use an inefficient, I believe, workaround to make the edge optional, and then clear the edge, and set the edge when upserting. See below

```
tx.Client().fooentity.
UpdateOneID(foo.ID()).
ClearBar().SetBarID(foo.BarID()).
Exec(ctx)
```

Business logic dictates this this O2O edge should be required, as fooentity will always maintain a relationship with bar. This solution feels wrong, and I should be able to set the edge directly and upsert. What am I missing?

## Steps to Reproduce 🕹

Steps:

1. Make a O2O two type required edge
2. set edge directly
3. try to upsert
4. witness constraint error

## Your Environment 🌎

| Tech | Version |
| ----------- | ------- |
| Go | 1.22.3 |
| Ent | 0.13.1 |
| Database | PostgresSQL 15.4 |
| Driver | "github.com/lib/pq" |

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.