// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the ContactFieldTemplateQuery builder.
func (cftq *ContactFieldTemplateQuery) Where(ps ...predicate.ContactFieldTemplate) *ContactFieldTemplateQuery {
	cftq.predicates = append(cftq.predicates, ps...)
	return cftq
}

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

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

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

// Order specifies how the records should be ordered.
func (cftq *ContactFieldTemplateQuery) Order(o ...contactfieldtemplate.OrderOption) *ContactFieldTemplateQuery {
	cftq.order = append(cftq.order, o...)
	return cftq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a ContactFieldTemplateSelect configured with the given aggregations.
func (cftq *ContactFieldTemplateQuery) Aggregate(fns ...AggregateFunc) *ContactFieldTemplateSelect {
	return cftq.Select().Aggregate(fns...)
}

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

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

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

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

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

// ContactFieldTemplateGroupBy is the group-by builder for ContactFieldTemplate entities.
type ContactFieldTemplateGroupBy struct {
	selector
	build *ContactFieldTemplateQuery
}

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

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

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

// ContactFieldTemplateSelect is the builder for selecting fields of ContactFieldTemplate entities.
type ContactFieldTemplateSelect struct {
	*ContactFieldTemplateQuery
	selector
}

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

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

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