// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the UsageDetailQuery builder.
func (udq *UsageDetailQuery) Where(ps ...predicate.UsageDetail) *UsageDetailQuery {
	udq.predicates = append(udq.predicates, ps...)
	return udq
}

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

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

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

// Order specifies how the records should be ordered.
func (udq *UsageDetailQuery) Order(o ...usagedetail.OrderOption) *UsageDetailQuery {
	udq.order = append(udq.order, o...)
	return udq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a UsageDetailSelect configured with the given aggregations.
func (udq *UsageDetailQuery) Aggregate(fns ...AggregateFunc) *UsageDetailSelect {
	return udq.Select().Aggregate(fns...)
}

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

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

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

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

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

// UsageDetailGroupBy is the group-by builder for UsageDetail entities.
type UsageDetailGroupBy struct {
	selector
	build *UsageDetailQuery
}

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

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

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

// UsageDetailSelect is the builder for selecting fields of UsageDetail entities.
type UsageDetailSelect struct {
	*UsageDetailQuery
	selector
}

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

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

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