// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"

	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/casbackend"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/organization"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun"
	"github.com/google/uuid"
)

// CASBackendQuery is the builder for querying CASBackend entities.
type CASBackendQuery struct {
	config
	ctx              *QueryContext
	order            []casbackend.OrderOption
	inters           []Interceptor
	predicates       []predicate.CASBackend
	withOrganization *OrganizationQuery
	withWorkflowRun  *WorkflowRunQuery
	withFKs          bool
	modifiers        []func(*sql.Selector)
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the CASBackendQuery builder.
func (cbq *CASBackendQuery) Where(ps ...predicate.CASBackend) *CASBackendQuery {
	cbq.predicates = append(cbq.predicates, ps...)
	return cbq
}

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

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

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

// Order specifies how the records should be ordered.
func (cbq *CASBackendQuery) Order(o ...casbackend.OrderOption) *CASBackendQuery {
	cbq.order = append(cbq.order, o...)
	return cbq
}

// QueryOrganization chains the current query on the "organization" edge.
func (cbq *CASBackendQuery) QueryOrganization() *OrganizationQuery {
	query := (&OrganizationClient{config: cbq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := cbq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := cbq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(casbackend.Table, casbackend.FieldID, selector),
			sqlgraph.To(organization.Table, organization.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, casbackend.OrganizationTable, casbackend.OrganizationColumn),
		)
		fromU = sqlgraph.SetNeighbors(cbq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryWorkflowRun chains the current query on the "workflow_run" edge.
func (cbq *CASBackendQuery) QueryWorkflowRun() *WorkflowRunQuery {
	query := (&WorkflowRunClient{config: cbq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := cbq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := cbq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(casbackend.Table, casbackend.FieldID, selector),
			sqlgraph.To(workflowrun.Table, workflowrun.FieldID),
			sqlgraph.Edge(sqlgraph.M2M, true, casbackend.WorkflowRunTable, casbackend.WorkflowRunPrimaryKey...),
		)
		fromU = sqlgraph.SetNeighbors(cbq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

// FirstID returns the first CASBackend ID from the query.
// Returns a *NotFoundError when no CASBackend ID was found.
func (cbq *CASBackendQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
	var ids []uuid.UUID
	if ids, err = cbq.Limit(1).IDs(setContextOp(ctx, cbq.ctx, ent.OpQueryFirstID)); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{casbackend.Label}
		return
	}
	return ids[0], nil
}

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

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

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

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

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

// All executes the query and returns a list of CASBackends.
func (cbq *CASBackendQuery) All(ctx context.Context) ([]*CASBackend, error) {
	ctx = setContextOp(ctx, cbq.ctx, ent.OpQueryAll)
	if err := cbq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*CASBackend, *CASBackendQuery]()
	return withInterceptors[[]*CASBackend](ctx, cbq, qr, cbq.inters)
}

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

// IDs executes the query and returns a list of CASBackend IDs.
func (cbq *CASBackendQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
	if cbq.ctx.Unique == nil && cbq.path != nil {
		cbq.Unique(true)
	}
	ctx = setContextOp(ctx, cbq.ctx, ent.OpQueryIDs)
	if err = cbq.Select(casbackend.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

// Clone returns a duplicate of the CASBackendQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (cbq *CASBackendQuery) Clone() *CASBackendQuery {
	if cbq == nil {
		return nil
	}
	return &CASBackendQuery{
		config:           cbq.config,
		ctx:              cbq.ctx.Clone(),
		order:            append([]casbackend.OrderOption{}, cbq.order...),
		inters:           append([]Interceptor{}, cbq.inters...),
		predicates:       append([]predicate.CASBackend{}, cbq.predicates...),
		withOrganization: cbq.withOrganization.Clone(),
		withWorkflowRun:  cbq.withWorkflowRun.Clone(),
		// clone intermediate query.
		sql:       cbq.sql.Clone(),
		path:      cbq.path,
		modifiers: append([]func(*sql.Selector){}, cbq.modifiers...),
	}
}

// WithOrganization tells the query-builder to eager-load the nodes that are connected to
// the "organization" edge. The optional arguments are used to configure the query builder of the edge.
func (cbq *CASBackendQuery) WithOrganization(opts ...func(*OrganizationQuery)) *CASBackendQuery {
	query := (&OrganizationClient{config: cbq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	cbq.withOrganization = query
	return cbq
}

// WithWorkflowRun tells the query-builder to eager-load the nodes that are connected to
// the "workflow_run" edge. The optional arguments are used to configure the query builder of the edge.
func (cbq *CASBackendQuery) WithWorkflowRun(opts ...func(*WorkflowRunQuery)) *CASBackendQuery {
	query := (&WorkflowRunClient{config: cbq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	cbq.withWorkflowRun = query
	return cbq
}

// 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 {
//		Location string `json:"location,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.CASBackend.Query().
//		GroupBy(casbackend.FieldLocation).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (cbq *CASBackendQuery) GroupBy(field string, fields ...string) *CASBackendGroupBy {
	cbq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &CASBackendGroupBy{build: cbq}
	grbuild.flds = &cbq.ctx.Fields
	grbuild.label = casbackend.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 {
//		Location string `json:"location,omitempty"`
//	}
//
//	client.CASBackend.Query().
//		Select(casbackend.FieldLocation).
//		Scan(ctx, &v)
func (cbq *CASBackendQuery) Select(fields ...string) *CASBackendSelect {
	cbq.ctx.Fields = append(cbq.ctx.Fields, fields...)
	sbuild := &CASBackendSelect{CASBackendQuery: cbq}
	sbuild.label = casbackend.Label
	sbuild.flds, sbuild.scan = &cbq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a CASBackendSelect configured with the given aggregations.
func (cbq *CASBackendQuery) Aggregate(fns ...AggregateFunc) *CASBackendSelect {
	return cbq.Select().Aggregate(fns...)
}

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

func (cbq *CASBackendQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CASBackend, error) {
	var (
		nodes       = []*CASBackend{}
		withFKs     = cbq.withFKs
		_spec       = cbq.querySpec()
		loadedTypes = [2]bool{
			cbq.withOrganization != nil,
			cbq.withWorkflowRun != nil,
		}
	)
	if cbq.withOrganization != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, casbackend.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*CASBackend).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &CASBackend{config: cbq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(cbq.modifiers) > 0 {
		_spec.Modifiers = cbq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, cbq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := cbq.withOrganization; query != nil {
		if err := cbq.loadOrganization(ctx, query, nodes, nil,
			func(n *CASBackend, e *Organization) { n.Edges.Organization = e }); err != nil {
			return nil, err
		}
	}
	if query := cbq.withWorkflowRun; query != nil {
		if err := cbq.loadWorkflowRun(ctx, query, nodes,
			func(n *CASBackend) { n.Edges.WorkflowRun = []*WorkflowRun{} },
			func(n *CASBackend, e *WorkflowRun) { n.Edges.WorkflowRun = append(n.Edges.WorkflowRun, e) }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (cbq *CASBackendQuery) loadOrganization(ctx context.Context, query *OrganizationQuery, nodes []*CASBackend, init func(*CASBackend), assign func(*CASBackend, *Organization)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*CASBackend)
	for i := range nodes {
		if nodes[i].organization_cas_backends == nil {
			continue
		}
		fk := *nodes[i].organization_cas_backends
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(organization.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 "organization_cas_backends" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (cbq *CASBackendQuery) loadWorkflowRun(ctx context.Context, query *WorkflowRunQuery, nodes []*CASBackend, init func(*CASBackend), assign func(*CASBackend, *WorkflowRun)) error {
	edgeIDs := make([]driver.Value, len(nodes))
	byID := make(map[uuid.UUID]*CASBackend)
	nids := make(map[uuid.UUID]map[*CASBackend]struct{})
	for i, node := range nodes {
		edgeIDs[i] = node.ID
		byID[node.ID] = node
		if init != nil {
			init(node)
		}
	}
	query.Where(func(s *sql.Selector) {
		joinT := sql.Table(casbackend.WorkflowRunTable)
		s.Join(joinT).On(s.C(workflowrun.FieldID), joinT.C(casbackend.WorkflowRunPrimaryKey[0]))
		s.Where(sql.InValues(joinT.C(casbackend.WorkflowRunPrimaryKey[1]), edgeIDs...))
		columns := s.SelectedColumns()
		s.Select(joinT.C(casbackend.WorkflowRunPrimaryKey[1]))
		s.AppendSelect(columns...)
		s.SetDistinct(false)
	})
	if err := query.prepareQuery(ctx); err != nil {
		return err
	}
	qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
		return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
			assign := spec.Assign
			values := spec.ScanValues
			spec.ScanValues = func(columns []string) ([]any, error) {
				values, err := values(columns[1:])
				if err != nil {
					return nil, err
				}
				return append([]any{new(uuid.UUID)}, values...), nil
			}
			spec.Assign = func(columns []string, values []any) error {
				outValue := *values[0].(*uuid.UUID)
				inValue := *values[1].(*uuid.UUID)
				if nids[inValue] == nil {
					nids[inValue] = map[*CASBackend]struct{}{byID[outValue]: {}}
					return assign(columns[1:], values[1:])
				}
				nids[inValue][byID[outValue]] = struct{}{}
				return nil
			}
		})
	})
	neighbors, err := withInterceptors[[]*WorkflowRun](ctx, query, qr, query.inters)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected "workflow_run" node returned %v`, n.ID)
		}
		for kn := range nodes {
			assign(kn, n)
		}
	}
	return nil
}

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

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

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

// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (cbq *CASBackendQuery) ForUpdate(opts ...sql.LockOption) *CASBackendQuery {
	if cbq.driver.Dialect() == dialect.Postgres {
		cbq.Unique(false)
	}
	cbq.modifiers = append(cbq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return cbq
}

// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (cbq *CASBackendQuery) ForShare(opts ...sql.LockOption) *CASBackendQuery {
	if cbq.driver.Dialect() == dialect.Postgres {
		cbq.Unique(false)
	}
	cbq.modifiers = append(cbq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return cbq
}

// Modify adds a query modifier for attaching custom logic to queries.
func (cbq *CASBackendQuery) Modify(modifiers ...func(s *sql.Selector)) *CASBackendSelect {
	cbq.modifiers = append(cbq.modifiers, modifiers...)
	return cbq.Select()
}

// CASBackendGroupBy is the group-by builder for CASBackend entities.
type CASBackendGroupBy struct {
	selector
	build *CASBackendQuery
}

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

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

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

// CASBackendSelect is the builder for selecting fields of CASBackend entities.
type CASBackendSelect struct {
	*CASBackendQuery
	selector
}

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

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

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

// Modify adds a query modifier for attaching custom logic to queries.
func (cbs *CASBackendSelect) Modify(modifiers ...func(s *sql.Selector)) *CASBackendSelect {
	cbs.modifiers = append(cbs.modifiers, modifiers...)
	return cbs
}
