machine_query.go 16 KB

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