// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"database/sql/driver"
	"fmt"
	"math"

	"entgo.io/ent"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/buildbarn/bb-portal/ent/gen/ent/bazelinvocation"
	"github.com/buildbarn/bb-portal/ent/gen/ent/eventfile"
	"github.com/buildbarn/bb-portal/ent/gen/ent/predicate"
)

// EventFileQuery is the builder for querying EventFile entities.
type EventFileQuery struct {
	config
	ctx                 *QueryContext
	order               []eventfile.OrderOption
	inters              []Interceptor
	predicates          []predicate.EventFile
	withBazelInvocation *BazelInvocationQuery
	modifiers           []func(*sql.Selector)
	loadTotal           []func(context.Context, []*EventFile) error
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the EventFileQuery builder.
func (efq *EventFileQuery) Where(ps ...predicate.EventFile) *EventFileQuery {
	efq.predicates = append(efq.predicates, ps...)
	return efq
}

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

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

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

// Order specifies how the records should be ordered.
func (efq *EventFileQuery) Order(o ...eventfile.OrderOption) *EventFileQuery {
	efq.order = append(efq.order, o...)
	return efq
}

// QueryBazelInvocation chains the current query on the "bazel_invocation" edge.
func (efq *EventFileQuery) QueryBazelInvocation() *BazelInvocationQuery {
	query := (&BazelInvocationClient{config: efq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := efq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := efq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(eventfile.Table, eventfile.FieldID, selector),
			sqlgraph.To(bazelinvocation.Table, bazelinvocation.FieldID),
			sqlgraph.Edge(sqlgraph.O2O, false, eventfile.BazelInvocationTable, eventfile.BazelInvocationColumn),
		)
		fromU = sqlgraph.SetNeighbors(efq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

// FirstID returns the first EventFile ID from the query.
// Returns a *NotFoundError when no EventFile ID was found.
func (efq *EventFileQuery) FirstID(ctx context.Context) (id int, err error) {
	var ids []int
	if ids, err = efq.Limit(1).IDs(setContextOp(ctx, efq.ctx, ent.OpQueryFirstID)); err != nil {
		return
	}
	if len(ids) == 0 {
		err = &NotFoundError{eventfile.Label}
		return
	}
	return ids[0], nil
}

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

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

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

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

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

// All executes the query and returns a list of EventFiles.
func (efq *EventFileQuery) All(ctx context.Context) ([]*EventFile, error) {
	ctx = setContextOp(ctx, efq.ctx, ent.OpQueryAll)
	if err := efq.prepareQuery(ctx); err != nil {
		return nil, err
	}
	qr := querierAll[[]*EventFile, *EventFileQuery]()
	return withInterceptors[[]*EventFile](ctx, efq, qr, efq.inters)
}

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

// IDs executes the query and returns a list of EventFile IDs.
func (efq *EventFileQuery) IDs(ctx context.Context) (ids []int, err error) {
	if efq.ctx.Unique == nil && efq.path != nil {
		efq.Unique(true)
	}
	ctx = setContextOp(ctx, efq.ctx, ent.OpQueryIDs)
	if err = efq.Select(eventfile.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

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

// WithBazelInvocation tells the query-builder to eager-load the nodes that are connected to
// the "bazel_invocation" edge. The optional arguments are used to configure the query builder of the edge.
func (efq *EventFileQuery) WithBazelInvocation(opts ...func(*BazelInvocationQuery)) *EventFileQuery {
	query := (&BazelInvocationClient{config: efq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	efq.withBazelInvocation = query
	return efq
}

// 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 {
//		URL string `json:"url,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.EventFile.Query().
//		GroupBy(eventfile.FieldURL).
//		Aggregate(ent.Count()).
//		Scan(ctx, &v)
func (efq *EventFileQuery) GroupBy(field string, fields ...string) *EventFileGroupBy {
	efq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &EventFileGroupBy{build: efq}
	grbuild.flds = &efq.ctx.Fields
	grbuild.label = eventfile.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 {
//		URL string `json:"url,omitempty"`
//	}
//
//	client.EventFile.Query().
//		Select(eventfile.FieldURL).
//		Scan(ctx, &v)
func (efq *EventFileQuery) Select(fields ...string) *EventFileSelect {
	efq.ctx.Fields = append(efq.ctx.Fields, fields...)
	sbuild := &EventFileSelect{EventFileQuery: efq}
	sbuild.label = eventfile.Label
	sbuild.flds, sbuild.scan = &efq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a EventFileSelect configured with the given aggregations.
func (efq *EventFileQuery) Aggregate(fns ...AggregateFunc) *EventFileSelect {
	return efq.Select().Aggregate(fns...)
}

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

func (efq *EventFileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*EventFile, error) {
	var (
		nodes       = []*EventFile{}
		_spec       = efq.querySpec()
		loadedTypes = [1]bool{
			efq.withBazelInvocation != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*EventFile).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &EventFile{config: efq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(efq.modifiers) > 0 {
		_spec.Modifiers = efq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, efq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := efq.withBazelInvocation; query != nil {
		if err := efq.loadBazelInvocation(ctx, query, nodes, nil,
			func(n *EventFile, e *BazelInvocation) { n.Edges.BazelInvocation = e }); err != nil {
			return nil, err
		}
	}
	for i := range efq.loadTotal {
		if err := efq.loadTotal[i](ctx, nodes); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (efq *EventFileQuery) loadBazelInvocation(ctx context.Context, query *BazelInvocationQuery, nodes []*EventFile, init func(*EventFile), assign func(*EventFile, *BazelInvocation)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[int]*EventFile)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
	}
	query.withFKs = true
	query.Where(predicate.BazelInvocation(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(eventfile.BazelInvocationColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.event_file_bazel_invocation
		if fk == nil {
			return fmt.Errorf(`foreign-key "event_file_bazel_invocation" is nil for node %v`, n.ID)
		}
		node, ok := nodeids[*fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "event_file_bazel_invocation" returned %v for node %v`, *fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// EventFileGroupBy is the group-by builder for EventFile entities.
type EventFileGroupBy struct {
	selector
	build *EventFileQuery
}

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

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

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

// EventFileSelect is the builder for selecting fields of EventFile entities.
type EventFileSelect struct {
	*EventFileQuery
	selector
}

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

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

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