// Code generated by entc, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

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

	"github.com/pingcap/test-infra/common/model"
	"github.com/pingcap/test-infra/services/tcms/service/store/v2/ent/internal"
	"github.com/pingcap/test-infra/services/tcms/service/store/v2/ent/predicate"
	"github.com/pingcap/test-infra/services/tcms/service/store/v2/ent/resourceduration"
)

// ResourceDurationQuery is the builder for querying ResourceDuration entities.
type ResourceDurationQuery struct {
	config
	limit      *int
	offset     *int
	unique     *bool
	order      []OrderFunc
	fields     []string
	predicates []predicate.ResourceDuration
	modifiers  []func(s *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 ResourceDurationQuery builder.
func (rdq *ResourceDurationQuery) Where(ps ...predicate.ResourceDuration) *ResourceDurationQuery {
	rdq.predicates = append(rdq.predicates, ps...)
	return rdq
}

// Limit adds a limit step to the query.
func (rdq *ResourceDurationQuery) Limit(limit int) *ResourceDurationQuery {
	rdq.limit = &limit
	return rdq
}

// Offset adds an offset step to the query.
func (rdq *ResourceDurationQuery) Offset(offset int) *ResourceDurationQuery {
	rdq.offset = &offset
	return rdq
}

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

// Order adds an order step to the query.
func (rdq *ResourceDurationQuery) Order(o ...OrderFunc) *ResourceDurationQuery {
	rdq.order = append(rdq.order, o...)
	return rdq
}

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

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

// FirstID returns the first ResourceDuration ID from the query.
// Returns a *NotFoundError when no ResourceDuration ID was found.
func (rdq *ResourceDurationQuery) FirstID(ctx context.Context) (id model.ID, err error) {
	var ids []model.ID
	if ids, err = rdq.Limit(1).IDs(ctx); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{resourceduration.Label}
		return
	}
	return ids[0], nil
}

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

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

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

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

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

// All executes the query and returns a list of ResourceDurations.
func (rdq *ResourceDurationQuery) All(ctx context.Context) ([]*ResourceDuration, error) {
	if err := rdq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	return rdq.sqlAll(ctx)
}

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

// IDs executes the query and returns a list of ResourceDuration IDs.
func (rdq *ResourceDurationQuery) IDs(ctx context.Context) ([]model.ID, error) {
	var ids []model.ID
	if err := rdq.Select(resourceduration.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

// Count returns the count of the given query.
func (rdq *ResourceDurationQuery) Count(ctx context.Context) (int, error) {
	if err := rdq.prepareQuery(ctx); err != nil {
		return 0, err
	}
	return rdq.sqlCount(ctx)
}

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

// Exist returns true if the query has elements in the graph.
func (rdq *ResourceDurationQuery) Exist(ctx context.Context) (bool, error) {
	if err := rdq.prepareQuery(ctx); err != nil {
		return false, err
	}
	return rdq.sqlExist(ctx)
}

// ExistX is like Exist, but panics if an error occurs.
func (rdq *ResourceDurationQuery) ExistX(ctx context.Context) bool {
	exist, err := rdq.Exist(ctx)
	if err != nil {
		panic(err)
	}
	return exist
}

// Clone returns a duplicate of the ResourceDurationQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (rdq *ResourceDurationQuery) Clone() *ResourceDurationQuery {
	if rdq == nil {
		return nil
	}
	return &ResourceDurationQuery{
		config:     rdq.config,
		limit:      rdq.limit,
		offset:     rdq.offset,
		order:      append([]OrderFunc{}, rdq.order...),
		predicates: append([]predicate.ResourceDuration{}, rdq.predicates...),
		// clone intermediate query.
		sql:    rdq.sql.Clone(),
		path:   rdq.path,
		unique: rdq.unique,
	}
}

// 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:"createdAt,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.ResourceDuration.Query().
//		GroupBy(resourceduration.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
//
func (rdq *ResourceDurationQuery) GroupBy(field string, fields ...string) *ResourceDurationGroupBy {
	grbuild := &ResourceDurationGroupBy{config: rdq.config}
	grbuild.fields = append([]string{field}, fields...)
	grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
		if err := rdq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		return rdq.sqlQuery(ctx), nil
	}
	grbuild.label = resourceduration.Label
	grbuild.flds, grbuild.scan = &grbuild.fields, 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:"createdAt,omitempty"`
//	}
//
//	client.ResourceDuration.Query().
//		Select(resourceduration.FieldCreatedAt).
//		Scan(ctx, &v)
//
func (rdq *ResourceDurationQuery) Select(fields ...string) *ResourceDurationSelect {
	rdq.fields = append(rdq.fields, fields...)
	selbuild := &ResourceDurationSelect{ResourceDurationQuery: rdq}
	selbuild.label = resourceduration.Label
	selbuild.flds, selbuild.scan = &rdq.fields, selbuild.Scan
	return selbuild
}

func (rdq *ResourceDurationQuery) prepareQuery(ctx context.Context) error {
	for _, f := range rdq.fields {
		if !resourceduration.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
		}
	}
	if rdq.path != nil {
		prev, err := rdq.path(ctx)
		if err != nil {
			return err
		}
		rdq.sql = prev
	}
	return nil
}

func (rdq *ResourceDurationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ResourceDuration, error) {
	var (
		nodes = []*ResourceDuration{}
		_spec = rdq.querySpec()
	)
	_spec.ScanValues = func(columns []string) ([]interface{}, error) {
		return (*ResourceDuration).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []interface{}) error {
		node := &ResourceDuration{config: rdq.config}
		nodes = append(nodes, node)
		return node.assignValues(columns, values)
	}
	_spec.Node.Schema = rdq.schemaConfig.ResourceDuration
	ctx = internal.NewSchemaConfigContext(ctx, rdq.schemaConfig)
	if len(rdq.modifiers) > 0 {
		_spec.Modifiers = rdq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, rdq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	return nodes, nil
}

func (rdq *ResourceDurationQuery) sqlCount(ctx context.Context) (int, error) {
	_spec := rdq.querySpec()
	_spec.Node.Schema = rdq.schemaConfig.ResourceDuration
	ctx = internal.NewSchemaConfigContext(ctx, rdq.schemaConfig)
	if len(rdq.modifiers) > 0 {
		_spec.Modifiers = rdq.modifiers
	}
	_spec.Node.Columns = rdq.fields
	if len(rdq.fields) > 0 {
		_spec.Unique = rdq.unique != nil && *rdq.unique
	}
	return sqlgraph.CountNodes(ctx, rdq.driver, _spec)
}

func (rdq *ResourceDurationQuery) sqlExist(ctx context.Context) (bool, error) {
	n, err := rdq.sqlCount(ctx)
	if err != nil {
		return false, fmt.Errorf("ent: check existence: %w", err)
	}
	return n > 0, nil
}

func (rdq *ResourceDurationQuery) querySpec() *sqlgraph.QuerySpec {
	_spec := &sqlgraph.QuerySpec{
		Node: &sqlgraph.NodeSpec{
			Table:   resourceduration.Table,
			Columns: resourceduration.Columns,
			ID: &sqlgraph.FieldSpec{
				Type:   field.TypeUint64,
				Column: resourceduration.FieldID,
			},
		},
		From:   rdq.sql,
		Unique: true,
	}
	if unique := rdq.unique; unique != nil {
		_spec.Unique = *unique
	}
	if fields := rdq.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, resourceduration.FieldID)
		for i := range fields {
			if fields[i] != resourceduration.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
			}
		}
	}
	if ps := rdq.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if limit := rdq.limit; limit != nil {
		_spec.Limit = *limit
	}
	if offset := rdq.offset; offset != nil {
		_spec.Offset = *offset
	}
	if ps := rdq.order; len(ps) > 0 {
		_spec.Order = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	return _spec
}

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

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

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

// ResourceDurationGroupBy is the group-by builder for ResourceDuration entities.
type ResourceDurationGroupBy struct {
	config
	selector
	fields []string
	fns    []AggregateFunc
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

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

// Scan applies the group-by query and scans the result into the given value.
func (rdgb *ResourceDurationGroupBy) Scan(ctx context.Context, v interface{}) error {
	query, err := rdgb.path(ctx)
	if err != nil {
		return err
	}
	rdgb.sql = query
	return rdgb.sqlScan(ctx, v)
}

func (rdgb *ResourceDurationGroupBy) sqlScan(ctx context.Context, v interface{}) error {
	for _, f := range rdgb.fields {
		if !resourceduration.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
		}
	}
	selector := rdgb.sqlQuery()
	if err := selector.Err(); err != nil {
		return err
	}
	rows := &sql.Rows{}
	query, args := selector.Query()
	if err := rdgb.driver.Query(ctx, query, args, rows); err != nil {
		return err
	}
	defer rows.Close()
	return sql.ScanSlice(rows, v)
}

func (rdgb *ResourceDurationGroupBy) sqlQuery() *sql.Selector {
	selector := rdgb.sql.Select()
	aggregation := make([]string, 0, len(rdgb.fns))
	for _, fn := range rdgb.fns {
		aggregation = append(aggregation, fn(selector))
	}
	// If no columns were selected in a custom aggregation function, the default
	// selection is the fields used for "group-by", and the aggregation functions.
	if len(selector.SelectedColumns()) == 0 {
		columns := make([]string, 0, len(rdgb.fields)+len(rdgb.fns))
		for _, f := range rdgb.fields {
			columns = append(columns, selector.C(f))
		}
		columns = append(columns, aggregation...)
		selector.Select(columns...)
	}
	return selector.GroupBy(selector.Columns(rdgb.fields...)...)
}

// ResourceDurationSelect is the builder for selecting fields of ResourceDuration entities.
type ResourceDurationSelect struct {
	*ResourceDurationQuery
	selector
	// intermediate query (i.e. traversal path).
	sql *sql.Selector
}

// Scan applies the selector query and scans the result into the given value.
func (rds *ResourceDurationSelect) Scan(ctx context.Context, v interface{}) error {
	if err := rds.prepareQuery(ctx); err != nil {
		return err
	}
	rds.sql = rds.ResourceDurationQuery.sqlQuery(ctx)
	return rds.sqlScan(ctx, v)
}

func (rds *ResourceDurationSelect) sqlScan(ctx context.Context, v interface{}) error {
	rows := &sql.Rows{}
	query, args := rds.sql.Query()
	if err := rds.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 (rds *ResourceDurationSelect) Modify(modifiers ...func(s *sql.Selector)) *ResourceDurationSelect {
	rds.modifiers = append(rds.modifiers, modifiers...)
	return rds
}
