// Code generated by ent, DO NOT EDIT.

package serversitemicros

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

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

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

// Where adds a new predicate for the DocServerGetProjectQuery builder.
func (dsgpq *DocServerGetProjectQuery) Where(ps ...predicate.DocServerGetProject) *DocServerGetProjectQuery {
	dsgpq.predicates = append(dsgpq.predicates, ps...)
	return dsgpq
}

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

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

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

// Order specifies how the records should be ordered.
func (dsgpq *DocServerGetProjectQuery) Order(o ...docservergetproject.OrderOption) *DocServerGetProjectQuery {
	dsgpq.order = append(dsgpq.order, o...)
	return dsgpq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Clone returns a duplicate of the DocServerGetProjectQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (dsgpq *DocServerGetProjectQuery) Clone() *DocServerGetProjectQuery {
	if dsgpq == nil {
		return nil
	}
	return &DocServerGetProjectQuery{
		config:     dsgpq.config,
		ctx:        dsgpq.ctx.Clone(),
		order:      append([]docservergetproject.OrderOption{}, dsgpq.order...),
		inters:     append([]Interceptor{}, dsgpq.inters...),
		predicates: append([]predicate.DocServerGetProject{}, dsgpq.predicates...),
		// clone intermediate query.
		sql:  dsgpq.sql.Clone(),
		path: dsgpq.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.DocServerGetProject.Query().
//		GroupBy(docservergetproject.FieldServerProjectID).
//		Aggregate(serversitemicros.Count()).
//		Scan(ctx, &v)
func (dsgpq *DocServerGetProjectQuery) GroupBy(field string, fields ...string) *DocServerGetProjectGroupBy {
	dsgpq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &DocServerGetProjectGroupBy{build: dsgpq}
	grbuild.flds = &dsgpq.ctx.Fields
	grbuild.label = docservergetproject.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.DocServerGetProject.Query().
//		Select(docservergetproject.FieldServerProjectID).
//		Scan(ctx, &v)
func (dsgpq *DocServerGetProjectQuery) Select(fields ...string) *DocServerGetProjectSelect {
	dsgpq.ctx.Fields = append(dsgpq.ctx.Fields, fields...)
	sbuild := &DocServerGetProjectSelect{DocServerGetProjectQuery: dsgpq}
	sbuild.label = docservergetproject.Label
	sbuild.flds, sbuild.scan = &dsgpq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a DocServerGetProjectSelect configured with the given aggregations.
func (dsgpq *DocServerGetProjectQuery) Aggregate(fns ...AggregateFunc) *DocServerGetProjectSelect {
	return dsgpq.Select().Aggregate(fns...)
}

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

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

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

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

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

// DocServerGetProjectGroupBy is the group-by builder for DocServerGetProject entities.
type DocServerGetProjectGroupBy struct {
	selector
	build *DocServerGetProjectQuery
}

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

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

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

// DocServerGetProjectSelect is the builder for selecting fields of DocServerGetProject entities.
type DocServerGetProjectSelect struct {
	*DocServerGetProjectQuery
	selector
}

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

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

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