mirror of
https://github.com/ent/ent.git
synced 2026-05-24 09:31:56 +03:00
entc/gen: move mutation hooks logic to a shared generic function (#3180)
This commit is contained in:
@@ -101,49 +101,7 @@ func (cc *CommentCreate) Mutation() *CommentMutation {
|
||||
|
||||
// Save creates the Comment in the database.
|
||||
func (cc *CommentCreate) Save(ctx context.Context) (*Comment, error) {
|
||||
var (
|
||||
err error
|
||||
node *Comment
|
||||
)
|
||||
if len(cc.hooks) == 0 {
|
||||
if err = cc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, err = cc.sqlSave(ctx)
|
||||
} else {
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*CommentMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err = cc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cc.mutation = mutation
|
||||
if node, err = cc.sqlSave(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &node.ID
|
||||
mutation.done = true
|
||||
return node, err
|
||||
})
|
||||
for i := len(cc.hooks) - 1; i >= 0; i-- {
|
||||
if cc.hooks[i] == nil {
|
||||
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = cc.hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, cc.mutation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nv, ok := v.(*Comment)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected node type %T returned from CommentMutation", v)
|
||||
}
|
||||
node = nv
|
||||
}
|
||||
return node, err
|
||||
return withHooks[*Comment, CommentMutation](ctx, cc.sqlSave, cc.mutation, cc.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
@@ -180,6 +138,9 @@ func (cc *CommentCreate) check() error {
|
||||
}
|
||||
|
||||
func (cc *CommentCreate) sqlSave(ctx context.Context) (*Comment, error) {
|
||||
if err := cc.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := cc.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
@@ -189,6 +150,8 @@ func (cc *CommentCreate) sqlSave(ctx context.Context) (*Comment, error) {
|
||||
}
|
||||
id := _spec.ID.Value.(int64)
|
||||
_node.ID = int(id)
|
||||
cc.mutation.id = &_node.ID
|
||||
cc.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user