// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"
	"registry-backend/ent/ciworkflowresult"
	"registry-backend/ent/gitcommit"
	"registry-backend/ent/predicate"
	"registry-backend/ent/storagefile"

	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/google/uuid"
)

// CIWorkflowResultQuery is the builder for querying CIWorkflowResult entities.
type CIWorkflowResultQuery struct {
	config
	ctx             *QueryContext
	order           []ciworkflowresult.OrderOption
	inters          []Interceptor
	predicates      []predicate.CIWorkflowResult
	withGitcommit   *GitCommitQuery
	withStorageFile *StorageFileQuery
	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 CIWorkflowResultQuery builder.
func (cwrq *CIWorkflowResultQuery) Where(ps ...predicate.CIWorkflowResult) *CIWorkflowResultQuery {
	cwrq.predicates = append(cwrq.predicates, ps...)
	return cwrq
}

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

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

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

// Order specifies how the records should be ordered.
func (cwrq *CIWorkflowResultQuery) Order(o ...ciworkflowresult.OrderOption) *CIWorkflowResultQuery {
	cwrq.order = append(cwrq.order, o...)
	return cwrq
}

// QueryGitcommit chains the current query on the "gitcommit" edge.
func (cwrq *CIWorkflowResultQuery) QueryGitcommit() *GitCommitQuery {
	query := (&GitCommitClient{config: cwrq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := cwrq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := cwrq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(ciworkflowresult.Table, ciworkflowresult.FieldID, selector),
			sqlgraph.To(gitcommit.Table, gitcommit.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, ciworkflowresult.GitcommitTable, ciworkflowresult.GitcommitColumn),
		)
		fromU = sqlgraph.SetNeighbors(cwrq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryStorageFile chains the current query on the "storage_file" edge.
func (cwrq *CIWorkflowResultQuery) QueryStorageFile() *StorageFileQuery {
	query := (&StorageFileClient{config: cwrq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := cwrq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := cwrq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(ciworkflowresult.Table, ciworkflowresult.FieldID, selector),
			sqlgraph.To(storagefile.Table, storagefile.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, ciworkflowresult.StorageFileTable, ciworkflowresult.StorageFileColumn),
		)
		fromU = sqlgraph.SetNeighbors(cwrq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

// IDs executes the query and returns a list of CIWorkflowResult IDs.
func (cwrq *CIWorkflowResultQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
	if cwrq.ctx.Unique == nil && cwrq.path != nil {
		cwrq.Unique(true)
	}
	ctx = setContextOp(ctx, cwrq.ctx, "IDs")
	if err = cwrq.Select(ciworkflowresult.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

// WithGitcommit tells the query-builder to eager-load the nodes that are connected to
// the "gitcommit" edge. The optional arguments are used to configure the query builder of the edge.
func (cwrq *CIWorkflowResultQuery) WithGitcommit(opts ...func(*GitCommitQuery)) *CIWorkflowResultQuery {
	query := (&GitCommitClient{config: cwrq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	cwrq.withGitcommit = query
	return cwrq
}

// WithStorageFile tells the query-builder to eager-load the nodes that are connected to
// the "storage_file" edge. The optional arguments are used to configure the query builder of the edge.
func (cwrq *CIWorkflowResultQuery) WithStorageFile(opts ...func(*StorageFileQuery)) *CIWorkflowResultQuery {
	query := (&StorageFileClient{config: cwrq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	cwrq.withStorageFile = query
	return cwrq
}

// 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 {
//		CreateTime time.Time `json:"create_time,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.CIWorkflowResult.Query().
//		GroupBy(ciworkflowresult.FieldCreateTime).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (cwrq *CIWorkflowResultQuery) GroupBy(field string, fields ...string) *CIWorkflowResultGroupBy {
	cwrq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &CIWorkflowResultGroupBy{build: cwrq}
	grbuild.flds = &cwrq.ctx.Fields
	grbuild.label = ciworkflowresult.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 {
//		CreateTime time.Time `json:"create_time,omitempty"`
//	}
//
//	client.CIWorkflowResult.Query().
//		Select(ciworkflowresult.FieldCreateTime).
//		Scan(ctx, &v)
func (cwrq *CIWorkflowResultQuery) Select(fields ...string) *CIWorkflowResultSelect {
	cwrq.ctx.Fields = append(cwrq.ctx.Fields, fields...)
	sbuild := &CIWorkflowResultSelect{CIWorkflowResultQuery: cwrq}
	sbuild.label = ciworkflowresult.Label
	sbuild.flds, sbuild.scan = &cwrq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a CIWorkflowResultSelect configured with the given aggregations.
func (cwrq *CIWorkflowResultQuery) Aggregate(fns ...AggregateFunc) *CIWorkflowResultSelect {
	return cwrq.Select().Aggregate(fns...)
}

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

func (cwrq *CIWorkflowResultQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*CIWorkflowResult, error) {
	var (
		nodes       = []*CIWorkflowResult{}
		withFKs     = cwrq.withFKs
		_spec       = cwrq.querySpec()
		loadedTypes = [2]bool{
			cwrq.withGitcommit != nil,
			cwrq.withStorageFile != nil,
		}
	)
	if cwrq.withGitcommit != nil {
		withFKs = true
	}
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, ciworkflowresult.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*CIWorkflowResult).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &CIWorkflowResult{config: cwrq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(cwrq.modifiers) > 0 {
		_spec.Modifiers = cwrq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, cwrq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := cwrq.withGitcommit; query != nil {
		if err := cwrq.loadGitcommit(ctx, query, nodes, nil,
			func(n *CIWorkflowResult, e *GitCommit) { n.Edges.Gitcommit = e }); err != nil {
			return nil, err
		}
	}
	if query := cwrq.withStorageFile; query != nil {
		if err := cwrq.loadStorageFile(ctx, query, nodes,
			func(n *CIWorkflowResult) { n.Edges.StorageFile = []*StorageFile{} },
			func(n *CIWorkflowResult, e *StorageFile) { n.Edges.StorageFile = append(n.Edges.StorageFile, e) }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (cwrq *CIWorkflowResultQuery) loadGitcommit(ctx context.Context, query *GitCommitQuery, nodes []*CIWorkflowResult, init func(*CIWorkflowResult), assign func(*CIWorkflowResult, *GitCommit)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*CIWorkflowResult)
	for i := range nodes {
		if nodes[i].git_commit_results == nil {
			continue
		}
		fk := *nodes[i].git_commit_results
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(gitcommit.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 "git_commit_results" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (cwrq *CIWorkflowResultQuery) loadStorageFile(ctx context.Context, query *StorageFileQuery, nodes []*CIWorkflowResult, init func(*CIWorkflowResult), assign func(*CIWorkflowResult, *StorageFile)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*CIWorkflowResult)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	query.withFKs = true
	query.Where(predicate.StorageFile(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(ciworkflowresult.StorageFileColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.ci_workflow_result_storage_file
		if fk == nil {
			return fmt.Errorf(`foreign-key "ci_workflow_result_storage_file" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "ci_workflow_result_storage_file" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

func (cwrq *CIWorkflowResultQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(cwrq.driver.Dialect())
	t1 := builder.Table(ciworkflowresult.Table)
	columns := cwrq.ctx.Fields
	if len(columns) == 0 {
		columns = ciworkflowresult.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if cwrq.sql != nil {
		selector = cwrq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if cwrq.ctx.Unique != nil && *cwrq.ctx.Unique {
		selector.Distinct()
	}
	for _, m := range cwrq.modifiers {
		m(selector)
	}
	for _, p := range cwrq.predicates {
		p(selector)
	}
	for _, p := range cwrq.order {
		p(selector)
	}
	if offset := cwrq.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 := cwrq.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 (cwrq *CIWorkflowResultQuery) ForUpdate(opts ...sql.LockOption) *CIWorkflowResultQuery {
	if cwrq.driver.Dialect() == dialect.Postgres {
		cwrq.Unique(false)
	}
	cwrq.modifiers = append(cwrq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return cwrq
}

// 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 (cwrq *CIWorkflowResultQuery) ForShare(opts ...sql.LockOption) *CIWorkflowResultQuery {
	if cwrq.driver.Dialect() == dialect.Postgres {
		cwrq.Unique(false)
	}
	cwrq.modifiers = append(cwrq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return cwrq
}

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

// CIWorkflowResultGroupBy is the group-by builder for CIWorkflowResult entities.
type CIWorkflowResultGroupBy struct {
	selector
	build *CIWorkflowResultQuery
}

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

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

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

// CIWorkflowResultSelect is the builder for selecting fields of CIWorkflowResult entities.
type CIWorkflowResultSelect struct {
	*CIWorkflowResultQuery
	selector
}

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

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

func (cwrs *CIWorkflowResultSelect) sqlScan(ctx context.Context, root *CIWorkflowResultQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(cwrs.fns))
	for _, fn := range cwrs.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*cwrs.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 := cwrs.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 (cwrs *CIWorkflowResultSelect) Modify(modifiers ...func(s *sql.Selector)) *CIWorkflowResultSelect {
	cwrs.modifiers = append(cwrs.modifiers, modifiers...)
	return cwrs
}
