// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"
	"registry-backend/ent/predicate"
	"registry-backend/ent/publisher"
	"registry-backend/ent/publisherpermission"
	"registry-backend/ent/user"

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

// PublisherPermissionQuery is the builder for querying PublisherPermission entities.
type PublisherPermissionQuery struct {
	config
	ctx           *QueryContext
	order         []publisherpermission.OrderOption
	inters        []Interceptor
	predicates    []predicate.PublisherPermission
	withUser      *UserQuery
	withPublisher *PublisherQuery
	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 PublisherPermissionQuery builder.
func (ppq *PublisherPermissionQuery) Where(ps ...predicate.PublisherPermission) *PublisherPermissionQuery {
	ppq.predicates = append(ppq.predicates, ps...)
	return ppq
}

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

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

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

// Order specifies how the records should be ordered.
func (ppq *PublisherPermissionQuery) Order(o ...publisherpermission.OrderOption) *PublisherPermissionQuery {
	ppq.order = append(ppq.order, o...)
	return ppq
}

// QueryUser chains the current query on the "user" edge.
func (ppq *PublisherPermissionQuery) QueryUser() *UserQuery {
	query := (&UserClient{config: ppq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ppq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ppq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(publisherpermission.Table, publisherpermission.FieldID, selector),
			sqlgraph.To(user.Table, user.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, publisherpermission.UserTable, publisherpermission.UserColumn),
		)
		fromU = sqlgraph.SetNeighbors(ppq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryPublisher chains the current query on the "publisher" edge.
func (ppq *PublisherPermissionQuery) QueryPublisher() *PublisherQuery {
	query := (&PublisherClient{config: ppq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := ppq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := ppq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(publisherpermission.Table, publisherpermission.FieldID, selector),
			sqlgraph.To(publisher.Table, publisher.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, publisherpermission.PublisherTable, publisherpermission.PublisherColumn),
		)
		fromU = sqlgraph.SetNeighbors(ppq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (ppq *PublisherPermissionQuery) WithUser(opts ...func(*UserQuery)) *PublisherPermissionQuery {
	query := (&UserClient{config: ppq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ppq.withUser = query
	return ppq
}

// WithPublisher tells the query-builder to eager-load the nodes that are connected to
// the "publisher" edge. The optional arguments are used to configure the query builder of the edge.
func (ppq *PublisherPermissionQuery) WithPublisher(opts ...func(*PublisherQuery)) *PublisherPermissionQuery {
	query := (&PublisherClient{config: ppq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	ppq.withPublisher = query
	return ppq
}

// 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 {
//		Permission schema.PublisherPermissionType `json:"permission,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.PublisherPermission.Query().
//		GroupBy(publisherpermission.FieldPermission).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (ppq *PublisherPermissionQuery) GroupBy(field string, fields ...string) *PublisherPermissionGroupBy {
	ppq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &PublisherPermissionGroupBy{build: ppq}
	grbuild.flds = &ppq.ctx.Fields
	grbuild.label = publisherpermission.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 {
//		Permission schema.PublisherPermissionType `json:"permission,omitempty"`
//	}
//
//	client.PublisherPermission.Query().
//		Select(publisherpermission.FieldPermission).
//		Scan(ctx, &v)
func (ppq *PublisherPermissionQuery) Select(fields ...string) *PublisherPermissionSelect {
	ppq.ctx.Fields = append(ppq.ctx.Fields, fields...)
	sbuild := &PublisherPermissionSelect{PublisherPermissionQuery: ppq}
	sbuild.label = publisherpermission.Label
	sbuild.flds, sbuild.scan = &ppq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a PublisherPermissionSelect configured with the given aggregations.
func (ppq *PublisherPermissionQuery) Aggregate(fns ...AggregateFunc) *PublisherPermissionSelect {
	return ppq.Select().Aggregate(fns...)
}

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

func (ppq *PublisherPermissionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*PublisherPermission, error) {
	var (
		nodes       = []*PublisherPermission{}
		_spec       = ppq.querySpec()
		loadedTypes = [2]bool{
			ppq.withUser != nil,
			ppq.withPublisher != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*PublisherPermission).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &PublisherPermission{config: ppq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(ppq.modifiers) > 0 {
		_spec.Modifiers = ppq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, ppq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := ppq.withUser; query != nil {
		if err := ppq.loadUser(ctx, query, nodes, nil,
			func(n *PublisherPermission, e *User) { n.Edges.User = e }); err != nil {
			return nil, err
		}
	}
	if query := ppq.withPublisher; query != nil {
		if err := ppq.loadPublisher(ctx, query, nodes, nil,
			func(n *PublisherPermission, e *Publisher) { n.Edges.Publisher = e }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (ppq *PublisherPermissionQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*PublisherPermission, init func(*PublisherPermission), assign func(*PublisherPermission, *User)) error {
	ids := make([]string, 0, len(nodes))
	nodeids := make(map[string][]*PublisherPermission)
	for i := range nodes {
		fk := nodes[i].UserID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(user.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 "user_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (ppq *PublisherPermissionQuery) loadPublisher(ctx context.Context, query *PublisherQuery, nodes []*PublisherPermission, init func(*PublisherPermission), assign func(*PublisherPermission, *Publisher)) error {
	ids := make([]string, 0, len(nodes))
	nodeids := make(map[string][]*PublisherPermission)
	for i := range nodes {
		fk := nodes[i].PublisherID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(publisher.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 "publisher_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}

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

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

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

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

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

// PublisherPermissionGroupBy is the group-by builder for PublisherPermission entities.
type PublisherPermissionGroupBy struct {
	selector
	build *PublisherPermissionQuery
}

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

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

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

// PublisherPermissionSelect is the builder for selecting fields of PublisherPermission entities.
type PublisherPermissionSelect struct {
	*PublisherPermissionQuery
	selector
}

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

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

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