ent/doc: m2m bidi example

Reviewed By: alexsn

Differential Revision: D17051159

fbshipit-source-id: 38a10d91e9d39db5381edc4c1cc4d4fe09655d6e
This commit is contained in:
Ariel Mashraki
2019-08-26 08:00:21 -07:00
committed by Facebook Github Bot
parent 7c3c4ff834
commit 0572a78e4c
24 changed files with 2439 additions and 7 deletions

View File

@@ -0,0 +1,118 @@
// 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
}