// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"
	"wechat-api/ent/contact"
	"wechat-api/ent/messagerecords"
	"wechat-api/ent/predicate"
	"wechat-api/ent/sopnode"
	"wechat-api/ent/sopstage"

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

// MessageRecordsQuery is the builder for querying MessageRecords entities.
type MessageRecordsQuery struct {
	config
	ctx                *QueryContext
	order              []messagerecords.OrderOption
	inters             []Interceptor
	predicates         []predicate.MessageRecords
	withSopStage       *SopStageQuery
	withSopNode        *SopNodeQuery
	withMessageContact *ContactQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the MessageRecordsQuery builder.
func (mrq *MessageRecordsQuery) Where(ps ...predicate.MessageRecords) *MessageRecordsQuery {
	mrq.predicates = append(mrq.predicates, ps...)
	return mrq
}

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

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

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

// Order specifies how the records should be ordered.
func (mrq *MessageRecordsQuery) Order(o ...messagerecords.OrderOption) *MessageRecordsQuery {
	mrq.order = append(mrq.order, o...)
	return mrq
}

// QuerySopStage chains the current query on the "sop_stage" edge.
func (mrq *MessageRecordsQuery) QuerySopStage() *SopStageQuery {
	query := (&SopStageClient{config: mrq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mrq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mrq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(messagerecords.Table, messagerecords.FieldID, selector),
			sqlgraph.To(sopstage.Table, sopstage.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, messagerecords.SopStageTable, messagerecords.SopStageColumn),
		)
		fromU = sqlgraph.SetNeighbors(mrq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QuerySopNode chains the current query on the "sop_node" edge.
func (mrq *MessageRecordsQuery) QuerySopNode() *SopNodeQuery {
	query := (&SopNodeClient{config: mrq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mrq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mrq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(messagerecords.Table, messagerecords.FieldID, selector),
			sqlgraph.To(sopnode.Table, sopnode.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, messagerecords.SopNodeTable, messagerecords.SopNodeColumn),
		)
		fromU = sqlgraph.SetNeighbors(mrq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryMessageContact chains the current query on the "message_contact" edge.
func (mrq *MessageRecordsQuery) QueryMessageContact() *ContactQuery {
	query := (&ContactClient{config: mrq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := mrq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := mrq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(messagerecords.Table, messagerecords.FieldID, selector),
			sqlgraph.To(contact.Table, contact.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, messagerecords.MessageContactTable, messagerecords.MessageContactColumn),
		)
		fromU = sqlgraph.SetNeighbors(mrq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the MessageRecordsQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (mrq *MessageRecordsQuery) Clone() *MessageRecordsQuery {
	if mrq == nil {
		return nil
	}
	return &MessageRecordsQuery{
		config:             mrq.config,
		ctx:                mrq.ctx.Clone(),
		order:              append([]messagerecords.OrderOption{}, mrq.order...),
		inters:             append([]Interceptor{}, mrq.inters...),
		predicates:         append([]predicate.MessageRecords{}, mrq.predicates...),
		withSopStage:       mrq.withSopStage.Clone(),
		withSopNode:        mrq.withSopNode.Clone(),
		withMessageContact: mrq.withMessageContact.Clone(),
		// clone intermediate query.
		sql:  mrq.sql.Clone(),
		path: mrq.path,
	}
}

// WithSopStage tells the query-builder to eager-load the nodes that are connected to
// the "sop_stage" edge. The optional arguments are used to configure the query builder of the edge.
func (mrq *MessageRecordsQuery) WithSopStage(opts ...func(*SopStageQuery)) *MessageRecordsQuery {
	query := (&SopStageClient{config: mrq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mrq.withSopStage = query
	return mrq
}

// WithSopNode tells the query-builder to eager-load the nodes that are connected to
// the "sop_node" edge. The optional arguments are used to configure the query builder of the edge.
func (mrq *MessageRecordsQuery) WithSopNode(opts ...func(*SopNodeQuery)) *MessageRecordsQuery {
	query := (&SopNodeClient{config: mrq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mrq.withSopNode = query
	return mrq
}

// WithMessageContact tells the query-builder to eager-load the nodes that are connected to
// the "message_contact" edge. The optional arguments are used to configure the query builder of the edge.
func (mrq *MessageRecordsQuery) WithMessageContact(opts ...func(*ContactQuery)) *MessageRecordsQuery {
	query := (&ContactClient{config: mrq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	mrq.withMessageContact = query
	return mrq
}

// 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.MessageRecords.Query().
//		GroupBy(messagerecords.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (mrq *MessageRecordsQuery) GroupBy(field string, fields ...string) *MessageRecordsGroupBy {
	mrq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &MessageRecordsGroupBy{build: mrq}
	grbuild.flds = &mrq.ctx.Fields
	grbuild.label = messagerecords.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.MessageRecords.Query().
//		Select(messagerecords.FieldCreatedAt).
//		Scan(ctx, &v)
func (mrq *MessageRecordsQuery) Select(fields ...string) *MessageRecordsSelect {
	mrq.ctx.Fields = append(mrq.ctx.Fields, fields...)
	sbuild := &MessageRecordsSelect{MessageRecordsQuery: mrq}
	sbuild.label = messagerecords.Label
	sbuild.flds, sbuild.scan = &mrq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a MessageRecordsSelect configured with the given aggregations.
func (mrq *MessageRecordsQuery) Aggregate(fns ...AggregateFunc) *MessageRecordsSelect {
	return mrq.Select().Aggregate(fns...)
}

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

func (mrq *MessageRecordsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*MessageRecords, error) {
	var (
		nodes       = []*MessageRecords{}
		_spec       = mrq.querySpec()
		loadedTypes = [3]bool{
			mrq.withSopStage != nil,
			mrq.withSopNode != nil,
			mrq.withMessageContact != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*MessageRecords).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &MessageRecords{config: mrq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, mrq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := mrq.withSopStage; query != nil {
		if err := mrq.loadSopStage(ctx, query, nodes, nil,
			func(n *MessageRecords, e *SopStage) { n.Edges.SopStage = e }); err != nil {
			return nil, err
		}
	}
	if query := mrq.withSopNode; query != nil {
		if err := mrq.loadSopNode(ctx, query, nodes, nil,
			func(n *MessageRecords, e *SopNode) { n.Edges.SopNode = e }); err != nil {
			return nil, err
		}
	}
	if query := mrq.withMessageContact; query != nil {
		if err := mrq.loadMessageContact(ctx, query, nodes, nil,
			func(n *MessageRecords, e *Contact) { n.Edges.MessageContact = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (mrq *MessageRecordsQuery) loadSopStage(ctx context.Context, query *SopStageQuery, nodes []*MessageRecords, init func(*MessageRecords), assign func(*MessageRecords, *SopStage)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*MessageRecords)
	for i := range nodes {
		fk := nodes[i].SourceID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(sopstage.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "source_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (mrq *MessageRecordsQuery) loadSopNode(ctx context.Context, query *SopNodeQuery, nodes []*MessageRecords, init func(*MessageRecords), assign func(*MessageRecords, *SopNode)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*MessageRecords)
	for i := range nodes {
		fk := nodes[i].SubSourceID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(sopnode.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "sub_source_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (mrq *MessageRecordsQuery) loadMessageContact(ctx context.Context, query *ContactQuery, nodes []*MessageRecords, init func(*MessageRecords), assign func(*MessageRecords, *Contact)) error {
	ids := make([]uint64, 0, len(nodes))
	nodeids := make(map[uint64][]*MessageRecords)
	for i := range nodes {
		fk := nodes[i].ContactID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(contact.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "contact_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// MessageRecordsGroupBy is the group-by builder for MessageRecords entities.
type MessageRecordsGroupBy struct {
	selector
	build *MessageRecordsQuery
}

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

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

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

// MessageRecordsSelect is the builder for selecting fields of MessageRecords entities.
type MessageRecordsSelect struct {
	*MessageRecordsQuery
	selector
}

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

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

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