// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the WxCardVisitQuery builder.
func (wcvq *WxCardVisitQuery) Where(ps ...predicate.WxCardVisit) *WxCardVisitQuery {
	wcvq.predicates = append(wcvq.predicates, ps...)
	return wcvq
}

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

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

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

// Order specifies how the records should be ordered.
func (wcvq *WxCardVisitQuery) Order(o ...wxcardvisit.OrderOption) *WxCardVisitQuery {
	wcvq.order = append(wcvq.order, o...)
	return wcvq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the WxCardVisitQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (wcvq *WxCardVisitQuery) Clone() *WxCardVisitQuery {
	if wcvq == nil {
		return nil
	}
	return &WxCardVisitQuery{
		config:     wcvq.config,
		ctx:        wcvq.ctx.Clone(),
		order:      append([]wxcardvisit.OrderOption{}, wcvq.order...),
		inters:     append([]Interceptor{}, wcvq.inters...),
		predicates: append([]predicate.WxCardVisit{}, wcvq.predicates...),
		// clone intermediate query.
		sql:  wcvq.sql.Clone(),
		path: wcvq.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.WxCardVisit.Query().
//		GroupBy(wxcardvisit.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (wcvq *WxCardVisitQuery) GroupBy(field string, fields ...string) *WxCardVisitGroupBy {
	wcvq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &WxCardVisitGroupBy{build: wcvq}
	grbuild.flds = &wcvq.ctx.Fields
	grbuild.label = wxcardvisit.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.WxCardVisit.Query().
//		Select(wxcardvisit.FieldCreatedAt).
//		Scan(ctx, &v)
func (wcvq *WxCardVisitQuery) Select(fields ...string) *WxCardVisitSelect {
	wcvq.ctx.Fields = append(wcvq.ctx.Fields, fields...)
	sbuild := &WxCardVisitSelect{WxCardVisitQuery: wcvq}
	sbuild.label = wxcardvisit.Label
	sbuild.flds, sbuild.scan = &wcvq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a WxCardVisitSelect configured with the given aggregations.
func (wcvq *WxCardVisitQuery) Aggregate(fns ...AggregateFunc) *WxCardVisitSelect {
	return wcvq.Select().Aggregate(fns...)
}

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

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

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

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

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

// WxCardVisitGroupBy is the group-by builder for WxCardVisit entities.
type WxCardVisitGroupBy struct {
	selector
	build *WxCardVisitQuery
}

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

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

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

// WxCardVisitSelect is the builder for selecting fields of WxCardVisit entities.
type WxCardVisitSelect struct {
	*WxCardVisitQuery
	selector
}

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

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

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