entc/gen: move mutation hooks logic to a shared generic function (#3180)

This commit is contained in:
Ariel Mashraki
2022-12-19 17:36:29 +02:00
committed by GitHub
parent 4e662b9e51
commit 34bd0b7b6f
443 changed files with 3082 additions and 19327 deletions

View File

@@ -56,49 +56,7 @@ func (uc *UserCreate) Mutation() *UserMutation {
// Save creates the User in the database.
func (uc *UserCreate) Save(ctx context.Context) (*User, error) {
var (
err error
node *User
)
if len(uc.hooks) == 0 {
if err = uc.check(); err != nil {
return nil, err
}
node, err = uc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = uc.check(); err != nil {
return nil, err
}
uc.mutation = mutation
if node, err = uc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(uc.hooks) - 1; i >= 0; i-- {
if uc.hooks[i] == nil {
return nil, fmt.Errorf("versioned: uninitialized hook (forgotten import versioned/runtime?)")
}
mut = uc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, uc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*User)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from UserMutation", v)
}
node = nv
}
return node, err
return withHooks[*User, UserMutation](ctx, uc.sqlSave, uc.mutation, uc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
@@ -140,6 +98,9 @@ func (uc *UserCreate) check() error {
}
func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) {
if err := uc.check(); err != nil {
return nil, err
}
_node, _spec := uc.createSpec()
if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
@@ -149,6 +110,8 @@ func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) {
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
uc.mutation.id = &_node.ID
uc.mutation.done = true
return _node, nil
}