alert_query.go 22 KB

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