// Code generated by ent, DO NOT EDIT.

package serversitemicros

import (
	"context"
	"convert-server/domain/entity/serversitemicros/docserverproject"
	"convert-server/domain/entity/serversitemicros/predicate"
	"fmt"
	"math"

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

// DocServerProjectQuery is the builder for querying DocServerProject entities.
type DocServerProjectQuery struct {
	config
	ctx        *QueryContext
	order      []docserverproject.OrderOption
	inters     []Interceptor
	predicates []predicate.DocServerProject
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the DocServerProjectQuery builder.
func (dspq *DocServerProjectQuery) Where(ps ...predicate.DocServerProject) *DocServerProjectQuery {
	dspq.predicates = append(dspq.predicates, ps...)
	return dspq
}

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

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

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

// Order specifies how the records should be ordered.
func (dspq *DocServerProjectQuery) Order(o ...docserverproject.OrderOption) *DocServerProjectQuery {
	dspq.order = append(dspq.order, o...)
	return dspq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Exist returns true if the query has elements in the graph.
func (dspq *DocServerProjectQuery) Exist(ctx context.Context) (bool, error) {
	ctx = setContextOp(ctx, dspq.ctx, "Exist")
	switch _, err := dspq.FirstID(ctx); {
	case IsNotFound(err):
		return false, nil
	case err != nil:
		return false, fmt.Errorf("serversitemicros: check existence: %w", err)
	default:
		return true, nil
	}
}

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

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

// 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 {
//		ProjectName string `json:"project_name,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.DocServerProject.Query().
//		GroupBy(docserverproject.FieldProjectName).
//		Aggregate(serversitemicros.Count()).
//		Scan(ctx, &v)
func (dspq *DocServerProjectQuery) GroupBy(field string, fields ...string) *DocServerProjectGroupBy {
	dspq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &DocServerProjectGroupBy{build: dspq}
	grbuild.flds = &dspq.ctx.Fields
	grbuild.label = docserverproject.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 {
//		ProjectName string `json:"project_name,omitempty"`
//	}
//
//	client.DocServerProject.Query().
//		Select(docserverproject.FieldProjectName).
//		Scan(ctx, &v)
func (dspq *DocServerProjectQuery) Select(fields ...string) *DocServerProjectSelect {
	dspq.ctx.Fields = append(dspq.ctx.Fields, fields...)
	sbuild := &DocServerProjectSelect{DocServerProjectQuery: dspq}
	sbuild.label = docserverproject.Label
	sbuild.flds, sbuild.scan = &dspq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a DocServerProjectSelect configured with the given aggregations.
func (dspq *DocServerProjectQuery) Aggregate(fns ...AggregateFunc) *DocServerProjectSelect {
	return dspq.Select().Aggregate(fns...)
}

func (dspq *DocServerProjectQuery) prepareQuery(ctx context.Context) error {
	for _, inter := range dspq.inters {
		if inter == nil {
			return fmt.Errorf("serversitemicros: uninitialized interceptor (forgotten import serversitemicros/runtime?)")
		}
		if trv, ok := inter.(Traverser); ok {
			if err := trv.Traverse(ctx, dspq); err != nil {
				return err
			}
		}
	}
	for _, f := range dspq.ctx.Fields {
		if !docserverproject.ValidColumn(f) {
			return &ValidationError{Name: f, err: fmt.Errorf("serversitemicros: invalid field %q for query", f)}
		}
	}
	if dspq.path != nil {
		prev, err := dspq.path(ctx)
		if err != nil {
			return err
		}
		dspq.sql = prev
	}
	return nil
}

func (dspq *DocServerProjectQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DocServerProject, error) {
	var (
		nodes = []*DocServerProject{}
		_spec = dspq.querySpec()
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*DocServerProject).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &DocServerProject{config: dspq.config}
		nodes = append(nodes, node)
		return node.assignValues(columns, values)
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, dspq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	return nodes, nil
}

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

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

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

// DocServerProjectGroupBy is the group-by builder for DocServerProject entities.
type DocServerProjectGroupBy struct {
	selector
	build *DocServerProjectQuery
}

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

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

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

// DocServerProjectSelect is the builder for selecting fields of DocServerProject entities.
type DocServerProjectSelect struct {
	*DocServerProjectQuery
	selector
}

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

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

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