// Code generated by ent, DO NOT EDIT.

package ent

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

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/cloudreve/Cloudreve/v4/ent/entity"
	"github.com/cloudreve/Cloudreve/v4/ent/file"
	"github.com/cloudreve/Cloudreve/v4/ent/group"
	"github.com/cloudreve/Cloudreve/v4/ent/node"
	"github.com/cloudreve/Cloudreve/v4/ent/predicate"
	"github.com/cloudreve/Cloudreve/v4/ent/storagepolicy"
)

// StoragePolicyQuery is the builder for querying StoragePolicy entities.
type StoragePolicyQuery struct {
	config
	ctx          *QueryContext
	order        []storagepolicy.OrderOption
	inters       []Interceptor
	predicates   []predicate.StoragePolicy
	withGroups   *GroupQuery
	withFiles    *FileQuery
	withEntities *EntityQuery
	withNode     *NodeQuery
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the StoragePolicyQuery builder.
func (spq *StoragePolicyQuery) Where(ps ...predicate.StoragePolicy) *StoragePolicyQuery {
	spq.predicates = append(spq.predicates, ps...)
	return spq
}

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

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

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

// Order specifies how the records should be ordered.
func (spq *StoragePolicyQuery) Order(o ...storagepolicy.OrderOption) *StoragePolicyQuery {
	spq.order = append(spq.order, o...)
	return spq
}

// QueryGroups chains the current query on the "groups" edge.
func (spq *StoragePolicyQuery) QueryGroups() *GroupQuery {
	query := (&GroupClient{config: spq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := spq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := spq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(storagepolicy.Table, storagepolicy.FieldID, selector),
			sqlgraph.To(group.Table, group.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, storagepolicy.GroupsTable, storagepolicy.GroupsColumn),
		)
		fromU = sqlgraph.SetNeighbors(spq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryFiles chains the current query on the "files" edge.
func (spq *StoragePolicyQuery) QueryFiles() *FileQuery {
	query := (&FileClient{config: spq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := spq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := spq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(storagepolicy.Table, storagepolicy.FieldID, selector),
			sqlgraph.To(file.Table, file.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, storagepolicy.FilesTable, storagepolicy.FilesColumn),
		)
		fromU = sqlgraph.SetNeighbors(spq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryEntities chains the current query on the "entities" edge.
func (spq *StoragePolicyQuery) QueryEntities() *EntityQuery {
	query := (&EntityClient{config: spq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := spq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := spq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(storagepolicy.Table, storagepolicy.FieldID, selector),
			sqlgraph.To(entity.Table, entity.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, storagepolicy.EntitiesTable, storagepolicy.EntitiesColumn),
		)
		fromU = sqlgraph.SetNeighbors(spq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryNode chains the current query on the "node" edge.
func (spq *StoragePolicyQuery) QueryNode() *NodeQuery {
	query := (&NodeClient{config: spq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := spq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := spq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(storagepolicy.Table, storagepolicy.FieldID, selector),
			sqlgraph.To(node.Table, node.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, storagepolicy.NodeTable, storagepolicy.NodeColumn),
		)
		fromU = sqlgraph.SetNeighbors(spq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithGroups tells the query-builder to eager-load the nodes that are connected to
// the "groups" edge. The optional arguments are used to configure the query builder of the edge.
func (spq *StoragePolicyQuery) WithGroups(opts ...func(*GroupQuery)) *StoragePolicyQuery {
	query := (&GroupClient{config: spq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	spq.withGroups = query
	return spq
}

// WithFiles tells the query-builder to eager-load the nodes that are connected to
// the "files" edge. The optional arguments are used to configure the query builder of the edge.
func (spq *StoragePolicyQuery) WithFiles(opts ...func(*FileQuery)) *StoragePolicyQuery {
	query := (&FileClient{config: spq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	spq.withFiles = query
	return spq
}

// WithEntities tells the query-builder to eager-load the nodes that are connected to
// the "entities" edge. The optional arguments are used to configure the query builder of the edge.
func (spq *StoragePolicyQuery) WithEntities(opts ...func(*EntityQuery)) *StoragePolicyQuery {
	query := (&EntityClient{config: spq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	spq.withEntities = query
	return spq
}

// WithNode tells the query-builder to eager-load the nodes that are connected to
// the "node" edge. The optional arguments are used to configure the query builder of the edge.
func (spq *StoragePolicyQuery) WithNode(opts ...func(*NodeQuery)) *StoragePolicyQuery {
	query := (&NodeClient{config: spq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	spq.withNode = query
	return spq
}

// 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.StoragePolicy.Query().
//		GroupBy(storagepolicy.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (spq *StoragePolicyQuery) GroupBy(field string, fields ...string) *StoragePolicyGroupBy {
	spq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &StoragePolicyGroupBy{build: spq}
	grbuild.flds = &spq.ctx.Fields
	grbuild.label = storagepolicy.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.StoragePolicy.Query().
//		Select(storagepolicy.FieldCreatedAt).
//		Scan(ctx, &v)
func (spq *StoragePolicyQuery) Select(fields ...string) *StoragePolicySelect {
	spq.ctx.Fields = append(spq.ctx.Fields, fields...)
	sbuild := &StoragePolicySelect{StoragePolicyQuery: spq}
	sbuild.label = storagepolicy.Label
	sbuild.flds, sbuild.scan = &spq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a StoragePolicySelect configured with the given aggregations.
func (spq *StoragePolicyQuery) Aggregate(fns ...AggregateFunc) *StoragePolicySelect {
	return spq.Select().Aggregate(fns...)
}

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

func (spq *StoragePolicyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*StoragePolicy, error) {
	var (
		nodes       = []*StoragePolicy{}
		_spec       = spq.querySpec()
		loadedTypes = [4]bool{
			spq.withGroups != nil,
			spq.withFiles != nil,
			spq.withEntities != nil,
			spq.withNode != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*StoragePolicy).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &StoragePolicy{config: spq.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, spq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := spq.withGroups; query != nil {
		if err := spq.loadGroups(ctx, query, nodes,
			func(n *StoragePolicy) { n.Edges.Groups = []*Group{} },
			func(n *StoragePolicy, e *Group) { n.Edges.Groups = append(n.Edges.Groups, e) }); err != nil {
			return nil, err
		}
	}
	if query := spq.withFiles; query != nil {
		if err := spq.loadFiles(ctx, query, nodes,
			func(n *StoragePolicy) { n.Edges.Files = []*File{} },
			func(n *StoragePolicy, e *File) { n.Edges.Files = append(n.Edges.Files, e) }); err != nil {
			return nil, err
		}
	}
	if query := spq.withEntities; query != nil {
		if err := spq.loadEntities(ctx, query, nodes,
			func(n *StoragePolicy) { n.Edges.Entities = []*Entity{} },
			func(n *StoragePolicy, e *Entity) { n.Edges.Entities = append(n.Edges.Entities, e) }); err != nil {
			return nil, err
		}
	}
	if query := spq.withNode; query != nil {
		if err := spq.loadNode(ctx, query, nodes, nil,
			func(n *StoragePolicy, e *Node) { n.Edges.Node = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (spq *StoragePolicyQuery) loadGroups(ctx context.Context, query *GroupQuery, nodes []*StoragePolicy, init func(*StoragePolicy), assign func(*StoragePolicy, *Group)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*StoragePolicy)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	if len(query.ctx.Fields) > 0 {
		query.ctx.AppendFieldOnce(group.FieldStoragePolicyID)
	}
	query.Where(predicate.Group(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(storagepolicy.GroupsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.StoragePolicyID
		node, ok := nodeids[fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "storage_policy_id" returned %v for node %v`, fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (spq *StoragePolicyQuery) loadFiles(ctx context.Context, query *FileQuery, nodes []*StoragePolicy, init func(*StoragePolicy), assign func(*StoragePolicy, *File)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*StoragePolicy)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	if len(query.ctx.Fields) > 0 {
		query.ctx.AppendFieldOnce(file.FieldStoragePolicyFiles)
	}
	query.Where(predicate.File(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(storagepolicy.FilesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.StoragePolicyFiles
		node, ok := nodeids[fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "storage_policy_files" returned %v for node %v`, fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (spq *StoragePolicyQuery) loadEntities(ctx context.Context, query *EntityQuery, nodes []*StoragePolicy, init func(*StoragePolicy), assign func(*StoragePolicy, *Entity)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*StoragePolicy)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	if len(query.ctx.Fields) > 0 {
		query.ctx.AppendFieldOnce(entity.FieldStoragePolicyEntities)
	}
	query.Where(predicate.Entity(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(storagepolicy.EntitiesColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.StoragePolicyEntities
		node, ok := nodeids[fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "storage_policy_entities" returned %v for node %v`, fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}
func (spq *StoragePolicyQuery) loadNode(ctx context.Context, query *NodeQuery, nodes []*StoragePolicy, init func(*StoragePolicy), assign func(*StoragePolicy, *Node)) error {
	ids := make([]int, 0, len(nodes))
	nodeids := make(map[int][]*StoragePolicy)
	for i := range nodes {
		fk := nodes[i].NodeID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(node.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 "node_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

// StoragePolicyGroupBy is the group-by builder for StoragePolicy entities.
type StoragePolicyGroupBy struct {
	selector
	build *StoragePolicyQuery
}

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

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

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

// StoragePolicySelect is the builder for selecting fields of StoragePolicy entities.
type StoragePolicySelect struct {
	*StoragePolicyQuery
	selector
}

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

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

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