1 Star 0 Fork 0

DaMeng/Ent

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
node_query.go 18.64 KB
一键复制 编辑 原始数据 按行查看 历史
DaMeng 提交于 2024-10-24 16:04 . :tada:fork ent
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
// 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"
"database/sql/driver"
"fmt"
"math"
"gitee.com/damengde/ent/dialect/sql"
"gitee.com/damengde/ent/dialect/sql/sqlgraph"
"gitee.com/damengde/ent/examples/o2mrecur/ent/node"
"gitee.com/damengde/ent/examples/o2mrecur/ent/predicate"
"gitee.com/damengde/ent/schema/field"
)
// NodeQuery is the builder for querying Node entities.
type NodeQuery struct {
config
ctx *QueryContext
order []node.OrderOption
inters []Interceptor
predicates []predicate.Node
withParent *NodeQuery
withChildren *NodeQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the NodeQuery builder.
func (nq *NodeQuery) Where(ps ...predicate.Node) *NodeQuery {
nq.predicates = append(nq.predicates, ps...)
return nq
}
// Limit the number of records to be returned by this query.
func (nq *NodeQuery) Limit(limit int) *NodeQuery {
nq.ctx.Limit = &limit
return nq
}
// Offset to start from.
func (nq *NodeQuery) Offset(offset int) *NodeQuery {
nq.ctx.Offset = &offset
return nq
}
// 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 (nq *NodeQuery) Unique(unique bool) *NodeQuery {
nq.ctx.Unique = &unique
return nq
}
// Order specifies how the records should be ordered.
func (nq *NodeQuery) Order(o ...node.OrderOption) *NodeQuery {
nq.order = append(nq.order, o...)
return nq
}
// QueryParent chains the current query on the "parent" edge.
func (nq *NodeQuery) QueryParent() *NodeQuery {
query := (&NodeClient{config: nq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := nq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := nq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(node.Table, node.FieldID, selector),
sqlgraph.To(node.Table, node.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, node.ParentTable, node.ParentColumn),
)
fromU = sqlgraph.SetNeighbors(nq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryChildren chains the current query on the "children" edge.
func (nq *NodeQuery) QueryChildren() *NodeQuery {
query := (&NodeClient{config: nq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := nq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := nq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(node.Table, node.FieldID, selector),
sqlgraph.To(node.Table, node.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, node.ChildrenTable, node.ChildrenColumn),
)
fromU = sqlgraph.SetNeighbors(nq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Node entity from the query.
// Returns a *NotFoundError when no Node was found.
func (nq *NodeQuery) First(ctx context.Context) (*Node, error) {
nodes, err := nq.Limit(1).All(setContextOp(ctx, nq.ctx, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{node.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (nq *NodeQuery) FirstX(ctx context.Context) *Node {
node, err := nq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Node ID from the query.
// Returns a *NotFoundError when no Node ID was found.
func (nq *NodeQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = nq.Limit(1).IDs(setContextOp(ctx, nq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{node.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (nq *NodeQuery) FirstIDX(ctx context.Context) int {
id, err := nq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Node entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Node entity is found.
// Returns a *NotFoundError when no Node entities are found.
func (nq *NodeQuery) Only(ctx context.Context) (*Node, error) {
nodes, err := nq.Limit(2).All(setContextOp(ctx, nq.ctx, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{node.Label}
default:
return nil, &NotSingularError{node.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (nq *NodeQuery) OnlyX(ctx context.Context) *Node {
node, err := nq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Node ID in the query.
// Returns a *NotSingularError when more than one Node ID is found.
// Returns a *NotFoundError when no entities are found.
func (nq *NodeQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = nq.Limit(2).IDs(setContextOp(ctx, nq.ctx, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{node.Label}
default:
err = &NotSingularError{node.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (nq *NodeQuery) OnlyIDX(ctx context.Context) int {
id, err := nq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Nodes.
func (nq *NodeQuery) All(ctx context.Context) ([]*Node, error) {
ctx = setContextOp(ctx, nq.ctx, "All")
if err := nq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Node, *NodeQuery]()
return withInterceptors[[]*Node](ctx, nq, qr, nq.inters)
}
// AllX is like All, but panics if an error occurs.
func (nq *NodeQuery) AllX(ctx context.Context) []*Node {
nodes, err := nq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Node IDs.
func (nq *NodeQuery) IDs(ctx context.Context) (ids []int, err error) {
if nq.ctx.Unique == nil && nq.path != nil {
nq.Unique(true)
}
ctx = setContextOp(ctx, nq.ctx, "IDs")
if err = nq.Select(node.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (nq *NodeQuery) IDsX(ctx context.Context) []int {
ids, err := nq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (nq *NodeQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, nq.ctx, "Count")
if err := nq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, nq, querierCount[*NodeQuery](), nq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (nq *NodeQuery) CountX(ctx context.Context) int {
count, err := nq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (nq *NodeQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, nq.ctx, "Exist")
switch _, err := nq.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 (nq *NodeQuery) ExistX(ctx context.Context) bool {
exist, err := nq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the NodeQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (nq *NodeQuery) Clone() *NodeQuery {
if nq == nil {
return nil
}
return &NodeQuery{
config: nq.config,
ctx: nq.ctx.Clone(),
order: append([]node.OrderOption{}, nq.order...),
inters: append([]Interceptor{}, nq.inters...),
predicates: append([]predicate.Node{}, nq.predicates...),
withParent: nq.withParent.Clone(),
withChildren: nq.withChildren.Clone(),
// clone intermediate query.
sql: nq.sql.Clone(),
path: nq.path,
}
}
// WithParent tells the query-builder to eager-load the nodes that are connected to
// the "parent" edge. The optional arguments are used to configure the query builder of the edge.
func (nq *NodeQuery) WithParent(opts ...func(*NodeQuery)) *NodeQuery {
query := (&NodeClient{config: nq.config}).Query()
for _, opt := range opts {
opt(query)
}
nq.withParent = query
return nq
}
// WithChildren tells the query-builder to eager-load the nodes that are connected to
// the "children" edge. The optional arguments are used to configure the query builder of the edge.
func (nq *NodeQuery) WithChildren(opts ...func(*NodeQuery)) *NodeQuery {
query := (&NodeClient{config: nq.config}).Query()
for _, opt := range opts {
opt(query)
}
nq.withChildren = query
return nq
}
// 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 {
// Value int `json:"value,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Node.Query().
// GroupBy(node.FieldValue).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (nq *NodeQuery) GroupBy(field string, fields ...string) *NodeGroupBy {
nq.ctx.Fields = append([]string{field}, fields...)
grbuild := &NodeGroupBy{build: nq}
grbuild.flds = &nq.ctx.Fields
grbuild.label = node.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 {
// Value int `json:"value,omitempty"`
// }
//
// client.Node.Query().
// Select(node.FieldValue).
// Scan(ctx, &v)
func (nq *NodeQuery) Select(fields ...string) *NodeSelect {
nq.ctx.Fields = append(nq.ctx.Fields, fields...)
sbuild := &NodeSelect{NodeQuery: nq}
sbuild.label = node.Label
sbuild.flds, sbuild.scan = &nq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a NodeSelect configured with the given aggregations.
func (nq *NodeQuery) Aggregate(fns ...AggregateFunc) *NodeSelect {
return nq.Select().Aggregate(fns...)
}
func (nq *NodeQuery) prepareQuery(ctx context.Context) error {
for _, inter := range nq.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, nq); err != nil {
return err
}
}
}
for _, f := range nq.ctx.Fields {
if !node.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if nq.path != nil {
prev, err := nq.path(ctx)
if err != nil {
return err
}
nq.sql = prev
}
return nil
}
func (nq *NodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Node, error) {
var (
nodes = []*Node{}
_spec = nq.querySpec()
loadedTypes = [2]bool{
nq.withParent != nil,
nq.withChildren != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Node).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Node{config: nq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, nq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := nq.withParent; query != nil {
if err := nq.loadParent(ctx, query, nodes, nil,
func(n *Node, e *Node) { n.Edges.Parent = e }); err != nil {
return nil, err
}
}
if query := nq.withChildren; query != nil {
if err := nq.loadChildren(ctx, query, nodes,
func(n *Node) { n.Edges.Children = []*Node{} },
func(n *Node, e *Node) { n.Edges.Children = append(n.Edges.Children, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (nq *NodeQuery) loadParent(ctx context.Context, query *NodeQuery, nodes []*Node, init func(*Node), assign func(*Node, *Node)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Node)
for i := range nodes {
fk := nodes[i].ParentID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(node.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 "parent_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (nq *NodeQuery) loadChildren(ctx context.Context, query *NodeQuery, nodes []*Node, init func(*Node), assign func(*Node, *Node)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*Node)
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(node.FieldParentID)
}
query.Where(predicate.Node(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(node.ChildrenColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.ParentID
node, ok := nodeids[fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "parent_id" returned %v for node %v`, fk, n.ID)
}
assign(node, n)
}
return nil
}
func (nq *NodeQuery) sqlCount(ctx context.Context) (int, error) {
_spec := nq.querySpec()
_spec.Node.Columns = nq.ctx.Fields
if len(nq.ctx.Fields) > 0 {
_spec.Unique = nq.ctx.Unique != nil && *nq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, nq.driver, _spec)
}
func (nq *NodeQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(node.Table, node.Columns, sqlgraph.NewFieldSpec(node.FieldID, field.TypeInt))
_spec.From = nq.sql
if unique := nq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if nq.path != nil {
_spec.Unique = true
}
if fields := nq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, node.FieldID)
for i := range fields {
if fields[i] != node.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if nq.withParent != nil {
_spec.Node.AddColumnOnce(node.FieldParentID)
}
}
if ps := nq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := nq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := nq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := nq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (nq *NodeQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(nq.driver.Dialect())
t1 := builder.Table(node.Table)
columns := nq.ctx.Fields
if len(columns) == 0 {
columns = node.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if nq.sql != nil {
selector = nq.sql
selector.Select(selector.Columns(columns...)...)
}
if nq.ctx.Unique != nil && *nq.ctx.Unique {
selector.Distinct()
}
for _, p := range nq.predicates {
p(selector)
}
for _, p := range nq.order {
p(selector)
}
if offset := nq.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 := nq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// NodeGroupBy is the group-by builder for Node entities.
type NodeGroupBy struct {
selector
build *NodeQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ngb *NodeGroupBy) Aggregate(fns ...AggregateFunc) *NodeGroupBy {
ngb.fns = append(ngb.fns, fns...)
return ngb
}
// Scan applies the selector query and scans the result into the given value.
func (ngb *NodeGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, ngb.build.ctx, "GroupBy")
if err := ngb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*NodeQuery, *NodeGroupBy](ctx, ngb.build, ngb, ngb.build.inters, v)
}
func (ngb *NodeGroupBy) sqlScan(ctx context.Context, root *NodeQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(ngb.fns))
for _, fn := range ngb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*ngb.flds)+len(ngb.fns))
for _, f := range *ngb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*ngb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := ngb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// NodeSelect is the builder for selecting fields of Node entities.
type NodeSelect struct {
*NodeQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (ns *NodeSelect) Aggregate(fns ...AggregateFunc) *NodeSelect {
ns.fns = append(ns.fns, fns...)
return ns
}
// Scan applies the selector query and scans the result into the given value.
func (ns *NodeSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, ns.ctx, "Select")
if err := ns.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*NodeQuery, *NodeSelect](ctx, ns.NodeQuery, ns, ns.inters, v)
}
func (ns *NodeSelect) sqlScan(ctx context.Context, root *NodeQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(ns.fns))
for _, fn := range ns.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*ns.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 := ns.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/damengde/ent.git
git@gitee.com:damengde/ent.git
damengde
ent
Ent
90870c5ba095

搜索帮助

0d507c66 1850385 C8b1a773 1850385