event_query.go 15 KB

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