// Code generated by ent, DO NOT EDIT.

package db

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/chaitin/MonkeyCode/backend/db/admin"
	"github.com/chaitin/MonkeyCode/backend/db/predicate"
	"github.com/chaitin/MonkeyCode/backend/db/usergroup"
	"github.com/chaitin/MonkeyCode/backend/db/usergroupadmin"
	"github.com/google/uuid"
)

// UserGroupAdminQuery is the builder for querying UserGroupAdmin entities.
type UserGroupAdminQuery struct {
	config
	ctx           *QueryContext
	order         []usergroupadmin.OrderOption
	inters        []Interceptor
	predicates    []predicate.UserGroupAdmin
	withUserGroup *UserGroupQuery
	withAdmin     *AdminQuery
	modifiers     []func(*sql.Selector)
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the UserGroupAdminQuery builder.
func (ugaq *UserGroupAdminQuery) Where(ps ...predicate.UserGroupAdmin) *UserGroupAdminQuery {
	ugaq.predicates = append(ugaq.predicates, ps...)
	return ugaq
}

// Limit the number of records to be returned by this query.
func (ugaq *UserGroupAdminQuery) Limit(limit int) *UserGroupAdminQuery {
	ugaq.ctx.Limit = &limit
	return ugaq
}

// Offset to start from.
func (ugaq *UserGroupAdminQuery) Offset(offset int) *UserGroupAdminQuery {
	ugaq.ctx.Offset = &offset
	return ugaq
}

// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (ugaq *UserGroupAdminQuery) Unique(unique bool) *UserGroupAdminQuery {
	ugaq.ctx.Unique = &unique
	return ugaq
}

// Order specifies how the records should be ordered.
func (ugaq *UserGroupAdminQuery) Order(o ...usergroupadmin.OrderOption) *UserGroupAdminQuery {
	ugaq.order = append(ugaq.order, o...)
	return ugaq
}

// QueryUserGroup chains the current query on the "user_group" edge.
func (ugaq *UserGroupAdminQuery) QueryUserGroup() *UserGroupQuery {
	query := (&UserGroupClient{config: ugaq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ugaq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ugaq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(usergroupadmin.Table, usergroupadmin.FieldID, selector),
			sqlgraph.To(usergroup.Table, usergroup.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, usergroupadmin.UserGroupTable, usergroupadmin.UserGroupColumn),
		)
		fromU = sqlgraph.SetNeighbors(ugaq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryAdmin chains the current query on the "admin" edge.
func (ugaq *UserGroupAdminQuery) QueryAdmin() *AdminQuery {
	query := (&AdminClient{config: ugaq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ugaq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ugaq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(usergroupadmin.Table, usergroupadmin.FieldID, selector),
			sqlgraph.To(admin.Table, admin.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, false, usergroupadmin.AdminTable, usergroupadmin.AdminColumn),
		)
		fromU = sqlgraph.SetNeighbors(ugaq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// First returns the first UserGroupAdmin entity from the query.
// Returns a *NotFoundError when no UserGroupAdmin was found.
func (ugaq *UserGroupAdminQuery) First(ctx context.Context) (*UserGroupAdmin, error) {
	nodes, err := ugaq.Limit(1).All(setContextOp(ctx, ugaq.ctx, ent.OpQueryFirst))
	if err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nil, &NotFoundError{usergroupadmin.Label}
	}
	return nodes[0], nil
}

// FirstX is like First, but panics if an error occurs.
func (ugaq *UserGroupAdminQuery) FirstX(ctx context.Context) *UserGroupAdmin {
	node, err := ugaq.First(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return node
}

// FirstID returns the first UserGroupAdmin ID from the query.
// Returns a *NotFoundError when no UserGroupAdmin ID was found.
func (ugaq *UserGroupAdminQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
	var ids []uuid.UUID
	if ids, err = ugaq.Limit(1).IDs(setContextOp(ctx, ugaq.ctx, ent.OpQueryFirstID)); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{usergroupadmin.Label}
		return
	}
	return ids[0], nil
}

// FirstIDX is like FirstID, but panics if an error occurs.
func (ugaq *UserGroupAdminQuery) FirstIDX(ctx context.Context) uuid.UUID {
	id, err := ugaq.FirstID(ctx)
	if err != nil && !IsNotFound(err) {
		panic(err)
	}
	return id
}

// Only returns a single UserGroupAdmin entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one UserGroupAdmin entity is found.
// Returns a *NotFoundError when no UserGroupAdmin entities are found.
func (ugaq *UserGroupAdminQuery) Only(ctx context.Context) (*UserGroupAdmin, error) {
	nodes, err := ugaq.Limit(2).All(setContextOp(ctx, ugaq.ctx, ent.OpQueryOnly))
	if err != nil {
		return nil, err
	}
	switch len(nodes) {
	case 1:
		return nodes[0], nil
	case 0:
		return nil, &NotFoundError{usergroupadmin.Label}
	default:
		return nil, &NotSingularError{usergroupadmin.Label}
	}
}

// OnlyX is like Only, but panics if an error occurs.
func (ugaq *UserGroupAdminQuery) OnlyX(ctx context.Context) *UserGroupAdmin {
	node, err := ugaq.Only(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// OnlyID is like Only, but returns the only UserGroupAdmin ID in the query.
// Returns a *NotSingularError when more than one UserGroupAdmin ID is found.
// Returns a *NotFoundError when no entities are found.
func (ugaq *UserGroupAdminQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
	var ids []uuid.UUID
	if ids, err = ugaq.Limit(2).IDs(setContextOp(ctx, ugaq.ctx, ent.OpQueryOnlyID)); err != nil {
		return
	}
	switch len(ids) {
	case 1:
		id = ids[0]
	case 0:
		err = &NotFoundError{usergroupadmin.Label}
	default:
		err = &NotSingularError{usergroupadmin.Label}
	}
	return
}

// OnlyIDX is like OnlyID, but panics if an error occurs.
func (ugaq *UserGroupAdminQuery) OnlyIDX(ctx context.Context) uuid.UUID {
	id, err := ugaq.OnlyID(ctx)
	if err != nil {
		panic(err)
	}
	return id
}

// All executes the query and returns a list of UserGroupAdmins.
func (ugaq *UserGroupAdminQuery) All(ctx context.Context) ([]*UserGroupAdmin, error) {
	ctx = setContextOp(ctx, ugaq.ctx, ent.OpQueryAll)
	if err := ugaq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*UserGroupAdmin, *UserGroupAdminQuery]()
	return withInterceptors[[]*UserGroupAdmin](ctx, ugaq, qr, ugaq.inters)
}

// AllX is like All, but panics if an error occurs.
func (ugaq *UserGroupAdminQuery) AllX(ctx context.Context) []*UserGroupAdmin {
	nodes, err := ugaq.All(ctx)
	if err != nil {
		panic(err)
	}
	return nodes
}

// IDs executes the query and returns a list of UserGroupAdmin IDs.
func (ugaq *UserGroupAdminQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
	if ugaq.ctx.Unique == nil && ugaq.path != nil {
		ugaq.Unique(true)
	}
	ctx = setContextOp(ctx, ugaq.ctx, ent.OpQueryIDs)
	if err = ugaq.Select(usergroupadmin.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

// IDsX is like IDs, but panics if an error occurs.
func (ugaq *UserGroupAdminQuery) IDsX(ctx context.Context) []uuid.UUID {
	ids, err := ugaq.IDs(ctx)
	if err != nil {
		panic(err)
	}
	return ids
}

// Count returns the count of the given query.
func (ugaq *UserGroupAdminQuery) Count(ctx context.Context) (int, error) {
	ctx = setContextOp(ctx, ugaq.ctx, ent.OpQueryCount)
	if err := ugaq.prepareQuery(ctx); err != nil {
		return 0, err
	}
	return withInterceptors[int](ctx, ugaq, querierCount[*UserGroupAdminQuery](), ugaq.inters)
}

// CountX is like Count, but panics if an error occurs.
func (ugaq *UserGroupAdminQuery) CountX(ctx context.Context) int {
	count, err := ugaq.Count(ctx)
	if err != nil {
		panic(err)
	}
	return count
}

// Exist returns true if the query has elements in the graph.
func (ugaq *UserGroupAdminQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, ugaq.ctx, ent.OpQueryExist)
	switch _, err := ugaq.FirstID(ctx); {
	case IsNotFound(err):
		return false, nil
	case err != nil:
		return false, fmt.Errorf("db: check existence: %w", err)
	default:
		return true, nil
	}
}

// ExistX is like Exist, but panics if an error occurs.
func (ugaq *UserGroupAdminQuery) ExistX(ctx context.Context) bool {
	exist, err := ugaq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

// Clone returns a duplicate of the UserGroupAdminQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (ugaq *UserGroupAdminQuery) Clone() *UserGroupAdminQuery {
	if ugaq == nil {
		return nil
	}
	return &UserGroupAdminQuery{
		config:        ugaq.config,
		ctx:           ugaq.ctx.Clone(),
		order:         append([]usergroupadmin.OrderOption{}, ugaq.order...),
		inters:        append([]Interceptor{}, ugaq.inters...),
		predicates:    append([]predicate.UserGroupAdmin{}, ugaq.predicates...),
		withUserGroup: ugaq.withUserGroup.Clone(),
		withAdmin:     ugaq.withAdmin.Clone(),
		// clone intermediate query.
		sql:       ugaq.sql.Clone(),
		path:      ugaq.path,
		modifiers: append([]func(*sql.Selector){}, ugaq.modifiers...),
	}
}

// WithUserGroup tells the query-builder to eager-load the nodes that are connected to
// the "user_group" edge. The optional arguments are used to configure the query builder of the edge.
func (ugaq *UserGroupAdminQuery) WithUserGroup(opts ...func(*UserGroupQuery)) *UserGroupAdminQuery {
	query := (&UserGroupClient{config: ugaq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ugaq.withUserGroup = query
	return ugaq
}

// WithAdmin tells the query-builder to eager-load the nodes that are connected to
// the "admin" edge. The optional arguments are used to configure the query builder of the edge.
func (ugaq *UserGroupAdminQuery) WithAdmin(opts ...func(*AdminQuery)) *UserGroupAdminQuery {
	query := (&AdminClient{config: ugaq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ugaq.withAdmin = query
	return ugaq
}

// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
//	var v []struct {
//		UserGroupID uuid.UUID `json:"user_group_id,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.UserGroupAdmin.Query().
//		GroupBy(usergroupadmin.FieldUserGroupID).
//		Aggregate(db.Count()).
//		Scan(ctx, &v)
func (ugaq *UserGroupAdminQuery) GroupBy(field string, fields ...string) *UserGroupAdminGroupBy {
	ugaq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &UserGroupAdminGroupBy{build: ugaq}
	grbuild.flds = &ugaq.ctx.Fields
	grbuild.label = usergroupadmin.Label
	grbuild.scan = grbuild.Scan
	return grbuild
}

// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
//	var v []struct {
//		UserGroupID uuid.UUID `json:"user_group_id,omitempty"`
//	}
//
//	client.UserGroupAdmin.Query().
//		Select(usergroupadmin.FieldUserGroupID).
//		Scan(ctx, &v)
func (ugaq *UserGroupAdminQuery) Select(fields ...string) *UserGroupAdminSelect {
	ugaq.ctx.Fields = append(ugaq.ctx.Fields, fields...)
	sbuild := &UserGroupAdminSelect{UserGroupAdminQuery: ugaq}
	sbuild.label = usergroupadmin.Label
	sbuild.flds, sbuild.scan = &ugaq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a UserGroupAdminSelect configured with the given aggregations.
func (ugaq *UserGroupAdminQuery) Aggregate(fns ...AggregateFunc) *UserGroupAdminSelect {
	return ugaq.Select().Aggregate(fns...)
}

func (ugaq *UserGroupAdminQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range ugaq.inters {
		if inter == nil {
			return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)")
		}
		if trv, ok := inter.(Traverser); ok {
			if err := trv.Traverse(ctx, ugaq); err != nil {
				return err
			}
		}
	}
	for _, f := range ugaq.ctx.Fields {
		if !usergroupadmin.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
		}
	}
	if ugaq.path != nil {
		prev, err := ugaq.path(ctx)
		if err != nil {
			return err
		}
		ugaq.sql = prev
	}
	return nil
}

func (ugaq *UserGroupAdminQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserGroupAdmin, error) {
	var (
		nodes       = []*UserGroupAdmin{}
		_spec       = ugaq.querySpec()
		loadedTypes = [2]bool{
			ugaq.withUserGroup != nil,
			ugaq.withAdmin != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*UserGroupAdmin).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &UserGroupAdmin{config: ugaq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(ugaq.modifiers) > 0 {
		_spec.Modifiers = ugaq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, ugaq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := ugaq.withUserGroup; query != nil {
		if err := ugaq.loadUserGroup(ctx, query, nodes, nil,
			func(n *UserGroupAdmin, e *UserGroup) { n.Edges.UserGroup = e }); err != nil {
			return nil, err
		}
	}
	if query := ugaq.withAdmin; query != nil {
		if err := ugaq.loadAdmin(ctx, query, nodes, nil,
			func(n *UserGroupAdmin, e *Admin) { n.Edges.Admin = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (ugaq *UserGroupAdminQuery) loadUserGroup(ctx context.Context, query *UserGroupQuery, nodes []*UserGroupAdmin, init func(*UserGroupAdmin), assign func(*UserGroupAdmin, *UserGroup)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*UserGroupAdmin)
	for i := range nodes {
		fk := nodes[i].UserGroupID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(usergroup.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "user_group_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (ugaq *UserGroupAdminQuery) loadAdmin(ctx context.Context, query *AdminQuery, nodes []*UserGroupAdmin, init func(*UserGroupAdmin), assign func(*UserGroupAdmin, *Admin)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*UserGroupAdmin)
	for i := range nodes {
		fk := nodes[i].AdminID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(admin.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "admin_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

func (ugaq *UserGroupAdminQuery) sqlCount(ctx context.Context) (int, error) {
	_spec := ugaq.querySpec()
	if len(ugaq.modifiers) > 0 {
		_spec.Modifiers = ugaq.modifiers
	}
	_spec.Node.Columns = ugaq.ctx.Fields
	if len(ugaq.ctx.Fields) > 0 {
		_spec.Unique = ugaq.ctx.Unique != nil && *ugaq.ctx.Unique
	}
	return sqlgraph.CountNodes(ctx, ugaq.driver, _spec)
}

func (ugaq *UserGroupAdminQuery) querySpec() *sqlgraph.QuerySpec {
	_spec := sqlgraph.NewQuerySpec(usergroupadmin.Table, usergroupadmin.Columns, sqlgraph.NewFieldSpec(usergroupadmin.FieldID, field.TypeUUID))
	_spec.From = ugaq.sql
	if unique := ugaq.ctx.Unique; unique != nil {
		_spec.Unique = *unique
	} else if ugaq.path != nil {
		_spec.Unique = true
	}
	if fields := ugaq.ctx.Fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, usergroupadmin.FieldID)
		for i := range fields {
			if fields[i] != usergroupadmin.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
			}
		}
		if ugaq.withUserGroup != nil {
			_spec.Node.AddColumnOnce(usergroupadmin.FieldUserGroupID)
		}
		if ugaq.withAdmin != nil {
			_spec.Node.AddColumnOnce(usergroupadmin.FieldAdminID)
		}
	}
	if ps := ugaq.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if limit := ugaq.ctx.Limit; limit != nil {
		_spec.Limit = *limit
	}
	if offset := ugaq.ctx.Offset; offset != nil {
		_spec.Offset = *offset
	}
	if ps := ugaq.order; len(ps) > 0 {
		_spec.Order = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	return _spec
}

func (ugaq *UserGroupAdminQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(ugaq.driver.Dialect())
	t1 := builder.Table(usergroupadmin.Table)
	columns := ugaq.ctx.Fields
	if len(columns) == 0 {
		columns = usergroupadmin.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if ugaq.sql != nil {
		selector = ugaq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if ugaq.ctx.Unique != nil && *ugaq.ctx.Unique {
		selector.Distinct()
	}
	for _, m := range ugaq.modifiers {
		m(selector)
	}
	for _, p := range ugaq.predicates {
		p(selector)
	}
	for _, p := range ugaq.order {
		p(selector)
	}
	if offset := ugaq.ctx.Offset; offset != nil {
		// limit is mandatory for offset clause. We start
		// with default value, and override it below if needed.
		selector.Offset(*offset).Limit(math.MaxInt32)
	}
	if limit := ugaq.ctx.Limit; limit != nil {
		selector.Limit(*limit)
	}
	return selector
}

// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (ugaq *UserGroupAdminQuery) ForUpdate(opts ...sql.LockOption) *UserGroupAdminQuery {
	if ugaq.driver.Dialect() == dialect.Postgres {
		ugaq.Unique(false)
	}
	ugaq.modifiers = append(ugaq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return ugaq
}

// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (ugaq *UserGroupAdminQuery) ForShare(opts ...sql.LockOption) *UserGroupAdminQuery {
	if ugaq.driver.Dialect() == dialect.Postgres {
		ugaq.Unique(false)
	}
	ugaq.modifiers = append(ugaq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return ugaq
}

// Modify adds a query modifier for attaching custom logic to queries.
func (ugaq *UserGroupAdminQuery) Modify(modifiers ...func(s *sql.Selector)) *UserGroupAdminSelect {
	ugaq.modifiers = append(ugaq.modifiers, modifiers...)
	return ugaq.Select()
}

// UserGroupAdminGroupBy is the group-by builder for UserGroupAdmin entities.
type UserGroupAdminGroupBy struct {
	selector
	build *UserGroupAdminQuery
}

// Aggregate adds the given aggregation functions to the group-by query.
func (ugagb *UserGroupAdminGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupAdminGroupBy {
	ugagb.fns = append(ugagb.fns, fns...)
	return ugagb
}

// Scan applies the selector query and scans the result into the given value.
func (ugagb *UserGroupAdminGroupBy) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, ugagb.build.ctx, ent.OpQueryGroupBy)
	if err := ugagb.build.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*UserGroupAdminQuery, *UserGroupAdminGroupBy](ctx, ugagb.build, ugagb, ugagb.build.inters, v)
}

func (ugagb *UserGroupAdminGroupBy) sqlScan(ctx context.Context, root *UserGroupAdminQuery, v any) error {
	selector := root.sqlQuery(ctx).Select()
	aggregation := make([]string, 0, len(ugagb.fns))
	for _, fn := range ugagb.fns {
		aggregation = append(aggregation, fn(selector))
	}
	if len(selector.SelectedColumns()) == 0 {
		columns := make([]string, 0, len(*ugagb.flds)+len(ugagb.fns))
		for _, f := range *ugagb.flds {
			columns = append(columns, selector.C(f))
		}
		columns = append(columns, aggregation...)
		selector.Select(columns...)
	}
	selector.GroupBy(selector.Columns(*ugagb.flds...)...)
	if err := selector.Err(); err != nil {
		return err
	}
	rows := &sql.Rows{}
	query, args := selector.Query()
	if err := ugagb.build.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}

// UserGroupAdminSelect is the builder for selecting fields of UserGroupAdmin entities.
type UserGroupAdminSelect struct {
	*UserGroupAdminQuery
	selector
}

// Aggregate adds the given aggregation functions to the selector query.
func (ugas *UserGroupAdminSelect) Aggregate(fns ...AggregateFunc) *UserGroupAdminSelect {
	ugas.fns = append(ugas.fns, fns...)
	return ugas
}

// Scan applies the selector query and scans the result into the given value.
func (ugas *UserGroupAdminSelect) Scan(ctx context.Context, v any) error {
	ctx = setContextOp(ctx, ugas.ctx, ent.OpQuerySelect)
	if err := ugas.prepareQuery(ctx); err != nil {
		return err
	}
	return scanWithInterceptors[*UserGroupAdminQuery, *UserGroupAdminSelect](ctx, ugas.UserGroupAdminQuery, ugas, ugas.inters, v)
}

func (ugas *UserGroupAdminSelect) sqlScan(ctx context.Context, root *UserGroupAdminQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(ugas.fns))
	for _, fn := range ugas.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*ugas.selector.flds); {
	case n == 0 && len(aggregation) > 0:
		selector.Select(aggregation...)
	case n != 0 && len(aggregation) > 0:
		selector.AppendSelect(aggregation...)
	}
	rows := &sql.Rows{}
	query, args := selector.Query()
	if err := ugas.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}

// Modify adds a query modifier for attaching custom logic to queries.
func (ugas *UserGroupAdminSelect) Modify(modifiers ...func(s *sql.Selector)) *UserGroupAdminSelect {
	ugas.modifiers = append(ugas.modifiers, modifiers...)
	return ugas
}
