pcmt/ent/hibp_query.go
surtur 74546f996b
All checks were successful
continuous-integration/drone/push Build is passing
ent: add/extend entities, tests, validation
2023-08-19 04:52:15 +02:00

615 lines
17 KiB
Go

// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"git.dotya.ml/mirre-mt/pcmt/ent/hibp"
"git.dotya.ml/mirre-mt/pcmt/ent/predicate"
"git.dotya.ml/mirre-mt/pcmt/ent/trackedbreaches"
"github.com/google/uuid"
)
// HIBPQuery is the builder for querying HIBP entities.
type HIBPQuery struct {
config
ctx *QueryContext
order []hibp.OrderOption
inters []Interceptor
predicates []predicate.HIBP
withTrackedBreaches *TrackedBreachesQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the HIBPQuery builder.
func (hq *HIBPQuery) Where(ps ...predicate.HIBP) *HIBPQuery {
hq.predicates = append(hq.predicates, ps...)
return hq
}
// Limit the number of records to be returned by this query.
func (hq *HIBPQuery) Limit(limit int) *HIBPQuery {
hq.ctx.Limit = &limit
return hq
}
// Offset to start from.
func (hq *HIBPQuery) Offset(offset int) *HIBPQuery {
hq.ctx.Offset = &offset
return hq
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (hq *HIBPQuery) Unique(unique bool) *HIBPQuery {
hq.ctx.Unique = &unique
return hq
}
// Order specifies how the records should be ordered.
func (hq *HIBPQuery) Order(o ...hibp.OrderOption) *HIBPQuery {
hq.order = append(hq.order, o...)
return hq
}
// QueryTrackedBreaches chains the current query on the "tracked_breaches" edge.
func (hq *HIBPQuery) QueryTrackedBreaches() *TrackedBreachesQuery {
query := (&TrackedBreachesClient{config: hq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := hq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := hq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(hibp.Table, hibp.FieldID, selector),
sqlgraph.To(trackedbreaches.Table, trackedbreaches.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, hibp.TrackedBreachesTable, hibp.TrackedBreachesColumn),
)
fromU = sqlgraph.SetNeighbors(hq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first HIBP entity from the query.
// Returns a *NotFoundError when no HIBP was found.
func (hq *HIBPQuery) First(ctx context.Context) (*HIBP, error) {
nodes, err := hq.Limit(1).All(setContextOp(ctx, hq.ctx, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{hibp.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (hq *HIBPQuery) FirstX(ctx context.Context) *HIBP {
node, err := hq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first HIBP ID from the query.
// Returns a *NotFoundError when no HIBP ID was found.
func (hq *HIBPQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = hq.Limit(1).IDs(setContextOp(ctx, hq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{hibp.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (hq *HIBPQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := hq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single HIBP entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one HIBP entity is found.
// Returns a *NotFoundError when no HIBP entities are found.
func (hq *HIBPQuery) Only(ctx context.Context) (*HIBP, error) {
nodes, err := hq.Limit(2).All(setContextOp(ctx, hq.ctx, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{hibp.Label}
default:
return nil, &NotSingularError{hibp.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (hq *HIBPQuery) OnlyX(ctx context.Context) *HIBP {
node, err := hq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only HIBP ID in the query.
// Returns a *NotSingularError when more than one HIBP ID is found.
// Returns a *NotFoundError when no entities are found.
func (hq *HIBPQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = hq.Limit(2).IDs(setContextOp(ctx, hq.ctx, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{hibp.Label}
default:
err = &NotSingularError{hibp.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (hq *HIBPQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := hq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of HIBPs.
func (hq *HIBPQuery) All(ctx context.Context) ([]*HIBP, error) {
ctx = setContextOp(ctx, hq.ctx, "All")
if err := hq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*HIBP, *HIBPQuery]()
return withInterceptors[[]*HIBP](ctx, hq, qr, hq.inters)
}
// AllX is like All, but panics if an error occurs.
func (hq *HIBPQuery) AllX(ctx context.Context) []*HIBP {
nodes, err := hq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of HIBP IDs.
func (hq *HIBPQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
if hq.ctx.Unique == nil && hq.path != nil {
hq.Unique(true)
}
ctx = setContextOp(ctx, hq.ctx, "IDs")
if err = hq.Select(hibp.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (hq *HIBPQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := hq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (hq *HIBPQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, hq.ctx, "Count")
if err := hq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, hq, querierCount[*HIBPQuery](), hq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (hq *HIBPQuery) CountX(ctx context.Context) int {
count, err := hq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (hq *HIBPQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, hq.ctx, "Exist")
switch _, err := hq.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (hq *HIBPQuery) ExistX(ctx context.Context) bool {
exist, err := hq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the HIBPQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (hq *HIBPQuery) Clone() *HIBPQuery {
if hq == nil {
return nil
}
return &HIBPQuery{
config: hq.config,
ctx: hq.ctx.Clone(),
order: append([]hibp.OrderOption{}, hq.order...),
inters: append([]Interceptor{}, hq.inters...),
predicates: append([]predicate.HIBP{}, hq.predicates...),
withTrackedBreaches: hq.withTrackedBreaches.Clone(),
// clone intermediate query.
sql: hq.sql.Clone(),
path: hq.path,
}
}
// WithTrackedBreaches tells the query-builder to eager-load the nodes that are connected to
// the "tracked_breaches" edge. The optional arguments are used to configure the query builder of the edge.
func (hq *HIBPQuery) WithTrackedBreaches(opts ...func(*TrackedBreachesQuery)) *HIBPQuery {
query := (&TrackedBreachesClient{config: hq.config}).Query()
for _, opt := range opts {
opt(query)
}
hq.withTrackedBreaches = query
return hq
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.HIBP.Query().
// GroupBy(hibp.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (hq *HIBPQuery) GroupBy(field string, fields ...string) *HIBPGroupBy {
hq.ctx.Fields = append([]string{field}, fields...)
grbuild := &HIBPGroupBy{build: hq}
grbuild.flds = &hq.ctx.Fields
grbuild.label = hibp.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// }
//
// client.HIBP.Query().
// Select(hibp.FieldName).
// Scan(ctx, &v)
func (hq *HIBPQuery) Select(fields ...string) *HIBPSelect {
hq.ctx.Fields = append(hq.ctx.Fields, fields...)
sbuild := &HIBPSelect{HIBPQuery: hq}
sbuild.label = hibp.Label
sbuild.flds, sbuild.scan = &hq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a HIBPSelect configured with the given aggregations.
func (hq *HIBPQuery) Aggregate(fns ...AggregateFunc) *HIBPSelect {
return hq.Select().Aggregate(fns...)
}
func (hq *HIBPQuery) prepareQuery(ctx context.Context) error {
for _, inter := range hq.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, hq); err != nil {
return err
}
}
}
for _, f := range hq.ctx.Fields {
if !hibp.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if hq.path != nil {
prev, err := hq.path(ctx)
if err != nil {
return err
}
hq.sql = prev
}
return nil
}
func (hq *HIBPQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*HIBP, error) {
var (
nodes = []*HIBP{}
withFKs = hq.withFKs
_spec = hq.querySpec()
loadedTypes = [1]bool{
hq.withTrackedBreaches != nil,
}
)
if hq.withTrackedBreaches != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, hibp.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*HIBP).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &HIBP{config: hq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, hq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := hq.withTrackedBreaches; query != nil {
if err := hq.loadTrackedBreaches(ctx, query, nodes, nil,
func(n *HIBP, e *TrackedBreaches) { n.Edges.TrackedBreaches = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (hq *HIBPQuery) loadTrackedBreaches(ctx context.Context, query *TrackedBreachesQuery, nodes []*HIBP, init func(*HIBP), assign func(*HIBP, *TrackedBreaches)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*HIBP)
for i := range nodes {
if nodes[i].tracked_breaches_hibp == nil {
continue
}
fk := *nodes[i].tracked_breaches_hibp
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(trackedbreaches.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "tracked_breaches_hibp" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (hq *HIBPQuery) sqlCount(ctx context.Context) (int, error) {
_spec := hq.querySpec()
_spec.Node.Columns = hq.ctx.Fields
if len(hq.ctx.Fields) > 0 {
_spec.Unique = hq.ctx.Unique != nil && *hq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, hq.driver, _spec)
}
func (hq *HIBPQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(hibp.Table, hibp.Columns, sqlgraph.NewFieldSpec(hibp.FieldID, field.TypeUUID))
_spec.From = hq.sql
if unique := hq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if hq.path != nil {
_spec.Unique = true
}
if fields := hq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, hibp.FieldID)
for i := range fields {
if fields[i] != hibp.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := hq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := hq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := hq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := hq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (hq *HIBPQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(hq.driver.Dialect())
t1 := builder.Table(hibp.Table)
columns := hq.ctx.Fields
if len(columns) == 0 {
columns = hibp.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if hq.sql != nil {
selector = hq.sql
selector.Select(selector.Columns(columns...)...)
}
if hq.ctx.Unique != nil && *hq.ctx.Unique {
selector.Distinct()
}
for _, p := range hq.predicates {
p(selector)
}
for _, p := range hq.order {
p(selector)
}
if offset := hq.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := hq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// HIBPGroupBy is the group-by builder for HIBP entities.
type HIBPGroupBy struct {
selector
build *HIBPQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (hgb *HIBPGroupBy) Aggregate(fns ...AggregateFunc) *HIBPGroupBy {
hgb.fns = append(hgb.fns, fns...)
return hgb
}
// Scan applies the selector query and scans the result into the given value.
func (hgb *HIBPGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, hgb.build.ctx, "GroupBy")
if err := hgb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*HIBPQuery, *HIBPGroupBy](ctx, hgb.build, hgb, hgb.build.inters, v)
}
func (hgb *HIBPGroupBy) sqlScan(ctx context.Context, root *HIBPQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(hgb.fns))
for _, fn := range hgb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*hgb.flds)+len(hgb.fns))
for _, f := range *hgb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*hgb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := hgb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// HIBPSelect is the builder for selecting fields of HIBP entities.
type HIBPSelect struct {
*HIBPQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (hs *HIBPSelect) Aggregate(fns ...AggregateFunc) *HIBPSelect {
hs.fns = append(hs.fns, fns...)
return hs
}
// Scan applies the selector query and scans the result into the given value.
func (hs *HIBPSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, hs.ctx, "Select")
if err := hs.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*HIBPQuery, *HIBPSelect](ctx, hs.HIBPQuery, hs, hs.inters, v)
}
func (hs *HIBPSelect) sqlScan(ctx context.Context, root *HIBPQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(hs.fns))
for _, fn := range hs.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*hs.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := hs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}