// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/predicate"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/user"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/usermeta"
)

// UserMetaQuery is the builder for querying UserMeta entities.
type UserMetaQuery struct {
	config
	ctx        *QueryContext
	order      []usermeta.OrderOption
	inters     []Interceptor
	predicates []predicate.UserMeta
	withUser   *UserQuery
	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 UserMetaQuery builder.
func (umq *UserMetaQuery) Where(ps ...predicate.UserMeta) *UserMetaQuery {
	umq.predicates = append(umq.predicates, ps...)
	return umq
}

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

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

// 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 (umq *UserMetaQuery) Unique(unique bool) *UserMetaQuery {
	umq.ctx.Unique = &unique
	return umq
}

// Order specifies how the records should be ordered.
func (umq *UserMetaQuery) Order(o ...usermeta.OrderOption) *UserMetaQuery {
	umq.order = append(umq.order, o...)
	return umq
}

// QueryUser chains the current query on the "user" edge.
func (umq *UserMetaQuery) QueryUser() *UserQuery {
	query := (&UserClient{config: umq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := umq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := umq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(usermeta.Table, usermeta.FieldID, selector),
			sqlgraph.To(user.Table, user.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, usermeta.UserTable, usermeta.UserColumn),
		)
		fromU = sqlgraph.SetNeighbors(umq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

// FirstID returns the first UserMeta ID from the query.
// Returns a *NotFoundError when no UserMeta ID was found.
func (umq *UserMetaQuery) FirstID(ctx context.Context) (id int64, err error) {
	var ids []int64
	if ids, err = umq.Limit(1).IDs(setContextOp(ctx, umq.ctx, "FirstID")); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{usermeta.Label}
		return
	}
	return ids[0], nil
}

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

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

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

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

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

// All executes the query and returns a list of UserMetaSlice.
func (umq *UserMetaQuery) All(ctx context.Context) ([]*UserMeta, error) {
	ctx = setContextOp(ctx, umq.ctx, "All")
	if err := umq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*UserMeta, *UserMetaQuery]()
	return withInterceptors[[]*UserMeta](ctx, umq, qr, umq.inters)
}

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

// IDs executes the query and returns a list of UserMeta IDs.
func (umq *UserMetaQuery) IDs(ctx context.Context) (ids []int64, err error) {
	if umq.ctx.Unique == nil && umq.path != nil {
		umq.Unique(true)
	}
	ctx = setContextOp(ctx, umq.ctx, "IDs")
	if err = umq.Select(usermeta.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

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

// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (umq *UserMetaQuery) WithUser(opts ...func(*UserQuery)) *UserMetaQuery {
	query := (&UserClient{config: umq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	umq.withUser = query
	return umq
}

// 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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.UserMeta.Query().
//		GroupBy(usermeta.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (umq *UserMetaQuery) GroupBy(field string, fields ...string) *UserMetaGroupBy {
	umq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &UserMetaGroupBy{build: umq}
	grbuild.flds = &umq.ctx.Fields
	grbuild.label = usermeta.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 {
//		CreatedAt time.Time `json:"created_at,omitempty"`
//	}
//
//	client.UserMeta.Query().
//		Select(usermeta.FieldCreatedAt).
//		Scan(ctx, &v)
func (umq *UserMetaQuery) Select(fields ...string) *UserMetaSelect {
	umq.ctx.Fields = append(umq.ctx.Fields, fields...)
	sbuild := &UserMetaSelect{UserMetaQuery: umq}
	sbuild.label = usermeta.Label
	sbuild.flds, sbuild.scan = &umq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a UserMetaSelect configured with the given aggregations.
func (umq *UserMetaQuery) Aggregate(fns ...AggregateFunc) *UserMetaSelect {
	return umq.Select().Aggregate(fns...)
}

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

func (umq *UserMetaQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserMeta, error) {
	var (
		nodes       = []*UserMeta{}
		_spec       = umq.querySpec()
		loadedTypes = [1]bool{
			umq.withUser != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*UserMeta).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &UserMeta{config: umq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(umq.modifiers) > 0 {
		_spec.Modifiers = umq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, umq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := umq.withUser; query != nil {
		if err := umq.loadUser(ctx, query, nodes, nil,
			func(n *UserMeta, e *User) { n.Edges.User = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (umq *UserMetaQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*UserMeta, init func(*UserMeta), assign func(*UserMeta, *User)) error {
	ids := make([]int64, 0, len(nodes))
	nodeids := make(map[int64][]*UserMeta)
	for i := range nodes {
		fk := nodes[i].UserID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(user.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_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

func (umq *UserMetaQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(umq.driver.Dialect())
	t1 := builder.Table(usermeta.Table)
	columns := umq.ctx.Fields
	if len(columns) == 0 {
		columns = usermeta.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if umq.sql != nil {
		selector = umq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if umq.ctx.Unique != nil && *umq.ctx.Unique {
		selector.Distinct()
	}
	for _, m := range umq.modifiers {
		m(selector)
	}
	for _, p := range umq.predicates {
		p(selector)
	}
	for _, p := range umq.order {
		p(selector)
	}
	if offset := umq.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 := umq.ctx.Limit; limit != nil {
		selector.Limit(*limit)
	}
	return selector
}

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

// UserMetaGroupBy is the group-by builder for UserMeta entities.
type UserMetaGroupBy struct {
	selector
	build *UserMetaQuery
}

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

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

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

// UserMetaSelect is the builder for selecting fields of UserMeta entities.
type UserMetaSelect struct {
	*UserMetaQuery
	selector
}

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

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

func (ums *UserMetaSelect) sqlScan(ctx context.Context, root *UserMetaQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(ums.fns))
	for _, fn := range ums.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*ums.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 := ums.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 (ums *UserMetaSelect) Modify(modifiers ...func(s *sql.Selector)) *UserMetaSelect {
	ums.modifiers = append(ums.modifiers, modifiers...)
	return ums
}
