// 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/testbedinfo"
)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the TestbedInfoQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (tiq *TestbedInfoQuery) Clone() *TestbedInfoQuery {
	if tiq == nil {
		return nil
	}
	return &TestbedInfoQuery{
		config:     tiq.config,
		limit:      tiq.limit,
		offset:     tiq.offset,
		order:      append([]OrderFunc{}, tiq.order...),
		predicates: append([]predicate.TestbedInfo{}, tiq.predicates...),
		// clone intermediate query.
		sql:    tiq.sql.Clone(),
		path:   tiq.path,
		unique: tiq.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.TestbedInfo.Query().
//		GroupBy(testbedinfo.FieldCreatedAt).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
//
func (tiq *TestbedInfoQuery) GroupBy(field string, fields ...string) *TestbedInfoGroupBy {
	grbuild := &TestbedInfoGroupBy{config: tiq.config}
	grbuild.fields = append([]string{field}, fields...)
	grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
		if err := tiq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		return tiq.sqlQuery(ctx), nil
	}
	grbuild.label = testbedinfo.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.TestbedInfo.Query().
//		Select(testbedinfo.FieldCreatedAt).
//		Scan(ctx, &v)
//
func (tiq *TestbedInfoQuery) Select(fields ...string) *TestbedInfoSelect {
	tiq.fields = append(tiq.fields, fields...)
	selbuild := &TestbedInfoSelect{TestbedInfoQuery: tiq}
	selbuild.label = testbedinfo.Label
	selbuild.flds, selbuild.scan = &tiq.fields, selbuild.Scan
	return selbuild
}

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

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

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

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

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

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

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

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

// TestbedInfoGroupBy is the group-by builder for TestbedInfo entities.
type TestbedInfoGroupBy 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 (tigb *TestbedInfoGroupBy) Aggregate(fns ...AggregateFunc) *TestbedInfoGroupBy {
	tigb.fns = append(tigb.fns, fns...)
	return tigb
}

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

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

func (tigb *TestbedInfoGroupBy) sqlQuery() *sql.Selector {
	selector := tigb.sql.Select()
	aggregation := make([]string, 0, len(tigb.fns))
	for _, fn := range tigb.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(tigb.fields)+len(tigb.fns))
		for _, f := range tigb.fields {
			columns = append(columns, selector.C(f))
		}
		columns = append(columns, aggregation...)
		selector.Select(columns...)
	}
	return selector.GroupBy(selector.Columns(tigb.fields...)...)
}

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

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

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