// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the LabelTaggingQuery builder.
func (ltq *LabelTaggingQuery) Where(ps ...predicate.LabelTagging) *LabelTaggingQuery {
	ltq.predicates = append(ltq.predicates, ps...)
	return ltq
}

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

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

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

// Order specifies how the records should be ordered.
func (ltq *LabelTaggingQuery) Order(o ...labeltagging.OrderOption) *LabelTaggingQuery {
	ltq.order = append(ltq.order, o...)
	return ltq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a LabelTaggingSelect configured with the given aggregations.
func (ltq *LabelTaggingQuery) Aggregate(fns ...AggregateFunc) *LabelTaggingSelect {
	return ltq.Select().Aggregate(fns...)
}

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

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

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

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

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

// LabelTaggingGroupBy is the group-by builder for LabelTagging entities.
type LabelTaggingGroupBy struct {
	selector
	build *LabelTaggingQuery
}

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

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

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

// LabelTaggingSelect is the builder for selecting fields of LabelTagging entities.
type LabelTaggingSelect struct {
	*LabelTaggingQuery
	selector
}

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

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

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