// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"
	"time"

	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
	"github.com/lightsparkdev/spark/common/keys"
	"github.com/lightsparkdev/spark/so/ent/depositaddress"
	"github.com/lightsparkdev/spark/so/ent/schema/schematype"
	"github.com/lightsparkdev/spark/so/ent/tree"
	"github.com/lightsparkdev/spark/so/ent/treenode"
)

// TreeCreate is the builder for creating a Tree entity.
type TreeCreate struct {
	config
	mutation *TreeMutation
	hooks    []Hook
	conflict []sql.ConflictOption
}

// SetCreateTime sets the "create_time" field.
func (tc *TreeCreate) SetCreateTime(t time.Time) *TreeCreate {
	tc.mutation.SetCreateTime(t)
	return tc
}

// SetNillableCreateTime sets the "create_time" field if the given value is not nil.
func (tc *TreeCreate) SetNillableCreateTime(t *time.Time) *TreeCreate {
	if t != nil {
		tc.SetCreateTime(*t)
	}
	return tc
}

// SetUpdateTime sets the "update_time" field.
func (tc *TreeCreate) SetUpdateTime(t time.Time) *TreeCreate {
	tc.mutation.SetUpdateTime(t)
	return tc
}

// SetNillableUpdateTime sets the "update_time" field if the given value is not nil.
func (tc *TreeCreate) SetNillableUpdateTime(t *time.Time) *TreeCreate {
	if t != nil {
		tc.SetUpdateTime(*t)
	}
	return tc
}

// SetOwnerIdentityPubkey sets the "owner_identity_pubkey" field.
func (tc *TreeCreate) SetOwnerIdentityPubkey(k keys.Public) *TreeCreate {
	tc.mutation.SetOwnerIdentityPubkey(k)
	return tc
}

// SetStatus sets the "status" field.
func (tc *TreeCreate) SetStatus(ss schematype.TreeStatus) *TreeCreate {
	tc.mutation.SetStatus(ss)
	return tc
}

// SetNetwork sets the "network" field.
func (tc *TreeCreate) SetNetwork(s schematype.Network) *TreeCreate {
	tc.mutation.SetNetwork(s)
	return tc
}

// SetBaseTxid sets the "base_txid" field.
func (tc *TreeCreate) SetBaseTxid(b []byte) *TreeCreate {
	tc.mutation.SetBaseTxid(b)
	return tc
}

// SetVout sets the "vout" field.
func (tc *TreeCreate) SetVout(i int16) *TreeCreate {
	tc.mutation.SetVout(i)
	return tc
}

// SetID sets the "id" field.
func (tc *TreeCreate) SetID(u uuid.UUID) *TreeCreate {
	tc.mutation.SetID(u)
	return tc
}

// SetNillableID sets the "id" field if the given value is not nil.
func (tc *TreeCreate) SetNillableID(u *uuid.UUID) *TreeCreate {
	if u != nil {
		tc.SetID(*u)
	}
	return tc
}

// SetRootID sets the "root" edge to the TreeNode entity by ID.
func (tc *TreeCreate) SetRootID(id uuid.UUID) *TreeCreate {
	tc.mutation.SetRootID(id)
	return tc
}

// SetNillableRootID sets the "root" edge to the TreeNode entity by ID if the given value is not nil.
func (tc *TreeCreate) SetNillableRootID(id *uuid.UUID) *TreeCreate {
	if id != nil {
		tc = tc.SetRootID(*id)
	}
	return tc
}

// SetRoot sets the "root" edge to the TreeNode entity.
func (tc *TreeCreate) SetRoot(t *TreeNode) *TreeCreate {
	return tc.SetRootID(t.ID)
}

// AddNodeIDs adds the "nodes" edge to the TreeNode entity by IDs.
func (tc *TreeCreate) AddNodeIDs(ids ...uuid.UUID) *TreeCreate {
	tc.mutation.AddNodeIDs(ids...)
	return tc
}

// AddNodes adds the "nodes" edges to the TreeNode entity.
func (tc *TreeCreate) AddNodes(t ...*TreeNode) *TreeCreate {
	ids := make([]uuid.UUID, len(t))
	for i := range t {
		ids[i] = t[i].ID
	}
	return tc.AddNodeIDs(ids...)
}

// SetDepositAddressID sets the "deposit_address" edge to the DepositAddress entity by ID.
func (tc *TreeCreate) SetDepositAddressID(id uuid.UUID) *TreeCreate {
	tc.mutation.SetDepositAddressID(id)
	return tc
}

// SetNillableDepositAddressID sets the "deposit_address" edge to the DepositAddress entity by ID if the given value is not nil.
func (tc *TreeCreate) SetNillableDepositAddressID(id *uuid.UUID) *TreeCreate {
	if id != nil {
		tc = tc.SetDepositAddressID(*id)
	}
	return tc
}

// SetDepositAddress sets the "deposit_address" edge to the DepositAddress entity.
func (tc *TreeCreate) SetDepositAddress(d *DepositAddress) *TreeCreate {
	return tc.SetDepositAddressID(d.ID)
}

// Mutation returns the TreeMutation object of the builder.
func (tc *TreeCreate) Mutation() *TreeMutation {
	return tc.mutation
}

// Save creates the Tree in the database.
func (tc *TreeCreate) Save(ctx context.Context) (*Tree, error) {
	tc.defaults()
	return withHooks(ctx, tc.sqlSave, tc.mutation, tc.hooks)
}

// SaveX calls Save and panics if Save returns an error.
func (tc *TreeCreate) SaveX(ctx context.Context) *Tree {
	v, err := tc.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

// Exec executes the query.
func (tc *TreeCreate) Exec(ctx context.Context) error {
	_, err := tc.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (tc *TreeCreate) ExecX(ctx context.Context) {
	if err := tc.Exec(ctx); err != nil {
		panic(err)
	}
}

// defaults sets the default values of the builder before save.
func (tc *TreeCreate) defaults() {
	if _, ok := tc.mutation.CreateTime(); !ok {
		v := tree.DefaultCreateTime()
		tc.mutation.SetCreateTime(v)
	}
	if _, ok := tc.mutation.UpdateTime(); !ok {
		v := tree.DefaultUpdateTime()
		tc.mutation.SetUpdateTime(v)
	}
	if _, ok := tc.mutation.ID(); !ok {
		v := tree.DefaultID()
		tc.mutation.SetID(v)
	}
}

// check runs all checks and user-defined validators on the builder.
func (tc *TreeCreate) check() error {
	if _, ok := tc.mutation.CreateTime(); !ok {
		return &ValidationError{Name: "create_time", err: errors.New(`ent: missing required field "Tree.create_time"`)}
	}
	if _, ok := tc.mutation.UpdateTime(); !ok {
		return &ValidationError{Name: "update_time", err: errors.New(`ent: missing required field "Tree.update_time"`)}
	}
	if _, ok := tc.mutation.OwnerIdentityPubkey(); !ok {
		return &ValidationError{Name: "owner_identity_pubkey", err: errors.New(`ent: missing required field "Tree.owner_identity_pubkey"`)}
	}
	if _, ok := tc.mutation.Status(); !ok {
		return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "Tree.status"`)}
	}
	if v, ok := tc.mutation.Status(); ok {
		if err := tree.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Tree.status": %w`, err)}
		}
	}
	if _, ok := tc.mutation.Network(); !ok {
		return &ValidationError{Name: "network", err: errors.New(`ent: missing required field "Tree.network"`)}
	}
	if v, ok := tc.mutation.Network(); ok {
		if err := tree.NetworkValidator(v); err != nil {
			return &ValidationError{Name: "network", err: fmt.Errorf(`ent: validator failed for field "Tree.network": %w`, err)}
		}
	}
	if _, ok := tc.mutation.BaseTxid(); !ok {
		return &ValidationError{Name: "base_txid", err: errors.New(`ent: missing required field "Tree.base_txid"`)}
	}
	if v, ok := tc.mutation.BaseTxid(); ok {
		if err := tree.BaseTxidValidator(v); err != nil {
			return &ValidationError{Name: "base_txid", err: fmt.Errorf(`ent: validator failed for field "Tree.base_txid": %w`, err)}
		}
	}
	if _, ok := tc.mutation.Vout(); !ok {
		return &ValidationError{Name: "vout", err: errors.New(`ent: missing required field "Tree.vout"`)}
	}
	if v, ok := tc.mutation.Vout(); ok {
		if err := tree.VoutValidator(v); err != nil {
			return &ValidationError{Name: "vout", err: fmt.Errorf(`ent: validator failed for field "Tree.vout": %w`, err)}
		}
	}
	return nil
}

func (tc *TreeCreate) sqlSave(ctx context.Context) (*Tree, error) {
	if err := tc.check(); err != nil {
		return nil, err
	}
	_node, _spec := tc.createSpec()
	if err := sqlgraph.CreateNode(ctx, tc.driver, _spec); err != nil {
		if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	if _spec.ID.Value != nil {
		if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
			_node.ID = *id
		} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
			return nil, err
		}
	}
	tc.mutation.id = &_node.ID
	tc.mutation.done = true
	return _node, nil
}

func (tc *TreeCreate) createSpec() (*Tree, *sqlgraph.CreateSpec) {
	var (
		_node = &Tree{config: tc.config}
		_spec = sqlgraph.NewCreateSpec(tree.Table, sqlgraph.NewFieldSpec(tree.FieldID, field.TypeUUID))
	)
	_spec.OnConflict = tc.conflict
	if id, ok := tc.mutation.ID(); ok {
		_node.ID = id
		_spec.ID.Value = &id
	}
	if value, ok := tc.mutation.CreateTime(); ok {
		_spec.SetField(tree.FieldCreateTime, field.TypeTime, value)
		_node.CreateTime = value
	}
	if value, ok := tc.mutation.UpdateTime(); ok {
		_spec.SetField(tree.FieldUpdateTime, field.TypeTime, value)
		_node.UpdateTime = value
	}
	if value, ok := tc.mutation.OwnerIdentityPubkey(); ok {
		_spec.SetField(tree.FieldOwnerIdentityPubkey, field.TypeBytes, value)
		_node.OwnerIdentityPubkey = value
	}
	if value, ok := tc.mutation.Status(); ok {
		_spec.SetField(tree.FieldStatus, field.TypeEnum, value)
		_node.Status = value
	}
	if value, ok := tc.mutation.Network(); ok {
		_spec.SetField(tree.FieldNetwork, field.TypeEnum, value)
		_node.Network = value
	}
	if value, ok := tc.mutation.BaseTxid(); ok {
		_spec.SetField(tree.FieldBaseTxid, field.TypeBytes, value)
		_node.BaseTxid = value
	}
	if value, ok := tc.mutation.Vout(); ok {
		_spec.SetField(tree.FieldVout, field.TypeInt16, value)
		_node.Vout = value
	}
	if nodes := tc.mutation.RootIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: false,
			Table:   tree.RootTable,
			Columns: []string{tree.RootColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(treenode.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.tree_root = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := tc.mutation.NodesIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2M,
			Inverse: true,
			Table:   tree.NodesTable,
			Columns: []string{tree.NodesColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(treenode.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges = append(_spec.Edges, edge)
	}
	if nodes := tc.mutation.DepositAddressIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.O2O,
			Inverse: true,
			Table:   tree.DepositAddressTable,
			Columns: []string{tree.DepositAddressColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(depositaddress.FieldID, field.TypeUUID),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_node.deposit_address_tree = &nodes[0]
		_spec.Edges = append(_spec.Edges, edge)
	}
	return _node, _spec
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Tree.Create().
//		SetCreateTime(v).
//		OnConflict(
//			// Update the row with the new values
//			// the was proposed for insertion.
//			sql.ResolveWithNewValues(),
//		).
//		// Override some of the fields with custom
//		// update values.
//		Update(func(u *ent.TreeUpsert) {
//			SetCreateTime(v+v).
//		}).
//		Exec(ctx)
func (tc *TreeCreate) OnConflict(opts ...sql.ConflictOption) *TreeUpsertOne {
	tc.conflict = opts
	return &TreeUpsertOne{
		create: tc,
	}
}

// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
//	client.Tree.Create().
//		OnConflict(sql.ConflictColumns(columns...)).
//		Exec(ctx)
func (tc *TreeCreate) OnConflictColumns(columns ...string) *TreeUpsertOne {
	tc.conflict = append(tc.conflict, sql.ConflictColumns(columns...))
	return &TreeUpsertOne{
		create: tc,
	}
}

type (
	// TreeUpsertOne is the builder for "upsert"-ing
	//  one Tree node.
	TreeUpsertOne struct {
		create *TreeCreate
	}

	// TreeUpsert is the "OnConflict" setter.
	TreeUpsert struct {
		*sql.UpdateSet
	}
)

// SetUpdateTime sets the "update_time" field.
func (u *TreeUpsert) SetUpdateTime(v time.Time) *TreeUpsert {
	u.Set(tree.FieldUpdateTime, v)
	return u
}

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *TreeUpsert) UpdateUpdateTime() *TreeUpsert {
	u.SetExcluded(tree.FieldUpdateTime)
	return u
}

// SetOwnerIdentityPubkey sets the "owner_identity_pubkey" field.
func (u *TreeUpsert) SetOwnerIdentityPubkey(v keys.Public) *TreeUpsert {
	u.Set(tree.FieldOwnerIdentityPubkey, v)
	return u
}

// UpdateOwnerIdentityPubkey sets the "owner_identity_pubkey" field to the value that was provided on create.
func (u *TreeUpsert) UpdateOwnerIdentityPubkey() *TreeUpsert {
	u.SetExcluded(tree.FieldOwnerIdentityPubkey)
	return u
}

// SetStatus sets the "status" field.
func (u *TreeUpsert) SetStatus(v schematype.TreeStatus) *TreeUpsert {
	u.Set(tree.FieldStatus, v)
	return u
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *TreeUpsert) UpdateStatus() *TreeUpsert {
	u.SetExcluded(tree.FieldStatus)
	return u
}

// SetNetwork sets the "network" field.
func (u *TreeUpsert) SetNetwork(v schematype.Network) *TreeUpsert {
	u.Set(tree.FieldNetwork, v)
	return u
}

// UpdateNetwork sets the "network" field to the value that was provided on create.
func (u *TreeUpsert) UpdateNetwork() *TreeUpsert {
	u.SetExcluded(tree.FieldNetwork)
	return u
}

// SetBaseTxid sets the "base_txid" field.
func (u *TreeUpsert) SetBaseTxid(v []byte) *TreeUpsert {
	u.Set(tree.FieldBaseTxid, v)
	return u
}

// UpdateBaseTxid sets the "base_txid" field to the value that was provided on create.
func (u *TreeUpsert) UpdateBaseTxid() *TreeUpsert {
	u.SetExcluded(tree.FieldBaseTxid)
	return u
}

// SetVout sets the "vout" field.
func (u *TreeUpsert) SetVout(v int16) *TreeUpsert {
	u.Set(tree.FieldVout, v)
	return u
}

// UpdateVout sets the "vout" field to the value that was provided on create.
func (u *TreeUpsert) UpdateVout() *TreeUpsert {
	u.SetExcluded(tree.FieldVout)
	return u
}

// AddVout adds v to the "vout" field.
func (u *TreeUpsert) AddVout(v int16) *TreeUpsert {
	u.Add(tree.FieldVout, v)
	return u
}

// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
// Using this option is equivalent to using:
//
//	client.Tree.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(tree.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *TreeUpsertOne) UpdateNewValues() *TreeUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
		if _, exists := u.create.mutation.ID(); exists {
			s.SetIgnore(tree.FieldID)
		}
		if _, exists := u.create.mutation.CreateTime(); exists {
			s.SetIgnore(tree.FieldCreateTime)
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.Tree.Create().
//	    OnConflict(sql.ResolveWithIgnore()).
//	    Exec(ctx)
func (u *TreeUpsertOne) Ignore() *TreeUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
	return u
}

// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *TreeUpsertOne) DoNothing() *TreeUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

// Update allows overriding fields `UPDATE` values. See the TreeCreate.OnConflict
// documentation for more info.
func (u *TreeUpsertOne) Update(set func(*TreeUpsert)) *TreeUpsertOne {
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
		set(&TreeUpsert{UpdateSet: update})
	}))
	return u
}

// SetUpdateTime sets the "update_time" field.
func (u *TreeUpsertOne) SetUpdateTime(v time.Time) *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.SetUpdateTime(v)
	})
}

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *TreeUpsertOne) UpdateUpdateTime() *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateUpdateTime()
	})
}

// SetOwnerIdentityPubkey sets the "owner_identity_pubkey" field.
func (u *TreeUpsertOne) SetOwnerIdentityPubkey(v keys.Public) *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.SetOwnerIdentityPubkey(v)
	})
}

// UpdateOwnerIdentityPubkey sets the "owner_identity_pubkey" field to the value that was provided on create.
func (u *TreeUpsertOne) UpdateOwnerIdentityPubkey() *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateOwnerIdentityPubkey()
	})
}

// SetStatus sets the "status" field.
func (u *TreeUpsertOne) SetStatus(v schematype.TreeStatus) *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.SetStatus(v)
	})
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *TreeUpsertOne) UpdateStatus() *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateStatus()
	})
}

// SetNetwork sets the "network" field.
func (u *TreeUpsertOne) SetNetwork(v schematype.Network) *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.SetNetwork(v)
	})
}

// UpdateNetwork sets the "network" field to the value that was provided on create.
func (u *TreeUpsertOne) UpdateNetwork() *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateNetwork()
	})
}

// SetBaseTxid sets the "base_txid" field.
func (u *TreeUpsertOne) SetBaseTxid(v []byte) *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.SetBaseTxid(v)
	})
}

// UpdateBaseTxid sets the "base_txid" field to the value that was provided on create.
func (u *TreeUpsertOne) UpdateBaseTxid() *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateBaseTxid()
	})
}

// SetVout sets the "vout" field.
func (u *TreeUpsertOne) SetVout(v int16) *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.SetVout(v)
	})
}

// AddVout adds v to the "vout" field.
func (u *TreeUpsertOne) AddVout(v int16) *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.AddVout(v)
	})
}

// UpdateVout sets the "vout" field to the value that was provided on create.
func (u *TreeUpsertOne) UpdateVout() *TreeUpsertOne {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateVout()
	})
}

// Exec executes the query.
func (u *TreeUpsertOne) Exec(ctx context.Context) error {
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for TreeCreate.OnConflict")
	}
	return u.create.Exec(ctx)
}

// ExecX is like Exec, but panics if an error occurs.
func (u *TreeUpsertOne) ExecX(ctx context.Context) {
	if err := u.create.Exec(ctx); err != nil {
		panic(err)
	}
}

// Exec executes the UPSERT query and returns the inserted/updated ID.
func (u *TreeUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
	if u.create.driver.Dialect() == dialect.MySQL {
		// In case of "ON CONFLICT", there is no way to get back non-numeric ID
		// fields from the database since MySQL does not support the RETURNING clause.
		return id, errors.New("ent: TreeUpsertOne.ID is not supported by MySQL driver. Use TreeUpsertOne.Exec instead")
	}
	node, err := u.create.Save(ctx)
	if err != nil {
		return id, err
	}
	return node.ID, nil
}

// IDX is like ID, but panics if an error occurs.
func (u *TreeUpsertOne) IDX(ctx context.Context) uuid.UUID {
	id, err := u.ID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

// TreeCreateBulk is the builder for creating many Tree entities in bulk.
type TreeCreateBulk struct {
	config
	err      error
	builders []*TreeCreate
	conflict []sql.ConflictOption
}

// Save creates the Tree entities in the database.
func (tcb *TreeCreateBulk) Save(ctx context.Context) ([]*Tree, error) {
	if tcb.err != nil {
		return nil, tcb.err
	}
	specs := make([]*sqlgraph.CreateSpec, len(tcb.builders))
	nodes := make([]*Tree, len(tcb.builders))
	mutators := make([]Mutator, len(tcb.builders))
	for i := range tcb.builders {
		func(i int, root context.Context) {
			builder := tcb.builders[i]
			builder.defaults()
			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
				mutation, ok := m.(*TreeMutation)
				if !ok {
					return nil, fmt.Errorf("unexpected mutation type %T", m)
				}
				if err := builder.check(); err != nil {
					return nil, err
				}
				builder.mutation = mutation
				var err error
				nodes[i], specs[i] = builder.createSpec()
				if i < len(mutators)-1 {
					_, err = mutators[i+1].Mutate(root, tcb.builders[i+1].mutation)
				} else {
					spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
					spec.OnConflict = tcb.conflict
					// Invoke the actual operation on the latest mutation in the chain.
					if err = sqlgraph.BatchCreate(ctx, tcb.driver, spec); err != nil {
						if sqlgraph.IsConstraintError(err) {
							err = &ConstraintError{msg: err.Error(), wrap: err}
						}
					}
				}
				if err != nil {
					return nil, err
				}
				mutation.id = &nodes[i].ID
				mutation.done = true
				return nodes[i], nil
			})
			for i := len(builder.hooks) - 1; i >= 0; i-- {
				mut = builder.hooks[i](mut)
			}
			mutators[i] = mut
		}(i, ctx)
	}
	if len(mutators) > 0 {
		if _, err := mutators[0].Mutate(ctx, tcb.builders[0].mutation); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

// SaveX is like Save, but panics if an error occurs.
func (tcb *TreeCreateBulk) SaveX(ctx context.Context) []*Tree {
	v, err := tcb.Save(ctx)
	if err != nil {
		panic(err)
	}
	return v
}

// Exec executes the query.
func (tcb *TreeCreateBulk) Exec(ctx context.Context) error {
	_, err := tcb.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (tcb *TreeCreateBulk) ExecX(ctx context.Context) {
	if err := tcb.Exec(ctx); err != nil {
		panic(err)
	}
}

// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
//	client.Tree.CreateBulk(builders...).
//		OnConflict(
//			// Update the row with the new values
//			// the was proposed for insertion.
//			sql.ResolveWithNewValues(),
//		).
//		// Override some of the fields with custom
//		// update values.
//		Update(func(u *ent.TreeUpsert) {
//			SetCreateTime(v+v).
//		}).
//		Exec(ctx)
func (tcb *TreeCreateBulk) OnConflict(opts ...sql.ConflictOption) *TreeUpsertBulk {
	tcb.conflict = opts
	return &TreeUpsertBulk{
		create: tcb,
	}
}

// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
//	client.Tree.Create().
//		OnConflict(sql.ConflictColumns(columns...)).
//		Exec(ctx)
func (tcb *TreeCreateBulk) OnConflictColumns(columns ...string) *TreeUpsertBulk {
	tcb.conflict = append(tcb.conflict, sql.ConflictColumns(columns...))
	return &TreeUpsertBulk{
		create: tcb,
	}
}

// TreeUpsertBulk is the builder for "upsert"-ing
// a bulk of Tree nodes.
type TreeUpsertBulk struct {
	create *TreeCreateBulk
}

// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
//	client.Tree.Create().
//		OnConflict(
//			sql.ResolveWithNewValues(),
//			sql.ResolveWith(func(u *sql.UpdateSet) {
//				u.SetIgnore(tree.FieldID)
//			}),
//		).
//		Exec(ctx)
func (u *TreeUpsertBulk) UpdateNewValues() *TreeUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
		for _, b := range u.create.builders {
			if _, exists := b.mutation.ID(); exists {
				s.SetIgnore(tree.FieldID)
			}
			if _, exists := b.mutation.CreateTime(); exists {
				s.SetIgnore(tree.FieldCreateTime)
			}
		}
	}))
	return u
}

// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
//	client.Tree.Create().
//		OnConflict(sql.ResolveWithIgnore()).
//		Exec(ctx)
func (u *TreeUpsertBulk) Ignore() *TreeUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
	return u
}

// DoNothing configures the conflict_action to `DO NOTHING`.
// Supported only by SQLite and PostgreSQL.
func (u *TreeUpsertBulk) DoNothing() *TreeUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.DoNothing())
	return u
}

// Update allows overriding fields `UPDATE` values. See the TreeCreateBulk.OnConflict
// documentation for more info.
func (u *TreeUpsertBulk) Update(set func(*TreeUpsert)) *TreeUpsertBulk {
	u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
		set(&TreeUpsert{UpdateSet: update})
	}))
	return u
}

// SetUpdateTime sets the "update_time" field.
func (u *TreeUpsertBulk) SetUpdateTime(v time.Time) *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.SetUpdateTime(v)
	})
}

// UpdateUpdateTime sets the "update_time" field to the value that was provided on create.
func (u *TreeUpsertBulk) UpdateUpdateTime() *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateUpdateTime()
	})
}

// SetOwnerIdentityPubkey sets the "owner_identity_pubkey" field.
func (u *TreeUpsertBulk) SetOwnerIdentityPubkey(v keys.Public) *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.SetOwnerIdentityPubkey(v)
	})
}

// UpdateOwnerIdentityPubkey sets the "owner_identity_pubkey" field to the value that was provided on create.
func (u *TreeUpsertBulk) UpdateOwnerIdentityPubkey() *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateOwnerIdentityPubkey()
	})
}

// SetStatus sets the "status" field.
func (u *TreeUpsertBulk) SetStatus(v schematype.TreeStatus) *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.SetStatus(v)
	})
}

// UpdateStatus sets the "status" field to the value that was provided on create.
func (u *TreeUpsertBulk) UpdateStatus() *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateStatus()
	})
}

// SetNetwork sets the "network" field.
func (u *TreeUpsertBulk) SetNetwork(v schematype.Network) *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.SetNetwork(v)
	})
}

// UpdateNetwork sets the "network" field to the value that was provided on create.
func (u *TreeUpsertBulk) UpdateNetwork() *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateNetwork()
	})
}

// SetBaseTxid sets the "base_txid" field.
func (u *TreeUpsertBulk) SetBaseTxid(v []byte) *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.SetBaseTxid(v)
	})
}

// UpdateBaseTxid sets the "base_txid" field to the value that was provided on create.
func (u *TreeUpsertBulk) UpdateBaseTxid() *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateBaseTxid()
	})
}

// SetVout sets the "vout" field.
func (u *TreeUpsertBulk) SetVout(v int16) *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.SetVout(v)
	})
}

// AddVout adds v to the "vout" field.
func (u *TreeUpsertBulk) AddVout(v int16) *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.AddVout(v)
	})
}

// UpdateVout sets the "vout" field to the value that was provided on create.
func (u *TreeUpsertBulk) UpdateVout() *TreeUpsertBulk {
	return u.Update(func(s *TreeUpsert) {
		s.UpdateVout()
	})
}

// Exec executes the query.
func (u *TreeUpsertBulk) Exec(ctx context.Context) error {
	if u.create.err != nil {
		return u.create.err
	}
	for i, b := range u.create.builders {
		if len(b.conflict) != 0 {
			return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the TreeCreateBulk instead", i)
		}
	}
	if len(u.create.conflict) == 0 {
		return errors.New("ent: missing options for TreeCreateBulk.OnConflict")
	}
	return u.create.Exec(ctx)
}

// ExecX is like Exec, but panics if an error occurs.
func (u *TreeUpsertBulk) ExecX(ctx context.Context) {
	if err := u.create.Exec(ctx); err != nil {
		panic(err)
	}
}
