// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"
	"wechat-api/ent/predicate"
	"wechat-api/ent/wxcarduser"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
)

// WxCardUserQuery is the builder for querying WxCardUser entities.
type WxCardUserQuery struct {
	config
	ctx        *QueryContext
	order      []wxcarduser.OrderOption
	inters     []Interceptor
	predicates []predicate.WxCardUser
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the WxCardUserQuery builder.
func (wcuq *WxCardUserQuery) Where(ps ...predicate.WxCardUser) *WxCardUserQuery {
	wcuq.predicates = append(wcuq.predicates, ps...)
	return wcuq
}

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

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

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

// Order specifies how the records should be ordered.
func (wcuq *WxCardUserQuery) Order(o ...wxcarduser.OrderOption) *WxCardUserQuery {
	wcuq.order = append(wcuq.order, o...)
	return wcuq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Exist returns true if the query has elements in the graph.
func (wcuq *WxCardUserQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, wcuq.ctx, "Exist")
	switch _, err := wcuq.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 (wcuq *WxCardUserQuery) ExistX(ctx context.Context) bool {
	exist, err := wcuq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

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

// 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.WxCardUser.Query().
//		GroupBy(wxcarduser.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (wcuq *WxCardUserQuery) GroupBy(field string, fields ...string) *WxCardUserGroupBy {
	wcuq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &WxCardUserGroupBy{build: wcuq}
	grbuild.flds = &wcuq.ctx.Fields
	grbuild.label = wxcarduser.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.WxCardUser.Query().
//		Select(wxcarduser.FieldCreatedAt).
//		Scan(ctx, &v)
func (wcuq *WxCardUserQuery) Select(fields ...string) *WxCardUserSelect {
	wcuq.ctx.Fields = append(wcuq.ctx.Fields, fields...)
	sbuild := &WxCardUserSelect{WxCardUserQuery: wcuq}
	sbuild.label = wxcarduser.Label
	sbuild.flds, sbuild.scan = &wcuq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a WxCardUserSelect configured with the given aggregations.
func (wcuq *WxCardUserQuery) Aggregate(fns ...AggregateFunc) *WxCardUserSelect {
	return wcuq.Select().Aggregate(fns...)
}

func (wcuq *WxCardUserQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range wcuq.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, wcuq); err != nil {
				return err
			}
		}
	}
	for _, f := range wcuq.ctx.Fields {
		if !wxcarduser.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
		}
	}
	if wcuq.path != nil {
		prev, err := wcuq.path(ctx)
		if err != nil {
			return err
		}
		wcuq.sql = prev
	}
	return nil
}

func (wcuq *WxCardUserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*WxCardUser, error) {
	var (
		nodes = []*WxCardUser{}
		_spec = wcuq.querySpec()
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*WxCardUser).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &WxCardUser{config: wcuq.config}
		nodes = append(nodes, node)
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, wcuq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	return nodes, nil
}

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

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

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

// WxCardUserGroupBy is the group-by builder for WxCardUser entities.
type WxCardUserGroupBy struct {
	selector
	build *WxCardUserQuery
}

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

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

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

// WxCardUserSelect is the builder for selecting fields of WxCardUser entities.
type WxCardUserSelect struct {
	*WxCardUserQuery
	selector
}

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

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

func (wcus *WxCardUserSelect) sqlScan(ctx context.Context, root *WxCardUserQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(wcus.fns))
	for _, fn := range wcus.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*wcus.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 := wcus.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}
