// Code generated by ent, DO NOT EDIT.

package db

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

	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/chaitin/MonkeyCode/backend/db/codesnippet"
	"github.com/chaitin/MonkeyCode/backend/db/predicate"
	"github.com/chaitin/MonkeyCode/backend/db/user"
	"github.com/chaitin/MonkeyCode/backend/db/workspace"
	"github.com/chaitin/MonkeyCode/backend/db/workspacefile"
	"github.com/google/uuid"
)

// WorkspaceFileQuery is the builder for querying WorkspaceFile entities.
type WorkspaceFileQuery struct {
	config
	ctx           *QueryContext
	order         []workspacefile.OrderOption
	inters        []Interceptor
	predicates    []predicate.WorkspaceFile
	withOwner     *UserQuery
	withWorkspace *WorkspaceQuery
	withSnippets  *CodeSnippetQuery
	modifiers     []func(*sql.Selector)
	// intermediate query (i.e. traversal path).
	sql  *sql.Selector
	path func(context.Context) (*sql.Selector, error)
}

// Where adds a new predicate for the WorkspaceFileQuery builder.
func (wfq *WorkspaceFileQuery) Where(ps ...predicate.WorkspaceFile) *WorkspaceFileQuery {
	wfq.predicates = append(wfq.predicates, ps...)
	return wfq
}

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

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

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

// Order specifies how the records should be ordered.
func (wfq *WorkspaceFileQuery) Order(o ...workspacefile.OrderOption) *WorkspaceFileQuery {
	wfq.order = append(wfq.order, o...)
	return wfq
}

// QueryOwner chains the current query on the "owner" edge.
func (wfq *WorkspaceFileQuery) QueryOwner() *UserQuery {
	query := (&UserClient{config: wfq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := wfq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := wfq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(workspacefile.Table, workspacefile.FieldID, selector),
			sqlgraph.To(user.Table, user.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, workspacefile.OwnerTable, workspacefile.OwnerColumn),
		)
		fromU = sqlgraph.SetNeighbors(wfq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QueryWorkspace chains the current query on the "workspace" edge.
func (wfq *WorkspaceFileQuery) QueryWorkspace() *WorkspaceQuery {
	query := (&WorkspaceClient{config: wfq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := wfq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := wfq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(workspacefile.Table, workspacefile.FieldID, selector),
			sqlgraph.To(workspace.Table, workspace.FieldID),
			sqlgraph.Edge(sqlgraph.M2O, true, workspacefile.WorkspaceTable, workspacefile.WorkspaceColumn),
		)
		fromU = sqlgraph.SetNeighbors(wfq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

// QuerySnippets chains the current query on the "snippets" edge.
func (wfq *WorkspaceFileQuery) QuerySnippets() *CodeSnippetQuery {
	query := (&CodeSnippetClient{config: wfq.config}).Query()
	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
		if err := wfq.prepareQuery(ctx); err != nil {
			return nil, err
		}
		selector := wfq.sqlQuery(ctx)
		if err := selector.Err(); err != nil {
			return nil, err
		}
		step := sqlgraph.NewStep(
			sqlgraph.From(workspacefile.Table, workspacefile.FieldID, selector),
			sqlgraph.To(codesnippet.Table, codesnippet.FieldID),
			sqlgraph.Edge(sqlgraph.O2M, false, workspacefile.SnippetsTable, workspacefile.SnippetsColumn),
		)
		fromU = sqlgraph.SetNeighbors(wfq.driver.Dialect(), step)
		return fromU, nil
	}
	return query
}

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

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

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

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

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

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

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

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

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

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

// IDs executes the query and returns a list of WorkspaceFile IDs.
func (wfq *WorkspaceFileQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
	if wfq.ctx.Unique == nil && wfq.path != nil {
		wfq.Unique(true)
	}
	ctx = setContextOp(ctx, wfq.ctx, ent.OpQueryIDs)
	if err = wfq.Select(workspacefile.FieldID).Scan(ctx, &ids); err != nil {
		return nil, err
	}
	return ids, nil
}

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

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

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

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

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

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

// WithOwner tells the query-builder to eager-load the nodes that are connected to
// the "owner" edge. The optional arguments are used to configure the query builder of the edge.
func (wfq *WorkspaceFileQuery) WithOwner(opts ...func(*UserQuery)) *WorkspaceFileQuery {
	query := (&UserClient{config: wfq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	wfq.withOwner = query
	return wfq
}

// WithWorkspace tells the query-builder to eager-load the nodes that are connected to
// the "workspace" edge. The optional arguments are used to configure the query builder of the edge.
func (wfq *WorkspaceFileQuery) WithWorkspace(opts ...func(*WorkspaceQuery)) *WorkspaceFileQuery {
	query := (&WorkspaceClient{config: wfq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	wfq.withWorkspace = query
	return wfq
}

// WithSnippets tells the query-builder to eager-load the nodes that are connected to
// the "snippets" edge. The optional arguments are used to configure the query builder of the edge.
func (wfq *WorkspaceFileQuery) WithSnippets(opts ...func(*CodeSnippetQuery)) *WorkspaceFileQuery {
	query := (&CodeSnippetClient{config: wfq.config}).Query()
	for _, opt := range opts {
		opt(query)
	}
	wfq.withSnippets = query
	return wfq
}

// 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 {
//		UserID uuid.UUID `json:"user_id,omitempty"`
//		Count int `json:"count,omitempty"`
//	}
//
//	client.WorkspaceFile.Query().
//		GroupBy(workspacefile.FieldUserID).
//		Aggregate(db.Count()).
//		Scan(ctx, &v)
func (wfq *WorkspaceFileQuery) GroupBy(field string, fields ...string) *WorkspaceFileGroupBy {
	wfq.ctx.Fields = append([]string{field}, fields...)
	grbuild := &WorkspaceFileGroupBy{build: wfq}
	grbuild.flds = &wfq.ctx.Fields
	grbuild.label = workspacefile.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 {
//		UserID uuid.UUID `json:"user_id,omitempty"`
//	}
//
//	client.WorkspaceFile.Query().
//		Select(workspacefile.FieldUserID).
//		Scan(ctx, &v)
func (wfq *WorkspaceFileQuery) Select(fields ...string) *WorkspaceFileSelect {
	wfq.ctx.Fields = append(wfq.ctx.Fields, fields...)
	sbuild := &WorkspaceFileSelect{WorkspaceFileQuery: wfq}
	sbuild.label = workspacefile.Label
	sbuild.flds, sbuild.scan = &wfq.ctx.Fields, sbuild.Scan
	return sbuild
}

// Aggregate returns a WorkspaceFileSelect configured with the given aggregations.
func (wfq *WorkspaceFileQuery) Aggregate(fns ...AggregateFunc) *WorkspaceFileSelect {
	return wfq.Select().Aggregate(fns...)
}

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

func (wfq *WorkspaceFileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*WorkspaceFile, error) {
	var (
		nodes       = []*WorkspaceFile{}
		_spec       = wfq.querySpec()
		loadedTypes = [3]bool{
			wfq.withOwner != nil,
			wfq.withWorkspace != nil,
			wfq.withSnippets != nil,
		}
	)
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*WorkspaceFile).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &WorkspaceFile{config: wfq.config}
		nodes = append(nodes, node)
		node.Edges.loadedTypes = loadedTypes
		return node.assignValues(columns, values)
	}
	if len(wfq.modifiers) > 0 {
		_spec.Modifiers = wfq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, wfq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	if query := wfq.withOwner; query != nil {
		if err := wfq.loadOwner(ctx, query, nodes, nil,
			func(n *WorkspaceFile, e *User) { n.Edges.Owner = e }); err != nil {
			return nil, err
		}
	}
	if query := wfq.withWorkspace; query != nil {
		if err := wfq.loadWorkspace(ctx, query, nodes, nil,
			func(n *WorkspaceFile, e *Workspace) { n.Edges.Workspace = e }); err != nil {
			return nil, err
		}
	}
	if query := wfq.withSnippets; query != nil {
		if err := wfq.loadSnippets(ctx, query, nodes,
			func(n *WorkspaceFile) { n.Edges.Snippets = []*CodeSnippet{} },
			func(n *WorkspaceFile, e *CodeSnippet) { n.Edges.Snippets = append(n.Edges.Snippets, e) }); err != nil {
			return nil, err
		}
	}
	return nodes, nil
}

func (wfq *WorkspaceFileQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*WorkspaceFile, init func(*WorkspaceFile), assign func(*WorkspaceFile, *User)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*WorkspaceFile)
	for i := range nodes {
		fk := nodes[i].UserID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(user.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (wfq *WorkspaceFileQuery) loadWorkspace(ctx context.Context, query *WorkspaceQuery, nodes []*WorkspaceFile, init func(*WorkspaceFile), assign func(*WorkspaceFile, *Workspace)) error {
	ids := make([]uuid.UUID, 0, len(nodes))
	nodeids := make(map[uuid.UUID][]*WorkspaceFile)
	for i := range nodes {
		fk := nodes[i].WorkspaceID
		if _, ok := nodeids[fk]; !ok {
			ids = append(ids, fk)
		}
		nodeids[fk] = append(nodeids[fk], nodes[i])
	}
	if len(ids) == 0 {
		return nil
	}
	query.Where(workspace.IDIn(ids...))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		nodes, ok := nodeids[n.ID]
		if !ok {
			return fmt.Errorf(`unexpected foreign-key "workspace_id" returned %v`, n.ID)
		}
		for i := range nodes {
			assign(nodes[i], n)
		}
	}
	return nil
}
func (wfq *WorkspaceFileQuery) loadSnippets(ctx context.Context, query *CodeSnippetQuery, nodes []*WorkspaceFile, init func(*WorkspaceFile), assign func(*WorkspaceFile, *CodeSnippet)) error {
	fks := make([]driver.Value, 0, len(nodes))
	nodeids := make(map[uuid.UUID]*WorkspaceFile)
	for i := range nodes {
		fks = append(fks, nodes[i].ID)
		nodeids[nodes[i].ID] = nodes[i]
		if init != nil {
			init(nodes[i])
		}
	}
	if len(query.ctx.Fields) > 0 {
		query.ctx.AppendFieldOnce(codesnippet.FieldWorkspaceFileID)
	}
	query.Where(predicate.CodeSnippet(func(s *sql.Selector) {
		s.Where(sql.InValues(s.C(workspacefile.SnippetsColumn), fks...))
	}))
	neighbors, err := query.All(ctx)
	if err != nil {
		return err
	}
	for _, n := range neighbors {
		fk := n.WorkspaceFileID
		node, ok := nodeids[fk]
		if !ok {
			return fmt.Errorf(`unexpected referenced foreign-key "workspace_file_id" returned %v for node %v`, fk, n.ID)
		}
		assign(node, n)
	}
	return nil
}

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

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

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

// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
// either committed or rolled-back.
func (wfq *WorkspaceFileQuery) ForUpdate(opts ...sql.LockOption) *WorkspaceFileQuery {
	if wfq.driver.Dialect() == dialect.Postgres {
		wfq.Unique(false)
	}
	wfq.modifiers = append(wfq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return wfq
}

// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
// on any rows that are read. Other sessions can read the rows, but cannot modify them
// until your transaction commits.
func (wfq *WorkspaceFileQuery) ForShare(opts ...sql.LockOption) *WorkspaceFileQuery {
	if wfq.driver.Dialect() == dialect.Postgres {
		wfq.Unique(false)
	}
	wfq.modifiers = append(wfq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return wfq
}

// Modify adds a query modifier for attaching custom logic to queries.
func (wfq *WorkspaceFileQuery) Modify(modifiers ...func(s *sql.Selector)) *WorkspaceFileSelect {
	wfq.modifiers = append(wfq.modifiers, modifiers...)
	return wfq.Select()
}

// WorkspaceFileGroupBy is the group-by builder for WorkspaceFile entities.
type WorkspaceFileGroupBy struct {
	selector
	build *WorkspaceFileQuery
}

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

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

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

// WorkspaceFileSelect is the builder for selecting fields of WorkspaceFile entities.
type WorkspaceFileSelect struct {
	*WorkspaceFileQuery
	selector
}

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

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

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

// Modify adds a query modifier for attaching custom logic to queries.
func (wfs *WorkspaceFileSelect) Modify(modifiers ...func(s *sql.Selector)) *WorkspaceFileSelect {
	wfs.modifiers = append(wfs.modifiers, modifiers...)
	return wfs
}
