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