// Code generated by ent, DO NOT EDIT.

package serversitemicros

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

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

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

// Where adds a new predicate for the DocServerCallbackQuery builder.
func (dscq *DocServerCallbackQuery) Where(ps ...predicate.DocServerCallback) *DocServerCallbackQuery {
	dscq.predicates = append(dscq.predicates, ps...)
	return dscq
}

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

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

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

// Order specifies how the records should be ordered.
func (dscq *DocServerCallbackQuery) Order(o ...docservercallback.OrderOption) *DocServerCallbackQuery {
	dscq.order = append(dscq.order, o...)
	return dscq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a DocServerCallbackSelect configured with the given aggregations.
func (dscq *DocServerCallbackQuery) Aggregate(fns ...AggregateFunc) *DocServerCallbackSelect {
	return dscq.Select().Aggregate(fns...)
}

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

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

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

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

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

// DocServerCallbackGroupBy is the group-by builder for DocServerCallback entities.
type DocServerCallbackGroupBy struct {
	selector
	build *DocServerCallbackQuery
}

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

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

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

// DocServerCallbackSelect is the builder for selecting fields of DocServerCallback entities.
type DocServerCallbackSelect struct {
	*DocServerCallbackQuery
	selector
}

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

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

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