// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the LabelLogQuery builder.
func (llq *LabelLogQuery) Where(ps ...predicate.LabelLog) *LabelLogQuery {
	llq.predicates = append(llq.predicates, ps...)
	return llq
}

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

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

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

// Order specifies how the records should be ordered.
func (llq *LabelLogQuery) Order(o ...labellog.OrderOption) *LabelLogQuery {
	llq.order = append(llq.order, o...)
	return llq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a LabelLogSelect configured with the given aggregations.
func (llq *LabelLogQuery) Aggregate(fns ...AggregateFunc) *LabelLogSelect {
	return llq.Select().Aggregate(fns...)
}

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

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

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

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

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

// LabelLogGroupBy is the group-by builder for LabelLog entities.
type LabelLogGroupBy struct {
	selector
	build *LabelLogQuery
}

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

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

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

// LabelLogSelect is the builder for selecting fields of LabelLog entities.
type LabelLogSelect struct {
	*LabelLogQuery
	selector
}

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

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

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