// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the EmployeeConfigQuery builder.
func (ecq *EmployeeConfigQuery) Where(ps ...predicate.EmployeeConfig) *EmployeeConfigQuery {
	ecq.predicates = append(ecq.predicates, ps...)
	return ecq
}

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

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

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

// Order specifies how the records should be ordered.
func (ecq *EmployeeConfigQuery) Order(o ...employeeconfig.OrderOption) *EmployeeConfigQuery {
	ecq.order = append(ecq.order, o...)
	return ecq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a EmployeeConfigSelect configured with the given aggregations.
func (ecq *EmployeeConfigQuery) Aggregate(fns ...AggregateFunc) *EmployeeConfigSelect {
	return ecq.Select().Aggregate(fns...)
}

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

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

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

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

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

// EmployeeConfigGroupBy is the group-by builder for EmployeeConfig entities.
type EmployeeConfigGroupBy struct {
	selector
	build *EmployeeConfigQuery
}

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

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

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

// EmployeeConfigSelect is the builder for selecting fields of EmployeeConfig entities.
type EmployeeConfigSelect struct {
	*EmployeeConfigQuery
	selector
}

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

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

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