/ ent / item_query.go
item_query.go
  1  // Code generated by ent, DO NOT EDIT.
  2  
  3  package ent
  4  
  5  import (
  6  	"context"
  7  	"database/sql/driver"
  8  	"fmt"
  9  	"math"
 10  
 11  	"entgo.io/ent/dialect/sql"
 12  	"entgo.io/ent/dialect/sql/sqlgraph"
 13  	"entgo.io/ent/schema/field"
 14  	"github.com/google/uuid"
 15  	"github.com/mrusme/journalist/ent/feed"
 16  	"github.com/mrusme/journalist/ent/item"
 17  	"github.com/mrusme/journalist/ent/predicate"
 18  	"github.com/mrusme/journalist/ent/read"
 19  	"github.com/mrusme/journalist/ent/user"
 20  )
 21  
 22  // ItemQuery is the builder for querying Item entities.
 23  type ItemQuery struct {
 24  	config
 25  	ctx             *QueryContext
 26  	order           []item.OrderOption
 27  	inters          []Interceptor
 28  	predicates      []predicate.Item
 29  	withFeed        *FeedQuery
 30  	withReadByUsers *UserQuery
 31  	withReads       *ReadQuery
 32  	withFKs         bool
 33  	// intermediate query (i.e. traversal path).
 34  	sql  *sql.Selector
 35  	path func(context.Context) (*sql.Selector, error)
 36  }
 37  
 38  // Where adds a new predicate for the ItemQuery builder.
 39  func (iq *ItemQuery) Where(ps ...predicate.Item) *ItemQuery {
 40  	iq.predicates = append(iq.predicates, ps...)
 41  	return iq
 42  }
 43  
 44  // Limit the number of records to be returned by this query.
 45  func (iq *ItemQuery) Limit(limit int) *ItemQuery {
 46  	iq.ctx.Limit = &limit
 47  	return iq
 48  }
 49  
 50  // Offset to start from.
 51  func (iq *ItemQuery) Offset(offset int) *ItemQuery {
 52  	iq.ctx.Offset = &offset
 53  	return iq
 54  }
 55  
 56  // Unique configures the query builder to filter duplicate records on query.
 57  // By default, unique is set to true, and can be disabled using this method.
 58  func (iq *ItemQuery) Unique(unique bool) *ItemQuery {
 59  	iq.ctx.Unique = &unique
 60  	return iq
 61  }
 62  
 63  // Order specifies how the records should be ordered.
 64  func (iq *ItemQuery) Order(o ...item.OrderOption) *ItemQuery {
 65  	iq.order = append(iq.order, o...)
 66  	return iq
 67  }
 68  
 69  // QueryFeed chains the current query on the "feed" edge.
 70  func (iq *ItemQuery) QueryFeed() *FeedQuery {
 71  	query := (&FeedClient{config: iq.config}).Query()
 72  	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
 73  		if err := iq.prepareQuery(ctx); err != nil {
 74  			return nil, err
 75  		}
 76  		selector := iq.sqlQuery(ctx)
 77  		if err := selector.Err(); err != nil {
 78  			return nil, err
 79  		}
 80  		step := sqlgraph.NewStep(
 81  			sqlgraph.From(item.Table, item.FieldID, selector),
 82  			sqlgraph.To(feed.Table, feed.FieldID),
 83  			sqlgraph.Edge(sqlgraph.M2O, true, item.FeedTable, item.FeedColumn),
 84  		)
 85  		fromU = sqlgraph.SetNeighbors(iq.driver.Dialect(), step)
 86  		return fromU, nil
 87  	}
 88  	return query
 89  }
 90  
 91  // QueryReadByUsers chains the current query on the "read_by_users" edge.
 92  func (iq *ItemQuery) QueryReadByUsers() *UserQuery {
 93  	query := (&UserClient{config: iq.config}).Query()
 94  	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
 95  		if err := iq.prepareQuery(ctx); err != nil {
 96  			return nil, err
 97  		}
 98  		selector := iq.sqlQuery(ctx)
 99  		if err := selector.Err(); err != nil {
100  			return nil, err
101  		}
102  		step := sqlgraph.NewStep(
103  			sqlgraph.From(item.Table, item.FieldID, selector),
104  			sqlgraph.To(user.Table, user.FieldID),
105  			sqlgraph.Edge(sqlgraph.M2M, true, item.ReadByUsersTable, item.ReadByUsersPrimaryKey...),
106  		)
107  		fromU = sqlgraph.SetNeighbors(iq.driver.Dialect(), step)
108  		return fromU, nil
109  	}
110  	return query
111  }
112  
113  // QueryReads chains the current query on the "reads" edge.
114  func (iq *ItemQuery) QueryReads() *ReadQuery {
115  	query := (&ReadClient{config: iq.config}).Query()
116  	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
117  		if err := iq.prepareQuery(ctx); err != nil {
118  			return nil, err
119  		}
120  		selector := iq.sqlQuery(ctx)
121  		if err := selector.Err(); err != nil {
122  			return nil, err
123  		}
124  		step := sqlgraph.NewStep(
125  			sqlgraph.From(item.Table, item.FieldID, selector),
126  			sqlgraph.To(read.Table, read.FieldID),
127  			sqlgraph.Edge(sqlgraph.O2M, true, item.ReadsTable, item.ReadsColumn),
128  		)
129  		fromU = sqlgraph.SetNeighbors(iq.driver.Dialect(), step)
130  		return fromU, nil
131  	}
132  	return query
133  }
134  
135  // First returns the first Item entity from the query.
136  // Returns a *NotFoundError when no Item was found.
137  func (iq *ItemQuery) First(ctx context.Context) (*Item, error) {
138  	nodes, err := iq.Limit(1).All(setContextOp(ctx, iq.ctx, "First"))
139  	if err != nil {
140  		return nil, err
141  	}
142  	if len(nodes) == 0 {
143  		return nil, &NotFoundError{item.Label}
144  	}
145  	return nodes[0], nil
146  }
147  
148  // FirstX is like First, but panics if an error occurs.
149  func (iq *ItemQuery) FirstX(ctx context.Context) *Item {
150  	node, err := iq.First(ctx)
151  	if err != nil && !IsNotFound(err) {
152  		panic(err)
153  	}
154  	return node
155  }
156  
157  // FirstID returns the first Item ID from the query.
158  // Returns a *NotFoundError when no Item ID was found.
159  func (iq *ItemQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
160  	var ids []uuid.UUID
161  	if ids, err = iq.Limit(1).IDs(setContextOp(ctx, iq.ctx, "FirstID")); err != nil {
162  		return
163  	}
164  	if len(ids) == 0 {
165  		err = &NotFoundError{item.Label}
166  		return
167  	}
168  	return ids[0], nil
169  }
170  
171  // FirstIDX is like FirstID, but panics if an error occurs.
172  func (iq *ItemQuery) FirstIDX(ctx context.Context) uuid.UUID {
173  	id, err := iq.FirstID(ctx)
174  	if err != nil && !IsNotFound(err) {
175  		panic(err)
176  	}
177  	return id
178  }
179  
180  // Only returns a single Item entity found by the query, ensuring it only returns one.
181  // Returns a *NotSingularError when more than one Item entity is found.
182  // Returns a *NotFoundError when no Item entities are found.
183  func (iq *ItemQuery) Only(ctx context.Context) (*Item, error) {
184  	nodes, err := iq.Limit(2).All(setContextOp(ctx, iq.ctx, "Only"))
185  	if err != nil {
186  		return nil, err
187  	}
188  	switch len(nodes) {
189  	case 1:
190  		return nodes[0], nil
191  	case 0:
192  		return nil, &NotFoundError{item.Label}
193  	default:
194  		return nil, &NotSingularError{item.Label}
195  	}
196  }
197  
198  // OnlyX is like Only, but panics if an error occurs.
199  func (iq *ItemQuery) OnlyX(ctx context.Context) *Item {
200  	node, err := iq.Only(ctx)
201  	if err != nil {
202  		panic(err)
203  	}
204  	return node
205  }
206  
207  // OnlyID is like Only, but returns the only Item ID in the query.
208  // Returns a *NotSingularError when more than one Item ID is found.
209  // Returns a *NotFoundError when no entities are found.
210  func (iq *ItemQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
211  	var ids []uuid.UUID
212  	if ids, err = iq.Limit(2).IDs(setContextOp(ctx, iq.ctx, "OnlyID")); err != nil {
213  		return
214  	}
215  	switch len(ids) {
216  	case 1:
217  		id = ids[0]
218  	case 0:
219  		err = &NotFoundError{item.Label}
220  	default:
221  		err = &NotSingularError{item.Label}
222  	}
223  	return
224  }
225  
226  // OnlyIDX is like OnlyID, but panics if an error occurs.
227  func (iq *ItemQuery) OnlyIDX(ctx context.Context) uuid.UUID {
228  	id, err := iq.OnlyID(ctx)
229  	if err != nil {
230  		panic(err)
231  	}
232  	return id
233  }
234  
235  // All executes the query and returns a list of Items.
236  func (iq *ItemQuery) All(ctx context.Context) ([]*Item, error) {
237  	ctx = setContextOp(ctx, iq.ctx, "All")
238  	if err := iq.prepareQuery(ctx); err != nil {
239  		return nil, err
240  	}
241  	qr := querierAll[[]*Item, *ItemQuery]()
242  	return withInterceptors[[]*Item](ctx, iq, qr, iq.inters)
243  }
244  
245  // AllX is like All, but panics if an error occurs.
246  func (iq *ItemQuery) AllX(ctx context.Context) []*Item {
247  	nodes, err := iq.All(ctx)
248  	if err != nil {
249  		panic(err)
250  	}
251  	return nodes
252  }
253  
254  // IDs executes the query and returns a list of Item IDs.
255  func (iq *ItemQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
256  	if iq.ctx.Unique == nil && iq.path != nil {
257  		iq.Unique(true)
258  	}
259  	ctx = setContextOp(ctx, iq.ctx, "IDs")
260  	if err = iq.Select(item.FieldID).Scan(ctx, &ids); err != nil {
261  		return nil, err
262  	}
263  	return ids, nil
264  }
265  
266  // IDsX is like IDs, but panics if an error occurs.
267  func (iq *ItemQuery) IDsX(ctx context.Context) []uuid.UUID {
268  	ids, err := iq.IDs(ctx)
269  	if err != nil {
270  		panic(err)
271  	}
272  	return ids
273  }
274  
275  // Count returns the count of the given query.
276  func (iq *ItemQuery) Count(ctx context.Context) (int, error) {
277  	ctx = setContextOp(ctx, iq.ctx, "Count")
278  	if err := iq.prepareQuery(ctx); err != nil {
279  		return 0, err
280  	}
281  	return withInterceptors[int](ctx, iq, querierCount[*ItemQuery](), iq.inters)
282  }
283  
284  // CountX is like Count, but panics if an error occurs.
285  func (iq *ItemQuery) CountX(ctx context.Context) int {
286  	count, err := iq.Count(ctx)
287  	if err != nil {
288  		panic(err)
289  	}
290  	return count
291  }
292  
293  // Exist returns true if the query has elements in the graph.
294  func (iq *ItemQuery) Exist(ctx context.Context) (bool, error) {
295  	ctx = setContextOp(ctx, iq.ctx, "Exist")
296  	switch _, err := iq.FirstID(ctx); {
297  	case IsNotFound(err):
298  		return false, nil
299  	case err != nil:
300  		return false, fmt.Errorf("ent: check existence: %w", err)
301  	default:
302  		return true, nil
303  	}
304  }
305  
306  // ExistX is like Exist, but panics if an error occurs.
307  func (iq *ItemQuery) ExistX(ctx context.Context) bool {
308  	exist, err := iq.Exist(ctx)
309  	if err != nil {
310  		panic(err)
311  	}
312  	return exist
313  }
314  
315  // Clone returns a duplicate of the ItemQuery builder, including all associated steps. It can be
316  // used to prepare common query builders and use them differently after the clone is made.
317  func (iq *ItemQuery) Clone() *ItemQuery {
318  	if iq == nil {
319  		return nil
320  	}
321  	return &ItemQuery{
322  		config:          iq.config,
323  		ctx:             iq.ctx.Clone(),
324  		order:           append([]item.OrderOption{}, iq.order...),
325  		inters:          append([]Interceptor{}, iq.inters...),
326  		predicates:      append([]predicate.Item{}, iq.predicates...),
327  		withFeed:        iq.withFeed.Clone(),
328  		withReadByUsers: iq.withReadByUsers.Clone(),
329  		withReads:       iq.withReads.Clone(),
330  		// clone intermediate query.
331  		sql:  iq.sql.Clone(),
332  		path: iq.path,
333  	}
334  }
335  
336  // WithFeed tells the query-builder to eager-load the nodes that are connected to
337  // the "feed" edge. The optional arguments are used to configure the query builder of the edge.
338  func (iq *ItemQuery) WithFeed(opts ...func(*FeedQuery)) *ItemQuery {
339  	query := (&FeedClient{config: iq.config}).Query()
340  	for _, opt := range opts {
341  		opt(query)
342  	}
343  	iq.withFeed = query
344  	return iq
345  }
346  
347  // WithReadByUsers tells the query-builder to eager-load the nodes that are connected to
348  // the "read_by_users" edge. The optional arguments are used to configure the query builder of the edge.
349  func (iq *ItemQuery) WithReadByUsers(opts ...func(*UserQuery)) *ItemQuery {
350  	query := (&UserClient{config: iq.config}).Query()
351  	for _, opt := range opts {
352  		opt(query)
353  	}
354  	iq.withReadByUsers = query
355  	return iq
356  }
357  
358  // WithReads tells the query-builder to eager-load the nodes that are connected to
359  // the "reads" edge. The optional arguments are used to configure the query builder of the edge.
360  func (iq *ItemQuery) WithReads(opts ...func(*ReadQuery)) *ItemQuery {
361  	query := (&ReadClient{config: iq.config}).Query()
362  	for _, opt := range opts {
363  		opt(query)
364  	}
365  	iq.withReads = query
366  	return iq
367  }
368  
369  // GroupBy is used to group vertices by one or more fields/columns.
370  // It is often used with aggregate functions, like: count, max, mean, min, sum.
371  //
372  // Example:
373  //
374  //	var v []struct {
375  //		ItemGUID string `json:"item_guid,omitempty"`
376  //		Count int `json:"count,omitempty"`
377  //	}
378  //
379  //	client.Item.Query().
380  //		GroupBy(item.FieldItemGUID).
381  //		Aggregate(ent.Count()).
382  //		Scan(ctx, &v)
383  func (iq *ItemQuery) GroupBy(field string, fields ...string) *ItemGroupBy {
384  	iq.ctx.Fields = append([]string{field}, fields...)
385  	grbuild := &ItemGroupBy{build: iq}
386  	grbuild.flds = &iq.ctx.Fields
387  	grbuild.label = item.Label
388  	grbuild.scan = grbuild.Scan
389  	return grbuild
390  }
391  
392  // Select allows the selection one or more fields/columns for the given query,
393  // instead of selecting all fields in the entity.
394  //
395  // Example:
396  //
397  //	var v []struct {
398  //		ItemGUID string `json:"item_guid,omitempty"`
399  //	}
400  //
401  //	client.Item.Query().
402  //		Select(item.FieldItemGUID).
403  //		Scan(ctx, &v)
404  func (iq *ItemQuery) Select(fields ...string) *ItemSelect {
405  	iq.ctx.Fields = append(iq.ctx.Fields, fields...)
406  	sbuild := &ItemSelect{ItemQuery: iq}
407  	sbuild.label = item.Label
408  	sbuild.flds, sbuild.scan = &iq.ctx.Fields, sbuild.Scan
409  	return sbuild
410  }
411  
412  // Aggregate returns a ItemSelect configured with the given aggregations.
413  func (iq *ItemQuery) Aggregate(fns ...AggregateFunc) *ItemSelect {
414  	return iq.Select().Aggregate(fns...)
415  }
416  
417  func (iq *ItemQuery) prepareQuery(ctx context.Context) error {
418  	for _, inter := range iq.inters {
419  		if inter == nil {
420  			return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
421  		}
422  		if trv, ok := inter.(Traverser); ok {
423  			if err := trv.Traverse(ctx, iq); err != nil {
424  				return err
425  			}
426  		}
427  	}
428  	for _, f := range iq.ctx.Fields {
429  		if !item.ValidColumn(f) {
430  			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
431  		}
432  	}
433  	if iq.path != nil {
434  		prev, err := iq.path(ctx)
435  		if err != nil {
436  			return err
437  		}
438  		iq.sql = prev
439  	}
440  	return nil
441  }
442  
443  func (iq *ItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Item, error) {
444  	var (
445  		nodes       = []*Item{}
446  		withFKs     = iq.withFKs
447  		_spec       = iq.querySpec()
448  		loadedTypes = [3]bool{
449  			iq.withFeed != nil,
450  			iq.withReadByUsers != nil,
451  			iq.withReads != nil,
452  		}
453  	)
454  	if iq.withFeed != nil {
455  		withFKs = true
456  	}
457  	if withFKs {
458  		_spec.Node.Columns = append(_spec.Node.Columns, item.ForeignKeys...)
459  	}
460  	_spec.ScanValues = func(columns []string) ([]any, error) {
461  		return (*Item).scanValues(nil, columns)
462  	}
463  	_spec.Assign = func(columns []string, values []any) error {
464  		node := &Item{config: iq.config}
465  		nodes = append(nodes, node)
466  		node.Edges.loadedTypes = loadedTypes
467  		return node.assignValues(columns, values)
468  	}
469  	for i := range hooks {
470  		hooks[i](ctx, _spec)
471  	}
472  	if err := sqlgraph.QueryNodes(ctx, iq.driver, _spec); err != nil {
473  		return nil, err
474  	}
475  	if len(nodes) == 0 {
476  		return nodes, nil
477  	}
478  	if query := iq.withFeed; query != nil {
479  		if err := iq.loadFeed(ctx, query, nodes, nil,
480  			func(n *Item, e *Feed) { n.Edges.Feed = e }); err != nil {
481  			return nil, err
482  		}
483  	}
484  	if query := iq.withReadByUsers; query != nil {
485  		if err := iq.loadReadByUsers(ctx, query, nodes,
486  			func(n *Item) { n.Edges.ReadByUsers = []*User{} },
487  			func(n *Item, e *User) { n.Edges.ReadByUsers = append(n.Edges.ReadByUsers, e) }); err != nil {
488  			return nil, err
489  		}
490  	}
491  	if query := iq.withReads; query != nil {
492  		if err := iq.loadReads(ctx, query, nodes,
493  			func(n *Item) { n.Edges.Reads = []*Read{} },
494  			func(n *Item, e *Read) { n.Edges.Reads = append(n.Edges.Reads, e) }); err != nil {
495  			return nil, err
496  		}
497  	}
498  	return nodes, nil
499  }
500  
501  func (iq *ItemQuery) loadFeed(ctx context.Context, query *FeedQuery, nodes []*Item, init func(*Item), assign func(*Item, *Feed)) error {
502  	ids := make([]uuid.UUID, 0, len(nodes))
503  	nodeids := make(map[uuid.UUID][]*Item)
504  	for i := range nodes {
505  		if nodes[i].feed_items == nil {
506  			continue
507  		}
508  		fk := *nodes[i].feed_items
509  		if _, ok := nodeids[fk]; !ok {
510  			ids = append(ids, fk)
511  		}
512  		nodeids[fk] = append(nodeids[fk], nodes[i])
513  	}
514  	if len(ids) == 0 {
515  		return nil
516  	}
517  	query.Where(feed.IDIn(ids...))
518  	neighbors, err := query.All(ctx)
519  	if err != nil {
520  		return err
521  	}
522  	for _, n := range neighbors {
523  		nodes, ok := nodeids[n.ID]
524  		if !ok {
525  			return fmt.Errorf(`unexpected foreign-key "feed_items" returned %v`, n.ID)
526  		}
527  		for i := range nodes {
528  			assign(nodes[i], n)
529  		}
530  	}
531  	return nil
532  }
533  func (iq *ItemQuery) loadReadByUsers(ctx context.Context, query *UserQuery, nodes []*Item, init func(*Item), assign func(*Item, *User)) error {
534  	edgeIDs := make([]driver.Value, len(nodes))
535  	byID := make(map[uuid.UUID]*Item)
536  	nids := make(map[uuid.UUID]map[*Item]struct{})
537  	for i, node := range nodes {
538  		edgeIDs[i] = node.ID
539  		byID[node.ID] = node
540  		if init != nil {
541  			init(node)
542  		}
543  	}
544  	query.Where(func(s *sql.Selector) {
545  		joinT := sql.Table(item.ReadByUsersTable)
546  		s.Join(joinT).On(s.C(user.FieldID), joinT.C(item.ReadByUsersPrimaryKey[0]))
547  		s.Where(sql.InValues(joinT.C(item.ReadByUsersPrimaryKey[1]), edgeIDs...))
548  		columns := s.SelectedColumns()
549  		s.Select(joinT.C(item.ReadByUsersPrimaryKey[1]))
550  		s.AppendSelect(columns...)
551  		s.SetDistinct(false)
552  	})
553  	if err := query.prepareQuery(ctx); err != nil {
554  		return err
555  	}
556  	qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
557  		return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
558  			assign := spec.Assign
559  			values := spec.ScanValues
560  			spec.ScanValues = func(columns []string) ([]any, error) {
561  				values, err := values(columns[1:])
562  				if err != nil {
563  					return nil, err
564  				}
565  				return append([]any{new(uuid.UUID)}, values...), nil
566  			}
567  			spec.Assign = func(columns []string, values []any) error {
568  				outValue := *values[0].(*uuid.UUID)
569  				inValue := *values[1].(*uuid.UUID)
570  				if nids[inValue] == nil {
571  					nids[inValue] = map[*Item]struct{}{byID[outValue]: {}}
572  					return assign(columns[1:], values[1:])
573  				}
574  				nids[inValue][byID[outValue]] = struct{}{}
575  				return nil
576  			}
577  		})
578  	})
579  	neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters)
580  	if err != nil {
581  		return err
582  	}
583  	for _, n := range neighbors {
584  		nodes, ok := nids[n.ID]
585  		if !ok {
586  			return fmt.Errorf(`unexpected "read_by_users" node returned %v`, n.ID)
587  		}
588  		for kn := range nodes {
589  			assign(kn, n)
590  		}
591  	}
592  	return nil
593  }
594  func (iq *ItemQuery) loadReads(ctx context.Context, query *ReadQuery, nodes []*Item, init func(*Item), assign func(*Item, *Read)) error {
595  	fks := make([]driver.Value, 0, len(nodes))
596  	nodeids := make(map[uuid.UUID]*Item)
597  	for i := range nodes {
598  		fks = append(fks, nodes[i].ID)
599  		nodeids[nodes[i].ID] = nodes[i]
600  		if init != nil {
601  			init(nodes[i])
602  		}
603  	}
604  	if len(query.ctx.Fields) > 0 {
605  		query.ctx.AppendFieldOnce(read.FieldItemID)
606  	}
607  	query.Where(predicate.Read(func(s *sql.Selector) {
608  		s.Where(sql.InValues(s.C(item.ReadsColumn), fks...))
609  	}))
610  	neighbors, err := query.All(ctx)
611  	if err != nil {
612  		return err
613  	}
614  	for _, n := range neighbors {
615  		fk := n.ItemID
616  		node, ok := nodeids[fk]
617  		if !ok {
618  			return fmt.Errorf(`unexpected referenced foreign-key "item_id" returned %v for node %v`, fk, n.ID)
619  		}
620  		assign(node, n)
621  	}
622  	return nil
623  }
624  
625  func (iq *ItemQuery) sqlCount(ctx context.Context) (int, error) {
626  	_spec := iq.querySpec()
627  	_spec.Node.Columns = iq.ctx.Fields
628  	if len(iq.ctx.Fields) > 0 {
629  		_spec.Unique = iq.ctx.Unique != nil && *iq.ctx.Unique
630  	}
631  	return sqlgraph.CountNodes(ctx, iq.driver, _spec)
632  }
633  
634  func (iq *ItemQuery) querySpec() *sqlgraph.QuerySpec {
635  	_spec := sqlgraph.NewQuerySpec(item.Table, item.Columns, sqlgraph.NewFieldSpec(item.FieldID, field.TypeUUID))
636  	_spec.From = iq.sql
637  	if unique := iq.ctx.Unique; unique != nil {
638  		_spec.Unique = *unique
639  	} else if iq.path != nil {
640  		_spec.Unique = true
641  	}
642  	if fields := iq.ctx.Fields; len(fields) > 0 {
643  		_spec.Node.Columns = make([]string, 0, len(fields))
644  		_spec.Node.Columns = append(_spec.Node.Columns, item.FieldID)
645  		for i := range fields {
646  			if fields[i] != item.FieldID {
647  				_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
648  			}
649  		}
650  	}
651  	if ps := iq.predicates; len(ps) > 0 {
652  		_spec.Predicate = func(selector *sql.Selector) {
653  			for i := range ps {
654  				ps[i](selector)
655  			}
656  		}
657  	}
658  	if limit := iq.ctx.Limit; limit != nil {
659  		_spec.Limit = *limit
660  	}
661  	if offset := iq.ctx.Offset; offset != nil {
662  		_spec.Offset = *offset
663  	}
664  	if ps := iq.order; len(ps) > 0 {
665  		_spec.Order = func(selector *sql.Selector) {
666  			for i := range ps {
667  				ps[i](selector)
668  			}
669  		}
670  	}
671  	return _spec
672  }
673  
674  func (iq *ItemQuery) sqlQuery(ctx context.Context) *sql.Selector {
675  	builder := sql.Dialect(iq.driver.Dialect())
676  	t1 := builder.Table(item.Table)
677  	columns := iq.ctx.Fields
678  	if len(columns) == 0 {
679  		columns = item.Columns
680  	}
681  	selector := builder.Select(t1.Columns(columns...)...).From(t1)
682  	if iq.sql != nil {
683  		selector = iq.sql
684  		selector.Select(selector.Columns(columns...)...)
685  	}
686  	if iq.ctx.Unique != nil && *iq.ctx.Unique {
687  		selector.Distinct()
688  	}
689  	for _, p := range iq.predicates {
690  		p(selector)
691  	}
692  	for _, p := range iq.order {
693  		p(selector)
694  	}
695  	if offset := iq.ctx.Offset; offset != nil {
696  		// limit is mandatory for offset clause. We start
697  		// with default value, and override it below if needed.
698  		selector.Offset(*offset).Limit(math.MaxInt32)
699  	}
700  	if limit := iq.ctx.Limit; limit != nil {
701  		selector.Limit(*limit)
702  	}
703  	return selector
704  }
705  
706  // ItemGroupBy is the group-by builder for Item entities.
707  type ItemGroupBy struct {
708  	selector
709  	build *ItemQuery
710  }
711  
712  // Aggregate adds the given aggregation functions to the group-by query.
713  func (igb *ItemGroupBy) Aggregate(fns ...AggregateFunc) *ItemGroupBy {
714  	igb.fns = append(igb.fns, fns...)
715  	return igb
716  }
717  
718  // Scan applies the selector query and scans the result into the given value.
719  func (igb *ItemGroupBy) Scan(ctx context.Context, v any) error {
720  	ctx = setContextOp(ctx, igb.build.ctx, "GroupBy")
721  	if err := igb.build.prepareQuery(ctx); err != nil {
722  		return err
723  	}
724  	return scanWithInterceptors[*ItemQuery, *ItemGroupBy](ctx, igb.build, igb, igb.build.inters, v)
725  }
726  
727  func (igb *ItemGroupBy) sqlScan(ctx context.Context, root *ItemQuery, v any) error {
728  	selector := root.sqlQuery(ctx).Select()
729  	aggregation := make([]string, 0, len(igb.fns))
730  	for _, fn := range igb.fns {
731  		aggregation = append(aggregation, fn(selector))
732  	}
733  	if len(selector.SelectedColumns()) == 0 {
734  		columns := make([]string, 0, len(*igb.flds)+len(igb.fns))
735  		for _, f := range *igb.flds {
736  			columns = append(columns, selector.C(f))
737  		}
738  		columns = append(columns, aggregation...)
739  		selector.Select(columns...)
740  	}
741  	selector.GroupBy(selector.Columns(*igb.flds...)...)
742  	if err := selector.Err(); err != nil {
743  		return err
744  	}
745  	rows := &sql.Rows{}
746  	query, args := selector.Query()
747  	if err := igb.build.driver.Query(ctx, query, args, rows); err != nil {
748  		return err
749  	}
750  	defer rows.Close()
751  	return sql.ScanSlice(rows, v)
752  }
753  
754  // ItemSelect is the builder for selecting fields of Item entities.
755  type ItemSelect struct {
756  	*ItemQuery
757  	selector
758  }
759  
760  // Aggregate adds the given aggregation functions to the selector query.
761  func (is *ItemSelect) Aggregate(fns ...AggregateFunc) *ItemSelect {
762  	is.fns = append(is.fns, fns...)
763  	return is
764  }
765  
766  // Scan applies the selector query and scans the result into the given value.
767  func (is *ItemSelect) Scan(ctx context.Context, v any) error {
768  	ctx = setContextOp(ctx, is.ctx, "Select")
769  	if err := is.prepareQuery(ctx); err != nil {
770  		return err
771  	}
772  	return scanWithInterceptors[*ItemQuery, *ItemSelect](ctx, is.ItemQuery, is, is.inters, v)
773  }
774  
775  func (is *ItemSelect) sqlScan(ctx context.Context, root *ItemQuery, v any) error {
776  	selector := root.sqlQuery(ctx)
777  	aggregation := make([]string, 0, len(is.fns))
778  	for _, fn := range is.fns {
779  		aggregation = append(aggregation, fn(selector))
780  	}
781  	switch n := len(*is.selector.flds); {
782  	case n == 0 && len(aggregation) > 0:
783  		selector.Select(aggregation...)
784  	case n != 0 && len(aggregation) > 0:
785  		selector.AppendSelect(aggregation...)
786  	}
787  	rows := &sql.Rows{}
788  	query, args := selector.Query()
789  	if err := is.driver.Query(ctx, query, args, rows); err != nil {
790  		return err
791  	}
792  	defer rows.Close()
793  	return sql.ScanSlice(rows, v)
794  }