github.com/crowdsecurity/crowdsec@v1.6.1/pkg/database/ent/decision_query.go (about)

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