// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.

// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"fmt"
	"math"

	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/entc/integration/ent/fieldtype"
	"entgo.io/ent/entc/integration/ent/predicate"
	"entgo.io/ent/schema/field"
)

// FieldTypeQuery is the builder for querying FieldType entities.
type FieldTypeQuery struct {
	config
	ctx        *QueryContext
	order      []fieldtype.Order
	inters     []Interceptor
	predicates []predicate.FieldType
	withFKs    bool
	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 FieldTypeQuery builder.
func (ftq *FieldTypeQuery) Where(ps ...predicate.FieldType) *FieldTypeQuery {
	ftq.predicates = append(ftq.predicates, ps...)
	return ftq
}

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

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

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

// Order specifies how the records should be ordered.
func (ftq *FieldTypeQuery) Order(o ...fieldtype.Order) *FieldTypeQuery {
	ftq.order = append(ftq.order, o...)
	return ftq
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// Aggregate returns a FieldTypeSelect configured with the given aggregations.
func (ftq *FieldTypeQuery) Aggregate(fns ...AggregateFunc) *FieldTypeSelect {
	return ftq.Select().Aggregate(fns...)
}

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

func (ftq *FieldTypeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*FieldType, error) {
	var (
		nodes   = []*FieldType{}
		withFKs = ftq.withFKs
		_spec   = ftq.querySpec()
	)
	if withFKs {
		_spec.Node.Columns = append(_spec.Node.Columns, fieldtype.ForeignKeys...)
	}
	_spec.ScanValues = func(columns []string) ([]any, error) {
		return (*FieldType).scanValues(nil, columns)
	}
	_spec.Assign = func(columns []string, values []any) error {
		node := &FieldType{config: ftq.config}
		nodes = append(nodes, node)
		return node.assignValues(columns, values)
	}
	if len(ftq.modifiers) > 0 {
		_spec.Modifiers = ftq.modifiers
	}
	for i := range hooks {
		hooks[i](ctx, _spec)
	}
	if err := sqlgraph.QueryNodes(ctx, ftq.driver, _spec); err != nil {
		return nil, err
	}
	if len(nodes) == 0 {
		return nodes, nil
	}
	return nodes, nil
}

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

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

func (ftq *FieldTypeQuery) sqlQuery(ctx context.Context) *sql.Selector {
	builder := sql.Dialect(ftq.driver.Dialect())
	t1 := builder.Table(fieldtype.Table)
	columns := ftq.ctx.Fields
	if len(columns) == 0 {
		columns = fieldtype.Columns
	}
	selector := builder.Select(t1.Columns(columns...)...).From(t1)
	if ftq.sql != nil {
		selector = ftq.sql
		selector.Select(selector.Columns(columns...)...)
	}
	if ftq.ctx.Unique != nil && *ftq.ctx.Unique {
		selector.Distinct()
	}
	for _, m := range ftq.modifiers {
		m(selector)
	}
	for _, p := range ftq.predicates {
		p(selector)
	}
	for _, p := range ftq.order {
		p(selector)
	}
	if offset := ftq.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 := ftq.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 (ftq *FieldTypeQuery) ForUpdate(opts ...sql.LockOption) *FieldTypeQuery {
	if ftq.driver.Dialect() == dialect.Postgres {
		ftq.Unique(false)
	}
	ftq.modifiers = append(ftq.modifiers, func(s *sql.Selector) {
		s.ForUpdate(opts...)
	})
	return ftq
}

// 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 (ftq *FieldTypeQuery) ForShare(opts ...sql.LockOption) *FieldTypeQuery {
	if ftq.driver.Dialect() == dialect.Postgres {
		ftq.Unique(false)
	}
	ftq.modifiers = append(ftq.modifiers, func(s *sql.Selector) {
		s.ForShare(opts...)
	})
	return ftq
}

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

// FieldTypeGroupBy is the group-by builder for FieldType entities.
type FieldTypeGroupBy struct {
	selector
	build *FieldTypeQuery
}

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

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

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

// FieldTypeSelect is the builder for selecting fields of FieldType entities.
type FieldTypeSelect struct {
	*FieldTypeQuery
	selector
}

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

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

func (fts *FieldTypeSelect) sqlScan(ctx context.Context, root *FieldTypeQuery, v any) error {
	selector := root.sqlQuery(ctx)
	aggregation := make([]string, 0, len(fts.fns))
	for _, fn := range fts.fns {
		aggregation = append(aggregation, fn(selector))
	}
	switch n := len(*fts.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 := fts.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 (fts *FieldTypeSelect) Modify(modifiers ...func(s *sql.Selector)) *FieldTypeSelect {
	fts.modifiers = append(fts.modifiers, modifiers...)
	return fts
}
