// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the CompapiAsynctaskQuery builder.
func (caq *CompapiAsynctaskQuery) Where(ps ...predicate.CompapiAsynctask) *CompapiAsynctaskQuery {
	caq.predicates = append(caq.predicates, ps...)
	return caq
}

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

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

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

// Order specifies how the records should be ordered.
func (caq *CompapiAsynctaskQuery) Order(o ...compapiasynctask.OrderOption) *CompapiAsynctaskQuery {
	caq.order = append(caq.order, o...)
	return caq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a CompapiAsynctaskSelect configured with the given aggregations.
func (caq *CompapiAsynctaskQuery) Aggregate(fns ...AggregateFunc) *CompapiAsynctaskSelect {
	return caq.Select().Aggregate(fns...)
}

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

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

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

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

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

// CompapiAsynctaskGroupBy is the group-by builder for CompapiAsynctask entities.
type CompapiAsynctaskGroupBy struct {
	selector
	build *CompapiAsynctaskQuery
}

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

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

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

// CompapiAsynctaskSelect is the builder for selecting fields of CompapiAsynctask entities.
type CompapiAsynctaskSelect struct {
	*CompapiAsynctaskQuery
	selector
}

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

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

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