// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the UsageStatisticDayQuery builder.
func (usdq *UsageStatisticDayQuery) Where(ps ...predicate.UsageStatisticDay) *UsageStatisticDayQuery {
	usdq.predicates = append(usdq.predicates, ps...)
	return usdq
}

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

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

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

// Order specifies how the records should be ordered.
func (usdq *UsageStatisticDayQuery) Order(o ...usagestatisticday.OrderOption) *UsageStatisticDayQuery {
	usdq.order = append(usdq.order, o...)
	return usdq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a UsageStatisticDaySelect configured with the given aggregations.
func (usdq *UsageStatisticDayQuery) Aggregate(fns ...AggregateFunc) *UsageStatisticDaySelect {
	return usdq.Select().Aggregate(fns...)
}

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

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

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

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

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

// UsageStatisticDayGroupBy is the group-by builder for UsageStatisticDay entities.
type UsageStatisticDayGroupBy struct {
	selector
	build *UsageStatisticDayQuery
}

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

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

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

// UsageStatisticDaySelect is the builder for selecting fields of UsageStatisticDay entities.
type UsageStatisticDaySelect struct {
	*UsageStatisticDayQuery
	selector
}

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

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

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