// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the UsageStatisticMonthQuery builder.
func (usmq *UsageStatisticMonthQuery) Where(ps ...predicate.UsageStatisticMonth) *UsageStatisticMonthQuery {
	usmq.predicates = append(usmq.predicates, ps...)
	return usmq
}

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

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

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

// Order specifies how the records should be ordered.
func (usmq *UsageStatisticMonthQuery) Order(o ...usagestatisticmonth.OrderOption) *UsageStatisticMonthQuery {
	usmq.order = append(usmq.order, o...)
	return usmq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a UsageStatisticMonthSelect configured with the given aggregations.
func (usmq *UsageStatisticMonthQuery) Aggregate(fns ...AggregateFunc) *UsageStatisticMonthSelect {
	return usmq.Select().Aggregate(fns...)
}

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

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

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

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

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

// UsageStatisticMonthGroupBy is the group-by builder for UsageStatisticMonth entities.
type UsageStatisticMonthGroupBy struct {
	selector
	build *UsageStatisticMonthQuery
}

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

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

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

// UsageStatisticMonthSelect is the builder for selecting fields of UsageStatisticMonth entities.
type UsageStatisticMonthSelect struct {
	*UsageStatisticMonthQuery
	selector
}

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

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

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