// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the BatchMsgQuery builder.
func (bmq *BatchMsgQuery) Where(ps ...predicate.BatchMsg) *BatchMsgQuery {
	bmq.predicates = append(bmq.predicates, ps...)
	return bmq
}

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

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

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

// Order specifies how the records should be ordered.
func (bmq *BatchMsgQuery) Order(o ...batchmsg.OrderOption) *BatchMsgQuery {
	bmq.order = append(bmq.order, o...)
	return bmq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a BatchMsgSelect configured with the given aggregations.
func (bmq *BatchMsgQuery) Aggregate(fns ...AggregateFunc) *BatchMsgSelect {
	return bmq.Select().Aggregate(fns...)
}

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

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

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

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

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

// BatchMsgGroupBy is the group-by builder for BatchMsg entities.
type BatchMsgGroupBy struct {
	selector
	build *BatchMsgQuery
}

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

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

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

// BatchMsgSelect is the builder for selecting fields of BatchMsg entities.
type BatchMsgSelect struct {
	*BatchMsgQuery
	selector
}

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

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

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