// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the CreditBalanceQuery builder.
func (cbq *CreditBalanceQuery) Where(ps ...predicate.CreditBalance) *CreditBalanceQuery {
	cbq.predicates = append(cbq.predicates, ps...)
	return cbq
}

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

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

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

// Order specifies how the records should be ordered.
func (cbq *CreditBalanceQuery) Order(o ...creditbalance.OrderOption) *CreditBalanceQuery {
	cbq.order = append(cbq.order, o...)
	return cbq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a CreditBalanceSelect configured with the given aggregations.
func (cbq *CreditBalanceQuery) Aggregate(fns ...AggregateFunc) *CreditBalanceSelect {
	return cbq.Select().Aggregate(fns...)
}

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

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

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

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

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

// CreditBalanceGroupBy is the group-by builder for CreditBalance entities.
type CreditBalanceGroupBy struct {
	selector
	build *CreditBalanceQuery
}

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

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

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

// CreditBalanceSelect is the builder for selecting fields of CreditBalance entities.
type CreditBalanceSelect struct {
	*CreditBalanceQuery
	selector
}

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

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

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