// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the ChatRecordsQuery builder.
func (crq *ChatRecordsQuery) Where(ps ...predicate.ChatRecords) *ChatRecordsQuery {
	crq.predicates = append(crq.predicates, ps...)
	return crq
}

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

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

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

// Order specifies how the records should be ordered.
func (crq *ChatRecordsQuery) Order(o ...chatrecords.OrderOption) *ChatRecordsQuery {
	crq.order = append(crq.order, o...)
	return crq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a ChatRecordsSelect configured with the given aggregations.
func (crq *ChatRecordsQuery) Aggregate(fns ...AggregateFunc) *ChatRecordsSelect {
	return crq.Select().Aggregate(fns...)
}

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

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

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

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

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

// ChatRecordsGroupBy is the group-by builder for ChatRecords entities.
type ChatRecordsGroupBy struct {
	selector
	build *ChatRecordsQuery
}

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

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

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

// ChatRecordsSelect is the builder for selecting fields of ChatRecords entities.
type ChatRecordsSelect struct {
	*ChatRecordsQuery
	selector
}

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

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

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