// Code generated by ent, DO NOT EDIT.

package serversitemicros

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

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

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

// Where adds a new predicate for the DocServerAppQuery builder.
func (dsaq *DocServerAppQuery) Where(ps ...predicate.DocServerApp) *DocServerAppQuery {
	dsaq.predicates = append(dsaq.predicates, ps...)
	return dsaq
}

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

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

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

// Order specifies how the records should be ordered.
func (dsaq *DocServerAppQuery) Order(o ...docserverapp.OrderOption) *DocServerAppQuery {
	dsaq.order = append(dsaq.order, o...)
	return dsaq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the DocServerAppQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (dsaq *DocServerAppQuery) Clone() *DocServerAppQuery {
	if dsaq == nil {
		return nil
	}
	return &DocServerAppQuery{
		config:     dsaq.config,
		ctx:        dsaq.ctx.Clone(),
		order:      append([]docserverapp.OrderOption{}, dsaq.order...),
		inters:     append([]Interceptor{}, dsaq.inters...),
		predicates: append([]predicate.DocServerApp{}, dsaq.predicates...),
		// clone intermediate query.
		sql:  dsaq.sql.Clone(),
		path: dsaq.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 {
//		Application string `json:"application,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.DocServerApp.Query().
//		GroupBy(docserverapp.FieldApplication).
//		Aggregate(serversitemicros.Count()).
//		Scan(ctx, &v)
func (dsaq *DocServerAppQuery) GroupBy(field string, fields ...string) *DocServerAppGroupBy {
	dsaq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &DocServerAppGroupBy{build: dsaq}
	grbuild.flds = &dsaq.ctx.Fields
	grbuild.label = docserverapp.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 {
//		Application string `json:"application,omitempty"`
//	}
//
//	client.DocServerApp.Query().
//		Select(docserverapp.FieldApplication).
//		Scan(ctx, &v)
func (dsaq *DocServerAppQuery) Select(fields ...string) *DocServerAppSelect {
	dsaq.ctx.Fields = append(dsaq.ctx.Fields, fields...)
	sbuild := &DocServerAppSelect{DocServerAppQuery: dsaq}
	sbuild.label = docserverapp.Label
	sbuild.flds, sbuild.scan = &dsaq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a DocServerAppSelect configured with the given aggregations.
func (dsaq *DocServerAppQuery) Aggregate(fns ...AggregateFunc) *DocServerAppSelect {
	return dsaq.Select().Aggregate(fns...)
}

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

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

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

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

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

// DocServerAppGroupBy is the group-by builder for DocServerApp entities.
type DocServerAppGroupBy struct {
	selector
	build *DocServerAppQuery
}

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

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

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

// DocServerAppSelect is the builder for selecting fields of DocServerApp entities.
type DocServerAppSelect struct {
	*DocServerAppQuery
	selector
}

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

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

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