/ ent / token_query.go
token_query.go
  1  // Code generated by ent, DO NOT EDIT.
  2  
  3  package ent
  4  
  5  import (
  6  	"context"
  7  	"fmt"
  8  	"math"
  9  
 10  	"entgo.io/ent/dialect/sql"
 11  	"entgo.io/ent/dialect/sql/sqlgraph"
 12  	"entgo.io/ent/schema/field"
 13  	"github.com/google/uuid"
 14  	"github.com/mrusme/journalist/ent/predicate"
 15  	"github.com/mrusme/journalist/ent/token"
 16  	"github.com/mrusme/journalist/ent/user"
 17  )
 18  
 19  // TokenQuery is the builder for querying Token entities.
 20  type TokenQuery struct {
 21  	config
 22  	ctx        *QueryContext
 23  	order      []token.OrderOption
 24  	inters     []Interceptor
 25  	predicates []predicate.Token
 26  	withOwner  *UserQuery
 27  	withFKs    bool
 28  	// intermediate query (i.e. traversal path).
 29  	sql  *sql.Selector
 30  	path func(context.Context) (*sql.Selector, error)
 31  }
 32  
 33  // Where adds a new predicate for the TokenQuery builder.
 34  func (tq *TokenQuery) Where(ps ...predicate.Token) *TokenQuery {
 35  	tq.predicates = append(tq.predicates, ps...)
 36  	return tq
 37  }
 38  
 39  // Limit the number of records to be returned by this query.
 40  func (tq *TokenQuery) Limit(limit int) *TokenQuery {
 41  	tq.ctx.Limit = &limit
 42  	return tq
 43  }
 44  
 45  // Offset to start from.
 46  func (tq *TokenQuery) Offset(offset int) *TokenQuery {
 47  	tq.ctx.Offset = &offset
 48  	return tq
 49  }
 50  
 51  // Unique configures the query builder to filter duplicate records on query.
 52  // By default, unique is set to true, and can be disabled using this method.
 53  func (tq *TokenQuery) Unique(unique bool) *TokenQuery {
 54  	tq.ctx.Unique = &unique
 55  	return tq
 56  }
 57  
 58  // Order specifies how the records should be ordered.
 59  func (tq *TokenQuery) Order(o ...token.OrderOption) *TokenQuery {
 60  	tq.order = append(tq.order, o...)
 61  	return tq
 62  }
 63  
 64  // QueryOwner chains the current query on the "owner" edge.
 65  func (tq *TokenQuery) QueryOwner() *UserQuery {
 66  	query := (&UserClient{config: tq.config}).Query()
 67  	query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
 68  		if err := tq.prepareQuery(ctx); err != nil {
 69  			return nil, err
 70  		}
 71  		selector := tq.sqlQuery(ctx)
 72  		if err := selector.Err(); err != nil {
 73  			return nil, err
 74  		}
 75  		step := sqlgraph.NewStep(
 76  			sqlgraph.From(token.Table, token.FieldID, selector),
 77  			sqlgraph.To(user.Table, user.FieldID),
 78  			sqlgraph.Edge(sqlgraph.M2O, true, token.OwnerTable, token.OwnerColumn),
 79  		)
 80  		fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step)
 81  		return fromU, nil
 82  	}
 83  	return query
 84  }
 85  
 86  // First returns the first Token entity from the query.
 87  // Returns a *NotFoundError when no Token was found.
 88  func (tq *TokenQuery) First(ctx context.Context) (*Token, error) {
 89  	nodes, err := tq.Limit(1).All(setContextOp(ctx, tq.ctx, "First"))
 90  	if err != nil {
 91  		return nil, err
 92  	}
 93  	if len(nodes) == 0 {
 94  		return nil, &NotFoundError{token.Label}
 95  	}
 96  	return nodes[0], nil
 97  }
 98  
 99  // FirstX is like First, but panics if an error occurs.
100  func (tq *TokenQuery) FirstX(ctx context.Context) *Token {
101  	node, err := tq.First(ctx)
102  	if err != nil && !IsNotFound(err) {
103  		panic(err)
104  	}
105  	return node
106  }
107  
108  // FirstID returns the first Token ID from the query.
109  // Returns a *NotFoundError when no Token ID was found.
110  func (tq *TokenQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
111  	var ids []uuid.UUID
112  	if ids, err = tq.Limit(1).IDs(setContextOp(ctx, tq.ctx, "FirstID")); err != nil {
113  		return
114  	}
115  	if len(ids) == 0 {
116  		err = &NotFoundError{token.Label}
117  		return
118  	}
119  	return ids[0], nil
120  }
121  
122  // FirstIDX is like FirstID, but panics if an error occurs.
123  func (tq *TokenQuery) FirstIDX(ctx context.Context) uuid.UUID {
124  	id, err := tq.FirstID(ctx)
125  	if err != nil && !IsNotFound(err) {
126  		panic(err)
127  	}
128  	return id
129  }
130  
131  // Only returns a single Token entity found by the query, ensuring it only returns one.
132  // Returns a *NotSingularError when more than one Token entity is found.
133  // Returns a *NotFoundError when no Token entities are found.
134  func (tq *TokenQuery) Only(ctx context.Context) (*Token, error) {
135  	nodes, err := tq.Limit(2).All(setContextOp(ctx, tq.ctx, "Only"))
136  	if err != nil {
137  		return nil, err
138  	}
139  	switch len(nodes) {
140  	case 1:
141  		return nodes[0], nil
142  	case 0:
143  		return nil, &NotFoundError{token.Label}
144  	default:
145  		return nil, &NotSingularError{token.Label}
146  	}
147  }
148  
149  // OnlyX is like Only, but panics if an error occurs.
150  func (tq *TokenQuery) OnlyX(ctx context.Context) *Token {
151  	node, err := tq.Only(ctx)
152  	if err != nil {
153  		panic(err)
154  	}
155  	return node
156  }
157  
158  // OnlyID is like Only, but returns the only Token ID in the query.
159  // Returns a *NotSingularError when more than one Token ID is found.
160  // Returns a *NotFoundError when no entities are found.
161  func (tq *TokenQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
162  	var ids []uuid.UUID
163  	if ids, err = tq.Limit(2).IDs(setContextOp(ctx, tq.ctx, "OnlyID")); err != nil {
164  		return
165  	}
166  	switch len(ids) {
167  	case 1:
168  		id = ids[0]
169  	case 0:
170  		err = &NotFoundError{token.Label}
171  	default:
172  		err = &NotSingularError{token.Label}
173  	}
174  	return
175  }
176  
177  // OnlyIDX is like OnlyID, but panics if an error occurs.
178  func (tq *TokenQuery) OnlyIDX(ctx context.Context) uuid.UUID {
179  	id, err := tq.OnlyID(ctx)
180  	if err != nil {
181  		panic(err)
182  	}
183  	return id
184  }
185  
186  // All executes the query and returns a list of Tokens.
187  func (tq *TokenQuery) All(ctx context.Context) ([]*Token, error) {
188  	ctx = setContextOp(ctx, tq.ctx, "All")
189  	if err := tq.prepareQuery(ctx); err != nil {
190  		return nil, err
191  	}
192  	qr := querierAll[[]*Token, *TokenQuery]()
193  	return withInterceptors[[]*Token](ctx, tq, qr, tq.inters)
194  }
195  
196  // AllX is like All, but panics if an error occurs.
197  func (tq *TokenQuery) AllX(ctx context.Context) []*Token {
198  	nodes, err := tq.All(ctx)
199  	if err != nil {
200  		panic(err)
201  	}
202  	return nodes
203  }
204  
205  // IDs executes the query and returns a list of Token IDs.
206  func (tq *TokenQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
207  	if tq.ctx.Unique == nil && tq.path != nil {
208  		tq.Unique(true)
209  	}
210  	ctx = setContextOp(ctx, tq.ctx, "IDs")
211  	if err = tq.Select(token.FieldID).Scan(ctx, &ids); err != nil {
212  		return nil, err
213  	}
214  	return ids, nil
215  }
216  
217  // IDsX is like IDs, but panics if an error occurs.
218  func (tq *TokenQuery) IDsX(ctx context.Context) []uuid.UUID {
219  	ids, err := tq.IDs(ctx)
220  	if err != nil {
221  		panic(err)
222  	}
223  	return ids
224  }
225  
226  // Count returns the count of the given query.
227  func (tq *TokenQuery) Count(ctx context.Context) (int, error) {
228  	ctx = setContextOp(ctx, tq.ctx, "Count")
229  	if err := tq.prepareQuery(ctx); err != nil {
230  		return 0, err
231  	}
232  	return withInterceptors[int](ctx, tq, querierCount[*TokenQuery](), tq.inters)
233  }
234  
235  // CountX is like Count, but panics if an error occurs.
236  func (tq *TokenQuery) CountX(ctx context.Context) int {
237  	count, err := tq.Count(ctx)
238  	if err != nil {
239  		panic(err)
240  	}
241  	return count
242  }
243  
244  // Exist returns true if the query has elements in the graph.
245  func (tq *TokenQuery) Exist(ctx context.Context) (bool, error) {
246  	ctx = setContextOp(ctx, tq.ctx, "Exist")
247  	switch _, err := tq.FirstID(ctx); {
248  	case IsNotFound(err):
249  		return false, nil
250  	case err != nil:
251  		return false, fmt.Errorf("ent: check existence: %w", err)
252  	default:
253  		return true, nil
254  	}
255  }
256  
257  // ExistX is like Exist, but panics if an error occurs.
258  func (tq *TokenQuery) ExistX(ctx context.Context) bool {
259  	exist, err := tq.Exist(ctx)
260  	if err != nil {
261  		panic(err)
262  	}
263  	return exist
264  }
265  
266  // Clone returns a duplicate of the TokenQuery builder, including all associated steps. It can be
267  // used to prepare common query builders and use them differently after the clone is made.
268  func (tq *TokenQuery) Clone() *TokenQuery {
269  	if tq == nil {
270  		return nil
271  	}
272  	return &TokenQuery{
273  		config:     tq.config,
274  		ctx:        tq.ctx.Clone(),
275  		order:      append([]token.OrderOption{}, tq.order...),
276  		inters:     append([]Interceptor{}, tq.inters...),
277  		predicates: append([]predicate.Token{}, tq.predicates...),
278  		withOwner:  tq.withOwner.Clone(),
279  		// clone intermediate query.
280  		sql:  tq.sql.Clone(),
281  		path: tq.path,
282  	}
283  }
284  
285  // WithOwner tells the query-builder to eager-load the nodes that are connected to
286  // the "owner" edge. The optional arguments are used to configure the query builder of the edge.
287  func (tq *TokenQuery) WithOwner(opts ...func(*UserQuery)) *TokenQuery {
288  	query := (&UserClient{config: tq.config}).Query()
289  	for _, opt := range opts {
290  		opt(query)
291  	}
292  	tq.withOwner = query
293  	return tq
294  }
295  
296  // GroupBy is used to group vertices by one or more fields/columns.
297  // It is often used with aggregate functions, like: count, max, mean, min, sum.
298  //
299  // Example:
300  //
301  //	var v []struct {
302  //		Type string `json:"type,omitempty"`
303  //		Count int `json:"count,omitempty"`
304  //	}
305  //
306  //	client.Token.Query().
307  //		GroupBy(token.FieldType).
308  //		Aggregate(ent.Count()).
309  //		Scan(ctx, &v)
310  func (tq *TokenQuery) GroupBy(field string, fields ...string) *TokenGroupBy {
311  	tq.ctx.Fields = append([]string{field}, fields...)
312  	grbuild := &TokenGroupBy{build: tq}
313  	grbuild.flds = &tq.ctx.Fields
314  	grbuild.label = token.Label
315  	grbuild.scan = grbuild.Scan
316  	return grbuild
317  }
318  
319  // Select allows the selection one or more fields/columns for the given query,
320  // instead of selecting all fields in the entity.
321  //
322  // Example:
323  //
324  //	var v []struct {
325  //		Type string `json:"type,omitempty"`
326  //	}
327  //
328  //	client.Token.Query().
329  //		Select(token.FieldType).
330  //		Scan(ctx, &v)
331  func (tq *TokenQuery) Select(fields ...string) *TokenSelect {
332  	tq.ctx.Fields = append(tq.ctx.Fields, fields...)
333  	sbuild := &TokenSelect{TokenQuery: tq}
334  	sbuild.label = token.Label
335  	sbuild.flds, sbuild.scan = &tq.ctx.Fields, sbuild.Scan
336  	return sbuild
337  }
338  
339  // Aggregate returns a TokenSelect configured with the given aggregations.
340  func (tq *TokenQuery) Aggregate(fns ...AggregateFunc) *TokenSelect {
341  	return tq.Select().Aggregate(fns...)
342  }
343  
344  func (tq *TokenQuery) prepareQuery(ctx context.Context) error {
345  	for _, inter := range tq.inters {
346  		if inter == nil {
347  			return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
348  		}
349  		if trv, ok := inter.(Traverser); ok {
350  			if err := trv.Traverse(ctx, tq); err != nil {
351  				return err
352  			}
353  		}
354  	}
355  	for _, f := range tq.ctx.Fields {
356  		if !token.ValidColumn(f) {
357  			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
358  		}
359  	}
360  	if tq.path != nil {
361  		prev, err := tq.path(ctx)
362  		if err != nil {
363  			return err
364  		}
365  		tq.sql = prev
366  	}
367  	return nil
368  }
369  
370  func (tq *TokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Token, error) {
371  	var (
372  		nodes       = []*Token{}
373  		withFKs     = tq.withFKs
374  		_spec       = tq.querySpec()
375  		loadedTypes = [1]bool{
376  			tq.withOwner != nil,
377  		}
378  	)
379  	if tq.withOwner != nil {
380  		withFKs = true
381  	}
382  	if withFKs {
383  		_spec.Node.Columns = append(_spec.Node.Columns, token.ForeignKeys...)
384  	}
385  	_spec.ScanValues = func(columns []string) ([]any, error) {
386  		return (*Token).scanValues(nil, columns)
387  	}
388  	_spec.Assign = func(columns []string, values []any) error {
389  		node := &Token{config: tq.config}
390  		nodes = append(nodes, node)
391  		node.Edges.loadedTypes = loadedTypes
392  		return node.assignValues(columns, values)
393  	}
394  	for i := range hooks {
395  		hooks[i](ctx, _spec)
396  	}
397  	if err := sqlgraph.QueryNodes(ctx, tq.driver, _spec); err != nil {
398  		return nil, err
399  	}
400  	if len(nodes) == 0 {
401  		return nodes, nil
402  	}
403  	if query := tq.withOwner; query != nil {
404  		if err := tq.loadOwner(ctx, query, nodes, nil,
405  			func(n *Token, e *User) { n.Edges.Owner = e }); err != nil {
406  			return nil, err
407  		}
408  	}
409  	return nodes, nil
410  }
411  
412  func (tq *TokenQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Token, init func(*Token), assign func(*Token, *User)) error {
413  	ids := make([]uuid.UUID, 0, len(nodes))
414  	nodeids := make(map[uuid.UUID][]*Token)
415  	for i := range nodes {
416  		if nodes[i].user_tokens == nil {
417  			continue
418  		}
419  		fk := *nodes[i].user_tokens
420  		if _, ok := nodeids[fk]; !ok {
421  			ids = append(ids, fk)
422  		}
423  		nodeids[fk] = append(nodeids[fk], nodes[i])
424  	}
425  	if len(ids) == 0 {
426  		return nil
427  	}
428  	query.Where(user.IDIn(ids...))
429  	neighbors, err := query.All(ctx)
430  	if err != nil {
431  		return err
432  	}
433  	for _, n := range neighbors {
434  		nodes, ok := nodeids[n.ID]
435  		if !ok {
436  			return fmt.Errorf(`unexpected foreign-key "user_tokens" returned %v`, n.ID)
437  		}
438  		for i := range nodes {
439  			assign(nodes[i], n)
440  		}
441  	}
442  	return nil
443  }
444  
445  func (tq *TokenQuery) sqlCount(ctx context.Context) (int, error) {
446  	_spec := tq.querySpec()
447  	_spec.Node.Columns = tq.ctx.Fields
448  	if len(tq.ctx.Fields) > 0 {
449  		_spec.Unique = tq.ctx.Unique != nil && *tq.ctx.Unique
450  	}
451  	return sqlgraph.CountNodes(ctx, tq.driver, _spec)
452  }
453  
454  func (tq *TokenQuery) querySpec() *sqlgraph.QuerySpec {
455  	_spec := sqlgraph.NewQuerySpec(token.Table, token.Columns, sqlgraph.NewFieldSpec(token.FieldID, field.TypeUUID))
456  	_spec.From = tq.sql
457  	if unique := tq.ctx.Unique; unique != nil {
458  		_spec.Unique = *unique
459  	} else if tq.path != nil {
460  		_spec.Unique = true
461  	}
462  	if fields := tq.ctx.Fields; len(fields) > 0 {
463  		_spec.Node.Columns = make([]string, 0, len(fields))
464  		_spec.Node.Columns = append(_spec.Node.Columns, token.FieldID)
465  		for i := range fields {
466  			if fields[i] != token.FieldID {
467  				_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
468  			}
469  		}
470  	}
471  	if ps := tq.predicates; len(ps) > 0 {
472  		_spec.Predicate = func(selector *sql.Selector) {
473  			for i := range ps {
474  				ps[i](selector)
475  			}
476  		}
477  	}
478  	if limit := tq.ctx.Limit; limit != nil {
479  		_spec.Limit = *limit
480  	}
481  	if offset := tq.ctx.Offset; offset != nil {
482  		_spec.Offset = *offset
483  	}
484  	if ps := tq.order; len(ps) > 0 {
485  		_spec.Order = func(selector *sql.Selector) {
486  			for i := range ps {
487  				ps[i](selector)
488  			}
489  		}
490  	}
491  	return _spec
492  }
493  
494  func (tq *TokenQuery) sqlQuery(ctx context.Context) *sql.Selector {
495  	builder := sql.Dialect(tq.driver.Dialect())
496  	t1 := builder.Table(token.Table)
497  	columns := tq.ctx.Fields
498  	if len(columns) == 0 {
499  		columns = token.Columns
500  	}
501  	selector := builder.Select(t1.Columns(columns...)...).From(t1)
502  	if tq.sql != nil {
503  		selector = tq.sql
504  		selector.Select(selector.Columns(columns...)...)
505  	}
506  	if tq.ctx.Unique != nil && *tq.ctx.Unique {
507  		selector.Distinct()
508  	}
509  	for _, p := range tq.predicates {
510  		p(selector)
511  	}
512  	for _, p := range tq.order {
513  		p(selector)
514  	}
515  	if offset := tq.ctx.Offset; offset != nil {
516  		// limit is mandatory for offset clause. We start
517  		// with default value, and override it below if needed.
518  		selector.Offset(*offset).Limit(math.MaxInt32)
519  	}
520  	if limit := tq.ctx.Limit; limit != nil {
521  		selector.Limit(*limit)
522  	}
523  	return selector
524  }
525  
526  // TokenGroupBy is the group-by builder for Token entities.
527  type TokenGroupBy struct {
528  	selector
529  	build *TokenQuery
530  }
531  
532  // Aggregate adds the given aggregation functions to the group-by query.
533  func (tgb *TokenGroupBy) Aggregate(fns ...AggregateFunc) *TokenGroupBy {
534  	tgb.fns = append(tgb.fns, fns...)
535  	return tgb
536  }
537  
538  // Scan applies the selector query and scans the result into the given value.
539  func (tgb *TokenGroupBy) Scan(ctx context.Context, v any) error {
540  	ctx = setContextOp(ctx, tgb.build.ctx, "GroupBy")
541  	if err := tgb.build.prepareQuery(ctx); err != nil {
542  		return err
543  	}
544  	return scanWithInterceptors[*TokenQuery, *TokenGroupBy](ctx, tgb.build, tgb, tgb.build.inters, v)
545  }
546  
547  func (tgb *TokenGroupBy) sqlScan(ctx context.Context, root *TokenQuery, v any) error {
548  	selector := root.sqlQuery(ctx).Select()
549  	aggregation := make([]string, 0, len(tgb.fns))
550  	for _, fn := range tgb.fns {
551  		aggregation = append(aggregation, fn(selector))
552  	}
553  	if len(selector.SelectedColumns()) == 0 {
554  		columns := make([]string, 0, len(*tgb.flds)+len(tgb.fns))
555  		for _, f := range *tgb.flds {
556  			columns = append(columns, selector.C(f))
557  		}
558  		columns = append(columns, aggregation...)
559  		selector.Select(columns...)
560  	}
561  	selector.GroupBy(selector.Columns(*tgb.flds...)...)
562  	if err := selector.Err(); err != nil {
563  		return err
564  	}
565  	rows := &sql.Rows{}
566  	query, args := selector.Query()
567  	if err := tgb.build.driver.Query(ctx, query, args, rows); err != nil {
568  		return err
569  	}
570  	defer rows.Close()
571  	return sql.ScanSlice(rows, v)
572  }
573  
574  // TokenSelect is the builder for selecting fields of Token entities.
575  type TokenSelect struct {
576  	*TokenQuery
577  	selector
578  }
579  
580  // Aggregate adds the given aggregation functions to the selector query.
581  func (ts *TokenSelect) Aggregate(fns ...AggregateFunc) *TokenSelect {
582  	ts.fns = append(ts.fns, fns...)
583  	return ts
584  }
585  
586  // Scan applies the selector query and scans the result into the given value.
587  func (ts *TokenSelect) Scan(ctx context.Context, v any) error {
588  	ctx = setContextOp(ctx, ts.ctx, "Select")
589  	if err := ts.prepareQuery(ctx); err != nil {
590  		return err
591  	}
592  	return scanWithInterceptors[*TokenQuery, *TokenSelect](ctx, ts.TokenQuery, ts, ts.inters, v)
593  }
594  
595  func (ts *TokenSelect) sqlScan(ctx context.Context, root *TokenQuery, v any) error {
596  	selector := root.sqlQuery(ctx)
597  	aggregation := make([]string, 0, len(ts.fns))
598  	for _, fn := range ts.fns {
599  		aggregation = append(aggregation, fn(selector))
600  	}
601  	switch n := len(*ts.selector.flds); {
602  	case n == 0 && len(aggregation) > 0:
603  		selector.Select(aggregation...)
604  	case n != 0 && len(aggregation) > 0:
605  		selector.AppendSelect(aggregation...)
606  	}
607  	rows := &sql.Rows{}
608  	query, args := selector.Query()
609  	if err := ts.driver.Query(ctx, query, args, rows); err != nil {
610  		return err
611  	}
612  	defer rows.Close()
613  	return sql.ScanSlice(rows, v)
614  }