Files
ent/examples/m2mbidi/ent/user_create.go
Alex Snast 373769dfaf ent/gen: adding EqualFold predicate for string fields
Summary: Similar to `ContainsFold` predicate requires `--storage=sql` argument to be passed to entc.

Reviewed By: a8m

Differential Revision: D17074805

fbshipit-source-id: ced299154417fe2c9007cd6a7a504f53c8b2ef98
2019-08-27 10:48:53 -07:00

119 lines
2.5 KiB
Go

// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"github.com/facebookincubator/ent/examples/m2mbidi/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
age *int
name *string
friends map[int]struct{}
}
// SetAge sets the age field.
func (uc *UserCreate) SetAge(i int) *UserCreate {
uc.age = &i
return uc
}
// SetName sets the name field.
func (uc *UserCreate) SetName(s string) *UserCreate {
uc.name = &s
return uc
}
// AddFriendIDs adds the friends edge to User by ids.
func (uc *UserCreate) AddFriendIDs(ids ...int) *UserCreate {
if uc.friends == nil {
uc.friends = make(map[int]struct{})
}
for i := range ids {
uc.friends[ids[i]] = struct{}{}
}
return uc
}
// AddFriends adds the friends edges to User.
func (uc *UserCreate) AddFriends(u ...*User) *UserCreate {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return uc.AddFriendIDs(ids...)
}
// Save creates the User in the database.
func (uc *UserCreate) Save(ctx context.Context) (*User, error) {
if uc.age == nil {
return nil, errors.New("ent: missing required field \"age\"")
}
if uc.name == nil {
return nil, errors.New("ent: missing required field \"name\"")
}
return uc.sqlSave(ctx)
}
// SaveX calls Save and panics if Save returns an error.
func (uc *UserCreate) SaveX(ctx context.Context) *User {
v, err := uc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) {
var (
res sql.Result
u = &User{config: uc.config}
)
tx, err := uc.driver.Tx(ctx)
if err != nil {
return nil, err
}
builder := sql.Insert(user.Table).Default(uc.driver.Dialect())
if uc.age != nil {
builder.Set(user.FieldAge, *uc.age)
u.Age = *uc.age
}
if uc.name != nil {
builder.Set(user.FieldName, *uc.name)
u.Name = *uc.name
}
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
id, err := res.LastInsertId()
if err != nil {
return nil, rollback(tx, err)
}
u.ID = int(id)
if len(uc.friends) > 0 {
for eid := range uc.friends {
query, args := sql.Insert(user.FriendsTable).
Columns(user.FriendsPrimaryKey[0], user.FriendsPrimaryKey[1]).
Values(id, eid).
Values(eid, id).
Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
return u, nil
}