// Code generated by ent, DO NOT EDIT.

package ent

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

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

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

// Where adds a new predicate for the WpChatroomMemberQuery builder.
func (wcmq *WpChatroomMemberQuery) Where(ps ...predicate.WpChatroomMember) *WpChatroomMemberQuery {
	wcmq.predicates = append(wcmq.predicates, ps...)
	return wcmq
}

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

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

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

// Order specifies how the records should be ordered.
func (wcmq *WpChatroomMemberQuery) Order(o ...wpchatroommember.OrderOption) *WpChatroomMemberQuery {
	wcmq.order = append(wcmq.order, o...)
	return wcmq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a WpChatroomMemberSelect configured with the given aggregations.
func (wcmq *WpChatroomMemberQuery) Aggregate(fns ...AggregateFunc) *WpChatroomMemberSelect {
	return wcmq.Select().Aggregate(fns...)
}

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

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

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

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

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

// WpChatroomMemberGroupBy is the group-by builder for WpChatroomMember entities.
type WpChatroomMemberGroupBy struct {
	selector
	build *WpChatroomMemberQuery
}

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

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

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

// WpChatroomMemberSelect is the builder for selecting fields of WpChatroomMember entities.
type WpChatroomMemberSelect struct {
	*WpChatroomMemberQuery
	selector
}

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

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

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