diff --git a/ent/application.go b/ent/application.go index c5c391b0..743d5507 100644 --- a/ent/application.go +++ b/ent/application.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -7,7 +7,8 @@ import ( "strings" "time" - "github.com/facebook/ent/dialect/sql" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/gobench-io/gobench/v2/ent/application" ) @@ -32,17 +33,20 @@ type Application struct { Gomod string `json:"gomod,omitempty"` // Gosum holds the value of the "gosum" field. Gosum string `json:"gosum,omitempty"` + // Vu holds the value of the "vu" field. + Vu int `json:"vu,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the ApplicationQuery when eager-loading is set. - Edges ApplicationEdges `json:"edges"` + Edges ApplicationEdges `json:"edges"` + selectValues sql.SelectValues } // ApplicationEdges holds the relations/edges for other nodes in the graph. type ApplicationEdges struct { // Groups holds the value of the groups edge. - Groups []*Group + Groups []*Group `json:"groups,omitempty"` // Tags holds the value of the tags edge. - Tags []*Tag + Tags []*Tag `json:"tags,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [2]bool @@ -67,100 +71,129 @@ func (e ApplicationEdges) TagsOrErr() ([]*Tag, error) { } // scanValues returns the types for scanning values from sql.Rows. -func (*Application) scanValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // id - &sql.NullString{}, // name - &sql.NullString{}, // status - &sql.NullTime{}, // created_at - &sql.NullTime{}, // started_at - &sql.NullTime{}, // updated_at - &sql.NullString{}, // scenario - &sql.NullString{}, // gomod - &sql.NullString{}, // gosum +func (*Application) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case application.FieldID, application.FieldVu: + values[i] = new(sql.NullInt64) + case application.FieldName, application.FieldStatus, application.FieldScenario, application.FieldGomod, application.FieldGosum: + values[i] = new(sql.NullString) + case application.FieldCreatedAt, application.FieldStartedAt, application.FieldUpdatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } } + return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Application fields. -func (a *Application) assignValues(values ...interface{}) error { - if m, n := len(values), len(application.Columns); m < n { +func (a *Application) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } - value, ok := values[0].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - a.ID = int(value.Int64) - values = values[1:] - if value, ok := values[0].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field name", values[0]) - } else if value.Valid { - a.Name = value.String - } - if value, ok := values[1].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field status", values[1]) - } else if value.Valid { - a.Status = value.String - } - if value, ok := values[2].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field created_at", values[2]) - } else if value.Valid { - a.CreatedAt = value.Time - } - if value, ok := values[3].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field started_at", values[3]) - } else if value.Valid { - a.StartedAt = value.Time - } - if value, ok := values[4].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field updated_at", values[4]) - } else if value.Valid { - a.UpdatedAt = value.Time - } - if value, ok := values[5].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field scenario", values[5]) - } else if value.Valid { - a.Scenario = value.String - } - if value, ok := values[6].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field gomod", values[6]) - } else if value.Valid { - a.Gomod = value.String - } - if value, ok := values[7].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field gosum", values[7]) - } else if value.Valid { - a.Gosum = value.String + for i := range columns { + switch columns[i] { + case application.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + a.ID = int(value.Int64) + case application.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + a.Name = value.String + } + case application.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + a.Status = value.String + } + case application.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + a.CreatedAt = value.Time + } + case application.FieldStartedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field started_at", values[i]) + } else if value.Valid { + a.StartedAt = value.Time + } + case application.FieldUpdatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field updated_at", values[i]) + } else if value.Valid { + a.UpdatedAt = value.Time + } + case application.FieldScenario: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field scenario", values[i]) + } else if value.Valid { + a.Scenario = value.String + } + case application.FieldGomod: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field gomod", values[i]) + } else if value.Valid { + a.Gomod = value.String + } + case application.FieldGosum: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field gosum", values[i]) + } else if value.Valid { + a.Gosum = value.String + } + case application.FieldVu: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field vu", values[i]) + } else if value.Valid { + a.Vu = int(value.Int64) + } + default: + a.selectValues.Set(columns[i], values[i]) + } } return nil } -// QueryGroups queries the groups edge of the Application. +// Value returns the ent.Value that was dynamically selected and assigned to the Application. +// This includes values selected through modifiers, order, etc. +func (a *Application) Value(name string) (ent.Value, error) { + return a.selectValues.Get(name) +} + +// QueryGroups queries the "groups" edge of the Application entity. func (a *Application) QueryGroups() *GroupQuery { - return (&ApplicationClient{config: a.config}).QueryGroups(a) + return NewApplicationClient(a.config).QueryGroups(a) } -// QueryTags queries the tags edge of the Application. +// QueryTags queries the "tags" edge of the Application entity. func (a *Application) QueryTags() *TagQuery { - return (&ApplicationClient{config: a.config}).QueryTags(a) + return NewApplicationClient(a.config).QueryTags(a) } // Update returns a builder for updating this Application. -// Note that, you need to call Application.Unwrap() before calling this method, if this Application +// Note that you need to call Application.Unwrap() before calling this method if this Application // was returned from a transaction, and the transaction was committed or rolled back. func (a *Application) Update() *ApplicationUpdateOne { - return (&ApplicationClient{config: a.config}).UpdateOne(a) + return NewApplicationClient(a.config).UpdateOne(a) } -// Unwrap unwraps the entity that was returned from a transaction after it was closed, -// so that all next queries will be executed through the driver which created the transaction. +// Unwrap unwraps the Application entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. func (a *Application) Unwrap() *Application { - tx, ok := a.config.driver.(*txDriver) + _tx, ok := a.config.driver.(*txDriver) if !ok { panic("ent: Application is not a transactional entity") } - a.config.driver = tx.drv + a.config.driver = _tx.drv return a } @@ -168,32 +201,36 @@ func (a *Application) Unwrap() *Application { func (a *Application) String() string { var builder strings.Builder builder.WriteString("Application(") - builder.WriteString(fmt.Sprintf("id=%v", a.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", a.ID)) + builder.WriteString("name=") builder.WriteString(a.Name) - builder.WriteString(", status=") + builder.WriteString(", ") + builder.WriteString("status=") builder.WriteString(a.Status) - builder.WriteString(", created_at=") + builder.WriteString(", ") + builder.WriteString("created_at=") builder.WriteString(a.CreatedAt.Format(time.ANSIC)) - builder.WriteString(", started_at=") + builder.WriteString(", ") + builder.WriteString("started_at=") builder.WriteString(a.StartedAt.Format(time.ANSIC)) - builder.WriteString(", updated_at=") + builder.WriteString(", ") + builder.WriteString("updated_at=") builder.WriteString(a.UpdatedAt.Format(time.ANSIC)) - builder.WriteString(", scenario=") + builder.WriteString(", ") + builder.WriteString("scenario=") builder.WriteString(a.Scenario) - builder.WriteString(", gomod=") + builder.WriteString(", ") + builder.WriteString("gomod=") builder.WriteString(a.Gomod) - builder.WriteString(", gosum=") + builder.WriteString(", ") + builder.WriteString("gosum=") builder.WriteString(a.Gosum) + builder.WriteString(", ") + builder.WriteString("vu=") + builder.WriteString(fmt.Sprintf("%v", a.Vu)) builder.WriteByte(')') return builder.String() } // Applications is a parsable slice of Application. type Applications []*Application - -func (a Applications) config(cfg config) { - for _i := range a { - a[_i].config = cfg - } -} diff --git a/ent/application/application.go b/ent/application/application.go index e382f7c2..879678e0 100644 --- a/ent/application/application.go +++ b/ent/application/application.go @@ -1,9 +1,12 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package application import ( "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" ) const ( @@ -27,22 +30,22 @@ const ( FieldGomod = "gomod" // FieldGosum holds the string denoting the gosum field in the database. FieldGosum = "gosum" - + // FieldVu holds the string denoting the vu field in the database. + FieldVu = "vu" // EdgeGroups holds the string denoting the groups edge name in mutations. EdgeGroups = "groups" // EdgeTags holds the string denoting the tags edge name in mutations. EdgeTags = "tags" - // Table holds the table name of the application in the database. Table = "applications" - // GroupsTable is the table the holds the groups relation/edge. + // GroupsTable is the table that holds the groups relation/edge. GroupsTable = "groups" // GroupsInverseTable is the table name for the Group entity. // It exists in this package in order to avoid circular dependency with the "group" package. GroupsInverseTable = "groups" // GroupsColumn is the table column denoting the groups relation/edge. GroupsColumn = "application_groups" - // TagsTable is the table the holds the tags relation/edge. + // TagsTable is the table that holds the tags relation/edge. TagsTable = "tags" // TagsInverseTable is the table name for the Tag entity. // It exists in this package in order to avoid circular dependency with the "tag" package. @@ -62,6 +65,7 @@ var Columns = []string{ FieldScenario, FieldGomod, FieldGosum, + FieldVu, } // ValidColumn reports if the column name is valid (part of the table columns). @@ -75,14 +79,113 @@ func ValidColumn(column string) bool { } var ( - // DefaultCreatedAt holds the default value on creation for the created_at field. + // DefaultCreatedAt holds the default value on creation for the "created_at" field. DefaultCreatedAt func() time.Time - // DefaultUpdatedAt holds the default value on creation for the updated_at field. + // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. DefaultUpdatedAt func() time.Time - // UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. UpdateDefaultUpdatedAt func() time.Time - // DefaultGomod holds the default value on creation for the gomod field. + // DefaultGomod holds the default value on creation for the "gomod" field. DefaultGomod string - // DefaultGosum holds the default value on creation for the gosum field. + // DefaultGosum holds the default value on creation for the "gosum" field. DefaultGosum string + // DefaultVu holds the default value on creation for the "vu" field. + DefaultVu int + // VuValidator is a validator for the "vu" field. It is called by the builders before save. + VuValidator func(int) error ) + +// OrderOption defines the ordering options for the Application queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByStartedAt orders the results by the started_at field. +func ByStartedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStartedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByScenario orders the results by the scenario field. +func ByScenario(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldScenario, opts...).ToFunc() +} + +// ByGomod orders the results by the gomod field. +func ByGomod(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldGomod, opts...).ToFunc() +} + +// ByGosum orders the results by the gosum field. +func ByGosum(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldGosum, opts...).ToFunc() +} + +// ByVu orders the results by the vu field. +func ByVu(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVu, opts...).ToFunc() +} + +// ByGroupsCount orders the results by groups count. +func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newGroupsStep(), opts...) + } +} + +// ByGroups orders the results by groups terms. +func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGroupsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByTagsCount orders the results by tags count. +func ByTagsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newTagsStep(), opts...) + } +} + +// ByTags orders the results by tags terms. +func ByTags(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTagsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newGroupsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, GroupsTable, GroupsColumn), + ) +} +func newTagsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TagsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TagsTable, TagsColumn), + ) +} diff --git a/ent/application/where.go b/ent/application/where.go index 1f87f580..bad71e8c 100644 --- a/ent/application/where.go +++ b/ent/application/where.go @@ -1,949 +1,598 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package application import ( "time" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" "github.com/gobench-io/gobench/v2/ent/predicate" ) -// ID filters vertices based on their identifier. +// ID filters vertices based on their ID field. func ID(id int) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Application(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Application(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) + return predicate.Application(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) + return predicate.Application(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) + return predicate.Application(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) + return predicate.Application(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) + return predicate.Application(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) + return predicate.Application(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) + return predicate.Application(sql.FieldLTE(FieldID, id)) } // Name applies equality check predicate on the "name" field. It's identical to NameEQ. func Name(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldEQ(FieldName, v)) } // Status applies equality check predicate on the "status" field. It's identical to StatusEQ. func Status(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldEQ(FieldStatus, v)) } // CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. func CreatedAt(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCreatedAt), v)) - }) + return predicate.Application(sql.FieldEQ(FieldCreatedAt, v)) } // StartedAt applies equality check predicate on the "started_at" field. It's identical to StartedAtEQ. func StartedAt(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldStartedAt), v)) - }) + return predicate.Application(sql.FieldEQ(FieldStartedAt, v)) } // UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. func UpdatedAt(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUpdatedAt), v)) - }) + return predicate.Application(sql.FieldEQ(FieldUpdatedAt, v)) } // Scenario applies equality check predicate on the "scenario" field. It's identical to ScenarioEQ. func Scenario(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldEQ(FieldScenario, v)) } // Gomod applies equality check predicate on the "gomod" field. It's identical to GomodEQ. func Gomod(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldEQ(FieldGomod, v)) } // Gosum applies equality check predicate on the "gosum" field. It's identical to GosumEQ. func Gosum(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldEQ(FieldGosum, v)) +} + +// Vu applies equality check predicate on the "vu" field. It's identical to VuEQ. +func Vu(v int) predicate.Application { + return predicate.Application(sql.FieldEQ(FieldVu, v)) } // NameEQ applies the EQ predicate on the "name" field. func NameEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldEQ(FieldName, v)) } // NameNEQ applies the NEQ predicate on the "name" field. func NameNEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldNEQ(FieldName, v)) } // NameIn applies the In predicate on the "name" field. func NameIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldName), v...)) - }) + return predicate.Application(sql.FieldIn(FieldName, vs...)) } // NameNotIn applies the NotIn predicate on the "name" field. func NameNotIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldName), v...)) - }) + return predicate.Application(sql.FieldNotIn(FieldName, vs...)) } // NameGT applies the GT predicate on the "name" field. func NameGT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldGT(FieldName, v)) } // NameGTE applies the GTE predicate on the "name" field. func NameGTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldGTE(FieldName, v)) } // NameLT applies the LT predicate on the "name" field. func NameLT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldLT(FieldName, v)) } // NameLTE applies the LTE predicate on the "name" field. func NameLTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldLTE(FieldName, v)) } // NameContains applies the Contains predicate on the "name" field. func NameContains(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldContains(FieldName, v)) } // NameHasPrefix applies the HasPrefix predicate on the "name" field. func NameHasPrefix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldHasPrefix(FieldName, v)) } // NameHasSuffix applies the HasSuffix predicate on the "name" field. func NameHasSuffix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldHasSuffix(FieldName, v)) } // NameEqualFold applies the EqualFold predicate on the "name" field. func NameEqualFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldEqualFold(FieldName, v)) } // NameContainsFold applies the ContainsFold predicate on the "name" field. func NameContainsFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldName), v)) - }) + return predicate.Application(sql.FieldContainsFold(FieldName, v)) } // StatusEQ applies the EQ predicate on the "status" field. func StatusEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldEQ(FieldStatus, v)) } // StatusNEQ applies the NEQ predicate on the "status" field. func StatusNEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldNEQ(FieldStatus, v)) } // StatusIn applies the In predicate on the "status" field. func StatusIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldStatus), v...)) - }) + return predicate.Application(sql.FieldIn(FieldStatus, vs...)) } // StatusNotIn applies the NotIn predicate on the "status" field. func StatusNotIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldStatus), v...)) - }) + return predicate.Application(sql.FieldNotIn(FieldStatus, vs...)) } // StatusGT applies the GT predicate on the "status" field. func StatusGT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldGT(FieldStatus, v)) } // StatusGTE applies the GTE predicate on the "status" field. func StatusGTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldGTE(FieldStatus, v)) } // StatusLT applies the LT predicate on the "status" field. func StatusLT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldLT(FieldStatus, v)) } // StatusLTE applies the LTE predicate on the "status" field. func StatusLTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldLTE(FieldStatus, v)) } // StatusContains applies the Contains predicate on the "status" field. func StatusContains(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldContains(FieldStatus, v)) } // StatusHasPrefix applies the HasPrefix predicate on the "status" field. func StatusHasPrefix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldHasPrefix(FieldStatus, v)) } // StatusHasSuffix applies the HasSuffix predicate on the "status" field. func StatusHasSuffix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldHasSuffix(FieldStatus, v)) } // StatusEqualFold applies the EqualFold predicate on the "status" field. func StatusEqualFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldEqualFold(FieldStatus, v)) } // StatusContainsFold applies the ContainsFold predicate on the "status" field. func StatusContainsFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldStatus), v)) - }) + return predicate.Application(sql.FieldContainsFold(FieldStatus, v)) } // CreatedAtEQ applies the EQ predicate on the "created_at" field. func CreatedAtEQ(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCreatedAt), v)) - }) + return predicate.Application(sql.FieldEQ(FieldCreatedAt, v)) } // CreatedAtNEQ applies the NEQ predicate on the "created_at" field. func CreatedAtNEQ(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldCreatedAt), v)) - }) + return predicate.Application(sql.FieldNEQ(FieldCreatedAt, v)) } // CreatedAtIn applies the In predicate on the "created_at" field. func CreatedAtIn(vs ...time.Time) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldCreatedAt), v...)) - }) + return predicate.Application(sql.FieldIn(FieldCreatedAt, vs...)) } // CreatedAtNotIn applies the NotIn predicate on the "created_at" field. func CreatedAtNotIn(vs ...time.Time) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldCreatedAt), v...)) - }) + return predicate.Application(sql.FieldNotIn(FieldCreatedAt, vs...)) } // CreatedAtGT applies the GT predicate on the "created_at" field. func CreatedAtGT(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldCreatedAt), v)) - }) + return predicate.Application(sql.FieldGT(FieldCreatedAt, v)) } // CreatedAtGTE applies the GTE predicate on the "created_at" field. func CreatedAtGTE(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldCreatedAt), v)) - }) + return predicate.Application(sql.FieldGTE(FieldCreatedAt, v)) } // CreatedAtLT applies the LT predicate on the "created_at" field. func CreatedAtLT(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldCreatedAt), v)) - }) + return predicate.Application(sql.FieldLT(FieldCreatedAt, v)) } // CreatedAtLTE applies the LTE predicate on the "created_at" field. func CreatedAtLTE(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldCreatedAt), v)) - }) + return predicate.Application(sql.FieldLTE(FieldCreatedAt, v)) } // StartedAtEQ applies the EQ predicate on the "started_at" field. func StartedAtEQ(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldStartedAt), v)) - }) + return predicate.Application(sql.FieldEQ(FieldStartedAt, v)) } // StartedAtNEQ applies the NEQ predicate on the "started_at" field. func StartedAtNEQ(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldStartedAt), v)) - }) + return predicate.Application(sql.FieldNEQ(FieldStartedAt, v)) } // StartedAtIn applies the In predicate on the "started_at" field. func StartedAtIn(vs ...time.Time) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldStartedAt), v...)) - }) + return predicate.Application(sql.FieldIn(FieldStartedAt, vs...)) } // StartedAtNotIn applies the NotIn predicate on the "started_at" field. func StartedAtNotIn(vs ...time.Time) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldStartedAt), v...)) - }) + return predicate.Application(sql.FieldNotIn(FieldStartedAt, vs...)) } // StartedAtGT applies the GT predicate on the "started_at" field. func StartedAtGT(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldStartedAt), v)) - }) + return predicate.Application(sql.FieldGT(FieldStartedAt, v)) } // StartedAtGTE applies the GTE predicate on the "started_at" field. func StartedAtGTE(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldStartedAt), v)) - }) + return predicate.Application(sql.FieldGTE(FieldStartedAt, v)) } // StartedAtLT applies the LT predicate on the "started_at" field. func StartedAtLT(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldStartedAt), v)) - }) + return predicate.Application(sql.FieldLT(FieldStartedAt, v)) } // StartedAtLTE applies the LTE predicate on the "started_at" field. func StartedAtLTE(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldStartedAt), v)) - }) + return predicate.Application(sql.FieldLTE(FieldStartedAt, v)) } // StartedAtIsNil applies the IsNil predicate on the "started_at" field. func StartedAtIsNil() predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.IsNull(s.C(FieldStartedAt))) - }) + return predicate.Application(sql.FieldIsNull(FieldStartedAt)) } // StartedAtNotNil applies the NotNil predicate on the "started_at" field. func StartedAtNotNil() predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NotNull(s.C(FieldStartedAt))) - }) + return predicate.Application(sql.FieldNotNull(FieldStartedAt)) } // UpdatedAtEQ applies the EQ predicate on the "updated_at" field. func UpdatedAtEQ(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUpdatedAt), v)) - }) + return predicate.Application(sql.FieldEQ(FieldUpdatedAt, v)) } // UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. func UpdatedAtNEQ(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldUpdatedAt), v)) - }) + return predicate.Application(sql.FieldNEQ(FieldUpdatedAt, v)) } // UpdatedAtIn applies the In predicate on the "updated_at" field. func UpdatedAtIn(vs ...time.Time) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldUpdatedAt), v...)) - }) + return predicate.Application(sql.FieldIn(FieldUpdatedAt, vs...)) } // UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. func UpdatedAtNotIn(vs ...time.Time) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...)) - }) + return predicate.Application(sql.FieldNotIn(FieldUpdatedAt, vs...)) } // UpdatedAtGT applies the GT predicate on the "updated_at" field. func UpdatedAtGT(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldUpdatedAt), v)) - }) + return predicate.Application(sql.FieldGT(FieldUpdatedAt, v)) } // UpdatedAtGTE applies the GTE predicate on the "updated_at" field. func UpdatedAtGTE(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldUpdatedAt), v)) - }) + return predicate.Application(sql.FieldGTE(FieldUpdatedAt, v)) } // UpdatedAtLT applies the LT predicate on the "updated_at" field. func UpdatedAtLT(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldUpdatedAt), v)) - }) + return predicate.Application(sql.FieldLT(FieldUpdatedAt, v)) } // UpdatedAtLTE applies the LTE predicate on the "updated_at" field. func UpdatedAtLTE(v time.Time) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldUpdatedAt), v)) - }) + return predicate.Application(sql.FieldLTE(FieldUpdatedAt, v)) } // ScenarioEQ applies the EQ predicate on the "scenario" field. func ScenarioEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldEQ(FieldScenario, v)) } // ScenarioNEQ applies the NEQ predicate on the "scenario" field. func ScenarioNEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldNEQ(FieldScenario, v)) } // ScenarioIn applies the In predicate on the "scenario" field. func ScenarioIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldScenario), v...)) - }) + return predicate.Application(sql.FieldIn(FieldScenario, vs...)) } // ScenarioNotIn applies the NotIn predicate on the "scenario" field. func ScenarioNotIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldScenario), v...)) - }) + return predicate.Application(sql.FieldNotIn(FieldScenario, vs...)) } // ScenarioGT applies the GT predicate on the "scenario" field. func ScenarioGT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldGT(FieldScenario, v)) } // ScenarioGTE applies the GTE predicate on the "scenario" field. func ScenarioGTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldGTE(FieldScenario, v)) } // ScenarioLT applies the LT predicate on the "scenario" field. func ScenarioLT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldLT(FieldScenario, v)) } // ScenarioLTE applies the LTE predicate on the "scenario" field. func ScenarioLTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldLTE(FieldScenario, v)) } // ScenarioContains applies the Contains predicate on the "scenario" field. func ScenarioContains(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldContains(FieldScenario, v)) } // ScenarioHasPrefix applies the HasPrefix predicate on the "scenario" field. func ScenarioHasPrefix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldHasPrefix(FieldScenario, v)) } // ScenarioHasSuffix applies the HasSuffix predicate on the "scenario" field. func ScenarioHasSuffix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldHasSuffix(FieldScenario, v)) } // ScenarioEqualFold applies the EqualFold predicate on the "scenario" field. func ScenarioEqualFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldEqualFold(FieldScenario, v)) } // ScenarioContainsFold applies the ContainsFold predicate on the "scenario" field. func ScenarioContainsFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldScenario), v)) - }) + return predicate.Application(sql.FieldContainsFold(FieldScenario, v)) } // GomodEQ applies the EQ predicate on the "gomod" field. func GomodEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldEQ(FieldGomod, v)) } // GomodNEQ applies the NEQ predicate on the "gomod" field. func GomodNEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldNEQ(FieldGomod, v)) } // GomodIn applies the In predicate on the "gomod" field. func GomodIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldGomod), v...)) - }) + return predicate.Application(sql.FieldIn(FieldGomod, vs...)) } // GomodNotIn applies the NotIn predicate on the "gomod" field. func GomodNotIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldGomod), v...)) - }) + return predicate.Application(sql.FieldNotIn(FieldGomod, vs...)) } // GomodGT applies the GT predicate on the "gomod" field. func GomodGT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldGT(FieldGomod, v)) } // GomodGTE applies the GTE predicate on the "gomod" field. func GomodGTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldGTE(FieldGomod, v)) } // GomodLT applies the LT predicate on the "gomod" field. func GomodLT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldLT(FieldGomod, v)) } // GomodLTE applies the LTE predicate on the "gomod" field. func GomodLTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldLTE(FieldGomod, v)) } // GomodContains applies the Contains predicate on the "gomod" field. func GomodContains(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldContains(FieldGomod, v)) } // GomodHasPrefix applies the HasPrefix predicate on the "gomod" field. func GomodHasPrefix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldHasPrefix(FieldGomod, v)) } // GomodHasSuffix applies the HasSuffix predicate on the "gomod" field. func GomodHasSuffix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldHasSuffix(FieldGomod, v)) } // GomodEqualFold applies the EqualFold predicate on the "gomod" field. func GomodEqualFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldEqualFold(FieldGomod, v)) } // GomodContainsFold applies the ContainsFold predicate on the "gomod" field. func GomodContainsFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldGomod), v)) - }) + return predicate.Application(sql.FieldContainsFold(FieldGomod, v)) } // GosumEQ applies the EQ predicate on the "gosum" field. func GosumEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldEQ(FieldGosum, v)) } // GosumNEQ applies the NEQ predicate on the "gosum" field. func GosumNEQ(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldNEQ(FieldGosum, v)) } // GosumIn applies the In predicate on the "gosum" field. func GosumIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldGosum), v...)) - }) + return predicate.Application(sql.FieldIn(FieldGosum, vs...)) } // GosumNotIn applies the NotIn predicate on the "gosum" field. func GosumNotIn(vs ...string) predicate.Application { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Application(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldGosum), v...)) - }) + return predicate.Application(sql.FieldNotIn(FieldGosum, vs...)) } // GosumGT applies the GT predicate on the "gosum" field. func GosumGT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldGT(FieldGosum, v)) } // GosumGTE applies the GTE predicate on the "gosum" field. func GosumGTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldGTE(FieldGosum, v)) } // GosumLT applies the LT predicate on the "gosum" field. func GosumLT(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldLT(FieldGosum, v)) } // GosumLTE applies the LTE predicate on the "gosum" field. func GosumLTE(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldLTE(FieldGosum, v)) } // GosumContains applies the Contains predicate on the "gosum" field. func GosumContains(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldContains(FieldGosum, v)) } // GosumHasPrefix applies the HasPrefix predicate on the "gosum" field. func GosumHasPrefix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldHasPrefix(FieldGosum, v)) } // GosumHasSuffix applies the HasSuffix predicate on the "gosum" field. func GosumHasSuffix(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldHasSuffix(FieldGosum, v)) } // GosumEqualFold applies the EqualFold predicate on the "gosum" field. func GosumEqualFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldEqualFold(FieldGosum, v)) } // GosumContainsFold applies the ContainsFold predicate on the "gosum" field. func GosumContainsFold(v string) predicate.Application { - return predicate.Application(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldGosum), v)) - }) + return predicate.Application(sql.FieldContainsFold(FieldGosum, v)) +} + +// VuEQ applies the EQ predicate on the "vu" field. +func VuEQ(v int) predicate.Application { + return predicate.Application(sql.FieldEQ(FieldVu, v)) +} + +// VuNEQ applies the NEQ predicate on the "vu" field. +func VuNEQ(v int) predicate.Application { + return predicate.Application(sql.FieldNEQ(FieldVu, v)) +} + +// VuIn applies the In predicate on the "vu" field. +func VuIn(vs ...int) predicate.Application { + return predicate.Application(sql.FieldIn(FieldVu, vs...)) +} + +// VuNotIn applies the NotIn predicate on the "vu" field. +func VuNotIn(vs ...int) predicate.Application { + return predicate.Application(sql.FieldNotIn(FieldVu, vs...)) +} + +// VuGT applies the GT predicate on the "vu" field. +func VuGT(v int) predicate.Application { + return predicate.Application(sql.FieldGT(FieldVu, v)) +} + +// VuGTE applies the GTE predicate on the "vu" field. +func VuGTE(v int) predicate.Application { + return predicate.Application(sql.FieldGTE(FieldVu, v)) +} + +// VuLT applies the LT predicate on the "vu" field. +func VuLT(v int) predicate.Application { + return predicate.Application(sql.FieldLT(FieldVu, v)) +} + +// VuLTE applies the LTE predicate on the "vu" field. +func VuLTE(v int) predicate.Application { + return predicate.Application(sql.FieldLTE(FieldVu, v)) } // HasGroups applies the HasEdge predicate on the "groups" edge. @@ -951,7 +600,6 @@ func HasGroups() predicate.Application { return predicate.Application(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(GroupsTable, FieldID), sqlgraph.Edge(sqlgraph.O2M, false, GroupsTable, GroupsColumn), ) sqlgraph.HasNeighbors(s, step) @@ -961,11 +609,7 @@ func HasGroups() predicate.Application { // HasGroupsWith applies the HasEdge predicate on the "groups" edge with a given conditions (other predicates). func HasGroupsWith(preds ...predicate.Group) predicate.Application { return predicate.Application(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(GroupsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, GroupsTable, GroupsColumn), - ) + step := newGroupsStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -979,7 +623,6 @@ func HasTags() predicate.Application { return predicate.Application(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(TagsTable, FieldID), sqlgraph.Edge(sqlgraph.O2M, false, TagsTable, TagsColumn), ) sqlgraph.HasNeighbors(s, step) @@ -989,11 +632,7 @@ func HasTags() predicate.Application { // HasTagsWith applies the HasEdge predicate on the "tags" edge with a given conditions (other predicates). func HasTagsWith(preds ...predicate.Tag) predicate.Application { return predicate.Application(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(TagsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, TagsTable, TagsColumn), - ) + step := newTagsStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -1002,7 +641,7 @@ func HasTagsWith(preds ...predicate.Tag) predicate.Application { }) } -// And groups list of predicates with the AND operator between them. +// And groups predicates with the AND operator between them. func And(predicates ...predicate.Application) predicate.Application { return predicate.Application(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) @@ -1013,7 +652,7 @@ func And(predicates ...predicate.Application) predicate.Application { }) } -// Or groups list of predicates with the OR operator between them. +// Or groups predicates with the OR operator between them. func Or(predicates ...predicate.Application) predicate.Application { return predicate.Application(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) diff --git a/ent/application_create.go b/ent/application_create.go index adda519e..e37d4e19 100644 --- a/ent/application_create.go +++ b/ent/application_create.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -8,8 +8,8 @@ import ( "fmt" "time" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/group" "github.com/gobench-io/gobench/v2/ent/tag" @@ -22,25 +22,25 @@ type ApplicationCreate struct { hooks []Hook } -// SetName sets the name field. +// SetName sets the "name" field. func (ac *ApplicationCreate) SetName(s string) *ApplicationCreate { ac.mutation.SetName(s) return ac } -// SetStatus sets the status field. +// SetStatus sets the "status" field. func (ac *ApplicationCreate) SetStatus(s string) *ApplicationCreate { ac.mutation.SetStatus(s) return ac } -// SetCreatedAt sets the created_at field. +// SetCreatedAt sets the "created_at" field. func (ac *ApplicationCreate) SetCreatedAt(t time.Time) *ApplicationCreate { ac.mutation.SetCreatedAt(t) return ac } -// SetNillableCreatedAt sets the created_at field if the given value is not nil. +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. func (ac *ApplicationCreate) SetNillableCreatedAt(t *time.Time) *ApplicationCreate { if t != nil { ac.SetCreatedAt(*t) @@ -48,13 +48,13 @@ func (ac *ApplicationCreate) SetNillableCreatedAt(t *time.Time) *ApplicationCrea return ac } -// SetStartedAt sets the started_at field. +// SetStartedAt sets the "started_at" field. func (ac *ApplicationCreate) SetStartedAt(t time.Time) *ApplicationCreate { ac.mutation.SetStartedAt(t) return ac } -// SetNillableStartedAt sets the started_at field if the given value is not nil. +// SetNillableStartedAt sets the "started_at" field if the given value is not nil. func (ac *ApplicationCreate) SetNillableStartedAt(t *time.Time) *ApplicationCreate { if t != nil { ac.SetStartedAt(*t) @@ -62,13 +62,13 @@ func (ac *ApplicationCreate) SetNillableStartedAt(t *time.Time) *ApplicationCrea return ac } -// SetUpdatedAt sets the updated_at field. +// SetUpdatedAt sets the "updated_at" field. func (ac *ApplicationCreate) SetUpdatedAt(t time.Time) *ApplicationCreate { ac.mutation.SetUpdatedAt(t) return ac } -// SetNillableUpdatedAt sets the updated_at field if the given value is not nil. +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. func (ac *ApplicationCreate) SetNillableUpdatedAt(t *time.Time) *ApplicationCreate { if t != nil { ac.SetUpdatedAt(*t) @@ -76,19 +76,19 @@ func (ac *ApplicationCreate) SetNillableUpdatedAt(t *time.Time) *ApplicationCrea return ac } -// SetScenario sets the scenario field. +// SetScenario sets the "scenario" field. func (ac *ApplicationCreate) SetScenario(s string) *ApplicationCreate { ac.mutation.SetScenario(s) return ac } -// SetGomod sets the gomod field. +// SetGomod sets the "gomod" field. func (ac *ApplicationCreate) SetGomod(s string) *ApplicationCreate { ac.mutation.SetGomod(s) return ac } -// SetNillableGomod sets the gomod field if the given value is not nil. +// SetNillableGomod sets the "gomod" field if the given value is not nil. func (ac *ApplicationCreate) SetNillableGomod(s *string) *ApplicationCreate { if s != nil { ac.SetGomod(*s) @@ -96,13 +96,13 @@ func (ac *ApplicationCreate) SetNillableGomod(s *string) *ApplicationCreate { return ac } -// SetGosum sets the gosum field. +// SetGosum sets the "gosum" field. func (ac *ApplicationCreate) SetGosum(s string) *ApplicationCreate { ac.mutation.SetGosum(s) return ac } -// SetNillableGosum sets the gosum field if the given value is not nil. +// SetNillableGosum sets the "gosum" field if the given value is not nil. func (ac *ApplicationCreate) SetNillableGosum(s *string) *ApplicationCreate { if s != nil { ac.SetGosum(*s) @@ -110,13 +110,27 @@ func (ac *ApplicationCreate) SetNillableGosum(s *string) *ApplicationCreate { return ac } -// AddGroupIDs adds the groups edge to Group by ids. +// SetVu sets the "vu" field. +func (ac *ApplicationCreate) SetVu(i int) *ApplicationCreate { + ac.mutation.SetVu(i) + return ac +} + +// SetNillableVu sets the "vu" field if the given value is not nil. +func (ac *ApplicationCreate) SetNillableVu(i *int) *ApplicationCreate { + if i != nil { + ac.SetVu(*i) + } + return ac +} + +// AddGroupIDs adds the "groups" edge to the Group entity by IDs. func (ac *ApplicationCreate) AddGroupIDs(ids ...int) *ApplicationCreate { ac.mutation.AddGroupIDs(ids...) return ac } -// AddGroups adds the groups edges to Group. +// AddGroups adds the "groups" edges to the Group entity. func (ac *ApplicationCreate) AddGroups(g ...*Group) *ApplicationCreate { ids := make([]int, len(g)) for i := range g { @@ -125,13 +139,13 @@ func (ac *ApplicationCreate) AddGroups(g ...*Group) *ApplicationCreate { return ac.AddGroupIDs(ids...) } -// AddTagIDs adds the tags edge to Tag by ids. +// AddTagIDs adds the "tags" edge to the Tag entity by IDs. func (ac *ApplicationCreate) AddTagIDs(ids ...int) *ApplicationCreate { ac.mutation.AddTagIDs(ids...) return ac } -// AddTags adds the tags edges to Tag. +// AddTags adds the "tags" edges to the Tag entity. func (ac *ApplicationCreate) AddTags(t ...*Tag) *ApplicationCreate { ids := make([]int, len(t)) for i := range t { @@ -147,38 +161,8 @@ func (ac *ApplicationCreate) Mutation() *ApplicationMutation { // Save creates the Application in the database. func (ac *ApplicationCreate) Save(ctx context.Context) (*Application, error) { - var ( - err error - node *Application - ) ac.defaults() - if len(ac.hooks) == 0 { - if err = ac.check(); err != nil { - return nil, err - } - node, err = ac.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*ApplicationMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = ac.check(); err != nil { - return nil, err - } - ac.mutation = mutation - node, err = ac.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(ac.hooks) - 1; i >= 0; i-- { - mut = ac.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, ac.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, ac.sqlSave, ac.mutation, ac.hooks) } // SaveX calls Save and panics if Save returns an error. @@ -190,6 +174,19 @@ func (ac *ApplicationCreate) SaveX(ctx context.Context) *Application { return v } +// Exec executes the query. +func (ac *ApplicationCreate) Exec(ctx context.Context) error { + _, err := ac.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ac *ApplicationCreate) ExecX(ctx context.Context) { + if err := ac.Exec(ctx); err != nil { + panic(err) + } +} + // defaults sets the default values of the builder before save. func (ac *ApplicationCreate) defaults() { if _, ok := ac.mutation.CreatedAt(); !ok { @@ -208,122 +205,105 @@ func (ac *ApplicationCreate) defaults() { v := application.DefaultGosum ac.mutation.SetGosum(v) } + if _, ok := ac.mutation.Vu(); !ok { + v := application.DefaultVu + ac.mutation.SetVu(v) + } } // check runs all checks and user-defined validators on the builder. func (ac *ApplicationCreate) check() error { if _, ok := ac.mutation.Name(); !ok { - return &ValidationError{Name: "name", err: errors.New("ent: missing required field \"name\"")} + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Application.name"`)} } if _, ok := ac.mutation.Status(); !ok { - return &ValidationError{Name: "status", err: errors.New("ent: missing required field \"status\"")} + return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "Application.status"`)} } if _, ok := ac.mutation.CreatedAt(); !ok { - return &ValidationError{Name: "created_at", err: errors.New("ent: missing required field \"created_at\"")} + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Application.created_at"`)} } if _, ok := ac.mutation.UpdatedAt(); !ok { - return &ValidationError{Name: "updated_at", err: errors.New("ent: missing required field \"updated_at\"")} + return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Application.updated_at"`)} } if _, ok := ac.mutation.Scenario(); !ok { - return &ValidationError{Name: "scenario", err: errors.New("ent: missing required field \"scenario\"")} + return &ValidationError{Name: "scenario", err: errors.New(`ent: missing required field "Application.scenario"`)} } if _, ok := ac.mutation.Gomod(); !ok { - return &ValidationError{Name: "gomod", err: errors.New("ent: missing required field \"gomod\"")} + return &ValidationError{Name: "gomod", err: errors.New(`ent: missing required field "Application.gomod"`)} } if _, ok := ac.mutation.Gosum(); !ok { - return &ValidationError{Name: "gosum", err: errors.New("ent: missing required field \"gosum\"")} + return &ValidationError{Name: "gosum", err: errors.New(`ent: missing required field "Application.gosum"`)} + } + if _, ok := ac.mutation.Vu(); !ok { + return &ValidationError{Name: "vu", err: errors.New(`ent: missing required field "Application.vu"`)} + } + if v, ok := ac.mutation.Vu(); ok { + if err := application.VuValidator(v); err != nil { + return &ValidationError{Name: "vu", err: fmt.Errorf(`ent: validator failed for field "Application.vu": %w`, err)} + } } return nil } func (ac *ApplicationCreate) sqlSave(ctx context.Context) (*Application, error) { + if err := ac.check(); err != nil { + return nil, err + } _node, _spec := ac.createSpec() if err := sqlgraph.CreateNode(ctx, ac.driver, _spec); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } id := _spec.ID.Value.(int64) _node.ID = int(id) + ac.mutation.id = &_node.ID + ac.mutation.done = true return _node, nil } func (ac *ApplicationCreate) createSpec() (*Application, *sqlgraph.CreateSpec) { var ( _node = &Application{config: ac.config} - _spec = &sqlgraph.CreateSpec{ - Table: application.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, - } + _spec = sqlgraph.NewCreateSpec(application.Table, sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt)) ) if value, ok := ac.mutation.Name(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldName, - }) + _spec.SetField(application.FieldName, field.TypeString, value) _node.Name = value } if value, ok := ac.mutation.Status(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldStatus, - }) + _spec.SetField(application.FieldStatus, field.TypeString, value) _node.Status = value } if value, ok := ac.mutation.CreatedAt(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: application.FieldCreatedAt, - }) + _spec.SetField(application.FieldCreatedAt, field.TypeTime, value) _node.CreatedAt = value } if value, ok := ac.mutation.StartedAt(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: application.FieldStartedAt, - }) + _spec.SetField(application.FieldStartedAt, field.TypeTime, value) _node.StartedAt = value } if value, ok := ac.mutation.UpdatedAt(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: application.FieldUpdatedAt, - }) + _spec.SetField(application.FieldUpdatedAt, field.TypeTime, value) _node.UpdatedAt = value } if value, ok := ac.mutation.Scenario(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldScenario, - }) + _spec.SetField(application.FieldScenario, field.TypeString, value) _node.Scenario = value } if value, ok := ac.mutation.Gomod(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldGomod, - }) + _spec.SetField(application.FieldGomod, field.TypeString, value) _node.Gomod = value } if value, ok := ac.mutation.Gosum(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldGosum, - }) + _spec.SetField(application.FieldGosum, field.TypeString, value) _node.Gosum = value } + if value, ok := ac.mutation.Vu(); ok { + _spec.SetField(application.FieldVu, field.TypeInt, value) + _node.Vu = value + } if nodes := ac.mutation.GroupsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -332,10 +312,7 @@ func (ac *ApplicationCreate) createSpec() (*Application, *sqlgraph.CreateSpec) { Columns: []string{application.GroupsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -351,10 +328,7 @@ func (ac *ApplicationCreate) createSpec() (*Application, *sqlgraph.CreateSpec) { Columns: []string{application.TagsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -365,7 +339,7 @@ func (ac *ApplicationCreate) createSpec() (*Application, *sqlgraph.CreateSpec) { return _node, _spec } -// ApplicationCreateBulk is the builder for creating a bulk of Application entities. +// ApplicationCreateBulk is the builder for creating many Application entities in bulk. type ApplicationCreateBulk struct { config builders []*ApplicationCreate @@ -389,24 +363,28 @@ func (acb *ApplicationCreateBulk) Save(ctx context.Context) ([]*Application, err return nil, err } builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() var err error + nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, acb.builders[i+1].mutation) } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, acb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if err = sqlgraph.BatchCreate(ctx, acb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } } } - mutation.done = true if err != nil { return nil, err } - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { @@ -423,7 +401,7 @@ func (acb *ApplicationCreateBulk) Save(ctx context.Context) ([]*Application, err return nodes, nil } -// SaveX calls Save and panics if Save returns an error. +// SaveX is like Save, but panics if an error occurs. func (acb *ApplicationCreateBulk) SaveX(ctx context.Context) []*Application { v, err := acb.Save(ctx) if err != nil { @@ -431,3 +409,16 @@ func (acb *ApplicationCreateBulk) SaveX(ctx context.Context) []*Application { } return v } + +// Exec executes the query. +func (acb *ApplicationCreateBulk) Exec(ctx context.Context) error { + _, err := acb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (acb *ApplicationCreateBulk) ExecX(ctx context.Context) { + if err := acb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/application_delete.go b/ent/application_delete.go index 75345db4..02e8becb 100644 --- a/ent/application_delete.go +++ b/ent/application_delete.go @@ -1,14 +1,13 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/predicate" ) @@ -16,44 +15,19 @@ import ( // ApplicationDelete is the builder for deleting a Application entity. type ApplicationDelete struct { config - hooks []Hook - mutation *ApplicationMutation - predicates []predicate.Application + hooks []Hook + mutation *ApplicationMutation } -// Where adds a new predicate to the delete builder. +// Where appends a list predicates to the ApplicationDelete builder. func (ad *ApplicationDelete) Where(ps ...predicate.Application) *ApplicationDelete { - ad.predicates = append(ad.predicates, ps...) + ad.mutation.Where(ps...) return ad } // Exec executes the deletion query and returns how many vertices were deleted. func (ad *ApplicationDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(ad.hooks) == 0 { - affected, err = ad.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*ApplicationMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - ad.mutation = mutation - affected, err = ad.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(ad.hooks) - 1; i >= 0; i-- { - mut = ad.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, ad.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, ad.sqlExec, ad.mutation, ad.hooks) } // ExecX is like Exec, but panics if an error occurs. @@ -66,23 +40,20 @@ func (ad *ApplicationDelete) ExecX(ctx context.Context) int { } func (ad *ApplicationDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: application.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, - }, - } - if ps := ad.predicates; len(ps) > 0 { + _spec := sqlgraph.NewDeleteSpec(application.Table, sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt)) + if ps := ad.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - return sqlgraph.DeleteNodes(ctx, ad.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, ad.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ad.mutation.done = true + return affected, err } // ApplicationDeleteOne is the builder for deleting a single Application entity. @@ -90,6 +61,12 @@ type ApplicationDeleteOne struct { ad *ApplicationDelete } +// Where appends a list predicates to the ApplicationDelete builder. +func (ado *ApplicationDeleteOne) Where(ps ...predicate.Application) *ApplicationDeleteOne { + ado.ad.mutation.Where(ps...) + return ado +} + // Exec executes the deletion query. func (ado *ApplicationDeleteOne) Exec(ctx context.Context) error { n, err := ado.ad.Exec(ctx) @@ -105,5 +82,7 @@ func (ado *ApplicationDeleteOne) Exec(ctx context.Context) error { // ExecX is like Exec, but panics if an error occurs. func (ado *ApplicationDeleteOne) ExecX(ctx context.Context) { - ado.ad.ExecX(ctx) + if err := ado.Exec(ctx); err != nil { + panic(err) + } } diff --git a/ent/application_query.go b/ent/application_query.go index 304b7c45..a4490f6a 100644 --- a/ent/application_query.go +++ b/ent/application_query.go @@ -1,17 +1,16 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" "database/sql/driver" - "errors" "fmt" "math" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/group" "github.com/gobench-io/gobench/v2/ent/predicate" @@ -21,12 +20,10 @@ import ( // ApplicationQuery is the builder for querying Application entities. type ApplicationQuery struct { config - limit *int - offset *int - order []OrderFunc - unique []string + ctx *QueryContext + order []application.OrderOption + inters []Interceptor predicates []predicate.Application - // eager-loading edges. withGroups *GroupQuery withTags *TagQuery // intermediate query (i.e. traversal path). @@ -34,38 +31,45 @@ type ApplicationQuery struct { path func(context.Context) (*sql.Selector, error) } -// Where adds a new predicate for the builder. +// Where adds a new predicate for the ApplicationQuery builder. func (aq *ApplicationQuery) Where(ps ...predicate.Application) *ApplicationQuery { aq.predicates = append(aq.predicates, ps...) return aq } -// Limit adds a limit step to the query. +// Limit the number of records to be returned by this query. func (aq *ApplicationQuery) Limit(limit int) *ApplicationQuery { - aq.limit = &limit + aq.ctx.Limit = &limit return aq } -// Offset adds an offset step to the query. +// Offset to start from. func (aq *ApplicationQuery) Offset(offset int) *ApplicationQuery { - aq.offset = &offset + aq.ctx.Offset = &offset return aq } -// Order adds an order step to the query. -func (aq *ApplicationQuery) Order(o ...OrderFunc) *ApplicationQuery { +// 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 (aq *ApplicationQuery) Unique(unique bool) *ApplicationQuery { + aq.ctx.Unique = &unique + return aq +} + +// Order specifies how the records should be ordered. +func (aq *ApplicationQuery) Order(o ...application.OrderOption) *ApplicationQuery { aq.order = append(aq.order, o...) return aq } -// QueryGroups chains the current query on the groups edge. +// QueryGroups chains the current query on the "groups" edge. func (aq *ApplicationQuery) QueryGroups() *GroupQuery { - query := &GroupQuery{config: aq.config} + query := (&GroupClient{config: aq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := aq.prepareQuery(ctx); err != nil { return nil, err } - selector := aq.sqlQuery() + selector := aq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -80,14 +84,14 @@ func (aq *ApplicationQuery) QueryGroups() *GroupQuery { return query } -// QueryTags chains the current query on the tags edge. +// QueryTags chains the current query on the "tags" edge. func (aq *ApplicationQuery) QueryTags() *TagQuery { - query := &TagQuery{config: aq.config} + query := (&TagClient{config: aq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := aq.prepareQuery(ctx); err != nil { return nil, err } - selector := aq.sqlQuery() + selector := aq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -102,9 +106,10 @@ func (aq *ApplicationQuery) QueryTags() *TagQuery { return query } -// First returns the first Application entity in the query. Returns *NotFoundError when no application was found. +// First returns the first Application entity from the query. +// Returns a *NotFoundError when no Application was found. func (aq *ApplicationQuery) First(ctx context.Context) (*Application, error) { - nodes, err := aq.Limit(1).All(ctx) + nodes, err := aq.Limit(1).All(setContextOp(ctx, aq.ctx, "First")) if err != nil { return nil, err } @@ -123,10 +128,11 @@ func (aq *ApplicationQuery) FirstX(ctx context.Context) *Application { return node } -// FirstID returns the first Application id in the query. Returns *NotFoundError when no id was found. +// FirstID returns the first Application ID from the query. +// Returns a *NotFoundError when no Application ID was found. func (aq *ApplicationQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = aq.Limit(1).IDs(ctx); err != nil { + if ids, err = aq.Limit(1).IDs(setContextOp(ctx, aq.ctx, "FirstID")); err != nil { return } if len(ids) == 0 { @@ -136,8 +142,8 @@ func (aq *ApplicationQuery) FirstID(ctx context.Context) (id int, err error) { return ids[0], nil } -// FirstXID is like FirstID, but panics if an error occurs. -func (aq *ApplicationQuery) FirstXID(ctx context.Context) int { +// FirstIDX is like FirstID, but panics if an error occurs. +func (aq *ApplicationQuery) FirstIDX(ctx context.Context) int { id, err := aq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -145,9 +151,11 @@ func (aq *ApplicationQuery) FirstXID(ctx context.Context) int { return id } -// Only returns the only Application entity in the query, returns an error if not exactly one entity was returned. +// Only returns a single Application entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Application entity is found. +// Returns a *NotFoundError when no Application entities are found. func (aq *ApplicationQuery) Only(ctx context.Context) (*Application, error) { - nodes, err := aq.Limit(2).All(ctx) + nodes, err := aq.Limit(2).All(setContextOp(ctx, aq.ctx, "Only")) if err != nil { return nil, err } @@ -170,10 +178,12 @@ func (aq *ApplicationQuery) OnlyX(ctx context.Context) *Application { return node } -// OnlyID returns the only Application id in the query, returns an error if not exactly one id was returned. +// OnlyID is like Only, but returns the only Application ID in the query. +// Returns a *NotSingularError when more than one Application ID is found. +// Returns a *NotFoundError when no entities are found. func (aq *ApplicationQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = aq.Limit(2).IDs(ctx); err != nil { + if ids, err = aq.Limit(2).IDs(setContextOp(ctx, aq.ctx, "OnlyID")); err != nil { return } switch len(ids) { @@ -198,10 +208,12 @@ func (aq *ApplicationQuery) OnlyIDX(ctx context.Context) int { // All executes the query and returns a list of Applications. func (aq *ApplicationQuery) All(ctx context.Context) ([]*Application, error) { + ctx = setContextOp(ctx, aq.ctx, "All") if err := aq.prepareQuery(ctx); err != nil { return nil, err } - return aq.sqlAll(ctx) + qr := querierAll[[]*Application, *ApplicationQuery]() + return withInterceptors[[]*Application](ctx, aq, qr, aq.inters) } // AllX is like All, but panics if an error occurs. @@ -213,10 +225,13 @@ func (aq *ApplicationQuery) AllX(ctx context.Context) []*Application { return nodes } -// IDs executes the query and returns a list of Application ids. -func (aq *ApplicationQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := aq.Select(application.FieldID).Scan(ctx, &ids); err != nil { +// IDs executes the query and returns a list of Application IDs. +func (aq *ApplicationQuery) IDs(ctx context.Context) (ids []int, err error) { + if aq.ctx.Unique == nil && aq.path != nil { + aq.Unique(true) + } + ctx = setContextOp(ctx, aq.ctx, "IDs") + if err = aq.Select(application.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil @@ -233,10 +248,11 @@ func (aq *ApplicationQuery) IDsX(ctx context.Context) []int { // Count returns the count of the given query. func (aq *ApplicationQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, aq.ctx, "Count") if err := aq.prepareQuery(ctx); err != nil { return 0, err } - return aq.sqlCount(ctx) + return withInterceptors[int](ctx, aq, querierCount[*ApplicationQuery](), aq.inters) } // CountX is like Count, but panics if an error occurs. @@ -250,10 +266,15 @@ func (aq *ApplicationQuery) CountX(ctx context.Context) int { // Exist returns true if the query has elements in the graph. func (aq *ApplicationQuery) Exist(ctx context.Context) (bool, error) { - if err := aq.prepareQuery(ctx); err != nil { - return false, err + ctx = setContextOp(ctx, aq.ctx, "Exist") + switch _, err := aq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil } - return aq.sqlExist(ctx) } // ExistX is like Exist, but panics if an error occurs. @@ -265,26 +286,30 @@ func (aq *ApplicationQuery) ExistX(ctx context.Context) bool { return exist } -// Clone returns a duplicate of the query builder, including all associated steps. It can be +// Clone returns a duplicate of the ApplicationQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. func (aq *ApplicationQuery) Clone() *ApplicationQuery { + if aq == nil { + return nil + } return &ApplicationQuery{ config: aq.config, - limit: aq.limit, - offset: aq.offset, - order: append([]OrderFunc{}, aq.order...), - unique: append([]string{}, aq.unique...), + ctx: aq.ctx.Clone(), + order: append([]application.OrderOption{}, aq.order...), + inters: append([]Interceptor{}, aq.inters...), predicates: append([]predicate.Application{}, aq.predicates...), + withGroups: aq.withGroups.Clone(), + withTags: aq.withTags.Clone(), // clone intermediate query. sql: aq.sql.Clone(), path: aq.path, } } -// WithGroups tells the query-builder to eager-loads the nodes that are connected to -// the "groups" edge. The optional arguments used to configure the query builder of the edge. +// WithGroups tells the query-builder to eager-load the nodes that are connected to +// the "groups" edge. The optional arguments are used to configure the query builder of the edge. func (aq *ApplicationQuery) WithGroups(opts ...func(*GroupQuery)) *ApplicationQuery { - query := &GroupQuery{config: aq.config} + query := (&GroupClient{config: aq.config}).Query() for _, opt := range opts { opt(query) } @@ -292,10 +317,10 @@ func (aq *ApplicationQuery) WithGroups(opts ...func(*GroupQuery)) *ApplicationQu return aq } -// WithTags tells the query-builder to eager-loads the nodes that are connected to -// the "tags" edge. The optional arguments used to configure the query builder of the edge. +// WithTags tells the query-builder to eager-load the nodes that are connected to +// the "tags" edge. The optional arguments are used to configure the query builder of the edge. func (aq *ApplicationQuery) WithTags(opts ...func(*TagQuery)) *ApplicationQuery { - query := &TagQuery{config: aq.config} + query := (&TagClient{config: aq.config}).Query() for _, opt := range opts { opt(query) } @@ -303,7 +328,7 @@ func (aq *ApplicationQuery) WithTags(opts ...func(*TagQuery)) *ApplicationQuery return aq } -// GroupBy used to group vertices by one or more fields/columns. +// 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: @@ -317,20 +342,17 @@ func (aq *ApplicationQuery) WithTags(opts ...func(*TagQuery)) *ApplicationQuery // GroupBy(application.FieldName). // Aggregate(ent.Count()). // Scan(ctx, &v) -// func (aq *ApplicationQuery) GroupBy(field string, fields ...string) *ApplicationGroupBy { - group := &ApplicationGroupBy{config: aq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := aq.prepareQuery(ctx); err != nil { - return nil, err - } - return aq.sqlQuery(), nil - } - return group + aq.ctx.Fields = append([]string{field}, fields...) + grbuild := &ApplicationGroupBy{build: aq} + grbuild.flds = &aq.ctx.Fields + grbuild.label = application.Label + grbuild.scan = grbuild.Scan + return grbuild } -// Select one or more fields from the given query. +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. // // Example: // @@ -341,20 +363,35 @@ func (aq *ApplicationQuery) GroupBy(field string, fields ...string) *Application // client.Application.Query(). // Select(application.FieldName). // Scan(ctx, &v) -// -func (aq *ApplicationQuery) Select(field string, fields ...string) *ApplicationSelect { - selector := &ApplicationSelect{config: aq.config} - selector.fields = append([]string{field}, fields...) - selector.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := aq.prepareQuery(ctx); err != nil { - return nil, err - } - return aq.sqlQuery(), nil - } - return selector +func (aq *ApplicationQuery) Select(fields ...string) *ApplicationSelect { + aq.ctx.Fields = append(aq.ctx.Fields, fields...) + sbuild := &ApplicationSelect{ApplicationQuery: aq} + sbuild.label = application.Label + sbuild.flds, sbuild.scan = &aq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ApplicationSelect configured with the given aggregations. +func (aq *ApplicationQuery) Aggregate(fns ...AggregateFunc) *ApplicationSelect { + return aq.Select().Aggregate(fns...) } func (aq *ApplicationQuery) prepareQuery(ctx context.Context) error { + for _, inter := range aq.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, aq); err != nil { + return err + } + } + } + for _, f := range aq.ctx.Fields { + if !application.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } if aq.path != nil { prev, err := aq.path(ctx) if err != nil { @@ -365,7 +402,7 @@ func (aq *ApplicationQuery) prepareQuery(ctx context.Context) error { return nil } -func (aq *ApplicationQuery) sqlAll(ctx context.Context) ([]*Application, error) { +func (aq *ApplicationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Application, error) { var ( nodes = []*Application{} _spec = aq.querySpec() @@ -374,19 +411,17 @@ func (aq *ApplicationQuery) sqlAll(ctx context.Context) ([]*Application, error) aq.withTags != nil, } ) - _spec.ScanValues = func() []interface{} { + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Application).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { node := &Application{config: aq.config} nodes = append(nodes, node) - values := node.scanValues() - return values - } - _spec.Assign = func(values ...interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("ent: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] node.Edges.loadedTypes = loadedTypes - return node.assignValues(values...) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) } if err := sqlgraph.QueryNodes(ctx, aq.driver, _spec); err != nil { return nil, err @@ -394,91 +429,111 @@ func (aq *ApplicationQuery) sqlAll(ctx context.Context) ([]*Application, error) if len(nodes) == 0 { return nodes, nil } - if query := aq.withGroups; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*Application) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - } - query.withFKs = true - query.Where(predicate.Group(func(s *sql.Selector) { - s.Where(sql.InValues(application.GroupsColumn, fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { + if err := aq.loadGroups(ctx, query, nodes, + func(n *Application) { n.Edges.Groups = []*Group{} }, + func(n *Application, e *Group) { n.Edges.Groups = append(n.Edges.Groups, e) }); err != nil { return nil, err } - for _, n := range neighbors { - fk := n.application_groups - if fk == nil { - return nil, fmt.Errorf(`foreign-key "application_groups" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "application_groups" returned %v for node %v`, *fk, n.ID) - } - node.Edges.Groups = append(node.Edges.Groups, n) + } + if query := aq.withTags; query != nil { + if err := aq.loadTags(ctx, query, nodes, + func(n *Application) { n.Edges.Tags = []*Tag{} }, + func(n *Application, e *Tag) { n.Edges.Tags = append(n.Edges.Tags, e) }); err != nil { + return nil, err } } + return nodes, nil +} - if query := aq.withTags; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*Application) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] +func (aq *ApplicationQuery) loadGroups(ctx context.Context, query *GroupQuery, nodes []*Application, init func(*Application), assign func(*Application, *Group)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Application) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) } - query.withFKs = true - query.Where(predicate.Tag(func(s *sql.Selector) { - s.Where(sql.InValues(application.TagsColumn, fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err + } + query.withFKs = true + query.Where(predicate.Group(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(application.GroupsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.application_groups + if fk == nil { + return fmt.Errorf(`foreign-key "application_groups" is nil for node %v`, n.ID) } - for _, n := range neighbors { - fk := n.application_tags - if fk == nil { - return nil, fmt.Errorf(`foreign-key "application_tags" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "application_tags" returned %v for node %v`, *fk, n.ID) - } - node.Edges.Tags = append(node.Edges.Tags, n) + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "application_groups" returned %v for node %v`, *fk, n.ID) } + assign(node, n) } - - return nodes, nil + return nil +} +func (aq *ApplicationQuery) loadTags(ctx context.Context, query *TagQuery, nodes []*Application, init func(*Application), assign func(*Application, *Tag)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Application) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + query.Where(predicate.Tag(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(application.TagsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.application_tags + if fk == nil { + return fmt.Errorf(`foreign-key "application_tags" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "application_tags" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil } func (aq *ApplicationQuery) sqlCount(ctx context.Context) (int, error) { _spec := aq.querySpec() - return sqlgraph.CountNodes(ctx, aq.driver, _spec) -} - -func (aq *ApplicationQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := aq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("ent: check existence: %v", err) + _spec.Node.Columns = aq.ctx.Fields + if len(aq.ctx.Fields) > 0 { + _spec.Unique = aq.ctx.Unique != nil && *aq.ctx.Unique } - return n > 0, nil + return sqlgraph.CountNodes(ctx, aq.driver, _spec) } func (aq *ApplicationQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: application.Table, - Columns: application.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, - }, - From: aq.sql, - Unique: true, + _spec := sqlgraph.NewQuerySpec(application.Table, application.Columns, sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt)) + _spec.From = aq.sql + if unique := aq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if aq.path != nil { + _spec.Unique = true + } + if fields := aq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, application.FieldID) + for i := range fields { + if fields[i] != application.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } } if ps := aq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -487,55 +542,58 @@ func (aq *ApplicationQuery) querySpec() *sqlgraph.QuerySpec { } } } - if limit := aq.limit; limit != nil { + if limit := aq.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := aq.offset; offset != nil { + if offset := aq.ctx.Offset; offset != nil { _spec.Offset = *offset } if ps := aq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector, application.ValidColumn) + ps[i](selector) } } } return _spec } -func (aq *ApplicationQuery) sqlQuery() *sql.Selector { +func (aq *ApplicationQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(aq.driver.Dialect()) t1 := builder.Table(application.Table) - selector := builder.Select(t1.Columns(application.Columns...)...).From(t1) + columns := aq.ctx.Fields + if len(columns) == 0 { + columns = application.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) if aq.sql != nil { selector = aq.sql - selector.Select(selector.Columns(application.Columns...)...) + selector.Select(selector.Columns(columns...)...) + } + if aq.ctx.Unique != nil && *aq.ctx.Unique { + selector.Distinct() } for _, p := range aq.predicates { p(selector) } for _, p := range aq.order { - p(selector, application.ValidColumn) + p(selector) } - if offset := aq.offset; offset != nil { + if offset := aq.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 := aq.limit; limit != nil { + if limit := aq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector } -// ApplicationGroupBy is the builder for group-by Application entities. +// ApplicationGroupBy is the group-by builder for Application entities. type ApplicationGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) + selector + build *ApplicationQuery } // Aggregate adds the given aggregation functions to the group-by query. @@ -544,471 +602,80 @@ func (agb *ApplicationGroupBy) Aggregate(fns ...AggregateFunc) *ApplicationGroup return agb } -// Scan applies the group-by query and scan the result into the given value. -func (agb *ApplicationGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := agb.path(ctx) - if err != nil { +// Scan applies the selector query and scans the result into the given value. +func (agb *ApplicationGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, agb.build.ctx, "GroupBy") + if err := agb.build.prepareQuery(ctx); err != nil { return err } - agb.sql = query - return agb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (agb *ApplicationGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := agb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field. -func (agb *ApplicationGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(agb.fields) > 1 { - return nil, errors.New("ent: ApplicationGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := agb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (agb *ApplicationGroupBy) StringsX(ctx context.Context) []string { - v, err := agb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from group-by. It is only allowed when querying group-by with one field. -func (agb *ApplicationGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = agb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{application.Label} - default: - err = fmt.Errorf("ent: ApplicationGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (agb *ApplicationGroupBy) StringX(ctx context.Context) string { - v, err := agb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field. -func (agb *ApplicationGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(agb.fields) > 1 { - return nil, errors.New("ent: ApplicationGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := agb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil + return scanWithInterceptors[*ApplicationQuery, *ApplicationGroupBy](ctx, agb.build, agb, agb.build.inters, v) } -// IntsX is like Ints, but panics if an error occurs. -func (agb *ApplicationGroupBy) IntsX(ctx context.Context) []int { - v, err := agb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from group-by. It is only allowed when querying group-by with one field. -func (agb *ApplicationGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = agb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{application.Label} - default: - err = fmt.Errorf("ent: ApplicationGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (agb *ApplicationGroupBy) IntX(ctx context.Context) int { - v, err := agb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field. -func (agb *ApplicationGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(agb.fields) > 1 { - return nil, errors.New("ent: ApplicationGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := agb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (agb *ApplicationGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := agb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field. -func (agb *ApplicationGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = agb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{application.Label} - default: - err = fmt.Errorf("ent: ApplicationGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (agb *ApplicationGroupBy) Float64X(ctx context.Context) float64 { - v, err := agb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field. -func (agb *ApplicationGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(agb.fields) > 1 { - return nil, errors.New("ent: ApplicationGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := agb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (agb *ApplicationGroupBy) BoolsX(ctx context.Context) []bool { - v, err := agb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field. -func (agb *ApplicationGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = agb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{application.Label} - default: - err = fmt.Errorf("ent: ApplicationGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (agb *ApplicationGroupBy) BoolX(ctx context.Context) bool { - v, err := agb.Bool(ctx) - if err != nil { - panic(err) +func (agb *ApplicationGroupBy) sqlScan(ctx context.Context, root *ApplicationQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(agb.fns)) + for _, fn := range agb.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (agb *ApplicationGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range agb.fields { - if !application.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*agb.flds)+len(agb.fns)) + for _, f := range *agb.flds { + columns = append(columns, selector.C(f)) } + columns = append(columns, aggregation...) + selector.Select(columns...) } - selector := agb.sqlQuery() + selector.GroupBy(selector.Columns(*agb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := agb.driver.Query(ctx, query, args, rows); err != nil { + if err := agb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } -func (agb *ApplicationGroupBy) sqlQuery() *sql.Selector { - selector := agb.sql - columns := make([]string, 0, len(agb.fields)+len(agb.fns)) - columns = append(columns, agb.fields...) - for _, fn := range agb.fns { - columns = append(columns, fn(selector, application.ValidColumn)) - } - return selector.Select(columns...).GroupBy(agb.fields...) -} - -// ApplicationSelect is the builder for select fields of Application entities. +// ApplicationSelect is the builder for selecting fields of Application entities. type ApplicationSelect struct { - config - fields []string - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Scan applies the selector query and scan the result into the given value. -func (as *ApplicationSelect) Scan(ctx context.Context, v interface{}) error { - query, err := as.path(ctx) - if err != nil { - return err - } - as.sql = query - return as.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (as *ApplicationSelect) ScanX(ctx context.Context, v interface{}) { - if err := as.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from selector. It is only allowed when selecting one field. -func (as *ApplicationSelect) Strings(ctx context.Context) ([]string, error) { - if len(as.fields) > 1 { - return nil, errors.New("ent: ApplicationSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := as.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (as *ApplicationSelect) StringsX(ctx context.Context) []string { - v, err := as.Strings(ctx) - if err != nil { - panic(err) - } - return v + *ApplicationQuery + selector } -// String returns a single string from selector. It is only allowed when selecting one field. -func (as *ApplicationSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = as.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{application.Label} - default: - err = fmt.Errorf("ent: ApplicationSelect.Strings returned %d results when one was expected", len(v)) - } - return +// Aggregate adds the given aggregation functions to the selector query. +func (as *ApplicationSelect) Aggregate(fns ...AggregateFunc) *ApplicationSelect { + as.fns = append(as.fns, fns...) + return as } -// StringX is like String, but panics if an error occurs. -func (as *ApplicationSelect) StringX(ctx context.Context) string { - v, err := as.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from selector. It is only allowed when selecting one field. -func (as *ApplicationSelect) Ints(ctx context.Context) ([]int, error) { - if len(as.fields) > 1 { - return nil, errors.New("ent: ApplicationSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := as.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (as *ApplicationSelect) IntsX(ctx context.Context) []int { - v, err := as.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from selector. It is only allowed when selecting one field. -func (as *ApplicationSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = as.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{application.Label} - default: - err = fmt.Errorf("ent: ApplicationSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (as *ApplicationSelect) IntX(ctx context.Context) int { - v, err := as.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from selector. It is only allowed when selecting one field. -func (as *ApplicationSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(as.fields) > 1 { - return nil, errors.New("ent: ApplicationSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := as.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (as *ApplicationSelect) Float64sX(ctx context.Context) []float64 { - v, err := as.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from selector. It is only allowed when selecting one field. -func (as *ApplicationSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = as.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{application.Label} - default: - err = fmt.Errorf("ent: ApplicationSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (as *ApplicationSelect) Float64X(ctx context.Context) float64 { - v, err := as.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from selector. It is only allowed when selecting one field. -func (as *ApplicationSelect) Bools(ctx context.Context) ([]bool, error) { - if len(as.fields) > 1 { - return nil, errors.New("ent: ApplicationSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := as.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (as *ApplicationSelect) BoolsX(ctx context.Context) []bool { - v, err := as.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from selector. It is only allowed when selecting one field. -func (as *ApplicationSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = as.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{application.Label} - default: - err = fmt.Errorf("ent: ApplicationSelect.Bools returned %d results when one was expected", len(v)) +// Scan applies the selector query and scans the result into the given value. +func (as *ApplicationSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, as.ctx, "Select") + if err := as.prepareQuery(ctx); err != nil { + return err } - return + return scanWithInterceptors[*ApplicationQuery, *ApplicationSelect](ctx, as.ApplicationQuery, as, as.inters, v) } -// BoolX is like Bool, but panics if an error occurs. -func (as *ApplicationSelect) BoolX(ctx context.Context) bool { - v, err := as.Bool(ctx) - if err != nil { - panic(err) +func (as *ApplicationSelect) sqlScan(ctx context.Context, root *ApplicationQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(as.fns)) + for _, fn := range as.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (as *ApplicationSelect) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range as.fields { - if !application.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} - } + switch n := len(*as.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 := as.sqlQuery().Query() + query, args := selector.Query() if err := as.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } - -func (as *ApplicationSelect) sqlQuery() sql.Querier { - selector := as.sql - selector.Select(selector.Columns(as.fields...)...) - return selector -} diff --git a/ent/application_update.go b/ent/application_update.go index 892ac575..98fa3948 100644 --- a/ent/application_update.go +++ b/ent/application_update.go @@ -1,15 +1,16 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" "time" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/group" "github.com/gobench-io/gobench/v2/ent/predicate" @@ -19,36 +20,35 @@ import ( // ApplicationUpdate is the builder for updating Application entities. type ApplicationUpdate struct { config - hooks []Hook - mutation *ApplicationMutation - predicates []predicate.Application + hooks []Hook + mutation *ApplicationMutation } -// Where adds a new predicate for the builder. +// Where appends a list predicates to the ApplicationUpdate builder. func (au *ApplicationUpdate) Where(ps ...predicate.Application) *ApplicationUpdate { - au.predicates = append(au.predicates, ps...) + au.mutation.Where(ps...) return au } -// SetName sets the name field. +// SetName sets the "name" field. func (au *ApplicationUpdate) SetName(s string) *ApplicationUpdate { au.mutation.SetName(s) return au } -// SetStatus sets the status field. +// SetStatus sets the "status" field. func (au *ApplicationUpdate) SetStatus(s string) *ApplicationUpdate { au.mutation.SetStatus(s) return au } -// SetCreatedAt sets the created_at field. +// SetCreatedAt sets the "created_at" field. func (au *ApplicationUpdate) SetCreatedAt(t time.Time) *ApplicationUpdate { au.mutation.SetCreatedAt(t) return au } -// SetNillableCreatedAt sets the created_at field if the given value is not nil. +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. func (au *ApplicationUpdate) SetNillableCreatedAt(t *time.Time) *ApplicationUpdate { if t != nil { au.SetCreatedAt(*t) @@ -56,13 +56,13 @@ func (au *ApplicationUpdate) SetNillableCreatedAt(t *time.Time) *ApplicationUpda return au } -// SetStartedAt sets the started_at field. +// SetStartedAt sets the "started_at" field. func (au *ApplicationUpdate) SetStartedAt(t time.Time) *ApplicationUpdate { au.mutation.SetStartedAt(t) return au } -// SetNillableStartedAt sets the started_at field if the given value is not nil. +// SetNillableStartedAt sets the "started_at" field if the given value is not nil. func (au *ApplicationUpdate) SetNillableStartedAt(t *time.Time) *ApplicationUpdate { if t != nil { au.SetStartedAt(*t) @@ -70,31 +70,31 @@ func (au *ApplicationUpdate) SetNillableStartedAt(t *time.Time) *ApplicationUpda return au } -// ClearStartedAt clears the value of started_at. +// ClearStartedAt clears the value of the "started_at" field. func (au *ApplicationUpdate) ClearStartedAt() *ApplicationUpdate { au.mutation.ClearStartedAt() return au } -// SetUpdatedAt sets the updated_at field. +// SetUpdatedAt sets the "updated_at" field. func (au *ApplicationUpdate) SetUpdatedAt(t time.Time) *ApplicationUpdate { au.mutation.SetUpdatedAt(t) return au } -// SetScenario sets the scenario field. +// SetScenario sets the "scenario" field. func (au *ApplicationUpdate) SetScenario(s string) *ApplicationUpdate { au.mutation.SetScenario(s) return au } -// SetGomod sets the gomod field. +// SetGomod sets the "gomod" field. func (au *ApplicationUpdate) SetGomod(s string) *ApplicationUpdate { au.mutation.SetGomod(s) return au } -// SetNillableGomod sets the gomod field if the given value is not nil. +// SetNillableGomod sets the "gomod" field if the given value is not nil. func (au *ApplicationUpdate) SetNillableGomod(s *string) *ApplicationUpdate { if s != nil { au.SetGomod(*s) @@ -102,13 +102,13 @@ func (au *ApplicationUpdate) SetNillableGomod(s *string) *ApplicationUpdate { return au } -// SetGosum sets the gosum field. +// SetGosum sets the "gosum" field. func (au *ApplicationUpdate) SetGosum(s string) *ApplicationUpdate { au.mutation.SetGosum(s) return au } -// SetNillableGosum sets the gosum field if the given value is not nil. +// SetNillableGosum sets the "gosum" field if the given value is not nil. func (au *ApplicationUpdate) SetNillableGosum(s *string) *ApplicationUpdate { if s != nil { au.SetGosum(*s) @@ -116,13 +116,34 @@ func (au *ApplicationUpdate) SetNillableGosum(s *string) *ApplicationUpdate { return au } -// AddGroupIDs adds the groups edge to Group by ids. +// SetVu sets the "vu" field. +func (au *ApplicationUpdate) SetVu(i int) *ApplicationUpdate { + au.mutation.ResetVu() + au.mutation.SetVu(i) + return au +} + +// SetNillableVu sets the "vu" field if the given value is not nil. +func (au *ApplicationUpdate) SetNillableVu(i *int) *ApplicationUpdate { + if i != nil { + au.SetVu(*i) + } + return au +} + +// AddVu adds i to the "vu" field. +func (au *ApplicationUpdate) AddVu(i int) *ApplicationUpdate { + au.mutation.AddVu(i) + return au +} + +// AddGroupIDs adds the "groups" edge to the Group entity by IDs. func (au *ApplicationUpdate) AddGroupIDs(ids ...int) *ApplicationUpdate { au.mutation.AddGroupIDs(ids...) return au } -// AddGroups adds the groups edges to Group. +// AddGroups adds the "groups" edges to the Group entity. func (au *ApplicationUpdate) AddGroups(g ...*Group) *ApplicationUpdate { ids := make([]int, len(g)) for i := range g { @@ -131,13 +152,13 @@ func (au *ApplicationUpdate) AddGroups(g ...*Group) *ApplicationUpdate { return au.AddGroupIDs(ids...) } -// AddTagIDs adds the tags edge to Tag by ids. +// AddTagIDs adds the "tags" edge to the Tag entity by IDs. func (au *ApplicationUpdate) AddTagIDs(ids ...int) *ApplicationUpdate { au.mutation.AddTagIDs(ids...) return au } -// AddTags adds the tags edges to Tag. +// AddTags adds the "tags" edges to the Tag entity. func (au *ApplicationUpdate) AddTags(t ...*Tag) *ApplicationUpdate { ids := make([]int, len(t)) for i := range t { @@ -151,19 +172,19 @@ func (au *ApplicationUpdate) Mutation() *ApplicationMutation { return au.mutation } -// ClearGroups clears all "groups" edges to type Group. +// ClearGroups clears all "groups" edges to the Group entity. func (au *ApplicationUpdate) ClearGroups() *ApplicationUpdate { au.mutation.ClearGroups() return au } -// RemoveGroupIDs removes the groups edge to Group by ids. +// RemoveGroupIDs removes the "groups" edge to Group entities by IDs. func (au *ApplicationUpdate) RemoveGroupIDs(ids ...int) *ApplicationUpdate { au.mutation.RemoveGroupIDs(ids...) return au } -// RemoveGroups removes groups edges to Group. +// RemoveGroups removes "groups" edges to Group entities. func (au *ApplicationUpdate) RemoveGroups(g ...*Group) *ApplicationUpdate { ids := make([]int, len(g)) for i := range g { @@ -172,19 +193,19 @@ func (au *ApplicationUpdate) RemoveGroups(g ...*Group) *ApplicationUpdate { return au.RemoveGroupIDs(ids...) } -// ClearTags clears all "tags" edges to type Tag. +// ClearTags clears all "tags" edges to the Tag entity. func (au *ApplicationUpdate) ClearTags() *ApplicationUpdate { au.mutation.ClearTags() return au } -// RemoveTagIDs removes the tags edge to Tag by ids. +// RemoveTagIDs removes the "tags" edge to Tag entities by IDs. func (au *ApplicationUpdate) RemoveTagIDs(ids ...int) *ApplicationUpdate { au.mutation.RemoveTagIDs(ids...) return au } -// RemoveTags removes tags edges to Tag. +// RemoveTags removes "tags" edges to Tag entities. func (au *ApplicationUpdate) RemoveTags(t ...*Tag) *ApplicationUpdate { ids := make([]int, len(t)) for i := range t { @@ -193,34 +214,10 @@ func (au *ApplicationUpdate) RemoveTags(t ...*Tag) *ApplicationUpdate { return au.RemoveTagIDs(ids...) } -// Save executes the query and returns the number of rows/vertices matched by this operation. +// Save executes the query and returns the number of nodes affected by the update operation. func (au *ApplicationUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) au.defaults() - if len(au.hooks) == 0 { - affected, err = au.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*ApplicationMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - au.mutation = mutation - affected, err = au.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(au.hooks) - 1; i >= 0; i-- { - mut = au.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, au.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, au.sqlSave, au.mutation, au.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -253,18 +250,22 @@ func (au *ApplicationUpdate) defaults() { } } +// check runs all checks and user-defined validators on the builder. +func (au *ApplicationUpdate) check() error { + if v, ok := au.mutation.Vu(); ok { + if err := application.VuValidator(v); err != nil { + return &ValidationError{Name: "vu", err: fmt.Errorf(`ent: validator failed for field "Application.vu": %w`, err)} + } + } + return nil +} + func (au *ApplicationUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: application.Table, - Columns: application.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, - }, + if err := au.check(); err != nil { + return n, err } - if ps := au.predicates; len(ps) > 0 { + _spec := sqlgraph.NewUpdateSpec(application.Table, application.Columns, sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt)) + if ps := au.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -272,66 +273,37 @@ func (au *ApplicationUpdate) sqlSave(ctx context.Context) (n int, err error) { } } if value, ok := au.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldName, - }) + _spec.SetField(application.FieldName, field.TypeString, value) } if value, ok := au.mutation.Status(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldStatus, - }) + _spec.SetField(application.FieldStatus, field.TypeString, value) } if value, ok := au.mutation.CreatedAt(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: application.FieldCreatedAt, - }) + _spec.SetField(application.FieldCreatedAt, field.TypeTime, value) } if value, ok := au.mutation.StartedAt(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: application.FieldStartedAt, - }) + _spec.SetField(application.FieldStartedAt, field.TypeTime, value) } if au.mutation.StartedAtCleared() { - _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Column: application.FieldStartedAt, - }) + _spec.ClearField(application.FieldStartedAt, field.TypeTime) } if value, ok := au.mutation.UpdatedAt(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: application.FieldUpdatedAt, - }) + _spec.SetField(application.FieldUpdatedAt, field.TypeTime, value) } if value, ok := au.mutation.Scenario(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldScenario, - }) + _spec.SetField(application.FieldScenario, field.TypeString, value) } if value, ok := au.mutation.Gomod(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldGomod, - }) + _spec.SetField(application.FieldGomod, field.TypeString, value) } if value, ok := au.mutation.Gosum(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldGosum, - }) + _spec.SetField(application.FieldGosum, field.TypeString, value) + } + if value, ok := au.mutation.Vu(); ok { + _spec.SetField(application.FieldVu, field.TypeInt, value) + } + if value, ok := au.mutation.AddedVu(); ok { + _spec.AddField(application.FieldVu, field.TypeInt, value) } if au.mutation.GroupsCleared() { edge := &sqlgraph.EdgeSpec{ @@ -341,10 +313,7 @@ func (au *ApplicationUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{application.GroupsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -357,10 +326,7 @@ func (au *ApplicationUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{application.GroupsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -376,10 +342,7 @@ func (au *ApplicationUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{application.GroupsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -395,10 +358,7 @@ func (au *ApplicationUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{application.TagsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -411,10 +371,7 @@ func (au *ApplicationUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{application.TagsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -430,10 +387,7 @@ func (au *ApplicationUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{application.TagsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -444,40 +398,42 @@ func (au *ApplicationUpdate) sqlSave(ctx context.Context) (n int, err error) { if n, err = sqlgraph.UpdateNodes(ctx, au.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{application.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } + au.mutation.done = true return n, nil } // ApplicationUpdateOne is the builder for updating a single Application entity. type ApplicationUpdateOne struct { config + fields []string hooks []Hook mutation *ApplicationMutation } -// SetName sets the name field. +// SetName sets the "name" field. func (auo *ApplicationUpdateOne) SetName(s string) *ApplicationUpdateOne { auo.mutation.SetName(s) return auo } -// SetStatus sets the status field. +// SetStatus sets the "status" field. func (auo *ApplicationUpdateOne) SetStatus(s string) *ApplicationUpdateOne { auo.mutation.SetStatus(s) return auo } -// SetCreatedAt sets the created_at field. +// SetCreatedAt sets the "created_at" field. func (auo *ApplicationUpdateOne) SetCreatedAt(t time.Time) *ApplicationUpdateOne { auo.mutation.SetCreatedAt(t) return auo } -// SetNillableCreatedAt sets the created_at field if the given value is not nil. +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. func (auo *ApplicationUpdateOne) SetNillableCreatedAt(t *time.Time) *ApplicationUpdateOne { if t != nil { auo.SetCreatedAt(*t) @@ -485,13 +441,13 @@ func (auo *ApplicationUpdateOne) SetNillableCreatedAt(t *time.Time) *Application return auo } -// SetStartedAt sets the started_at field. +// SetStartedAt sets the "started_at" field. func (auo *ApplicationUpdateOne) SetStartedAt(t time.Time) *ApplicationUpdateOne { auo.mutation.SetStartedAt(t) return auo } -// SetNillableStartedAt sets the started_at field if the given value is not nil. +// SetNillableStartedAt sets the "started_at" field if the given value is not nil. func (auo *ApplicationUpdateOne) SetNillableStartedAt(t *time.Time) *ApplicationUpdateOne { if t != nil { auo.SetStartedAt(*t) @@ -499,31 +455,31 @@ func (auo *ApplicationUpdateOne) SetNillableStartedAt(t *time.Time) *Application return auo } -// ClearStartedAt clears the value of started_at. +// ClearStartedAt clears the value of the "started_at" field. func (auo *ApplicationUpdateOne) ClearStartedAt() *ApplicationUpdateOne { auo.mutation.ClearStartedAt() return auo } -// SetUpdatedAt sets the updated_at field. +// SetUpdatedAt sets the "updated_at" field. func (auo *ApplicationUpdateOne) SetUpdatedAt(t time.Time) *ApplicationUpdateOne { auo.mutation.SetUpdatedAt(t) return auo } -// SetScenario sets the scenario field. +// SetScenario sets the "scenario" field. func (auo *ApplicationUpdateOne) SetScenario(s string) *ApplicationUpdateOne { auo.mutation.SetScenario(s) return auo } -// SetGomod sets the gomod field. +// SetGomod sets the "gomod" field. func (auo *ApplicationUpdateOne) SetGomod(s string) *ApplicationUpdateOne { auo.mutation.SetGomod(s) return auo } -// SetNillableGomod sets the gomod field if the given value is not nil. +// SetNillableGomod sets the "gomod" field if the given value is not nil. func (auo *ApplicationUpdateOne) SetNillableGomod(s *string) *ApplicationUpdateOne { if s != nil { auo.SetGomod(*s) @@ -531,13 +487,13 @@ func (auo *ApplicationUpdateOne) SetNillableGomod(s *string) *ApplicationUpdateO return auo } -// SetGosum sets the gosum field. +// SetGosum sets the "gosum" field. func (auo *ApplicationUpdateOne) SetGosum(s string) *ApplicationUpdateOne { auo.mutation.SetGosum(s) return auo } -// SetNillableGosum sets the gosum field if the given value is not nil. +// SetNillableGosum sets the "gosum" field if the given value is not nil. func (auo *ApplicationUpdateOne) SetNillableGosum(s *string) *ApplicationUpdateOne { if s != nil { auo.SetGosum(*s) @@ -545,13 +501,34 @@ func (auo *ApplicationUpdateOne) SetNillableGosum(s *string) *ApplicationUpdateO return auo } -// AddGroupIDs adds the groups edge to Group by ids. +// SetVu sets the "vu" field. +func (auo *ApplicationUpdateOne) SetVu(i int) *ApplicationUpdateOne { + auo.mutation.ResetVu() + auo.mutation.SetVu(i) + return auo +} + +// SetNillableVu sets the "vu" field if the given value is not nil. +func (auo *ApplicationUpdateOne) SetNillableVu(i *int) *ApplicationUpdateOne { + if i != nil { + auo.SetVu(*i) + } + return auo +} + +// AddVu adds i to the "vu" field. +func (auo *ApplicationUpdateOne) AddVu(i int) *ApplicationUpdateOne { + auo.mutation.AddVu(i) + return auo +} + +// AddGroupIDs adds the "groups" edge to the Group entity by IDs. func (auo *ApplicationUpdateOne) AddGroupIDs(ids ...int) *ApplicationUpdateOne { auo.mutation.AddGroupIDs(ids...) return auo } -// AddGroups adds the groups edges to Group. +// AddGroups adds the "groups" edges to the Group entity. func (auo *ApplicationUpdateOne) AddGroups(g ...*Group) *ApplicationUpdateOne { ids := make([]int, len(g)) for i := range g { @@ -560,13 +537,13 @@ func (auo *ApplicationUpdateOne) AddGroups(g ...*Group) *ApplicationUpdateOne { return auo.AddGroupIDs(ids...) } -// AddTagIDs adds the tags edge to Tag by ids. +// AddTagIDs adds the "tags" edge to the Tag entity by IDs. func (auo *ApplicationUpdateOne) AddTagIDs(ids ...int) *ApplicationUpdateOne { auo.mutation.AddTagIDs(ids...) return auo } -// AddTags adds the tags edges to Tag. +// AddTags adds the "tags" edges to the Tag entity. func (auo *ApplicationUpdateOne) AddTags(t ...*Tag) *ApplicationUpdateOne { ids := make([]int, len(t)) for i := range t { @@ -580,19 +557,19 @@ func (auo *ApplicationUpdateOne) Mutation() *ApplicationMutation { return auo.mutation } -// ClearGroups clears all "groups" edges to type Group. +// ClearGroups clears all "groups" edges to the Group entity. func (auo *ApplicationUpdateOne) ClearGroups() *ApplicationUpdateOne { auo.mutation.ClearGroups() return auo } -// RemoveGroupIDs removes the groups edge to Group by ids. +// RemoveGroupIDs removes the "groups" edge to Group entities by IDs. func (auo *ApplicationUpdateOne) RemoveGroupIDs(ids ...int) *ApplicationUpdateOne { auo.mutation.RemoveGroupIDs(ids...) return auo } -// RemoveGroups removes groups edges to Group. +// RemoveGroups removes "groups" edges to Group entities. func (auo *ApplicationUpdateOne) RemoveGroups(g ...*Group) *ApplicationUpdateOne { ids := make([]int, len(g)) for i := range g { @@ -601,19 +578,19 @@ func (auo *ApplicationUpdateOne) RemoveGroups(g ...*Group) *ApplicationUpdateOne return auo.RemoveGroupIDs(ids...) } -// ClearTags clears all "tags" edges to type Tag. +// ClearTags clears all "tags" edges to the Tag entity. func (auo *ApplicationUpdateOne) ClearTags() *ApplicationUpdateOne { auo.mutation.ClearTags() return auo } -// RemoveTagIDs removes the tags edge to Tag by ids. +// RemoveTagIDs removes the "tags" edge to Tag entities by IDs. func (auo *ApplicationUpdateOne) RemoveTagIDs(ids ...int) *ApplicationUpdateOne { auo.mutation.RemoveTagIDs(ids...) return auo } -// RemoveTags removes tags edges to Tag. +// RemoveTags removes "tags" edges to Tag entities. func (auo *ApplicationUpdateOne) RemoveTags(t ...*Tag) *ApplicationUpdateOne { ids := make([]int, len(t)) for i := range t { @@ -622,34 +599,23 @@ func (auo *ApplicationUpdateOne) RemoveTags(t ...*Tag) *ApplicationUpdateOne { return auo.RemoveTagIDs(ids...) } -// Save executes the query and returns the updated entity. +// Where appends a list predicates to the ApplicationUpdate builder. +func (auo *ApplicationUpdateOne) Where(ps ...predicate.Application) *ApplicationUpdateOne { + auo.mutation.Where(ps...) + return auo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (auo *ApplicationUpdateOne) Select(field string, fields ...string) *ApplicationUpdateOne { + auo.fields = append([]string{field}, fields...) + return auo +} + +// Save executes the query and returns the updated Application entity. func (auo *ApplicationUpdateOne) Save(ctx context.Context) (*Application, error) { - var ( - err error - node *Application - ) auo.defaults() - if len(auo.hooks) == 0 { - node, err = auo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*ApplicationMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - auo.mutation = mutation - node, err = auo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(auo.hooks) - 1; i >= 0; i-- { - mut = auo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, auo.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, auo.sqlSave, auo.mutation, auo.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -682,83 +648,77 @@ func (auo *ApplicationUpdateOne) defaults() { } } +// check runs all checks and user-defined validators on the builder. +func (auo *ApplicationUpdateOne) check() error { + if v, ok := auo.mutation.Vu(); ok { + if err := application.VuValidator(v); err != nil { + return &ValidationError{Name: "vu", err: fmt.Errorf(`ent: validator failed for field "Application.vu": %w`, err)} + } + } + return nil +} + func (auo *ApplicationUpdateOne) sqlSave(ctx context.Context) (_node *Application, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: application.Table, - Columns: application.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, - }, + if err := auo.check(); err != nil { + return _node, err } + _spec := sqlgraph.NewUpdateSpec(application.Table, application.Columns, sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt)) id, ok := auo.mutation.ID() if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Application.ID for update")} + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Application.id" for update`)} } _spec.Node.ID.Value = id + if fields := auo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, application.FieldID) + for _, f := range fields { + if !application.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != application.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := auo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } if value, ok := auo.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldName, - }) + _spec.SetField(application.FieldName, field.TypeString, value) } if value, ok := auo.mutation.Status(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldStatus, - }) + _spec.SetField(application.FieldStatus, field.TypeString, value) } if value, ok := auo.mutation.CreatedAt(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: application.FieldCreatedAt, - }) + _spec.SetField(application.FieldCreatedAt, field.TypeTime, value) } if value, ok := auo.mutation.StartedAt(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: application.FieldStartedAt, - }) + _spec.SetField(application.FieldStartedAt, field.TypeTime, value) } if auo.mutation.StartedAtCleared() { - _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Column: application.FieldStartedAt, - }) + _spec.ClearField(application.FieldStartedAt, field.TypeTime) } if value, ok := auo.mutation.UpdatedAt(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeTime, - Value: value, - Column: application.FieldUpdatedAt, - }) + _spec.SetField(application.FieldUpdatedAt, field.TypeTime, value) } if value, ok := auo.mutation.Scenario(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldScenario, - }) + _spec.SetField(application.FieldScenario, field.TypeString, value) } if value, ok := auo.mutation.Gomod(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldGomod, - }) + _spec.SetField(application.FieldGomod, field.TypeString, value) } if value, ok := auo.mutation.Gosum(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: application.FieldGosum, - }) + _spec.SetField(application.FieldGosum, field.TypeString, value) + } + if value, ok := auo.mutation.Vu(); ok { + _spec.SetField(application.FieldVu, field.TypeInt, value) + } + if value, ok := auo.mutation.AddedVu(); ok { + _spec.AddField(application.FieldVu, field.TypeInt, value) } if auo.mutation.GroupsCleared() { edge := &sqlgraph.EdgeSpec{ @@ -768,10 +728,7 @@ func (auo *ApplicationUpdateOne) sqlSave(ctx context.Context) (_node *Applicatio Columns: []string{application.GroupsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -784,10 +741,7 @@ func (auo *ApplicationUpdateOne) sqlSave(ctx context.Context) (_node *Applicatio Columns: []string{application.GroupsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -803,10 +757,7 @@ func (auo *ApplicationUpdateOne) sqlSave(ctx context.Context) (_node *Applicatio Columns: []string{application.GroupsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -822,10 +773,7 @@ func (auo *ApplicationUpdateOne) sqlSave(ctx context.Context) (_node *Applicatio Columns: []string{application.TagsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -838,10 +786,7 @@ func (auo *ApplicationUpdateOne) sqlSave(ctx context.Context) (_node *Applicatio Columns: []string{application.TagsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -857,10 +802,7 @@ func (auo *ApplicationUpdateOne) sqlSave(ctx context.Context) (_node *Applicatio Columns: []string{application.TagsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -870,14 +812,15 @@ func (auo *ApplicationUpdateOne) sqlSave(ctx context.Context) (_node *Applicatio } _node = &Application{config: auo.config} _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues() + _spec.ScanValues = _node.scanValues if err = sqlgraph.UpdateNode(ctx, auo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{application.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } + auo.mutation.done = true return _node, nil } diff --git a/ent/client.go b/ent/client.go index 51a42c9b..66210c8f 100644 --- a/ent/client.go +++ b/ent/client.go @@ -1,14 +1,19 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" "log" "github.com/gobench-io/gobench/v2/ent/migrate" + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/gauge" @@ -17,10 +22,6 @@ import ( "github.com/gobench-io/gobench/v2/ent/histogram" "github.com/gobench-io/gobench/v2/ent/metric" "github.com/gobench-io/gobench/v2/ent/tag" - - "github.com/facebook/ent/dialect" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" ) // Client is the client that holds all ent builders. @@ -48,7 +49,7 @@ type Client struct { // NewClient creates a new client configured with the given options. func NewClient(opts ...Option) *Client { - cfg := config{log: log.Println, hooks: &hooks{}} + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} cfg.options(opts...) client := &Client{config: cfg} client.init() @@ -67,6 +68,55 @@ func (c *Client) init() { c.Tag = NewTagClient(c.config) } +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + // Open opens a database/sql.DB specified by the driver name and // the data source name, and returns a new client attached to it. // Optional parameters can be added for configuring the client. @@ -87,13 +137,14 @@ func Open(driverName, dataSourceName string, options ...Option) (*Client, error) // is used until the transaction is committed or rolled back. func (c *Client) Tx(ctx context.Context) (*Tx, error) { if _, ok := c.driver.(*txDriver); ok { - return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + return nil, errors.New("ent: cannot start a transaction within a transaction") } tx, err := newTx(ctx, c.driver) if err != nil { - return nil, fmt.Errorf("ent: starting a transaction: %v", err) + return nil, fmt.Errorf("ent: starting a transaction: %w", err) } - cfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks} + cfg := c.config + cfg.driver = tx return &Tx{ ctx: ctx, config: cfg, @@ -108,17 +159,21 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { }, nil } -// BeginTx returns a transactional client with options. +// BeginTx returns a transactional client with specified options. func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { if _, ok := c.driver.(*txDriver); ok { - return nil, fmt.Errorf("ent: cannot start a transaction within a transaction") + return nil, errors.New("ent: cannot start a transaction within a transaction") } - tx, err := c.driver.(*sql.Driver).BeginTx(ctx, opts) + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) if err != nil { - return nil, fmt.Errorf("ent: starting a transaction: %v", err) + return nil, fmt.Errorf("ent: starting a transaction: %w", err) } - cfg := config{driver: &txDriver{tx: tx, drv: c.driver}, log: c.log, debug: c.debug, hooks: c.hooks} + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ + ctx: ctx, config: cfg, Application: NewApplicationClient(cfg), Counter: NewCounterClient(cfg), @@ -137,12 +192,12 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) // Application. // Query(). // Count(ctx) -// func (c *Client) Debug() *Client { if c.debug { return c } - cfg := config{driver: dialect.Debug(c.driver, c.log), log: c.log, debug: true, hooks: c.hooks} + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) client := &Client{config: cfg} client.init() return client @@ -156,14 +211,47 @@ func (c *Client) Close() error { // Use adds the mutation hooks to all the entity clients. // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { - c.Application.Use(hooks...) - c.Counter.Use(hooks...) - c.Gauge.Use(hooks...) - c.Graph.Use(hooks...) - c.Group.Use(hooks...) - c.Histogram.Use(hooks...) - c.Metric.Use(hooks...) - c.Tag.Use(hooks...) + for _, n := range []interface{ Use(...Hook) }{ + c.Application, c.Counter, c.Gauge, c.Graph, c.Group, c.Histogram, c.Metric, + c.Tag, + } { + n.Use(hooks...) + } +} + +// Intercept adds the query interceptors to all the entity clients. +// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. +func (c *Client) Intercept(interceptors ...Interceptor) { + for _, n := range []interface{ Intercept(...Interceptor) }{ + c.Application, c.Counter, c.Gauge, c.Graph, c.Group, c.Histogram, c.Metric, + c.Tag, + } { + n.Intercept(interceptors...) + } +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *ApplicationMutation: + return c.Application.mutate(ctx, m) + case *CounterMutation: + return c.Counter.mutate(ctx, m) + case *GaugeMutation: + return c.Gauge.mutate(ctx, m) + case *GraphMutation: + return c.Graph.mutate(ctx, m) + case *GroupMutation: + return c.Group.mutate(ctx, m) + case *HistogramMutation: + return c.Histogram.mutate(ctx, m) + case *MetricMutation: + return c.Metric.mutate(ctx, m) + case *TagMutation: + return c.Tag.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } } // ApplicationClient is a client for the Application schema. @@ -182,13 +270,19 @@ func (c *ApplicationClient) Use(hooks ...Hook) { c.hooks.Application = append(c.hooks.Application, hooks...) } -// Create returns a create builder for Application. +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `application.Intercept(f(g(h())))`. +func (c *ApplicationClient) Intercept(interceptors ...Interceptor) { + c.inters.Application = append(c.inters.Application, interceptors...) +} + +// Create returns a builder for creating a Application entity. func (c *ApplicationClient) Create() *ApplicationCreate { mutation := newApplicationMutation(c.config, OpCreate) return &ApplicationCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// BulkCreate returns a builder for creating a bulk of Application entities. +// CreateBulk returns a builder for creating a bulk of Application entities. func (c *ApplicationClient) CreateBulk(builders ...*ApplicationCreate) *ApplicationCreateBulk { return &ApplicationCreateBulk{config: c.config, builders: builders} } @@ -217,12 +311,12 @@ func (c *ApplicationClient) Delete() *ApplicationDelete { return &ApplicationDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *ApplicationClient) DeleteOne(a *Application) *ApplicationDeleteOne { return c.DeleteOneID(a.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOneID returns a builder for deleting the given entity by its id. func (c *ApplicationClient) DeleteOneID(id int) *ApplicationDeleteOne { builder := c.Delete().Where(application.ID(id)) builder.mutation.id = &id @@ -232,7 +326,11 @@ func (c *ApplicationClient) DeleteOneID(id int) *ApplicationDeleteOne { // Query returns a query builder for Application. func (c *ApplicationClient) Query() *ApplicationQuery { - return &ApplicationQuery{config: c.config} + return &ApplicationQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeApplication}, + inters: c.Interceptors(), + } } // Get returns a Application entity by its id. @@ -251,8 +349,8 @@ func (c *ApplicationClient) GetX(ctx context.Context, id int) *Application { // QueryGroups queries the groups edge of a Application. func (c *ApplicationClient) QueryGroups(a *Application) *GroupQuery { - query := &GroupQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&GroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := a.ID step := sqlgraph.NewStep( sqlgraph.From(application.Table, application.FieldID, id), @@ -267,8 +365,8 @@ func (c *ApplicationClient) QueryGroups(a *Application) *GroupQuery { // QueryTags queries the tags edge of a Application. func (c *ApplicationClient) QueryTags(a *Application) *TagQuery { - query := &TagQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&TagClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := a.ID step := sqlgraph.NewStep( sqlgraph.From(application.Table, application.FieldID, id), @@ -286,6 +384,26 @@ func (c *ApplicationClient) Hooks() []Hook { return c.hooks.Application } +// Interceptors returns the client interceptors. +func (c *ApplicationClient) Interceptors() []Interceptor { + return c.inters.Application +} + +func (c *ApplicationClient) mutate(ctx context.Context, m *ApplicationMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ApplicationCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ApplicationUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ApplicationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ApplicationDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Application mutation op: %q", m.Op()) + } +} + // CounterClient is a client for the Counter schema. type CounterClient struct { config @@ -302,13 +420,19 @@ func (c *CounterClient) Use(hooks ...Hook) { c.hooks.Counter = append(c.hooks.Counter, hooks...) } -// Create returns a create builder for Counter. +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `counter.Intercept(f(g(h())))`. +func (c *CounterClient) Intercept(interceptors ...Interceptor) { + c.inters.Counter = append(c.inters.Counter, interceptors...) +} + +// Create returns a builder for creating a Counter entity. func (c *CounterClient) Create() *CounterCreate { mutation := newCounterMutation(c.config, OpCreate) return &CounterCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// BulkCreate returns a builder for creating a bulk of Counter entities. +// CreateBulk returns a builder for creating a bulk of Counter entities. func (c *CounterClient) CreateBulk(builders ...*CounterCreate) *CounterCreateBulk { return &CounterCreateBulk{config: c.config, builders: builders} } @@ -337,12 +461,12 @@ func (c *CounterClient) Delete() *CounterDelete { return &CounterDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *CounterClient) DeleteOne(co *Counter) *CounterDeleteOne { return c.DeleteOneID(co.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOneID returns a builder for deleting the given entity by its id. func (c *CounterClient) DeleteOneID(id int) *CounterDeleteOne { builder := c.Delete().Where(counter.ID(id)) builder.mutation.id = &id @@ -352,7 +476,11 @@ func (c *CounterClient) DeleteOneID(id int) *CounterDeleteOne { // Query returns a query builder for Counter. func (c *CounterClient) Query() *CounterQuery { - return &CounterQuery{config: c.config} + return &CounterQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCounter}, + inters: c.Interceptors(), + } } // Get returns a Counter entity by its id. @@ -371,8 +499,8 @@ func (c *CounterClient) GetX(ctx context.Context, id int) *Counter { // QueryMetric queries the metric edge of a Counter. func (c *CounterClient) QueryMetric(co *Counter) *MetricQuery { - query := &MetricQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&MetricClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := co.ID step := sqlgraph.NewStep( sqlgraph.From(counter.Table, counter.FieldID, id), @@ -390,6 +518,26 @@ func (c *CounterClient) Hooks() []Hook { return c.hooks.Counter } +// Interceptors returns the client interceptors. +func (c *CounterClient) Interceptors() []Interceptor { + return c.inters.Counter +} + +func (c *CounterClient) mutate(ctx context.Context, m *CounterMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CounterCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CounterUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CounterUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CounterDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Counter mutation op: %q", m.Op()) + } +} + // GaugeClient is a client for the Gauge schema. type GaugeClient struct { config @@ -406,13 +554,19 @@ func (c *GaugeClient) Use(hooks ...Hook) { c.hooks.Gauge = append(c.hooks.Gauge, hooks...) } -// Create returns a create builder for Gauge. +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `gauge.Intercept(f(g(h())))`. +func (c *GaugeClient) Intercept(interceptors ...Interceptor) { + c.inters.Gauge = append(c.inters.Gauge, interceptors...) +} + +// Create returns a builder for creating a Gauge entity. func (c *GaugeClient) Create() *GaugeCreate { mutation := newGaugeMutation(c.config, OpCreate) return &GaugeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// BulkCreate returns a builder for creating a bulk of Gauge entities. +// CreateBulk returns a builder for creating a bulk of Gauge entities. func (c *GaugeClient) CreateBulk(builders ...*GaugeCreate) *GaugeCreateBulk { return &GaugeCreateBulk{config: c.config, builders: builders} } @@ -441,12 +595,12 @@ func (c *GaugeClient) Delete() *GaugeDelete { return &GaugeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GaugeClient) DeleteOne(ga *Gauge) *GaugeDeleteOne { return c.DeleteOneID(ga.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOneID returns a builder for deleting the given entity by its id. func (c *GaugeClient) DeleteOneID(id int) *GaugeDeleteOne { builder := c.Delete().Where(gauge.ID(id)) builder.mutation.id = &id @@ -456,7 +610,11 @@ func (c *GaugeClient) DeleteOneID(id int) *GaugeDeleteOne { // Query returns a query builder for Gauge. func (c *GaugeClient) Query() *GaugeQuery { - return &GaugeQuery{config: c.config} + return &GaugeQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeGauge}, + inters: c.Interceptors(), + } } // Get returns a Gauge entity by its id. @@ -475,8 +633,8 @@ func (c *GaugeClient) GetX(ctx context.Context, id int) *Gauge { // QueryMetric queries the metric edge of a Gauge. func (c *GaugeClient) QueryMetric(ga *Gauge) *MetricQuery { - query := &MetricQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&MetricClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := ga.ID step := sqlgraph.NewStep( sqlgraph.From(gauge.Table, gauge.FieldID, id), @@ -494,6 +652,26 @@ func (c *GaugeClient) Hooks() []Hook { return c.hooks.Gauge } +// Interceptors returns the client interceptors. +func (c *GaugeClient) Interceptors() []Interceptor { + return c.inters.Gauge +} + +func (c *GaugeClient) mutate(ctx context.Context, m *GaugeMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&GaugeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&GaugeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&GaugeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&GaugeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Gauge mutation op: %q", m.Op()) + } +} + // GraphClient is a client for the Graph schema. type GraphClient struct { config @@ -510,13 +688,19 @@ func (c *GraphClient) Use(hooks ...Hook) { c.hooks.Graph = append(c.hooks.Graph, hooks...) } -// Create returns a create builder for Graph. +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `graph.Intercept(f(g(h())))`. +func (c *GraphClient) Intercept(interceptors ...Interceptor) { + c.inters.Graph = append(c.inters.Graph, interceptors...) +} + +// Create returns a builder for creating a Graph entity. func (c *GraphClient) Create() *GraphCreate { mutation := newGraphMutation(c.config, OpCreate) return &GraphCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// BulkCreate returns a builder for creating a bulk of Graph entities. +// CreateBulk returns a builder for creating a bulk of Graph entities. func (c *GraphClient) CreateBulk(builders ...*GraphCreate) *GraphCreateBulk { return &GraphCreateBulk{config: c.config, builders: builders} } @@ -545,12 +729,12 @@ func (c *GraphClient) Delete() *GraphDelete { return &GraphDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GraphClient) DeleteOne(gr *Graph) *GraphDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOneID returns a builder for deleting the given entity by its id. func (c *GraphClient) DeleteOneID(id int) *GraphDeleteOne { builder := c.Delete().Where(graph.ID(id)) builder.mutation.id = &id @@ -560,7 +744,11 @@ func (c *GraphClient) DeleteOneID(id int) *GraphDeleteOne { // Query returns a query builder for Graph. func (c *GraphClient) Query() *GraphQuery { - return &GraphQuery{config: c.config} + return &GraphQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeGraph}, + inters: c.Interceptors(), + } } // Get returns a Graph entity by its id. @@ -579,8 +767,8 @@ func (c *GraphClient) GetX(ctx context.Context, id int) *Graph { // QueryGroup queries the group edge of a Graph. func (c *GraphClient) QueryGroup(gr *Graph) *GroupQuery { - query := &GroupQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&GroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := gr.ID step := sqlgraph.NewStep( sqlgraph.From(graph.Table, graph.FieldID, id), @@ -595,8 +783,8 @@ func (c *GraphClient) QueryGroup(gr *Graph) *GroupQuery { // QueryMetrics queries the metrics edge of a Graph. func (c *GraphClient) QueryMetrics(gr *Graph) *MetricQuery { - query := &MetricQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&MetricClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := gr.ID step := sqlgraph.NewStep( sqlgraph.From(graph.Table, graph.FieldID, id), @@ -614,6 +802,26 @@ func (c *GraphClient) Hooks() []Hook { return c.hooks.Graph } +// Interceptors returns the client interceptors. +func (c *GraphClient) Interceptors() []Interceptor { + return c.inters.Graph +} + +func (c *GraphClient) mutate(ctx context.Context, m *GraphMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&GraphCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&GraphUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&GraphUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&GraphDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Graph mutation op: %q", m.Op()) + } +} + // GroupClient is a client for the Group schema. type GroupClient struct { config @@ -630,13 +838,19 @@ func (c *GroupClient) Use(hooks ...Hook) { c.hooks.Group = append(c.hooks.Group, hooks...) } -// Create returns a create builder for Group. +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `group.Intercept(f(g(h())))`. +func (c *GroupClient) Intercept(interceptors ...Interceptor) { + c.inters.Group = append(c.inters.Group, interceptors...) +} + +// Create returns a builder for creating a Group entity. func (c *GroupClient) Create() *GroupCreate { mutation := newGroupMutation(c.config, OpCreate) return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// BulkCreate returns a builder for creating a bulk of Group entities. +// CreateBulk returns a builder for creating a bulk of Group entities. func (c *GroupClient) CreateBulk(builders ...*GroupCreate) *GroupCreateBulk { return &GroupCreateBulk{config: c.config, builders: builders} } @@ -665,12 +879,12 @@ func (c *GroupClient) Delete() *GroupDelete { return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { return c.DeleteOneID(gr.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOneID returns a builder for deleting the given entity by its id. func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { builder := c.Delete().Where(group.ID(id)) builder.mutation.id = &id @@ -680,7 +894,11 @@ func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { // Query returns a query builder for Group. func (c *GroupClient) Query() *GroupQuery { - return &GroupQuery{config: c.config} + return &GroupQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeGroup}, + inters: c.Interceptors(), + } } // Get returns a Group entity by its id. @@ -699,8 +917,8 @@ func (c *GroupClient) GetX(ctx context.Context, id int) *Group { // QueryApplication queries the application edge of a Group. func (c *GroupClient) QueryApplication(gr *Group) *ApplicationQuery { - query := &ApplicationQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&ApplicationClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := gr.ID step := sqlgraph.NewStep( sqlgraph.From(group.Table, group.FieldID, id), @@ -715,8 +933,8 @@ func (c *GroupClient) QueryApplication(gr *Group) *ApplicationQuery { // QueryGraphs queries the graphs edge of a Group. func (c *GroupClient) QueryGraphs(gr *Group) *GraphQuery { - query := &GraphQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&GraphClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := gr.ID step := sqlgraph.NewStep( sqlgraph.From(group.Table, group.FieldID, id), @@ -734,6 +952,26 @@ func (c *GroupClient) Hooks() []Hook { return c.hooks.Group } +// Interceptors returns the client interceptors. +func (c *GroupClient) Interceptors() []Interceptor { + return c.inters.Group +} + +func (c *GroupClient) mutate(ctx context.Context, m *GroupMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&GroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&GroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Group mutation op: %q", m.Op()) + } +} + // HistogramClient is a client for the Histogram schema. type HistogramClient struct { config @@ -750,13 +988,19 @@ func (c *HistogramClient) Use(hooks ...Hook) { c.hooks.Histogram = append(c.hooks.Histogram, hooks...) } -// Create returns a create builder for Histogram. +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `histogram.Intercept(f(g(h())))`. +func (c *HistogramClient) Intercept(interceptors ...Interceptor) { + c.inters.Histogram = append(c.inters.Histogram, interceptors...) +} + +// Create returns a builder for creating a Histogram entity. func (c *HistogramClient) Create() *HistogramCreate { mutation := newHistogramMutation(c.config, OpCreate) return &HistogramCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// BulkCreate returns a builder for creating a bulk of Histogram entities. +// CreateBulk returns a builder for creating a bulk of Histogram entities. func (c *HistogramClient) CreateBulk(builders ...*HistogramCreate) *HistogramCreateBulk { return &HistogramCreateBulk{config: c.config, builders: builders} } @@ -785,12 +1029,12 @@ func (c *HistogramClient) Delete() *HistogramDelete { return &HistogramDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *HistogramClient) DeleteOne(h *Histogram) *HistogramDeleteOne { return c.DeleteOneID(h.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOneID returns a builder for deleting the given entity by its id. func (c *HistogramClient) DeleteOneID(id int) *HistogramDeleteOne { builder := c.Delete().Where(histogram.ID(id)) builder.mutation.id = &id @@ -800,7 +1044,11 @@ func (c *HistogramClient) DeleteOneID(id int) *HistogramDeleteOne { // Query returns a query builder for Histogram. func (c *HistogramClient) Query() *HistogramQuery { - return &HistogramQuery{config: c.config} + return &HistogramQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeHistogram}, + inters: c.Interceptors(), + } } // Get returns a Histogram entity by its id. @@ -819,8 +1067,8 @@ func (c *HistogramClient) GetX(ctx context.Context, id int) *Histogram { // QueryMetric queries the metric edge of a Histogram. func (c *HistogramClient) QueryMetric(h *Histogram) *MetricQuery { - query := &MetricQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&MetricClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := h.ID step := sqlgraph.NewStep( sqlgraph.From(histogram.Table, histogram.FieldID, id), @@ -838,6 +1086,26 @@ func (c *HistogramClient) Hooks() []Hook { return c.hooks.Histogram } +// Interceptors returns the client interceptors. +func (c *HistogramClient) Interceptors() []Interceptor { + return c.inters.Histogram +} + +func (c *HistogramClient) mutate(ctx context.Context, m *HistogramMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&HistogramCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&HistogramUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&HistogramUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&HistogramDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Histogram mutation op: %q", m.Op()) + } +} + // MetricClient is a client for the Metric schema. type MetricClient struct { config @@ -854,13 +1122,19 @@ func (c *MetricClient) Use(hooks ...Hook) { c.hooks.Metric = append(c.hooks.Metric, hooks...) } -// Create returns a create builder for Metric. +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `metric.Intercept(f(g(h())))`. +func (c *MetricClient) Intercept(interceptors ...Interceptor) { + c.inters.Metric = append(c.inters.Metric, interceptors...) +} + +// Create returns a builder for creating a Metric entity. func (c *MetricClient) Create() *MetricCreate { mutation := newMetricMutation(c.config, OpCreate) return &MetricCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// BulkCreate returns a builder for creating a bulk of Metric entities. +// CreateBulk returns a builder for creating a bulk of Metric entities. func (c *MetricClient) CreateBulk(builders ...*MetricCreate) *MetricCreateBulk { return &MetricCreateBulk{config: c.config, builders: builders} } @@ -889,12 +1163,12 @@ func (c *MetricClient) Delete() *MetricDelete { return &MetricDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *MetricClient) DeleteOne(m *Metric) *MetricDeleteOne { return c.DeleteOneID(m.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOneID returns a builder for deleting the given entity by its id. func (c *MetricClient) DeleteOneID(id int) *MetricDeleteOne { builder := c.Delete().Where(metric.ID(id)) builder.mutation.id = &id @@ -904,7 +1178,11 @@ func (c *MetricClient) DeleteOneID(id int) *MetricDeleteOne { // Query returns a query builder for Metric. func (c *MetricClient) Query() *MetricQuery { - return &MetricQuery{config: c.config} + return &MetricQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeMetric}, + inters: c.Interceptors(), + } } // Get returns a Metric entity by its id. @@ -923,8 +1201,8 @@ func (c *MetricClient) GetX(ctx context.Context, id int) *Metric { // QueryGraph queries the graph edge of a Metric. func (c *MetricClient) QueryGraph(m *Metric) *GraphQuery { - query := &GraphQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&GraphClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := m.ID step := sqlgraph.NewStep( sqlgraph.From(metric.Table, metric.FieldID, id), @@ -939,8 +1217,8 @@ func (c *MetricClient) QueryGraph(m *Metric) *GraphQuery { // QueryHistograms queries the histograms edge of a Metric. func (c *MetricClient) QueryHistograms(m *Metric) *HistogramQuery { - query := &HistogramQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&HistogramClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := m.ID step := sqlgraph.NewStep( sqlgraph.From(metric.Table, metric.FieldID, id), @@ -955,8 +1233,8 @@ func (c *MetricClient) QueryHistograms(m *Metric) *HistogramQuery { // QueryCounters queries the counters edge of a Metric. func (c *MetricClient) QueryCounters(m *Metric) *CounterQuery { - query := &CounterQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&CounterClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := m.ID step := sqlgraph.NewStep( sqlgraph.From(metric.Table, metric.FieldID, id), @@ -971,8 +1249,8 @@ func (c *MetricClient) QueryCounters(m *Metric) *CounterQuery { // QueryGauges queries the gauges edge of a Metric. func (c *MetricClient) QueryGauges(m *Metric) *GaugeQuery { - query := &GaugeQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&GaugeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := m.ID step := sqlgraph.NewStep( sqlgraph.From(metric.Table, metric.FieldID, id), @@ -990,6 +1268,26 @@ func (c *MetricClient) Hooks() []Hook { return c.hooks.Metric } +// Interceptors returns the client interceptors. +func (c *MetricClient) Interceptors() []Interceptor { + return c.inters.Metric +} + +func (c *MetricClient) mutate(ctx context.Context, m *MetricMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&MetricCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&MetricUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&MetricUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&MetricDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Metric mutation op: %q", m.Op()) + } +} + // TagClient is a client for the Tag schema. type TagClient struct { config @@ -1006,13 +1304,19 @@ func (c *TagClient) Use(hooks ...Hook) { c.hooks.Tag = append(c.hooks.Tag, hooks...) } -// Create returns a create builder for Tag. +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `tag.Intercept(f(g(h())))`. +func (c *TagClient) Intercept(interceptors ...Interceptor) { + c.inters.Tag = append(c.inters.Tag, interceptors...) +} + +// Create returns a builder for creating a Tag entity. func (c *TagClient) Create() *TagCreate { mutation := newTagMutation(c.config, OpCreate) return &TagCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// BulkCreate returns a builder for creating a bulk of Tag entities. +// CreateBulk returns a builder for creating a bulk of Tag entities. func (c *TagClient) CreateBulk(builders ...*TagCreate) *TagCreateBulk { return &TagCreateBulk{config: c.config, builders: builders} } @@ -1041,12 +1345,12 @@ func (c *TagClient) Delete() *TagDelete { return &TagDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } -// DeleteOne returns a delete builder for the given entity. +// DeleteOne returns a builder for deleting the given entity. func (c *TagClient) DeleteOne(t *Tag) *TagDeleteOne { return c.DeleteOneID(t.ID) } -// DeleteOneID returns a delete builder for the given id. +// DeleteOneID returns a builder for deleting the given entity by its id. func (c *TagClient) DeleteOneID(id int) *TagDeleteOne { builder := c.Delete().Where(tag.ID(id)) builder.mutation.id = &id @@ -1056,7 +1360,11 @@ func (c *TagClient) DeleteOneID(id int) *TagDeleteOne { // Query returns a query builder for Tag. func (c *TagClient) Query() *TagQuery { - return &TagQuery{config: c.config} + return &TagQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTag}, + inters: c.Interceptors(), + } } // Get returns a Tag entity by its id. @@ -1075,8 +1383,8 @@ func (c *TagClient) GetX(ctx context.Context, id int) *Tag { // QueryApplication queries the application edge of a Tag. func (c *TagClient) QueryApplication(t *Tag) *ApplicationQuery { - query := &ApplicationQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + query := (&ApplicationClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { id := t.ID step := sqlgraph.NewStep( sqlgraph.From(tag.Table, tag.FieldID, id), @@ -1093,3 +1401,34 @@ func (c *TagClient) QueryApplication(t *Tag) *ApplicationQuery { func (c *TagClient) Hooks() []Hook { return c.hooks.Tag } + +// Interceptors returns the client interceptors. +func (c *TagClient) Interceptors() []Interceptor { + return c.inters.Tag +} + +func (c *TagClient) mutate(ctx context.Context, m *TagMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TagCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TagUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TagUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TagDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Tag mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + Application, Counter, Gauge, Graph, Group, Histogram, Metric, Tag []ent.Hook + } + inters struct { + Application, Counter, Gauge, Graph, Group, Histogram, Metric, + Tag []ent.Interceptor + } +) diff --git a/ent/config.go b/ent/config.go deleted file mode 100644 index f95e940c..00000000 --- a/ent/config.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package ent - -import ( - "github.com/facebook/ent" - "github.com/facebook/ent/dialect" -) - -// Option function to configure the client. -type Option func(*config) - -// Config is the configuration for the client and its builder. -type config struct { - // driver used for executing database requests. - driver dialect.Driver - // debug enable a debug logging. - debug bool - // log used for logging on debug mode. - log func(...interface{}) - // hooks to execute on mutations. - hooks *hooks -} - -// hooks per client, for fast access. -type hooks struct { - Application []ent.Hook - Counter []ent.Hook - Gauge []ent.Hook - Graph []ent.Hook - Group []ent.Hook - Histogram []ent.Hook - Metric []ent.Hook - Tag []ent.Hook -} - -// Options applies the options on the config object. -func (c *config) options(opts ...Option) { - for _, opt := range opts { - opt(c) - } - if c.debug { - c.driver = dialect.Debug(c.driver, c.log) - } -} - -// Debug enables debug logging on the ent.Driver. -func Debug() Option { - return func(c *config) { - c.debug = true - } -} - -// Log sets the logging function for debug mode. -func Log(fn func(...interface{})) Option { - return func(c *config) { - c.log = fn - } -} - -// Driver configures the client driver. -func Driver(driver dialect.Driver) Option { - return func(c *config) { - c.driver = driver - } -} diff --git a/ent/context.go b/ent/context.go deleted file mode 100644 index b432b596..00000000 --- a/ent/context.go +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package ent - -import ( - "context" -) - -type clientCtxKey struct{} - -// FromContext returns the Client stored in a context, or nil if there isn't one. -func FromContext(ctx context.Context) *Client { - c, _ := ctx.Value(clientCtxKey{}).(*Client) - return c -} - -// NewContext returns a new context with the given Client attached. -func NewContext(parent context.Context, c *Client) context.Context { - return context.WithValue(parent, clientCtxKey{}, c) -} - -type txCtxKey struct{} - -// TxFromContext returns the Tx stored in a context, or nil if there isn't one. -func TxFromContext(ctx context.Context) *Tx { - tx, _ := ctx.Value(txCtxKey{}).(*Tx) - return tx -} - -// NewTxContext returns a new context with the given Client attached. -func NewTxContext(parent context.Context, tx *Tx) context.Context { - return context.WithValue(parent, txCtxKey{}, tx) -} diff --git a/ent/counter.go b/ent/counter.go index 3b76dfd5..758d1c19 100644 --- a/ent/counter.go +++ b/ent/counter.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -6,7 +6,8 @@ import ( "fmt" "strings" - "github.com/facebook/ent/dialect/sql" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/metric" ) @@ -26,12 +27,13 @@ type Counter struct { // The values are being populated by the CounterQuery when eager-loading is set. Edges CounterEdges `json:"edges"` metric_counters *int + selectValues sql.SelectValues } // CounterEdges holds the relations/edges for other nodes in the graph. type CounterEdges struct { // Metric holds the value of the metric edge. - Metric *Metric + Metric *Metric `json:"metric,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [1]bool @@ -42,8 +44,7 @@ type CounterEdges struct { func (e CounterEdges) MetricOrErr() (*Metric, error) { if e.loadedTypes[0] { if e.Metric == nil { - // The edge metric was loaded in eager-loading, - // but was not found. + // Edge was loaded but was not found. return nil, &NotFoundError{label: metric.Label} } return e.Metric, nil @@ -52,81 +53,95 @@ func (e CounterEdges) MetricOrErr() (*Metric, error) { } // scanValues returns the types for scanning values from sql.Rows. -func (*Counter) scanValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // id - &sql.NullInt64{}, // time - &sql.NullInt64{}, // count - &sql.NullString{}, // wID - } -} - -// fkValues returns the types for scanning foreign-keys values from sql.Rows. -func (*Counter) fkValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // metric_counters +func (*Counter) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case counter.FieldID, counter.FieldTime, counter.FieldCount: + values[i] = new(sql.NullInt64) + case counter.FieldWID: + values[i] = new(sql.NullString) + case counter.ForeignKeys[0]: // metric_counters + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } } + return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Counter fields. -func (c *Counter) assignValues(values ...interface{}) error { - if m, n := len(values), len(counter.Columns); m < n { +func (c *Counter) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } - value, ok := values[0].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - c.ID = int(value.Int64) - values = values[1:] - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field time", values[0]) - } else if value.Valid { - c.Time = value.Int64 - } - if value, ok := values[1].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field count", values[1]) - } else if value.Valid { - c.Count = value.Int64 - } - if value, ok := values[2].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field wID", values[2]) - } else if value.Valid { - c.WID = value.String - } - values = values[3:] - if len(values) == len(counter.ForeignKeys) { - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field metric_counters", value) - } else if value.Valid { - c.metric_counters = new(int) - *c.metric_counters = int(value.Int64) + for i := range columns { + switch columns[i] { + case counter.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + c.ID = int(value.Int64) + case counter.FieldTime: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field time", values[i]) + } else if value.Valid { + c.Time = value.Int64 + } + case counter.FieldCount: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field count", values[i]) + } else if value.Valid { + c.Count = value.Int64 + } + case counter.FieldWID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field wID", values[i]) + } else if value.Valid { + c.WID = value.String + } + case counter.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field metric_counters", value) + } else if value.Valid { + c.metric_counters = new(int) + *c.metric_counters = int(value.Int64) + } + default: + c.selectValues.Set(columns[i], values[i]) } } return nil } -// QueryMetric queries the metric edge of the Counter. +// Value returns the ent.Value that was dynamically selected and assigned to the Counter. +// This includes values selected through modifiers, order, etc. +func (c *Counter) Value(name string) (ent.Value, error) { + return c.selectValues.Get(name) +} + +// QueryMetric queries the "metric" edge of the Counter entity. func (c *Counter) QueryMetric() *MetricQuery { - return (&CounterClient{config: c.config}).QueryMetric(c) + return NewCounterClient(c.config).QueryMetric(c) } // Update returns a builder for updating this Counter. -// Note that, you need to call Counter.Unwrap() before calling this method, if this Counter +// Note that you need to call Counter.Unwrap() before calling this method if this Counter // was returned from a transaction, and the transaction was committed or rolled back. func (c *Counter) Update() *CounterUpdateOne { - return (&CounterClient{config: c.config}).UpdateOne(c) + return NewCounterClient(c.config).UpdateOne(c) } -// Unwrap unwraps the entity that was returned from a transaction after it was closed, -// so that all next queries will be executed through the driver which created the transaction. +// Unwrap unwraps the Counter entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. func (c *Counter) Unwrap() *Counter { - tx, ok := c.config.driver.(*txDriver) + _tx, ok := c.config.driver.(*txDriver) if !ok { panic("ent: Counter is not a transactional entity") } - c.config.driver = tx.drv + c.config.driver = _tx.drv return c } @@ -134,12 +149,14 @@ func (c *Counter) Unwrap() *Counter { func (c *Counter) String() string { var builder strings.Builder builder.WriteString("Counter(") - builder.WriteString(fmt.Sprintf("id=%v", c.ID)) - builder.WriteString(", time=") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("time=") builder.WriteString(fmt.Sprintf("%v", c.Time)) - builder.WriteString(", count=") + builder.WriteString(", ") + builder.WriteString("count=") builder.WriteString(fmt.Sprintf("%v", c.Count)) - builder.WriteString(", wID=") + builder.WriteString(", ") + builder.WriteString("wID=") builder.WriteString(c.WID) builder.WriteByte(')') return builder.String() @@ -147,9 +164,3 @@ func (c *Counter) String() string { // Counters is a parsable slice of Counter. type Counters []*Counter - -func (c Counters) config(cfg config) { - for _i := range c { - c[_i].config = cfg - } -} diff --git a/ent/counter/counter.go b/ent/counter/counter.go index 15e6b4a6..4378477d 100644 --- a/ent/counter/counter.go +++ b/ent/counter/counter.go @@ -1,7 +1,12 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package counter +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + const ( // Label holds the string label denoting the counter type in the database. Label = "counter" @@ -13,13 +18,11 @@ const ( FieldCount = "count" // FieldWID holds the string denoting the wid field in the database. FieldWID = "w_id" - // EdgeMetric holds the string denoting the metric edge name in mutations. EdgeMetric = "metric" - // Table holds the table name of the counter in the database. Table = "counters" - // MetricTable is the table the holds the metric relation/edge. + // MetricTable is the table that holds the metric relation/edge. MetricTable = "counters" // MetricInverseTable is the table name for the Metric entity. // It exists in this package in order to avoid circular dependency with the "metric" package. @@ -36,7 +39,8 @@ var Columns = []string{ FieldWID, } -// ForeignKeys holds the SQL foreign-keys that are owned by the Counter type. +// ForeignKeys holds the SQL foreign-keys that are owned by the "counters" +// table and are not defined as standalone fields in the schema. var ForeignKeys = []string{ "metric_counters", } @@ -55,3 +59,40 @@ func ValidColumn(column string) bool { } return false } + +// OrderOption defines the ordering options for the Counter queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByTime orders the results by the time field. +func ByTime(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTime, opts...).ToFunc() +} + +// ByCount orders the results by the count field. +func ByCount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCount, opts...).ToFunc() +} + +// ByWID orders the results by the wID field. +func ByWID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWID, opts...).ToFunc() +} + +// ByMetricField orders the results by metric field. +func ByMetricField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newMetricStep(), sql.OrderByField(field, opts...)) + } +} +func newMetricStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(MetricInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, MetricTable, MetricColumn), + ) +} diff --git a/ent/counter/where.go b/ent/counter/where.go index 258ecebb..2e7a3d45 100644 --- a/ent/counter/where.go +++ b/ent/counter/where.go @@ -1,378 +1,216 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package counter import ( - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" "github.com/gobench-io/gobench/v2/ent/predicate" ) -// ID filters vertices based on their identifier. +// ID filters vertices based on their ID field. func ID(id int) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Counter(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Counter(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) + return predicate.Counter(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) + return predicate.Counter(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) + return predicate.Counter(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) + return predicate.Counter(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) + return predicate.Counter(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) + return predicate.Counter(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) + return predicate.Counter(sql.FieldLTE(FieldID, id)) } // Time applies equality check predicate on the "time" field. It's identical to TimeEQ. func Time(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTime), v)) - }) + return predicate.Counter(sql.FieldEQ(FieldTime, v)) } // Count applies equality check predicate on the "count" field. It's identical to CountEQ. func Count(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCount), v)) - }) + return predicate.Counter(sql.FieldEQ(FieldCount, v)) } // WID applies equality check predicate on the "wID" field. It's identical to WIDEQ. func WID(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldEQ(FieldWID, v)) } // TimeEQ applies the EQ predicate on the "time" field. func TimeEQ(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTime), v)) - }) + return predicate.Counter(sql.FieldEQ(FieldTime, v)) } // TimeNEQ applies the NEQ predicate on the "time" field. func TimeNEQ(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldTime), v)) - }) + return predicate.Counter(sql.FieldNEQ(FieldTime, v)) } // TimeIn applies the In predicate on the "time" field. func TimeIn(vs ...int64) predicate.Counter { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Counter(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldTime), v...)) - }) + return predicate.Counter(sql.FieldIn(FieldTime, vs...)) } // TimeNotIn applies the NotIn predicate on the "time" field. func TimeNotIn(vs ...int64) predicate.Counter { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Counter(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldTime), v...)) - }) + return predicate.Counter(sql.FieldNotIn(FieldTime, vs...)) } // TimeGT applies the GT predicate on the "time" field. func TimeGT(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldTime), v)) - }) + return predicate.Counter(sql.FieldGT(FieldTime, v)) } // TimeGTE applies the GTE predicate on the "time" field. func TimeGTE(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldTime), v)) - }) + return predicate.Counter(sql.FieldGTE(FieldTime, v)) } // TimeLT applies the LT predicate on the "time" field. func TimeLT(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldTime), v)) - }) + return predicate.Counter(sql.FieldLT(FieldTime, v)) } // TimeLTE applies the LTE predicate on the "time" field. func TimeLTE(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldTime), v)) - }) + return predicate.Counter(sql.FieldLTE(FieldTime, v)) } // CountEQ applies the EQ predicate on the "count" field. func CountEQ(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCount), v)) - }) + return predicate.Counter(sql.FieldEQ(FieldCount, v)) } // CountNEQ applies the NEQ predicate on the "count" field. func CountNEQ(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldCount), v)) - }) + return predicate.Counter(sql.FieldNEQ(FieldCount, v)) } // CountIn applies the In predicate on the "count" field. func CountIn(vs ...int64) predicate.Counter { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Counter(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldCount), v...)) - }) + return predicate.Counter(sql.FieldIn(FieldCount, vs...)) } // CountNotIn applies the NotIn predicate on the "count" field. func CountNotIn(vs ...int64) predicate.Counter { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Counter(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldCount), v...)) - }) + return predicate.Counter(sql.FieldNotIn(FieldCount, vs...)) } // CountGT applies the GT predicate on the "count" field. func CountGT(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldCount), v)) - }) + return predicate.Counter(sql.FieldGT(FieldCount, v)) } // CountGTE applies the GTE predicate on the "count" field. func CountGTE(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldCount), v)) - }) + return predicate.Counter(sql.FieldGTE(FieldCount, v)) } // CountLT applies the LT predicate on the "count" field. func CountLT(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldCount), v)) - }) + return predicate.Counter(sql.FieldLT(FieldCount, v)) } // CountLTE applies the LTE predicate on the "count" field. func CountLTE(v int64) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldCount), v)) - }) + return predicate.Counter(sql.FieldLTE(FieldCount, v)) } // WIDEQ applies the EQ predicate on the "wID" field. func WIDEQ(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldEQ(FieldWID, v)) } // WIDNEQ applies the NEQ predicate on the "wID" field. func WIDNEQ(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldNEQ(FieldWID, v)) } // WIDIn applies the In predicate on the "wID" field. func WIDIn(vs ...string) predicate.Counter { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Counter(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldWID), v...)) - }) + return predicate.Counter(sql.FieldIn(FieldWID, vs...)) } // WIDNotIn applies the NotIn predicate on the "wID" field. func WIDNotIn(vs ...string) predicate.Counter { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Counter(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldWID), v...)) - }) + return predicate.Counter(sql.FieldNotIn(FieldWID, vs...)) } // WIDGT applies the GT predicate on the "wID" field. func WIDGT(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldGT(FieldWID, v)) } // WIDGTE applies the GTE predicate on the "wID" field. func WIDGTE(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldGTE(FieldWID, v)) } // WIDLT applies the LT predicate on the "wID" field. func WIDLT(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldLT(FieldWID, v)) } // WIDLTE applies the LTE predicate on the "wID" field. func WIDLTE(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldLTE(FieldWID, v)) } // WIDContains applies the Contains predicate on the "wID" field. func WIDContains(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldContains(FieldWID, v)) } // WIDHasPrefix applies the HasPrefix predicate on the "wID" field. func WIDHasPrefix(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldHasPrefix(FieldWID, v)) } // WIDHasSuffix applies the HasSuffix predicate on the "wID" field. func WIDHasSuffix(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldHasSuffix(FieldWID, v)) } // WIDEqualFold applies the EqualFold predicate on the "wID" field. func WIDEqualFold(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldEqualFold(FieldWID, v)) } // WIDContainsFold applies the ContainsFold predicate on the "wID" field. func WIDContainsFold(v string) predicate.Counter { - return predicate.Counter(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldWID), v)) - }) + return predicate.Counter(sql.FieldContainsFold(FieldWID, v)) } // HasMetric applies the HasEdge predicate on the "metric" edge. @@ -380,7 +218,6 @@ func HasMetric() predicate.Counter { return predicate.Counter(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(MetricTable, FieldID), sqlgraph.Edge(sqlgraph.M2O, true, MetricTable, MetricColumn), ) sqlgraph.HasNeighbors(s, step) @@ -390,11 +227,7 @@ func HasMetric() predicate.Counter { // HasMetricWith applies the HasEdge predicate on the "metric" edge with a given conditions (other predicates). func HasMetricWith(preds ...predicate.Metric) predicate.Counter { return predicate.Counter(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(MetricInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, MetricTable, MetricColumn), - ) + step := newMetricStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -403,7 +236,7 @@ func HasMetricWith(preds ...predicate.Metric) predicate.Counter { }) } -// And groups list of predicates with the AND operator between them. +// And groups predicates with the AND operator between them. func And(predicates ...predicate.Counter) predicate.Counter { return predicate.Counter(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) @@ -414,7 +247,7 @@ func And(predicates ...predicate.Counter) predicate.Counter { }) } -// Or groups list of predicates with the OR operator between them. +// Or groups predicates with the OR operator between them. func Or(predicates ...predicate.Counter) predicate.Counter { return predicate.Counter(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) diff --git a/ent/counter_create.go b/ent/counter_create.go index 8433fd36..819cac86 100644 --- a/ent/counter_create.go +++ b/ent/counter_create.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -7,8 +7,8 @@ import ( "errors" "fmt" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/metric" ) @@ -20,31 +20,31 @@ type CounterCreate struct { hooks []Hook } -// SetTime sets the time field. +// SetTime sets the "time" field. func (cc *CounterCreate) SetTime(i int64) *CounterCreate { cc.mutation.SetTime(i) return cc } -// SetCount sets the count field. +// SetCount sets the "count" field. func (cc *CounterCreate) SetCount(i int64) *CounterCreate { cc.mutation.SetCount(i) return cc } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (cc *CounterCreate) SetWID(s string) *CounterCreate { cc.mutation.SetWID(s) return cc } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by ID. func (cc *CounterCreate) SetMetricID(id int) *CounterCreate { cc.mutation.SetMetricID(id) return cc } -// SetNillableMetricID sets the metric edge to Metric by id if the given value is not nil. +// SetNillableMetricID sets the "metric" edge to the Metric entity by ID if the given value is not nil. func (cc *CounterCreate) SetNillableMetricID(id *int) *CounterCreate { if id != nil { cc = cc.SetMetricID(*id) @@ -52,7 +52,7 @@ func (cc *CounterCreate) SetNillableMetricID(id *int) *CounterCreate { return cc } -// SetMetric sets the metric edge to Metric. +// SetMetric sets the "metric" edge to the Metric entity. func (cc *CounterCreate) SetMetric(m *Metric) *CounterCreate { return cc.SetMetricID(m.ID) } @@ -64,37 +64,7 @@ func (cc *CounterCreate) Mutation() *CounterMutation { // Save creates the Counter in the database. func (cc *CounterCreate) Save(ctx context.Context) (*Counter, error) { - var ( - err error - node *Counter - ) - if len(cc.hooks) == 0 { - if err = cc.check(); err != nil { - return nil, err - } - node, err = cc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*CounterMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = cc.check(); err != nil { - return nil, err - } - cc.mutation = mutation - node, err = cc.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(cc.hooks) - 1; i >= 0; i-- { - mut = cc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, cc.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, cc.sqlSave, cc.mutation, cc.hooks) } // SaveX calls Save and panics if Save returns an error. @@ -106,66 +76,66 @@ func (cc *CounterCreate) SaveX(ctx context.Context) *Counter { return v } +// Exec executes the query. +func (cc *CounterCreate) Exec(ctx context.Context) error { + _, err := cc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cc *CounterCreate) ExecX(ctx context.Context) { + if err := cc.Exec(ctx); err != nil { + panic(err) + } +} + // check runs all checks and user-defined validators on the builder. func (cc *CounterCreate) check() error { if _, ok := cc.mutation.Time(); !ok { - return &ValidationError{Name: "time", err: errors.New("ent: missing required field \"time\"")} + return &ValidationError{Name: "time", err: errors.New(`ent: missing required field "Counter.time"`)} } if _, ok := cc.mutation.Count(); !ok { - return &ValidationError{Name: "count", err: errors.New("ent: missing required field \"count\"")} + return &ValidationError{Name: "count", err: errors.New(`ent: missing required field "Counter.count"`)} } if _, ok := cc.mutation.WID(); !ok { - return &ValidationError{Name: "wID", err: errors.New("ent: missing required field \"wID\"")} + return &ValidationError{Name: "wID", err: errors.New(`ent: missing required field "Counter.wID"`)} } return nil } func (cc *CounterCreate) sqlSave(ctx context.Context) (*Counter, error) { + if err := cc.check(); err != nil { + return nil, err + } _node, _spec := cc.createSpec() if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } id := _spec.ID.Value.(int64) _node.ID = int(id) + cc.mutation.id = &_node.ID + cc.mutation.done = true return _node, nil } func (cc *CounterCreate) createSpec() (*Counter, *sqlgraph.CreateSpec) { var ( _node = &Counter{config: cc.config} - _spec = &sqlgraph.CreateSpec{ - Table: counter.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, - } + _spec = sqlgraph.NewCreateSpec(counter.Table, sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt)) ) if value, ok := cc.mutation.Time(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldTime, - }) + _spec.SetField(counter.FieldTime, field.TypeInt64, value) _node.Time = value } if value, ok := cc.mutation.Count(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldCount, - }) + _spec.SetField(counter.FieldCount, field.TypeInt64, value) _node.Count = value } if value, ok := cc.mutation.WID(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: counter.FieldWID, - }) + _spec.SetField(counter.FieldWID, field.TypeString, value) _node.WID = value } if nodes := cc.mutation.MetricIDs(); len(nodes) > 0 { @@ -176,21 +146,19 @@ func (cc *CounterCreate) createSpec() (*Counter, *sqlgraph.CreateSpec) { Columns: []string{counter.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } + _node.metric_counters = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } return _node, _spec } -// CounterCreateBulk is the builder for creating a bulk of Counter entities. +// CounterCreateBulk is the builder for creating many Counter entities in bulk. type CounterCreateBulk struct { config builders []*CounterCreate @@ -213,24 +181,28 @@ func (ccb *CounterCreateBulk) Save(ctx context.Context) ([]*Counter, error) { return nil, err } builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() var err error + nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, ccb.builders[i+1].mutation) } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, ccb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if err = sqlgraph.BatchCreate(ctx, ccb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } } } - mutation.done = true if err != nil { return nil, err } - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { @@ -247,7 +219,7 @@ func (ccb *CounterCreateBulk) Save(ctx context.Context) ([]*Counter, error) { return nodes, nil } -// SaveX calls Save and panics if Save returns an error. +// SaveX is like Save, but panics if an error occurs. func (ccb *CounterCreateBulk) SaveX(ctx context.Context) []*Counter { v, err := ccb.Save(ctx) if err != nil { @@ -255,3 +227,16 @@ func (ccb *CounterCreateBulk) SaveX(ctx context.Context) []*Counter { } return v } + +// Exec executes the query. +func (ccb *CounterCreateBulk) Exec(ctx context.Context) error { + _, err := ccb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ccb *CounterCreateBulk) ExecX(ctx context.Context) { + if err := ccb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/counter_delete.go b/ent/counter_delete.go index a2e7cbb8..4e53f3c5 100644 --- a/ent/counter_delete.go +++ b/ent/counter_delete.go @@ -1,14 +1,13 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/predicate" ) @@ -16,44 +15,19 @@ import ( // CounterDelete is the builder for deleting a Counter entity. type CounterDelete struct { config - hooks []Hook - mutation *CounterMutation - predicates []predicate.Counter + hooks []Hook + mutation *CounterMutation } -// Where adds a new predicate to the delete builder. +// Where appends a list predicates to the CounterDelete builder. func (cd *CounterDelete) Where(ps ...predicate.Counter) *CounterDelete { - cd.predicates = append(cd.predicates, ps...) + cd.mutation.Where(ps...) return cd } // Exec executes the deletion query and returns how many vertices were deleted. func (cd *CounterDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(cd.hooks) == 0 { - affected, err = cd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*CounterMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - cd.mutation = mutation - affected, err = cd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(cd.hooks) - 1; i >= 0; i-- { - mut = cd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, cd.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, cd.sqlExec, cd.mutation, cd.hooks) } // ExecX is like Exec, but panics if an error occurs. @@ -66,23 +40,20 @@ func (cd *CounterDelete) ExecX(ctx context.Context) int { } func (cd *CounterDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: counter.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, - }, - } - if ps := cd.predicates; len(ps) > 0 { + _spec := sqlgraph.NewDeleteSpec(counter.Table, sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt)) + if ps := cd.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - return sqlgraph.DeleteNodes(ctx, cd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, cd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + cd.mutation.done = true + return affected, err } // CounterDeleteOne is the builder for deleting a single Counter entity. @@ -90,6 +61,12 @@ type CounterDeleteOne struct { cd *CounterDelete } +// Where appends a list predicates to the CounterDelete builder. +func (cdo *CounterDeleteOne) Where(ps ...predicate.Counter) *CounterDeleteOne { + cdo.cd.mutation.Where(ps...) + return cdo +} + // Exec executes the deletion query. func (cdo *CounterDeleteOne) Exec(ctx context.Context) error { n, err := cdo.cd.Exec(ctx) @@ -105,5 +82,7 @@ func (cdo *CounterDeleteOne) Exec(ctx context.Context) error { // ExecX is like Exec, but panics if an error occurs. func (cdo *CounterDeleteOne) ExecX(ctx context.Context) { - cdo.cd.ExecX(ctx) + if err := cdo.Exec(ctx); err != nil { + panic(err) + } } diff --git a/ent/counter_query.go b/ent/counter_query.go index 7484f0a5..39de7dd8 100644 --- a/ent/counter_query.go +++ b/ent/counter_query.go @@ -1,16 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "errors" "fmt" "math" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/metric" "github.com/gobench-io/gobench/v2/ent/predicate" @@ -19,12 +18,10 @@ import ( // CounterQuery is the builder for querying Counter entities. type CounterQuery struct { config - limit *int - offset *int - order []OrderFunc - unique []string + ctx *QueryContext + order []counter.OrderOption + inters []Interceptor predicates []predicate.Counter - // eager-loading edges. withMetric *MetricQuery withFKs bool // intermediate query (i.e. traversal path). @@ -32,38 +29,45 @@ type CounterQuery struct { path func(context.Context) (*sql.Selector, error) } -// Where adds a new predicate for the builder. +// Where adds a new predicate for the CounterQuery builder. func (cq *CounterQuery) Where(ps ...predicate.Counter) *CounterQuery { cq.predicates = append(cq.predicates, ps...) return cq } -// Limit adds a limit step to the query. +// Limit the number of records to be returned by this query. func (cq *CounterQuery) Limit(limit int) *CounterQuery { - cq.limit = &limit + cq.ctx.Limit = &limit return cq } -// Offset adds an offset step to the query. +// Offset to start from. func (cq *CounterQuery) Offset(offset int) *CounterQuery { - cq.offset = &offset + cq.ctx.Offset = &offset return cq } -// Order adds an order step to the query. -func (cq *CounterQuery) Order(o ...OrderFunc) *CounterQuery { +// 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 (cq *CounterQuery) Unique(unique bool) *CounterQuery { + cq.ctx.Unique = &unique + return cq +} + +// Order specifies how the records should be ordered. +func (cq *CounterQuery) Order(o ...counter.OrderOption) *CounterQuery { cq.order = append(cq.order, o...) return cq } -// QueryMetric chains the current query on the metric edge. +// QueryMetric chains the current query on the "metric" edge. func (cq *CounterQuery) QueryMetric() *MetricQuery { - query := &MetricQuery{config: cq.config} + query := (&MetricClient{config: cq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := cq.prepareQuery(ctx); err != nil { return nil, err } - selector := cq.sqlQuery() + selector := cq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -78,9 +82,10 @@ func (cq *CounterQuery) QueryMetric() *MetricQuery { return query } -// First returns the first Counter entity in the query. Returns *NotFoundError when no counter was found. +// First returns the first Counter entity from the query. +// Returns a *NotFoundError when no Counter was found. func (cq *CounterQuery) First(ctx context.Context) (*Counter, error) { - nodes, err := cq.Limit(1).All(ctx) + nodes, err := cq.Limit(1).All(setContextOp(ctx, cq.ctx, "First")) if err != nil { return nil, err } @@ -99,10 +104,11 @@ func (cq *CounterQuery) FirstX(ctx context.Context) *Counter { return node } -// FirstID returns the first Counter id in the query. Returns *NotFoundError when no id was found. +// FirstID returns the first Counter ID from the query. +// Returns a *NotFoundError when no Counter ID was found. func (cq *CounterQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = cq.Limit(1).IDs(ctx); err != nil { + if ids, err = cq.Limit(1).IDs(setContextOp(ctx, cq.ctx, "FirstID")); err != nil { return } if len(ids) == 0 { @@ -112,8 +118,8 @@ func (cq *CounterQuery) FirstID(ctx context.Context) (id int, err error) { return ids[0], nil } -// FirstXID is like FirstID, but panics if an error occurs. -func (cq *CounterQuery) FirstXID(ctx context.Context) int { +// FirstIDX is like FirstID, but panics if an error occurs. +func (cq *CounterQuery) FirstIDX(ctx context.Context) int { id, err := cq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -121,9 +127,11 @@ func (cq *CounterQuery) FirstXID(ctx context.Context) int { return id } -// Only returns the only Counter entity in the query, returns an error if not exactly one entity was returned. +// Only returns a single Counter entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Counter entity is found. +// Returns a *NotFoundError when no Counter entities are found. func (cq *CounterQuery) Only(ctx context.Context) (*Counter, error) { - nodes, err := cq.Limit(2).All(ctx) + nodes, err := cq.Limit(2).All(setContextOp(ctx, cq.ctx, "Only")) if err != nil { return nil, err } @@ -146,10 +154,12 @@ func (cq *CounterQuery) OnlyX(ctx context.Context) *Counter { return node } -// OnlyID returns the only Counter id in the query, returns an error if not exactly one id was returned. +// OnlyID is like Only, but returns the only Counter ID in the query. +// Returns a *NotSingularError when more than one Counter ID is found. +// Returns a *NotFoundError when no entities are found. func (cq *CounterQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = cq.Limit(2).IDs(ctx); err != nil { + if ids, err = cq.Limit(2).IDs(setContextOp(ctx, cq.ctx, "OnlyID")); err != nil { return } switch len(ids) { @@ -174,10 +184,12 @@ func (cq *CounterQuery) OnlyIDX(ctx context.Context) int { // All executes the query and returns a list of Counters. func (cq *CounterQuery) All(ctx context.Context) ([]*Counter, error) { + ctx = setContextOp(ctx, cq.ctx, "All") if err := cq.prepareQuery(ctx); err != nil { return nil, err } - return cq.sqlAll(ctx) + qr := querierAll[[]*Counter, *CounterQuery]() + return withInterceptors[[]*Counter](ctx, cq, qr, cq.inters) } // AllX is like All, but panics if an error occurs. @@ -189,10 +201,13 @@ func (cq *CounterQuery) AllX(ctx context.Context) []*Counter { return nodes } -// IDs executes the query and returns a list of Counter ids. -func (cq *CounterQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := cq.Select(counter.FieldID).Scan(ctx, &ids); err != nil { +// IDs executes the query and returns a list of Counter IDs. +func (cq *CounterQuery) IDs(ctx context.Context) (ids []int, err error) { + if cq.ctx.Unique == nil && cq.path != nil { + cq.Unique(true) + } + ctx = setContextOp(ctx, cq.ctx, "IDs") + if err = cq.Select(counter.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil @@ -209,10 +224,11 @@ func (cq *CounterQuery) IDsX(ctx context.Context) []int { // Count returns the count of the given query. func (cq *CounterQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, cq.ctx, "Count") if err := cq.prepareQuery(ctx); err != nil { return 0, err } - return cq.sqlCount(ctx) + return withInterceptors[int](ctx, cq, querierCount[*CounterQuery](), cq.inters) } // CountX is like Count, but panics if an error occurs. @@ -226,10 +242,15 @@ func (cq *CounterQuery) CountX(ctx context.Context) int { // Exist returns true if the query has elements in the graph. func (cq *CounterQuery) Exist(ctx context.Context) (bool, error) { - if err := cq.prepareQuery(ctx); err != nil { - return false, err + ctx = setContextOp(ctx, cq.ctx, "Exist") + switch _, err := cq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil } - return cq.sqlExist(ctx) } // ExistX is like Exist, but panics if an error occurs. @@ -241,26 +262,29 @@ func (cq *CounterQuery) ExistX(ctx context.Context) bool { return exist } -// Clone returns a duplicate of the query builder, including all associated steps. It can be +// Clone returns a duplicate of the CounterQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. func (cq *CounterQuery) Clone() *CounterQuery { + if cq == nil { + return nil + } return &CounterQuery{ config: cq.config, - limit: cq.limit, - offset: cq.offset, - order: append([]OrderFunc{}, cq.order...), - unique: append([]string{}, cq.unique...), + ctx: cq.ctx.Clone(), + order: append([]counter.OrderOption{}, cq.order...), + inters: append([]Interceptor{}, cq.inters...), predicates: append([]predicate.Counter{}, cq.predicates...), + withMetric: cq.withMetric.Clone(), // clone intermediate query. sql: cq.sql.Clone(), path: cq.path, } } -// WithMetric tells the query-builder to eager-loads the nodes that are connected to -// the "metric" edge. The optional arguments used to configure the query builder of the edge. +// WithMetric tells the query-builder to eager-load the nodes that are connected to +// the "metric" edge. The optional arguments are used to configure the query builder of the edge. func (cq *CounterQuery) WithMetric(opts ...func(*MetricQuery)) *CounterQuery { - query := &MetricQuery{config: cq.config} + query := (&MetricClient{config: cq.config}).Query() for _, opt := range opts { opt(query) } @@ -268,7 +292,7 @@ func (cq *CounterQuery) WithMetric(opts ...func(*MetricQuery)) *CounterQuery { return cq } -// GroupBy used to group vertices by one or more fields/columns. +// 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: @@ -282,20 +306,17 @@ func (cq *CounterQuery) WithMetric(opts ...func(*MetricQuery)) *CounterQuery { // GroupBy(counter.FieldTime). // Aggregate(ent.Count()). // Scan(ctx, &v) -// func (cq *CounterQuery) GroupBy(field string, fields ...string) *CounterGroupBy { - group := &CounterGroupBy{config: cq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := cq.prepareQuery(ctx); err != nil { - return nil, err - } - return cq.sqlQuery(), nil - } - return group + cq.ctx.Fields = append([]string{field}, fields...) + grbuild := &CounterGroupBy{build: cq} + grbuild.flds = &cq.ctx.Fields + grbuild.label = counter.Label + grbuild.scan = grbuild.Scan + return grbuild } -// Select one or more fields from the given query. +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. // // Example: // @@ -306,20 +327,35 @@ func (cq *CounterQuery) GroupBy(field string, fields ...string) *CounterGroupBy // client.Counter.Query(). // Select(counter.FieldTime). // Scan(ctx, &v) -// -func (cq *CounterQuery) Select(field string, fields ...string) *CounterSelect { - selector := &CounterSelect{config: cq.config} - selector.fields = append([]string{field}, fields...) - selector.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := cq.prepareQuery(ctx); err != nil { - return nil, err - } - return cq.sqlQuery(), nil - } - return selector +func (cq *CounterQuery) Select(fields ...string) *CounterSelect { + cq.ctx.Fields = append(cq.ctx.Fields, fields...) + sbuild := &CounterSelect{CounterQuery: cq} + sbuild.label = counter.Label + sbuild.flds, sbuild.scan = &cq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CounterSelect configured with the given aggregations. +func (cq *CounterQuery) Aggregate(fns ...AggregateFunc) *CounterSelect { + return cq.Select().Aggregate(fns...) } func (cq *CounterQuery) prepareQuery(ctx context.Context) error { + for _, inter := range cq.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, cq); err != nil { + return err + } + } + } + for _, f := range cq.ctx.Fields { + if !counter.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } if cq.path != nil { prev, err := cq.path(ctx) if err != nil { @@ -330,7 +366,7 @@ func (cq *CounterQuery) prepareQuery(ctx context.Context) error { return nil } -func (cq *CounterQuery) sqlAll(ctx context.Context) ([]*Counter, error) { +func (cq *CounterQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Counter, error) { var ( nodes = []*Counter{} withFKs = cq.withFKs @@ -345,22 +381,17 @@ func (cq *CounterQuery) sqlAll(ctx context.Context) ([]*Counter, error) { if withFKs { _spec.Node.Columns = append(_spec.Node.Columns, counter.ForeignKeys...) } - _spec.ScanValues = func() []interface{} { + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Counter).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { node := &Counter{config: cq.config} nodes = append(nodes, node) - values := node.scanValues() - if withFKs { - values = append(values, node.fkValues()...) - } - return values - } - _spec.Assign = func(values ...interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("ent: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] node.Edges.loadedTypes = loadedTypes - return node.assignValues(values...) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) } if err := sqlgraph.QueryNodes(ctx, cq.driver, _spec); err != nil { return nil, err @@ -368,60 +399,73 @@ func (cq *CounterQuery) sqlAll(ctx context.Context) ([]*Counter, error) { if len(nodes) == 0 { return nodes, nil } - if query := cq.withMetric; query != nil { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*Counter) - for i := range nodes { - if fk := nodes[i].metric_counters; fk != nil { - ids = append(ids, *fk) - nodeids[*fk] = append(nodeids[*fk], nodes[i]) - } - } - query.Where(metric.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { + if err := cq.loadMetric(ctx, query, nodes, nil, + func(n *Counter, e *Metric) { n.Edges.Metric = e }); err != nil { return nil, err } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "metric_counters" returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.Metric = n - } - } } - return nodes, nil } -func (cq *CounterQuery) sqlCount(ctx context.Context) (int, error) { - _spec := cq.querySpec() - return sqlgraph.CountNodes(ctx, cq.driver, _spec) +func (cq *CounterQuery) loadMetric(ctx context.Context, query *MetricQuery, nodes []*Counter, init func(*Counter), assign func(*Counter, *Metric)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Counter) + for i := range nodes { + if nodes[i].metric_counters == nil { + continue + } + fk := *nodes[i].metric_counters + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(metric.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 "metric_counters" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil } -func (cq *CounterQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := cq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("ent: check existence: %v", err) +func (cq *CounterQuery) sqlCount(ctx context.Context) (int, error) { + _spec := cq.querySpec() + _spec.Node.Columns = cq.ctx.Fields + if len(cq.ctx.Fields) > 0 { + _spec.Unique = cq.ctx.Unique != nil && *cq.ctx.Unique } - return n > 0, nil + return sqlgraph.CountNodes(ctx, cq.driver, _spec) } func (cq *CounterQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: counter.Table, - Columns: counter.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, - }, - From: cq.sql, - Unique: true, + _spec := sqlgraph.NewQuerySpec(counter.Table, counter.Columns, sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt)) + _spec.From = cq.sql + if unique := cq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if cq.path != nil { + _spec.Unique = true + } + if fields := cq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, counter.FieldID) + for i := range fields { + if fields[i] != counter.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } } if ps := cq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -430,55 +474,58 @@ func (cq *CounterQuery) querySpec() *sqlgraph.QuerySpec { } } } - if limit := cq.limit; limit != nil { + if limit := cq.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := cq.offset; offset != nil { + if offset := cq.ctx.Offset; offset != nil { _spec.Offset = *offset } if ps := cq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector, counter.ValidColumn) + ps[i](selector) } } } return _spec } -func (cq *CounterQuery) sqlQuery() *sql.Selector { +func (cq *CounterQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(cq.driver.Dialect()) t1 := builder.Table(counter.Table) - selector := builder.Select(t1.Columns(counter.Columns...)...).From(t1) + columns := cq.ctx.Fields + if len(columns) == 0 { + columns = counter.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) if cq.sql != nil { selector = cq.sql - selector.Select(selector.Columns(counter.Columns...)...) + selector.Select(selector.Columns(columns...)...) + } + if cq.ctx.Unique != nil && *cq.ctx.Unique { + selector.Distinct() } for _, p := range cq.predicates { p(selector) } for _, p := range cq.order { - p(selector, counter.ValidColumn) + p(selector) } - if offset := cq.offset; offset != nil { + if offset := cq.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 := cq.limit; limit != nil { + if limit := cq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector } -// CounterGroupBy is the builder for group-by Counter entities. +// CounterGroupBy is the group-by builder for Counter entities. type CounterGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) + selector + build *CounterQuery } // Aggregate adds the given aggregation functions to the group-by query. @@ -487,471 +534,80 @@ func (cgb *CounterGroupBy) Aggregate(fns ...AggregateFunc) *CounterGroupBy { return cgb } -// Scan applies the group-by query and scan the result into the given value. -func (cgb *CounterGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := cgb.path(ctx) - if err != nil { +// Scan applies the selector query and scans the result into the given value. +func (cgb *CounterGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, cgb.build.ctx, "GroupBy") + if err := cgb.build.prepareQuery(ctx); err != nil { return err } - cgb.sql = query - return cgb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (cgb *CounterGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := cgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field. -func (cgb *CounterGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(cgb.fields) > 1 { - return nil, errors.New("ent: CounterGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := cgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (cgb *CounterGroupBy) StringsX(ctx context.Context) []string { - v, err := cgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from group-by. It is only allowed when querying group-by with one field. -func (cgb *CounterGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = cgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{counter.Label} - default: - err = fmt.Errorf("ent: CounterGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (cgb *CounterGroupBy) StringX(ctx context.Context) string { - v, err := cgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field. -func (cgb *CounterGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(cgb.fields) > 1 { - return nil, errors.New("ent: CounterGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := cgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (cgb *CounterGroupBy) IntsX(ctx context.Context) []int { - v, err := cgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from group-by. It is only allowed when querying group-by with one field. -func (cgb *CounterGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = cgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{counter.Label} - default: - err = fmt.Errorf("ent: CounterGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (cgb *CounterGroupBy) IntX(ctx context.Context) int { - v, err := cgb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field. -func (cgb *CounterGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(cgb.fields) > 1 { - return nil, errors.New("ent: CounterGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := cgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (cgb *CounterGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := cgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field. -func (cgb *CounterGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = cgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{counter.Label} - default: - err = fmt.Errorf("ent: CounterGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (cgb *CounterGroupBy) Float64X(ctx context.Context) float64 { - v, err := cgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field. -func (cgb *CounterGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(cgb.fields) > 1 { - return nil, errors.New("ent: CounterGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := cgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil + return scanWithInterceptors[*CounterQuery, *CounterGroupBy](ctx, cgb.build, cgb, cgb.build.inters, v) } -// BoolsX is like Bools, but panics if an error occurs. -func (cgb *CounterGroupBy) BoolsX(ctx context.Context) []bool { - v, err := cgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field. -func (cgb *CounterGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = cgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{counter.Label} - default: - err = fmt.Errorf("ent: CounterGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (cgb *CounterGroupBy) BoolX(ctx context.Context) bool { - v, err := cgb.Bool(ctx) - if err != nil { - panic(err) +func (cgb *CounterGroupBy) sqlScan(ctx context.Context, root *CounterQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(cgb.fns)) + for _, fn := range cgb.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (cgb *CounterGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range cgb.fields { - if !counter.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*cgb.flds)+len(cgb.fns)) + for _, f := range *cgb.flds { + columns = append(columns, selector.C(f)) } + columns = append(columns, aggregation...) + selector.Select(columns...) } - selector := cgb.sqlQuery() + selector.GroupBy(selector.Columns(*cgb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := cgb.driver.Query(ctx, query, args, rows); err != nil { + if err := cgb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } -func (cgb *CounterGroupBy) sqlQuery() *sql.Selector { - selector := cgb.sql - columns := make([]string, 0, len(cgb.fields)+len(cgb.fns)) - columns = append(columns, cgb.fields...) - for _, fn := range cgb.fns { - columns = append(columns, fn(selector, counter.ValidColumn)) - } - return selector.Select(columns...).GroupBy(cgb.fields...) -} - -// CounterSelect is the builder for select fields of Counter entities. +// CounterSelect is the builder for selecting fields of Counter entities. type CounterSelect struct { - config - fields []string - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Scan applies the selector query and scan the result into the given value. -func (cs *CounterSelect) Scan(ctx context.Context, v interface{}) error { - query, err := cs.path(ctx) - if err != nil { - return err - } - cs.sql = query - return cs.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (cs *CounterSelect) ScanX(ctx context.Context, v interface{}) { - if err := cs.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from selector. It is only allowed when selecting one field. -func (cs *CounterSelect) Strings(ctx context.Context) ([]string, error) { - if len(cs.fields) > 1 { - return nil, errors.New("ent: CounterSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := cs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (cs *CounterSelect) StringsX(ctx context.Context) []string { - v, err := cs.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from selector. It is only allowed when selecting one field. -func (cs *CounterSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = cs.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{counter.Label} - default: - err = fmt.Errorf("ent: CounterSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (cs *CounterSelect) StringX(ctx context.Context) string { - v, err := cs.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from selector. It is only allowed when selecting one field. -func (cs *CounterSelect) Ints(ctx context.Context) ([]int, error) { - if len(cs.fields) > 1 { - return nil, errors.New("ent: CounterSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := cs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (cs *CounterSelect) IntsX(ctx context.Context) []int { - v, err := cs.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from selector. It is only allowed when selecting one field. -func (cs *CounterSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = cs.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{counter.Label} - default: - err = fmt.Errorf("ent: CounterSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (cs *CounterSelect) IntX(ctx context.Context) int { - v, err := cs.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from selector. It is only allowed when selecting one field. -func (cs *CounterSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(cs.fields) > 1 { - return nil, errors.New("ent: CounterSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := cs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (cs *CounterSelect) Float64sX(ctx context.Context) []float64 { - v, err := cs.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from selector. It is only allowed when selecting one field. -func (cs *CounterSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = cs.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{counter.Label} - default: - err = fmt.Errorf("ent: CounterSelect.Float64s returned %d results when one was expected", len(v)) - } - return + *CounterQuery + selector } -// Float64X is like Float64, but panics if an error occurs. -func (cs *CounterSelect) Float64X(ctx context.Context) float64 { - v, err := cs.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from selector. It is only allowed when selecting one field. -func (cs *CounterSelect) Bools(ctx context.Context) ([]bool, error) { - if len(cs.fields) > 1 { - return nil, errors.New("ent: CounterSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := cs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (cs *CounterSelect) BoolsX(ctx context.Context) []bool { - v, err := cs.Bools(ctx) - if err != nil { - panic(err) - } - return v +// Aggregate adds the given aggregation functions to the selector query. +func (cs *CounterSelect) Aggregate(fns ...AggregateFunc) *CounterSelect { + cs.fns = append(cs.fns, fns...) + return cs } -// Bool returns a single bool from selector. It is only allowed when selecting one field. -func (cs *CounterSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = cs.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{counter.Label} - default: - err = fmt.Errorf("ent: CounterSelect.Bools returned %d results when one was expected", len(v)) +// Scan applies the selector query and scans the result into the given value. +func (cs *CounterSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, cs.ctx, "Select") + if err := cs.prepareQuery(ctx); err != nil { + return err } - return + return scanWithInterceptors[*CounterQuery, *CounterSelect](ctx, cs.CounterQuery, cs, cs.inters, v) } -// BoolX is like Bool, but panics if an error occurs. -func (cs *CounterSelect) BoolX(ctx context.Context) bool { - v, err := cs.Bool(ctx) - if err != nil { - panic(err) +func (cs *CounterSelect) sqlScan(ctx context.Context, root *CounterQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(cs.fns)) + for _, fn := range cs.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (cs *CounterSelect) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range cs.fields { - if !counter.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} - } + switch n := len(*cs.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 := cs.sqlQuery().Query() + query, args := selector.Query() if err := cs.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } - -func (cs *CounterSelect) sqlQuery() sql.Querier { - selector := cs.sql - selector.Select(selector.Columns(cs.fields...)...) - return selector -} diff --git a/ent/counter_update.go b/ent/counter_update.go index ee21fa86..56ffe3ba 100644 --- a/ent/counter_update.go +++ b/ent/counter_update.go @@ -1,14 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/metric" "github.com/gobench-io/gobench/v2/ent/predicate" @@ -17,56 +18,55 @@ import ( // CounterUpdate is the builder for updating Counter entities. type CounterUpdate struct { config - hooks []Hook - mutation *CounterMutation - predicates []predicate.Counter + hooks []Hook + mutation *CounterMutation } -// Where adds a new predicate for the builder. +// Where appends a list predicates to the CounterUpdate builder. func (cu *CounterUpdate) Where(ps ...predicate.Counter) *CounterUpdate { - cu.predicates = append(cu.predicates, ps...) + cu.mutation.Where(ps...) return cu } -// SetTime sets the time field. +// SetTime sets the "time" field. func (cu *CounterUpdate) SetTime(i int64) *CounterUpdate { cu.mutation.ResetTime() cu.mutation.SetTime(i) return cu } -// AddTime adds i to time. +// AddTime adds i to the "time" field. func (cu *CounterUpdate) AddTime(i int64) *CounterUpdate { cu.mutation.AddTime(i) return cu } -// SetCount sets the count field. +// SetCount sets the "count" field. func (cu *CounterUpdate) SetCount(i int64) *CounterUpdate { cu.mutation.ResetCount() cu.mutation.SetCount(i) return cu } -// AddCount adds i to count. +// AddCount adds i to the "count" field. func (cu *CounterUpdate) AddCount(i int64) *CounterUpdate { cu.mutation.AddCount(i) return cu } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (cu *CounterUpdate) SetWID(s string) *CounterUpdate { cu.mutation.SetWID(s) return cu } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by ID. func (cu *CounterUpdate) SetMetricID(id int) *CounterUpdate { cu.mutation.SetMetricID(id) return cu } -// SetNillableMetricID sets the metric edge to Metric by id if the given value is not nil. +// SetNillableMetricID sets the "metric" edge to the Metric entity by ID if the given value is not nil. func (cu *CounterUpdate) SetNillableMetricID(id *int) *CounterUpdate { if id != nil { cu = cu.SetMetricID(*id) @@ -74,7 +74,7 @@ func (cu *CounterUpdate) SetNillableMetricID(id *int) *CounterUpdate { return cu } -// SetMetric sets the metric edge to Metric. +// SetMetric sets the "metric" edge to the Metric entity. func (cu *CounterUpdate) SetMetric(m *Metric) *CounterUpdate { return cu.SetMetricID(m.ID) } @@ -84,39 +84,15 @@ func (cu *CounterUpdate) Mutation() *CounterMutation { return cu.mutation } -// ClearMetric clears the "metric" edge to type Metric. +// ClearMetric clears the "metric" edge to the Metric entity. func (cu *CounterUpdate) ClearMetric() *CounterUpdate { cu.mutation.ClearMetric() return cu } -// Save executes the query and returns the number of rows/vertices matched by this operation. +// Save executes the query and returns the number of nodes affected by the update operation. func (cu *CounterUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(cu.hooks) == 0 { - affected, err = cu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*CounterMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - cu.mutation = mutation - affected, err = cu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(cu.hooks) - 1; i >= 0; i-- { - mut = cu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, cu.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, cu.sqlSave, cu.mutation, cu.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -142,17 +118,8 @@ func (cu *CounterUpdate) ExecX(ctx context.Context) { } func (cu *CounterUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: counter.Table, - Columns: counter.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, - }, - } - if ps := cu.predicates; len(ps) > 0 { + _spec := sqlgraph.NewUpdateSpec(counter.Table, counter.Columns, sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt)) + if ps := cu.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -160,39 +127,19 @@ func (cu *CounterUpdate) sqlSave(ctx context.Context) (n int, err error) { } } if value, ok := cu.mutation.Time(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldTime, - }) + _spec.SetField(counter.FieldTime, field.TypeInt64, value) } if value, ok := cu.mutation.AddedTime(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldTime, - }) + _spec.AddField(counter.FieldTime, field.TypeInt64, value) } if value, ok := cu.mutation.Count(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldCount, - }) + _spec.SetField(counter.FieldCount, field.TypeInt64, value) } if value, ok := cu.mutation.AddedCount(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldCount, - }) + _spec.AddField(counter.FieldCount, field.TypeInt64, value) } if value, ok := cu.mutation.WID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: counter.FieldWID, - }) + _spec.SetField(counter.FieldWID, field.TypeString, value) } if cu.mutation.MetricCleared() { edge := &sqlgraph.EdgeSpec{ @@ -202,10 +149,7 @@ func (cu *CounterUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{counter.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -218,10 +162,7 @@ func (cu *CounterUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{counter.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -232,60 +173,62 @@ func (cu *CounterUpdate) sqlSave(ctx context.Context) (n int, err error) { if n, err = sqlgraph.UpdateNodes(ctx, cu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{counter.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } + cu.mutation.done = true return n, nil } // CounterUpdateOne is the builder for updating a single Counter entity. type CounterUpdateOne struct { config + fields []string hooks []Hook mutation *CounterMutation } -// SetTime sets the time field. +// SetTime sets the "time" field. func (cuo *CounterUpdateOne) SetTime(i int64) *CounterUpdateOne { cuo.mutation.ResetTime() cuo.mutation.SetTime(i) return cuo } -// AddTime adds i to time. +// AddTime adds i to the "time" field. func (cuo *CounterUpdateOne) AddTime(i int64) *CounterUpdateOne { cuo.mutation.AddTime(i) return cuo } -// SetCount sets the count field. +// SetCount sets the "count" field. func (cuo *CounterUpdateOne) SetCount(i int64) *CounterUpdateOne { cuo.mutation.ResetCount() cuo.mutation.SetCount(i) return cuo } -// AddCount adds i to count. +// AddCount adds i to the "count" field. func (cuo *CounterUpdateOne) AddCount(i int64) *CounterUpdateOne { cuo.mutation.AddCount(i) return cuo } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (cuo *CounterUpdateOne) SetWID(s string) *CounterUpdateOne { cuo.mutation.SetWID(s) return cuo } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by ID. func (cuo *CounterUpdateOne) SetMetricID(id int) *CounterUpdateOne { cuo.mutation.SetMetricID(id) return cuo } -// SetNillableMetricID sets the metric edge to Metric by id if the given value is not nil. +// SetNillableMetricID sets the "metric" edge to the Metric entity by ID if the given value is not nil. func (cuo *CounterUpdateOne) SetNillableMetricID(id *int) *CounterUpdateOne { if id != nil { cuo = cuo.SetMetricID(*id) @@ -293,7 +236,7 @@ func (cuo *CounterUpdateOne) SetNillableMetricID(id *int) *CounterUpdateOne { return cuo } -// SetMetric sets the metric edge to Metric. +// SetMetric sets the "metric" edge to the Metric entity. func (cuo *CounterUpdateOne) SetMetric(m *Metric) *CounterUpdateOne { return cuo.SetMetricID(m.ID) } @@ -303,39 +246,28 @@ func (cuo *CounterUpdateOne) Mutation() *CounterMutation { return cuo.mutation } -// ClearMetric clears the "metric" edge to type Metric. +// ClearMetric clears the "metric" edge to the Metric entity. func (cuo *CounterUpdateOne) ClearMetric() *CounterUpdateOne { cuo.mutation.ClearMetric() return cuo } -// Save executes the query and returns the updated entity. +// Where appends a list predicates to the CounterUpdate builder. +func (cuo *CounterUpdateOne) Where(ps ...predicate.Counter) *CounterUpdateOne { + cuo.mutation.Where(ps...) + return cuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (cuo *CounterUpdateOne) Select(field string, fields ...string) *CounterUpdateOne { + cuo.fields = append([]string{field}, fields...) + return cuo +} + +// Save executes the query and returns the updated Counter entity. func (cuo *CounterUpdateOne) Save(ctx context.Context) (*Counter, error) { - var ( - err error - node *Counter - ) - if len(cuo.hooks) == 0 { - node, err = cuo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*CounterMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - cuo.mutation = mutation - node, err = cuo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(cuo.hooks) - 1; i >= 0; i-- { - mut = cuo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, cuo.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, cuo.sqlSave, cuo.mutation, cuo.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -361,55 +293,45 @@ func (cuo *CounterUpdateOne) ExecX(ctx context.Context) { } func (cuo *CounterUpdateOne) sqlSave(ctx context.Context) (_node *Counter, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: counter.Table, - Columns: counter.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, - }, - } + _spec := sqlgraph.NewUpdateSpec(counter.Table, counter.Columns, sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt)) id, ok := cuo.mutation.ID() if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Counter.ID for update")} + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Counter.id" for update`)} } _spec.Node.ID.Value = id + if fields := cuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, counter.FieldID) + for _, f := range fields { + if !counter.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != counter.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := cuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } if value, ok := cuo.mutation.Time(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldTime, - }) + _spec.SetField(counter.FieldTime, field.TypeInt64, value) } if value, ok := cuo.mutation.AddedTime(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldTime, - }) + _spec.AddField(counter.FieldTime, field.TypeInt64, value) } if value, ok := cuo.mutation.Count(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldCount, - }) + _spec.SetField(counter.FieldCount, field.TypeInt64, value) } if value, ok := cuo.mutation.AddedCount(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: counter.FieldCount, - }) + _spec.AddField(counter.FieldCount, field.TypeInt64, value) } if value, ok := cuo.mutation.WID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: counter.FieldWID, - }) + _spec.SetField(counter.FieldWID, field.TypeString, value) } if cuo.mutation.MetricCleared() { edge := &sqlgraph.EdgeSpec{ @@ -419,10 +341,7 @@ func (cuo *CounterUpdateOne) sqlSave(ctx context.Context) (_node *Counter, err e Columns: []string{counter.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -435,10 +354,7 @@ func (cuo *CounterUpdateOne) sqlSave(ctx context.Context) (_node *Counter, err e Columns: []string{counter.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -448,14 +364,15 @@ func (cuo *CounterUpdateOne) sqlSave(ctx context.Context) (_node *Counter, err e } _node = &Counter{config: cuo.config} _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues() + _spec.ScanValues = _node.scanValues if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{counter.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } + cuo.mutation.done = true return _node, nil } diff --git a/ent/ent.go b/ent/ent.go index 587180b3..febcdc9b 100644 --- a/ent/ent.go +++ b/ent/ent.go @@ -1,86 +1,148 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( + "context" "errors" "fmt" - "strings" - - "github.com/facebook/ent" - "github.com/facebook/ent/dialect" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" + "reflect" + "sync" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/gobench-io/gobench/v2/ent/application" + "github.com/gobench-io/gobench/v2/ent/counter" + "github.com/gobench-io/gobench/v2/ent/gauge" + "github.com/gobench-io/gobench/v2/ent/graph" + "github.com/gobench-io/gobench/v2/ent/group" + "github.com/gobench-io/gobench/v2/ent/histogram" + "github.com/gobench-io/gobench/v2/ent/metric" + "github.com/gobench-io/gobench/v2/ent/tag" ) -// ent aliases to avoid import conflict in user's code. +// ent aliases to avoid import conflicts in user's code. type ( - Op = ent.Op - Hook = ent.Hook - Value = ent.Value - Query = ent.Query - Policy = ent.Policy - Mutator = ent.Mutator - Mutation = ent.Mutation - MutateFunc = ent.MutateFunc + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc ) +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + // OrderFunc applies an ordering on the sql selector. -type OrderFunc func(*sql.Selector, func(string) bool) +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// columnChecker checks if the column exists in the given table. +func checkColumn(table, column string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + application.Table: application.ValidColumn, + counter.Table: counter.ValidColumn, + gauge.Table: gauge.ValidColumn, + graph.Table: graph.ValidColumn, + group.Table: group.ValidColumn, + histogram.Table: histogram.ValidColumn, + metric.Table: metric.ValidColumn, + tag.Table: tag.ValidColumn, + }) + }) + return columnCheck(table, column) +} // Asc applies the given fields in ASC order. -func Asc(fields ...string) OrderFunc { - return func(s *sql.Selector, check func(string) bool) { +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { for _, f := range fields { - if check(f) { - s.OrderBy(sql.Asc(f)) - } else { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("invalid field %q for ordering", f)}) + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) } + s.OrderBy(sql.Asc(s.C(f))) } } } // Desc applies the given fields in DESC order. -func Desc(fields ...string) OrderFunc { - return func(s *sql.Selector, check func(string) bool) { +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { for _, f := range fields { - if check(f) { - s.OrderBy(sql.Desc(f)) - } else { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("invalid field %q for ordering", f)}) + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) } + s.OrderBy(sql.Desc(s.C(f))) } } } // AggregateFunc applies an aggregation step on the group-by traversal/selector. -type AggregateFunc func(*sql.Selector, func(string) bool) string +type AggregateFunc func(*sql.Selector) string // As is a pseudo aggregation function for renaming another other functions with custom names. For example: // // GroupBy(field1, field2). // Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). // Scan(ctx, &v) -// func As(fn AggregateFunc, end string) AggregateFunc { - return func(s *sql.Selector, check func(string) bool) string { - return sql.As(fn(s, check), end) + return func(s *sql.Selector) string { + return sql.As(fn(s), end) } } // Count applies the "count" aggregation function on each group. func Count() AggregateFunc { - return func(s *sql.Selector, _ func(string) bool) string { + return func(s *sql.Selector) string { return sql.Count("*") } } // Max applies the "max" aggregation function on the given field of each group. func Max(field string) AggregateFunc { - return func(s *sql.Selector, check func(string) bool) string { - if !check(field) { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)}) + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } return sql.Max(s.C(field)) @@ -89,9 +151,9 @@ func Max(field string) AggregateFunc { // Mean applies the "mean" aggregation function on the given field of each group. func Mean(field string) AggregateFunc { - return func(s *sql.Selector, check func(string) bool) string { - if !check(field) { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)}) + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } return sql.Avg(s.C(field)) @@ -100,9 +162,9 @@ func Mean(field string) AggregateFunc { // Min applies the "min" aggregation function on the given field of each group. func Min(field string) AggregateFunc { - return func(s *sql.Selector, check func(string) bool) string { - if !check(field) { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)}) + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } return sql.Min(s.C(field)) @@ -111,16 +173,16 @@ func Min(field string) AggregateFunc { // Sum applies the "sum" aggregation function on the given field of each group. func Sum(field string) AggregateFunc { - return func(s *sql.Selector, check func(string) bool) string { - if !check(field) { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)}) + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } return sql.Sum(s.C(field)) } } -// ValidationError returns when validating a field fails. +// ValidationError returns when validating a field or edge fails. type ValidationError struct { Name string // Field or edge name. err error @@ -136,7 +198,7 @@ func (e *ValidationError) Unwrap() error { return e.err } -// IsValidationError returns a boolean indicating whether the error is a validaton error. +// IsValidationError returns a boolean indicating whether the error is a validation error. func IsValidationError(err error) bool { if err == nil { return false @@ -164,7 +226,7 @@ func IsNotFound(err error) bool { return errors.As(err, &e) } -// MaskNotFound masks nor found error. +// MaskNotFound masks not found error. func MaskNotFound(err error) error { if IsNotFound(err) { return nil @@ -237,34 +299,324 @@ func IsConstraintError(err error) bool { return errors.As(err, &e) } -func isSQLConstraintError(err error) (*ConstraintError, bool) { - var ( - msg = err.Error() - // error format per dialect. - errors = [...]string{ - "Error 1062", // MySQL 1062 error (ER_DUP_ENTRY). - "UNIQUE constraint failed", // SQLite. - "duplicate key value violates unique constraint", // PostgreSQL. +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) } - ) - if _, ok := err.(*sqlgraph.ConstraintError); ok { - return &ConstraintError{msg, err}, true + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) } - for i := range errors { - if strings.Contains(msg, errors[i]) { - return &ConstraintError{msg, err}, true + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) } - return nil, false + return vt, nil } -// rollback calls to tx.Rollback and wraps the given error with the rollback error if occurred. -func rollback(tx dialect.Tx, err error) error { - if rerr := tx.Rollback(); rerr != nil { - err = fmt.Errorf("%s: %v", err.Error(), rerr) +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) } - if err, ok := isSQLConstraintError(err); ok { + vv, err := qr.Query(ctx, rootQuery) + if err != nil { return err } - return err + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil } + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/ent/enttest/enttest.go b/ent/enttest/enttest.go index 5dce2eac..137e2858 100644 --- a/ent/enttest/enttest.go +++ b/ent/enttest/enttest.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package enttest @@ -9,7 +9,8 @@ import ( // required by schema hooks. _ "github.com/gobench-io/gobench/v2/ent/runtime" - "github.com/facebook/ent/dialect/sql/schema" + "entgo.io/ent/dialect/sql/schema" + "github.com/gobench-io/gobench/v2/ent/migrate" ) type ( @@ -17,7 +18,7 @@ type ( // testing.T and testing.B and used by enttest. TestingT interface { FailNow() - Error(...interface{}) + Error(...any) } // Option configures client creation. @@ -59,10 +60,7 @@ func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Cl t.Error(err) t.FailNow() } - if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { - t.Error(err) - t.FailNow() - } + migrateSchema(t, c, o) return c } @@ -70,9 +68,17 @@ func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Cl func NewClient(t TestingT, opts ...Option) *ent.Client { o := newOptions(opts) c := ent.NewClient(o.opts...) - if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil { + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *ent.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { t.Error(err) t.FailNow() } - return c } diff --git a/ent/gauge.go b/ent/gauge.go index 30b207fb..d7ee24d2 100644 --- a/ent/gauge.go +++ b/ent/gauge.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -6,7 +6,8 @@ import ( "fmt" "strings" - "github.com/facebook/ent/dialect/sql" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/gobench-io/gobench/v2/ent/gauge" "github.com/gobench-io/gobench/v2/ent/metric" ) @@ -26,12 +27,13 @@ type Gauge struct { // The values are being populated by the GaugeQuery when eager-loading is set. Edges GaugeEdges `json:"edges"` metric_gauges *int + selectValues sql.SelectValues } // GaugeEdges holds the relations/edges for other nodes in the graph. type GaugeEdges struct { // Metric holds the value of the metric edge. - Metric *Metric + Metric *Metric `json:"metric,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [1]bool @@ -42,8 +44,7 @@ type GaugeEdges struct { func (e GaugeEdges) MetricOrErr() (*Metric, error) { if e.loadedTypes[0] { if e.Metric == nil { - // The edge metric was loaded in eager-loading, - // but was not found. + // Edge was loaded but was not found. return nil, &NotFoundError{label: metric.Label} } return e.Metric, nil @@ -52,81 +53,95 @@ func (e GaugeEdges) MetricOrErr() (*Metric, error) { } // scanValues returns the types for scanning values from sql.Rows. -func (*Gauge) scanValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // id - &sql.NullInt64{}, // time - &sql.NullInt64{}, // value - &sql.NullString{}, // wID - } -} - -// fkValues returns the types for scanning foreign-keys values from sql.Rows. -func (*Gauge) fkValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // metric_gauges +func (*Gauge) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case gauge.FieldID, gauge.FieldTime, gauge.FieldValue: + values[i] = new(sql.NullInt64) + case gauge.FieldWID: + values[i] = new(sql.NullString) + case gauge.ForeignKeys[0]: // metric_gauges + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } } + return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Gauge fields. -func (ga *Gauge) assignValues(values ...interface{}) error { - if m, n := len(values), len(gauge.Columns); m < n { +func (ga *Gauge) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } - value, ok := values[0].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - ga.ID = int(value.Int64) - values = values[1:] - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field time", values[0]) - } else if value.Valid { - ga.Time = value.Int64 - } - if value, ok := values[1].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field value", values[1]) - } else if value.Valid { - ga.Value = value.Int64 - } - if value, ok := values[2].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field wID", values[2]) - } else if value.Valid { - ga.WID = value.String - } - values = values[3:] - if len(values) == len(gauge.ForeignKeys) { - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field metric_gauges", value) - } else if value.Valid { - ga.metric_gauges = new(int) - *ga.metric_gauges = int(value.Int64) + for i := range columns { + switch columns[i] { + case gauge.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + ga.ID = int(value.Int64) + case gauge.FieldTime: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field time", values[i]) + } else if value.Valid { + ga.Time = value.Int64 + } + case gauge.FieldValue: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field value", values[i]) + } else if value.Valid { + ga.Value = value.Int64 + } + case gauge.FieldWID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field wID", values[i]) + } else if value.Valid { + ga.WID = value.String + } + case gauge.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field metric_gauges", value) + } else if value.Valid { + ga.metric_gauges = new(int) + *ga.metric_gauges = int(value.Int64) + } + default: + ga.selectValues.Set(columns[i], values[i]) } } return nil } -// QueryMetric queries the metric edge of the Gauge. +// GetValue returns the ent.Value that was dynamically selected and assigned to the Gauge. +// This includes values selected through modifiers, order, etc. +func (ga *Gauge) GetValue(name string) (ent.Value, error) { + return ga.selectValues.Get(name) +} + +// QueryMetric queries the "metric" edge of the Gauge entity. func (ga *Gauge) QueryMetric() *MetricQuery { - return (&GaugeClient{config: ga.config}).QueryMetric(ga) + return NewGaugeClient(ga.config).QueryMetric(ga) } // Update returns a builder for updating this Gauge. -// Note that, you need to call Gauge.Unwrap() before calling this method, if this Gauge +// Note that you need to call Gauge.Unwrap() before calling this method if this Gauge // was returned from a transaction, and the transaction was committed or rolled back. func (ga *Gauge) Update() *GaugeUpdateOne { - return (&GaugeClient{config: ga.config}).UpdateOne(ga) + return NewGaugeClient(ga.config).UpdateOne(ga) } -// Unwrap unwraps the entity that was returned from a transaction after it was closed, -// so that all next queries will be executed through the driver which created the transaction. +// Unwrap unwraps the Gauge entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. func (ga *Gauge) Unwrap() *Gauge { - tx, ok := ga.config.driver.(*txDriver) + _tx, ok := ga.config.driver.(*txDriver) if !ok { panic("ent: Gauge is not a transactional entity") } - ga.config.driver = tx.drv + ga.config.driver = _tx.drv return ga } @@ -134,12 +149,14 @@ func (ga *Gauge) Unwrap() *Gauge { func (ga *Gauge) String() string { var builder strings.Builder builder.WriteString("Gauge(") - builder.WriteString(fmt.Sprintf("id=%v", ga.ID)) - builder.WriteString(", time=") + builder.WriteString(fmt.Sprintf("id=%v, ", ga.ID)) + builder.WriteString("time=") builder.WriteString(fmt.Sprintf("%v", ga.Time)) - builder.WriteString(", value=") + builder.WriteString(", ") + builder.WriteString("value=") builder.WriteString(fmt.Sprintf("%v", ga.Value)) - builder.WriteString(", wID=") + builder.WriteString(", ") + builder.WriteString("wID=") builder.WriteString(ga.WID) builder.WriteByte(')') return builder.String() @@ -147,9 +164,3 @@ func (ga *Gauge) String() string { // Gauges is a parsable slice of Gauge. type Gauges []*Gauge - -func (ga Gauges) config(cfg config) { - for _i := range ga { - ga[_i].config = cfg - } -} diff --git a/ent/gauge/gauge.go b/ent/gauge/gauge.go index de633864..4a02e59c 100644 --- a/ent/gauge/gauge.go +++ b/ent/gauge/gauge.go @@ -1,7 +1,12 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package gauge +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + const ( // Label holds the string label denoting the gauge type in the database. Label = "gauge" @@ -13,13 +18,11 @@ const ( FieldValue = "value" // FieldWID holds the string denoting the wid field in the database. FieldWID = "w_id" - // EdgeMetric holds the string denoting the metric edge name in mutations. EdgeMetric = "metric" - // Table holds the table name of the gauge in the database. Table = "gauges" - // MetricTable is the table the holds the metric relation/edge. + // MetricTable is the table that holds the metric relation/edge. MetricTable = "gauges" // MetricInverseTable is the table name for the Metric entity. // It exists in this package in order to avoid circular dependency with the "metric" package. @@ -36,7 +39,8 @@ var Columns = []string{ FieldWID, } -// ForeignKeys holds the SQL foreign-keys that are owned by the Gauge type. +// ForeignKeys holds the SQL foreign-keys that are owned by the "gauges" +// table and are not defined as standalone fields in the schema. var ForeignKeys = []string{ "metric_gauges", } @@ -55,3 +59,40 @@ func ValidColumn(column string) bool { } return false } + +// OrderOption defines the ordering options for the Gauge queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByTime orders the results by the time field. +func ByTime(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTime, opts...).ToFunc() +} + +// ByValue orders the results by the value field. +func ByValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldValue, opts...).ToFunc() +} + +// ByWID orders the results by the wID field. +func ByWID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWID, opts...).ToFunc() +} + +// ByMetricField orders the results by metric field. +func ByMetricField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newMetricStep(), sql.OrderByField(field, opts...)) + } +} +func newMetricStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(MetricInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, MetricTable, MetricColumn), + ) +} diff --git a/ent/gauge/where.go b/ent/gauge/where.go index 50f67a9c..a5e55b65 100644 --- a/ent/gauge/where.go +++ b/ent/gauge/where.go @@ -1,378 +1,216 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package gauge import ( - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" "github.com/gobench-io/gobench/v2/ent/predicate" ) -// ID filters vertices based on their identifier. +// ID filters vertices based on their ID field. func ID(id int) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Gauge(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Gauge(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) + return predicate.Gauge(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) + return predicate.Gauge(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) + return predicate.Gauge(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) + return predicate.Gauge(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) + return predicate.Gauge(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) + return predicate.Gauge(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) + return predicate.Gauge(sql.FieldLTE(FieldID, id)) } // Time applies equality check predicate on the "time" field. It's identical to TimeEQ. func Time(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTime), v)) - }) + return predicate.Gauge(sql.FieldEQ(FieldTime, v)) } // Value applies equality check predicate on the "value" field. It's identical to ValueEQ. func Value(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldValue), v)) - }) + return predicate.Gauge(sql.FieldEQ(FieldValue, v)) } // WID applies equality check predicate on the "wID" field. It's identical to WIDEQ. func WID(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldEQ(FieldWID, v)) } // TimeEQ applies the EQ predicate on the "time" field. func TimeEQ(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTime), v)) - }) + return predicate.Gauge(sql.FieldEQ(FieldTime, v)) } // TimeNEQ applies the NEQ predicate on the "time" field. func TimeNEQ(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldTime), v)) - }) + return predicate.Gauge(sql.FieldNEQ(FieldTime, v)) } // TimeIn applies the In predicate on the "time" field. func TimeIn(vs ...int64) predicate.Gauge { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Gauge(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldTime), v...)) - }) + return predicate.Gauge(sql.FieldIn(FieldTime, vs...)) } // TimeNotIn applies the NotIn predicate on the "time" field. func TimeNotIn(vs ...int64) predicate.Gauge { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Gauge(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldTime), v...)) - }) + return predicate.Gauge(sql.FieldNotIn(FieldTime, vs...)) } // TimeGT applies the GT predicate on the "time" field. func TimeGT(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldTime), v)) - }) + return predicate.Gauge(sql.FieldGT(FieldTime, v)) } // TimeGTE applies the GTE predicate on the "time" field. func TimeGTE(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldTime), v)) - }) + return predicate.Gauge(sql.FieldGTE(FieldTime, v)) } // TimeLT applies the LT predicate on the "time" field. func TimeLT(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldTime), v)) - }) + return predicate.Gauge(sql.FieldLT(FieldTime, v)) } // TimeLTE applies the LTE predicate on the "time" field. func TimeLTE(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldTime), v)) - }) + return predicate.Gauge(sql.FieldLTE(FieldTime, v)) } // ValueEQ applies the EQ predicate on the "value" field. func ValueEQ(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldValue), v)) - }) + return predicate.Gauge(sql.FieldEQ(FieldValue, v)) } // ValueNEQ applies the NEQ predicate on the "value" field. func ValueNEQ(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldValue), v)) - }) + return predicate.Gauge(sql.FieldNEQ(FieldValue, v)) } // ValueIn applies the In predicate on the "value" field. func ValueIn(vs ...int64) predicate.Gauge { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Gauge(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldValue), v...)) - }) + return predicate.Gauge(sql.FieldIn(FieldValue, vs...)) } // ValueNotIn applies the NotIn predicate on the "value" field. func ValueNotIn(vs ...int64) predicate.Gauge { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Gauge(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldValue), v...)) - }) + return predicate.Gauge(sql.FieldNotIn(FieldValue, vs...)) } // ValueGT applies the GT predicate on the "value" field. func ValueGT(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldValue), v)) - }) + return predicate.Gauge(sql.FieldGT(FieldValue, v)) } // ValueGTE applies the GTE predicate on the "value" field. func ValueGTE(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldValue), v)) - }) + return predicate.Gauge(sql.FieldGTE(FieldValue, v)) } // ValueLT applies the LT predicate on the "value" field. func ValueLT(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldValue), v)) - }) + return predicate.Gauge(sql.FieldLT(FieldValue, v)) } // ValueLTE applies the LTE predicate on the "value" field. func ValueLTE(v int64) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldValue), v)) - }) + return predicate.Gauge(sql.FieldLTE(FieldValue, v)) } // WIDEQ applies the EQ predicate on the "wID" field. func WIDEQ(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldEQ(FieldWID, v)) } // WIDNEQ applies the NEQ predicate on the "wID" field. func WIDNEQ(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldNEQ(FieldWID, v)) } // WIDIn applies the In predicate on the "wID" field. func WIDIn(vs ...string) predicate.Gauge { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Gauge(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldWID), v...)) - }) + return predicate.Gauge(sql.FieldIn(FieldWID, vs...)) } // WIDNotIn applies the NotIn predicate on the "wID" field. func WIDNotIn(vs ...string) predicate.Gauge { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Gauge(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldWID), v...)) - }) + return predicate.Gauge(sql.FieldNotIn(FieldWID, vs...)) } // WIDGT applies the GT predicate on the "wID" field. func WIDGT(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldGT(FieldWID, v)) } // WIDGTE applies the GTE predicate on the "wID" field. func WIDGTE(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldGTE(FieldWID, v)) } // WIDLT applies the LT predicate on the "wID" field. func WIDLT(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldLT(FieldWID, v)) } // WIDLTE applies the LTE predicate on the "wID" field. func WIDLTE(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldLTE(FieldWID, v)) } // WIDContains applies the Contains predicate on the "wID" field. func WIDContains(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldContains(FieldWID, v)) } // WIDHasPrefix applies the HasPrefix predicate on the "wID" field. func WIDHasPrefix(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldHasPrefix(FieldWID, v)) } // WIDHasSuffix applies the HasSuffix predicate on the "wID" field. func WIDHasSuffix(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldHasSuffix(FieldWID, v)) } // WIDEqualFold applies the EqualFold predicate on the "wID" field. func WIDEqualFold(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldEqualFold(FieldWID, v)) } // WIDContainsFold applies the ContainsFold predicate on the "wID" field. func WIDContainsFold(v string) predicate.Gauge { - return predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldWID), v)) - }) + return predicate.Gauge(sql.FieldContainsFold(FieldWID, v)) } // HasMetric applies the HasEdge predicate on the "metric" edge. @@ -380,7 +218,6 @@ func HasMetric() predicate.Gauge { return predicate.Gauge(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(MetricTable, FieldID), sqlgraph.Edge(sqlgraph.M2O, true, MetricTable, MetricColumn), ) sqlgraph.HasNeighbors(s, step) @@ -390,11 +227,7 @@ func HasMetric() predicate.Gauge { // HasMetricWith applies the HasEdge predicate on the "metric" edge with a given conditions (other predicates). func HasMetricWith(preds ...predicate.Metric) predicate.Gauge { return predicate.Gauge(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(MetricInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, MetricTable, MetricColumn), - ) + step := newMetricStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -403,7 +236,7 @@ func HasMetricWith(preds ...predicate.Metric) predicate.Gauge { }) } -// And groups list of predicates with the AND operator between them. +// And groups predicates with the AND operator between them. func And(predicates ...predicate.Gauge) predicate.Gauge { return predicate.Gauge(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) @@ -414,7 +247,7 @@ func And(predicates ...predicate.Gauge) predicate.Gauge { }) } -// Or groups list of predicates with the OR operator between them. +// Or groups predicates with the OR operator between them. func Or(predicates ...predicate.Gauge) predicate.Gauge { return predicate.Gauge(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) diff --git a/ent/gauge_create.go b/ent/gauge_create.go index 5b3462fa..99a57139 100644 --- a/ent/gauge_create.go +++ b/ent/gauge_create.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -7,8 +7,8 @@ import ( "errors" "fmt" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/gauge" "github.com/gobench-io/gobench/v2/ent/metric" ) @@ -20,31 +20,31 @@ type GaugeCreate struct { hooks []Hook } -// SetTime sets the time field. +// SetTime sets the "time" field. func (gc *GaugeCreate) SetTime(i int64) *GaugeCreate { gc.mutation.SetTime(i) return gc } -// SetValue sets the value field. +// SetValue sets the "value" field. func (gc *GaugeCreate) SetValue(i int64) *GaugeCreate { gc.mutation.SetValue(i) return gc } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (gc *GaugeCreate) SetWID(s string) *GaugeCreate { gc.mutation.SetWID(s) return gc } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by ID. func (gc *GaugeCreate) SetMetricID(id int) *GaugeCreate { gc.mutation.SetMetricID(id) return gc } -// SetNillableMetricID sets the metric edge to Metric by id if the given value is not nil. +// SetNillableMetricID sets the "metric" edge to the Metric entity by ID if the given value is not nil. func (gc *GaugeCreate) SetNillableMetricID(id *int) *GaugeCreate { if id != nil { gc = gc.SetMetricID(*id) @@ -52,7 +52,7 @@ func (gc *GaugeCreate) SetNillableMetricID(id *int) *GaugeCreate { return gc } -// SetMetric sets the metric edge to Metric. +// SetMetric sets the "metric" edge to the Metric entity. func (gc *GaugeCreate) SetMetric(m *Metric) *GaugeCreate { return gc.SetMetricID(m.ID) } @@ -64,37 +64,7 @@ func (gc *GaugeCreate) Mutation() *GaugeMutation { // Save creates the Gauge in the database. func (gc *GaugeCreate) Save(ctx context.Context) (*Gauge, error) { - var ( - err error - node *Gauge - ) - if len(gc.hooks) == 0 { - if err = gc.check(); err != nil { - return nil, err - } - node, err = gc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GaugeMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = gc.check(); err != nil { - return nil, err - } - gc.mutation = mutation - node, err = gc.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(gc.hooks) - 1; i >= 0; i-- { - mut = gc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, gc.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, gc.sqlSave, gc.mutation, gc.hooks) } // SaveX calls Save and panics if Save returns an error. @@ -106,66 +76,66 @@ func (gc *GaugeCreate) SaveX(ctx context.Context) *Gauge { return v } +// Exec executes the query. +func (gc *GaugeCreate) Exec(ctx context.Context) error { + _, err := gc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gc *GaugeCreate) ExecX(ctx context.Context) { + if err := gc.Exec(ctx); err != nil { + panic(err) + } +} + // check runs all checks and user-defined validators on the builder. func (gc *GaugeCreate) check() error { if _, ok := gc.mutation.Time(); !ok { - return &ValidationError{Name: "time", err: errors.New("ent: missing required field \"time\"")} + return &ValidationError{Name: "time", err: errors.New(`ent: missing required field "Gauge.time"`)} } if _, ok := gc.mutation.Value(); !ok { - return &ValidationError{Name: "value", err: errors.New("ent: missing required field \"value\"")} + return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "Gauge.value"`)} } if _, ok := gc.mutation.WID(); !ok { - return &ValidationError{Name: "wID", err: errors.New("ent: missing required field \"wID\"")} + return &ValidationError{Name: "wID", err: errors.New(`ent: missing required field "Gauge.wID"`)} } return nil } func (gc *GaugeCreate) sqlSave(ctx context.Context) (*Gauge, error) { + if err := gc.check(); err != nil { + return nil, err + } _node, _spec := gc.createSpec() if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } id := _spec.ID.Value.(int64) _node.ID = int(id) + gc.mutation.id = &_node.ID + gc.mutation.done = true return _node, nil } func (gc *GaugeCreate) createSpec() (*Gauge, *sqlgraph.CreateSpec) { var ( _node = &Gauge{config: gc.config} - _spec = &sqlgraph.CreateSpec{ - Table: gauge.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, - } + _spec = sqlgraph.NewCreateSpec(gauge.Table, sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt)) ) if value, ok := gc.mutation.Time(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldTime, - }) + _spec.SetField(gauge.FieldTime, field.TypeInt64, value) _node.Time = value } if value, ok := gc.mutation.Value(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldValue, - }) + _spec.SetField(gauge.FieldValue, field.TypeInt64, value) _node.Value = value } if value, ok := gc.mutation.WID(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: gauge.FieldWID, - }) + _spec.SetField(gauge.FieldWID, field.TypeString, value) _node.WID = value } if nodes := gc.mutation.MetricIDs(); len(nodes) > 0 { @@ -176,21 +146,19 @@ func (gc *GaugeCreate) createSpec() (*Gauge, *sqlgraph.CreateSpec) { Columns: []string{gauge.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } + _node.metric_gauges = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } return _node, _spec } -// GaugeCreateBulk is the builder for creating a bulk of Gauge entities. +// GaugeCreateBulk is the builder for creating many Gauge entities in bulk. type GaugeCreateBulk struct { config builders []*GaugeCreate @@ -213,24 +181,28 @@ func (gcb *GaugeCreateBulk) Save(ctx context.Context) ([]*Gauge, error) { return nil, err } builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() var err error + nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, gcb.builders[i+1].mutation) } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, gcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if err = sqlgraph.BatchCreate(ctx, gcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } } } - mutation.done = true if err != nil { return nil, err } - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { @@ -247,7 +219,7 @@ func (gcb *GaugeCreateBulk) Save(ctx context.Context) ([]*Gauge, error) { return nodes, nil } -// SaveX calls Save and panics if Save returns an error. +// SaveX is like Save, but panics if an error occurs. func (gcb *GaugeCreateBulk) SaveX(ctx context.Context) []*Gauge { v, err := gcb.Save(ctx) if err != nil { @@ -255,3 +227,16 @@ func (gcb *GaugeCreateBulk) SaveX(ctx context.Context) []*Gauge { } return v } + +// Exec executes the query. +func (gcb *GaugeCreateBulk) Exec(ctx context.Context) error { + _, err := gcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcb *GaugeCreateBulk) ExecX(ctx context.Context) { + if err := gcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/gauge_delete.go b/ent/gauge_delete.go index 7c6296cf..7b374f43 100644 --- a/ent/gauge_delete.go +++ b/ent/gauge_delete.go @@ -1,14 +1,13 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/gauge" "github.com/gobench-io/gobench/v2/ent/predicate" ) @@ -16,44 +15,19 @@ import ( // GaugeDelete is the builder for deleting a Gauge entity. type GaugeDelete struct { config - hooks []Hook - mutation *GaugeMutation - predicates []predicate.Gauge + hooks []Hook + mutation *GaugeMutation } -// Where adds a new predicate to the delete builder. +// Where appends a list predicates to the GaugeDelete builder. func (gd *GaugeDelete) Where(ps ...predicate.Gauge) *GaugeDelete { - gd.predicates = append(gd.predicates, ps...) + gd.mutation.Where(ps...) return gd } // Exec executes the deletion query and returns how many vertices were deleted. func (gd *GaugeDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(gd.hooks) == 0 { - affected, err = gd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GaugeMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - gd.mutation = mutation - affected, err = gd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(gd.hooks) - 1; i >= 0; i-- { - mut = gd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, gd.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, gd.sqlExec, gd.mutation, gd.hooks) } // ExecX is like Exec, but panics if an error occurs. @@ -66,23 +40,20 @@ func (gd *GaugeDelete) ExecX(ctx context.Context) int { } func (gd *GaugeDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: gauge.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, - }, - } - if ps := gd.predicates; len(ps) > 0 { + _spec := sqlgraph.NewDeleteSpec(gauge.Table, sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt)) + if ps := gd.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - return sqlgraph.DeleteNodes(ctx, gd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, gd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + gd.mutation.done = true + return affected, err } // GaugeDeleteOne is the builder for deleting a single Gauge entity. @@ -90,6 +61,12 @@ type GaugeDeleteOne struct { gd *GaugeDelete } +// Where appends a list predicates to the GaugeDelete builder. +func (gdo *GaugeDeleteOne) Where(ps ...predicate.Gauge) *GaugeDeleteOne { + gdo.gd.mutation.Where(ps...) + return gdo +} + // Exec executes the deletion query. func (gdo *GaugeDeleteOne) Exec(ctx context.Context) error { n, err := gdo.gd.Exec(ctx) @@ -105,5 +82,7 @@ func (gdo *GaugeDeleteOne) Exec(ctx context.Context) error { // ExecX is like Exec, but panics if an error occurs. func (gdo *GaugeDeleteOne) ExecX(ctx context.Context) { - gdo.gd.ExecX(ctx) + if err := gdo.Exec(ctx); err != nil { + panic(err) + } } diff --git a/ent/gauge_query.go b/ent/gauge_query.go index f520438f..940383f3 100644 --- a/ent/gauge_query.go +++ b/ent/gauge_query.go @@ -1,16 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "errors" "fmt" "math" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/gauge" "github.com/gobench-io/gobench/v2/ent/metric" "github.com/gobench-io/gobench/v2/ent/predicate" @@ -19,12 +18,10 @@ import ( // GaugeQuery is the builder for querying Gauge entities. type GaugeQuery struct { config - limit *int - offset *int - order []OrderFunc - unique []string + ctx *QueryContext + order []gauge.OrderOption + inters []Interceptor predicates []predicate.Gauge - // eager-loading edges. withMetric *MetricQuery withFKs bool // intermediate query (i.e. traversal path). @@ -32,38 +29,45 @@ type GaugeQuery struct { path func(context.Context) (*sql.Selector, error) } -// Where adds a new predicate for the builder. +// Where adds a new predicate for the GaugeQuery builder. func (gq *GaugeQuery) Where(ps ...predicate.Gauge) *GaugeQuery { gq.predicates = append(gq.predicates, ps...) return gq } -// Limit adds a limit step to the query. +// Limit the number of records to be returned by this query. func (gq *GaugeQuery) Limit(limit int) *GaugeQuery { - gq.limit = &limit + gq.ctx.Limit = &limit return gq } -// Offset adds an offset step to the query. +// Offset to start from. func (gq *GaugeQuery) Offset(offset int) *GaugeQuery { - gq.offset = &offset + gq.ctx.Offset = &offset return gq } -// Order adds an order step to the query. -func (gq *GaugeQuery) Order(o ...OrderFunc) *GaugeQuery { +// 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 (gq *GaugeQuery) Unique(unique bool) *GaugeQuery { + gq.ctx.Unique = &unique + return gq +} + +// Order specifies how the records should be ordered. +func (gq *GaugeQuery) Order(o ...gauge.OrderOption) *GaugeQuery { gq.order = append(gq.order, o...) return gq } -// QueryMetric chains the current query on the metric edge. +// QueryMetric chains the current query on the "metric" edge. func (gq *GaugeQuery) QueryMetric() *MetricQuery { - query := &MetricQuery{config: gq.config} + query := (&MetricClient{config: gq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := gq.prepareQuery(ctx); err != nil { return nil, err } - selector := gq.sqlQuery() + selector := gq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -78,9 +82,10 @@ func (gq *GaugeQuery) QueryMetric() *MetricQuery { return query } -// First returns the first Gauge entity in the query. Returns *NotFoundError when no gauge was found. +// First returns the first Gauge entity from the query. +// Returns a *NotFoundError when no Gauge was found. func (gq *GaugeQuery) First(ctx context.Context) (*Gauge, error) { - nodes, err := gq.Limit(1).All(ctx) + nodes, err := gq.Limit(1).All(setContextOp(ctx, gq.ctx, "First")) if err != nil { return nil, err } @@ -99,10 +104,11 @@ func (gq *GaugeQuery) FirstX(ctx context.Context) *Gauge { return node } -// FirstID returns the first Gauge id in the query. Returns *NotFoundError when no id was found. +// FirstID returns the first Gauge ID from the query. +// Returns a *NotFoundError when no Gauge ID was found. func (gq *GaugeQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = gq.Limit(1).IDs(ctx); err != nil { + if ids, err = gq.Limit(1).IDs(setContextOp(ctx, gq.ctx, "FirstID")); err != nil { return } if len(ids) == 0 { @@ -112,8 +118,8 @@ func (gq *GaugeQuery) FirstID(ctx context.Context) (id int, err error) { return ids[0], nil } -// FirstXID is like FirstID, but panics if an error occurs. -func (gq *GaugeQuery) FirstXID(ctx context.Context) int { +// FirstIDX is like FirstID, but panics if an error occurs. +func (gq *GaugeQuery) FirstIDX(ctx context.Context) int { id, err := gq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -121,9 +127,11 @@ func (gq *GaugeQuery) FirstXID(ctx context.Context) int { return id } -// Only returns the only Gauge entity in the query, returns an error if not exactly one entity was returned. +// Only returns a single Gauge entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Gauge entity is found. +// Returns a *NotFoundError when no Gauge entities are found. func (gq *GaugeQuery) Only(ctx context.Context) (*Gauge, error) { - nodes, err := gq.Limit(2).All(ctx) + nodes, err := gq.Limit(2).All(setContextOp(ctx, gq.ctx, "Only")) if err != nil { return nil, err } @@ -146,10 +154,12 @@ func (gq *GaugeQuery) OnlyX(ctx context.Context) *Gauge { return node } -// OnlyID returns the only Gauge id in the query, returns an error if not exactly one id was returned. +// OnlyID is like Only, but returns the only Gauge ID in the query. +// Returns a *NotSingularError when more than one Gauge ID is found. +// Returns a *NotFoundError when no entities are found. func (gq *GaugeQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = gq.Limit(2).IDs(ctx); err != nil { + if ids, err = gq.Limit(2).IDs(setContextOp(ctx, gq.ctx, "OnlyID")); err != nil { return } switch len(ids) { @@ -174,10 +184,12 @@ func (gq *GaugeQuery) OnlyIDX(ctx context.Context) int { // All executes the query and returns a list of Gauges. func (gq *GaugeQuery) All(ctx context.Context) ([]*Gauge, error) { + ctx = setContextOp(ctx, gq.ctx, "All") if err := gq.prepareQuery(ctx); err != nil { return nil, err } - return gq.sqlAll(ctx) + qr := querierAll[[]*Gauge, *GaugeQuery]() + return withInterceptors[[]*Gauge](ctx, gq, qr, gq.inters) } // AllX is like All, but panics if an error occurs. @@ -189,10 +201,13 @@ func (gq *GaugeQuery) AllX(ctx context.Context) []*Gauge { return nodes } -// IDs executes the query and returns a list of Gauge ids. -func (gq *GaugeQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := gq.Select(gauge.FieldID).Scan(ctx, &ids); err != nil { +// IDs executes the query and returns a list of Gauge IDs. +func (gq *GaugeQuery) IDs(ctx context.Context) (ids []int, err error) { + if gq.ctx.Unique == nil && gq.path != nil { + gq.Unique(true) + } + ctx = setContextOp(ctx, gq.ctx, "IDs") + if err = gq.Select(gauge.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil @@ -209,10 +224,11 @@ func (gq *GaugeQuery) IDsX(ctx context.Context) []int { // Count returns the count of the given query. func (gq *GaugeQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, gq.ctx, "Count") if err := gq.prepareQuery(ctx); err != nil { return 0, err } - return gq.sqlCount(ctx) + return withInterceptors[int](ctx, gq, querierCount[*GaugeQuery](), gq.inters) } // CountX is like Count, but panics if an error occurs. @@ -226,10 +242,15 @@ func (gq *GaugeQuery) CountX(ctx context.Context) int { // Exist returns true if the query has elements in the graph. func (gq *GaugeQuery) Exist(ctx context.Context) (bool, error) { - if err := gq.prepareQuery(ctx); err != nil { - return false, err + ctx = setContextOp(ctx, gq.ctx, "Exist") + switch _, err := gq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil } - return gq.sqlExist(ctx) } // ExistX is like Exist, but panics if an error occurs. @@ -241,26 +262,29 @@ func (gq *GaugeQuery) ExistX(ctx context.Context) bool { return exist } -// Clone returns a duplicate of the query builder, including all associated steps. It can be +// Clone returns a duplicate of the GaugeQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. func (gq *GaugeQuery) Clone() *GaugeQuery { + if gq == nil { + return nil + } return &GaugeQuery{ config: gq.config, - limit: gq.limit, - offset: gq.offset, - order: append([]OrderFunc{}, gq.order...), - unique: append([]string{}, gq.unique...), + ctx: gq.ctx.Clone(), + order: append([]gauge.OrderOption{}, gq.order...), + inters: append([]Interceptor{}, gq.inters...), predicates: append([]predicate.Gauge{}, gq.predicates...), + withMetric: gq.withMetric.Clone(), // clone intermediate query. sql: gq.sql.Clone(), path: gq.path, } } -// WithMetric tells the query-builder to eager-loads the nodes that are connected to -// the "metric" edge. The optional arguments used to configure the query builder of the edge. +// WithMetric tells the query-builder to eager-load the nodes that are connected to +// the "metric" edge. The optional arguments are used to configure the query builder of the edge. func (gq *GaugeQuery) WithMetric(opts ...func(*MetricQuery)) *GaugeQuery { - query := &MetricQuery{config: gq.config} + query := (&MetricClient{config: gq.config}).Query() for _, opt := range opts { opt(query) } @@ -268,7 +292,7 @@ func (gq *GaugeQuery) WithMetric(opts ...func(*MetricQuery)) *GaugeQuery { return gq } -// GroupBy used to group vertices by one or more fields/columns. +// 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: @@ -282,20 +306,17 @@ func (gq *GaugeQuery) WithMetric(opts ...func(*MetricQuery)) *GaugeQuery { // GroupBy(gauge.FieldTime). // Aggregate(ent.Count()). // Scan(ctx, &v) -// func (gq *GaugeQuery) GroupBy(field string, fields ...string) *GaugeGroupBy { - group := &GaugeGroupBy{config: gq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := gq.prepareQuery(ctx); err != nil { - return nil, err - } - return gq.sqlQuery(), nil - } - return group + gq.ctx.Fields = append([]string{field}, fields...) + grbuild := &GaugeGroupBy{build: gq} + grbuild.flds = &gq.ctx.Fields + grbuild.label = gauge.Label + grbuild.scan = grbuild.Scan + return grbuild } -// Select one or more fields from the given query. +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. // // Example: // @@ -306,20 +327,35 @@ func (gq *GaugeQuery) GroupBy(field string, fields ...string) *GaugeGroupBy { // client.Gauge.Query(). // Select(gauge.FieldTime). // Scan(ctx, &v) -// -func (gq *GaugeQuery) Select(field string, fields ...string) *GaugeSelect { - selector := &GaugeSelect{config: gq.config} - selector.fields = append([]string{field}, fields...) - selector.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := gq.prepareQuery(ctx); err != nil { - return nil, err - } - return gq.sqlQuery(), nil - } - return selector +func (gq *GaugeQuery) Select(fields ...string) *GaugeSelect { + gq.ctx.Fields = append(gq.ctx.Fields, fields...) + sbuild := &GaugeSelect{GaugeQuery: gq} + sbuild.label = gauge.Label + sbuild.flds, sbuild.scan = &gq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a GaugeSelect configured with the given aggregations. +func (gq *GaugeQuery) Aggregate(fns ...AggregateFunc) *GaugeSelect { + return gq.Select().Aggregate(fns...) } func (gq *GaugeQuery) prepareQuery(ctx context.Context) error { + for _, inter := range gq.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, gq); err != nil { + return err + } + } + } + for _, f := range gq.ctx.Fields { + if !gauge.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } if gq.path != nil { prev, err := gq.path(ctx) if err != nil { @@ -330,7 +366,7 @@ func (gq *GaugeQuery) prepareQuery(ctx context.Context) error { return nil } -func (gq *GaugeQuery) sqlAll(ctx context.Context) ([]*Gauge, error) { +func (gq *GaugeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Gauge, error) { var ( nodes = []*Gauge{} withFKs = gq.withFKs @@ -345,22 +381,17 @@ func (gq *GaugeQuery) sqlAll(ctx context.Context) ([]*Gauge, error) { if withFKs { _spec.Node.Columns = append(_spec.Node.Columns, gauge.ForeignKeys...) } - _spec.ScanValues = func() []interface{} { + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Gauge).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { node := &Gauge{config: gq.config} nodes = append(nodes, node) - values := node.scanValues() - if withFKs { - values = append(values, node.fkValues()...) - } - return values - } - _spec.Assign = func(values ...interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("ent: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] node.Edges.loadedTypes = loadedTypes - return node.assignValues(values...) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) } if err := sqlgraph.QueryNodes(ctx, gq.driver, _spec); err != nil { return nil, err @@ -368,60 +399,73 @@ func (gq *GaugeQuery) sqlAll(ctx context.Context) ([]*Gauge, error) { if len(nodes) == 0 { return nodes, nil } - if query := gq.withMetric; query != nil { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*Gauge) - for i := range nodes { - if fk := nodes[i].metric_gauges; fk != nil { - ids = append(ids, *fk) - nodeids[*fk] = append(nodeids[*fk], nodes[i]) - } - } - query.Where(metric.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { + if err := gq.loadMetric(ctx, query, nodes, nil, + func(n *Gauge, e *Metric) { n.Edges.Metric = e }); err != nil { return nil, err } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "metric_gauges" returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.Metric = n - } - } } - return nodes, nil } -func (gq *GaugeQuery) sqlCount(ctx context.Context) (int, error) { - _spec := gq.querySpec() - return sqlgraph.CountNodes(ctx, gq.driver, _spec) +func (gq *GaugeQuery) loadMetric(ctx context.Context, query *MetricQuery, nodes []*Gauge, init func(*Gauge), assign func(*Gauge, *Metric)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Gauge) + for i := range nodes { + if nodes[i].metric_gauges == nil { + continue + } + fk := *nodes[i].metric_gauges + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(metric.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 "metric_gauges" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil } -func (gq *GaugeQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := gq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("ent: check existence: %v", err) +func (gq *GaugeQuery) sqlCount(ctx context.Context) (int, error) { + _spec := gq.querySpec() + _spec.Node.Columns = gq.ctx.Fields + if len(gq.ctx.Fields) > 0 { + _spec.Unique = gq.ctx.Unique != nil && *gq.ctx.Unique } - return n > 0, nil + return sqlgraph.CountNodes(ctx, gq.driver, _spec) } func (gq *GaugeQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: gauge.Table, - Columns: gauge.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, - }, - From: gq.sql, - Unique: true, + _spec := sqlgraph.NewQuerySpec(gauge.Table, gauge.Columns, sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt)) + _spec.From = gq.sql + if unique := gq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if gq.path != nil { + _spec.Unique = true + } + if fields := gq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, gauge.FieldID) + for i := range fields { + if fields[i] != gauge.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } } if ps := gq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -430,55 +474,58 @@ func (gq *GaugeQuery) querySpec() *sqlgraph.QuerySpec { } } } - if limit := gq.limit; limit != nil { + if limit := gq.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := gq.offset; offset != nil { + if offset := gq.ctx.Offset; offset != nil { _spec.Offset = *offset } if ps := gq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector, gauge.ValidColumn) + ps[i](selector) } } } return _spec } -func (gq *GaugeQuery) sqlQuery() *sql.Selector { +func (gq *GaugeQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(gq.driver.Dialect()) t1 := builder.Table(gauge.Table) - selector := builder.Select(t1.Columns(gauge.Columns...)...).From(t1) + columns := gq.ctx.Fields + if len(columns) == 0 { + columns = gauge.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) if gq.sql != nil { selector = gq.sql - selector.Select(selector.Columns(gauge.Columns...)...) + selector.Select(selector.Columns(columns...)...) + } + if gq.ctx.Unique != nil && *gq.ctx.Unique { + selector.Distinct() } for _, p := range gq.predicates { p(selector) } for _, p := range gq.order { - p(selector, gauge.ValidColumn) + p(selector) } - if offset := gq.offset; offset != nil { + if offset := gq.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 := gq.limit; limit != nil { + if limit := gq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector } -// GaugeGroupBy is the builder for group-by Gauge entities. +// GaugeGroupBy is the group-by builder for Gauge entities. type GaugeGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) + selector + build *GaugeQuery } // Aggregate adds the given aggregation functions to the group-by query. @@ -487,471 +534,80 @@ func (ggb *GaugeGroupBy) Aggregate(fns ...AggregateFunc) *GaugeGroupBy { return ggb } -// Scan applies the group-by query and scan the result into the given value. -func (ggb *GaugeGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := ggb.path(ctx) - if err != nil { +// Scan applies the selector query and scans the result into the given value. +func (ggb *GaugeGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ggb.build.ctx, "GroupBy") + if err := ggb.build.prepareQuery(ctx); err != nil { return err } - ggb.sql = query - return ggb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (ggb *GaugeGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := ggb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field. -func (ggb *GaugeGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GaugeGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (ggb *GaugeGroupBy) StringsX(ctx context.Context) []string { - v, err := ggb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from group-by. It is only allowed when querying group-by with one field. -func (ggb *GaugeGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = ggb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{gauge.Label} - default: - err = fmt.Errorf("ent: GaugeGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (ggb *GaugeGroupBy) StringX(ctx context.Context) string { - v, err := ggb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field. -func (ggb *GaugeGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GaugeGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (ggb *GaugeGroupBy) IntsX(ctx context.Context) []int { - v, err := ggb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from group-by. It is only allowed when querying group-by with one field. -func (ggb *GaugeGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = ggb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{gauge.Label} - default: - err = fmt.Errorf("ent: GaugeGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (ggb *GaugeGroupBy) IntX(ctx context.Context) int { - v, err := ggb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field. -func (ggb *GaugeGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GaugeGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (ggb *GaugeGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := ggb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field. -func (ggb *GaugeGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = ggb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{gauge.Label} - default: - err = fmt.Errorf("ent: GaugeGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (ggb *GaugeGroupBy) Float64X(ctx context.Context) float64 { - v, err := ggb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field. -func (ggb *GaugeGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GaugeGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil + return scanWithInterceptors[*GaugeQuery, *GaugeGroupBy](ctx, ggb.build, ggb, ggb.build.inters, v) } -// BoolsX is like Bools, but panics if an error occurs. -func (ggb *GaugeGroupBy) BoolsX(ctx context.Context) []bool { - v, err := ggb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field. -func (ggb *GaugeGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = ggb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{gauge.Label} - default: - err = fmt.Errorf("ent: GaugeGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (ggb *GaugeGroupBy) BoolX(ctx context.Context) bool { - v, err := ggb.Bool(ctx) - if err != nil { - panic(err) +func (ggb *GaugeGroupBy) sqlScan(ctx context.Context, root *GaugeQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ggb.fns)) + for _, fn := range ggb.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (ggb *GaugeGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range ggb.fields { - if !gauge.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ggb.flds)+len(ggb.fns)) + for _, f := range *ggb.flds { + columns = append(columns, selector.C(f)) } + columns = append(columns, aggregation...) + selector.Select(columns...) } - selector := ggb.sqlQuery() + selector.GroupBy(selector.Columns(*ggb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := ggb.driver.Query(ctx, query, args, rows); err != nil { + if err := ggb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } -func (ggb *GaugeGroupBy) sqlQuery() *sql.Selector { - selector := ggb.sql - columns := make([]string, 0, len(ggb.fields)+len(ggb.fns)) - columns = append(columns, ggb.fields...) - for _, fn := range ggb.fns { - columns = append(columns, fn(selector, gauge.ValidColumn)) - } - return selector.Select(columns...).GroupBy(ggb.fields...) -} - -// GaugeSelect is the builder for select fields of Gauge entities. +// GaugeSelect is the builder for selecting fields of Gauge entities. type GaugeSelect struct { - config - fields []string - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Scan applies the selector query and scan the result into the given value. -func (gs *GaugeSelect) Scan(ctx context.Context, v interface{}) error { - query, err := gs.path(ctx) - if err != nil { - return err - } - gs.sql = query - return gs.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (gs *GaugeSelect) ScanX(ctx context.Context, v interface{}) { - if err := gs.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from selector. It is only allowed when selecting one field. -func (gs *GaugeSelect) Strings(ctx context.Context) ([]string, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GaugeSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (gs *GaugeSelect) StringsX(ctx context.Context) []string { - v, err := gs.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from selector. It is only allowed when selecting one field. -func (gs *GaugeSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = gs.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{gauge.Label} - default: - err = fmt.Errorf("ent: GaugeSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (gs *GaugeSelect) StringX(ctx context.Context) string { - v, err := gs.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from selector. It is only allowed when selecting one field. -func (gs *GaugeSelect) Ints(ctx context.Context) ([]int, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GaugeSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (gs *GaugeSelect) IntsX(ctx context.Context) []int { - v, err := gs.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from selector. It is only allowed when selecting one field. -func (gs *GaugeSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = gs.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{gauge.Label} - default: - err = fmt.Errorf("ent: GaugeSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (gs *GaugeSelect) IntX(ctx context.Context) int { - v, err := gs.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from selector. It is only allowed when selecting one field. -func (gs *GaugeSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GaugeSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (gs *GaugeSelect) Float64sX(ctx context.Context) []float64 { - v, err := gs.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from selector. It is only allowed when selecting one field. -func (gs *GaugeSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = gs.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{gauge.Label} - default: - err = fmt.Errorf("ent: GaugeSelect.Float64s returned %d results when one was expected", len(v)) - } - return + *GaugeQuery + selector } -// Float64X is like Float64, but panics if an error occurs. -func (gs *GaugeSelect) Float64X(ctx context.Context) float64 { - v, err := gs.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from selector. It is only allowed when selecting one field. -func (gs *GaugeSelect) Bools(ctx context.Context) ([]bool, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GaugeSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (gs *GaugeSelect) BoolsX(ctx context.Context) []bool { - v, err := gs.Bools(ctx) - if err != nil { - panic(err) - } - return v +// Aggregate adds the given aggregation functions to the selector query. +func (gs *GaugeSelect) Aggregate(fns ...AggregateFunc) *GaugeSelect { + gs.fns = append(gs.fns, fns...) + return gs } -// Bool returns a single bool from selector. It is only allowed when selecting one field. -func (gs *GaugeSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = gs.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{gauge.Label} - default: - err = fmt.Errorf("ent: GaugeSelect.Bools returned %d results when one was expected", len(v)) +// Scan applies the selector query and scans the result into the given value. +func (gs *GaugeSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, gs.ctx, "Select") + if err := gs.prepareQuery(ctx); err != nil { + return err } - return + return scanWithInterceptors[*GaugeQuery, *GaugeSelect](ctx, gs.GaugeQuery, gs, gs.inters, v) } -// BoolX is like Bool, but panics if an error occurs. -func (gs *GaugeSelect) BoolX(ctx context.Context) bool { - v, err := gs.Bool(ctx) - if err != nil { - panic(err) +func (gs *GaugeSelect) sqlScan(ctx context.Context, root *GaugeQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(gs.fns)) + for _, fn := range gs.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (gs *GaugeSelect) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range gs.fields { - if !gauge.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} - } + switch n := len(*gs.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 := gs.sqlQuery().Query() + query, args := selector.Query() if err := gs.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } - -func (gs *GaugeSelect) sqlQuery() sql.Querier { - selector := gs.sql - selector.Select(selector.Columns(gs.fields...)...) - return selector -} diff --git a/ent/gauge_update.go b/ent/gauge_update.go index 7fd22d04..05659ccd 100644 --- a/ent/gauge_update.go +++ b/ent/gauge_update.go @@ -1,14 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/gauge" "github.com/gobench-io/gobench/v2/ent/metric" "github.com/gobench-io/gobench/v2/ent/predicate" @@ -17,56 +18,55 @@ import ( // GaugeUpdate is the builder for updating Gauge entities. type GaugeUpdate struct { config - hooks []Hook - mutation *GaugeMutation - predicates []predicate.Gauge + hooks []Hook + mutation *GaugeMutation } -// Where adds a new predicate for the builder. +// Where appends a list predicates to the GaugeUpdate builder. func (gu *GaugeUpdate) Where(ps ...predicate.Gauge) *GaugeUpdate { - gu.predicates = append(gu.predicates, ps...) + gu.mutation.Where(ps...) return gu } -// SetTime sets the time field. +// SetTime sets the "time" field. func (gu *GaugeUpdate) SetTime(i int64) *GaugeUpdate { gu.mutation.ResetTime() gu.mutation.SetTime(i) return gu } -// AddTime adds i to time. +// AddTime adds i to the "time" field. func (gu *GaugeUpdate) AddTime(i int64) *GaugeUpdate { gu.mutation.AddTime(i) return gu } -// SetValue sets the value field. +// SetValue sets the "value" field. func (gu *GaugeUpdate) SetValue(i int64) *GaugeUpdate { gu.mutation.ResetValue() gu.mutation.SetValue(i) return gu } -// AddValue adds i to value. +// AddValue adds i to the "value" field. func (gu *GaugeUpdate) AddValue(i int64) *GaugeUpdate { gu.mutation.AddValue(i) return gu } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (gu *GaugeUpdate) SetWID(s string) *GaugeUpdate { gu.mutation.SetWID(s) return gu } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by ID. func (gu *GaugeUpdate) SetMetricID(id int) *GaugeUpdate { gu.mutation.SetMetricID(id) return gu } -// SetNillableMetricID sets the metric edge to Metric by id if the given value is not nil. +// SetNillableMetricID sets the "metric" edge to the Metric entity by ID if the given value is not nil. func (gu *GaugeUpdate) SetNillableMetricID(id *int) *GaugeUpdate { if id != nil { gu = gu.SetMetricID(*id) @@ -74,7 +74,7 @@ func (gu *GaugeUpdate) SetNillableMetricID(id *int) *GaugeUpdate { return gu } -// SetMetric sets the metric edge to Metric. +// SetMetric sets the "metric" edge to the Metric entity. func (gu *GaugeUpdate) SetMetric(m *Metric) *GaugeUpdate { return gu.SetMetricID(m.ID) } @@ -84,39 +84,15 @@ func (gu *GaugeUpdate) Mutation() *GaugeMutation { return gu.mutation } -// ClearMetric clears the "metric" edge to type Metric. +// ClearMetric clears the "metric" edge to the Metric entity. func (gu *GaugeUpdate) ClearMetric() *GaugeUpdate { gu.mutation.ClearMetric() return gu } -// Save executes the query and returns the number of rows/vertices matched by this operation. +// Save executes the query and returns the number of nodes affected by the update operation. func (gu *GaugeUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(gu.hooks) == 0 { - affected, err = gu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GaugeMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - gu.mutation = mutation - affected, err = gu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(gu.hooks) - 1; i >= 0; i-- { - mut = gu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, gu.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, gu.sqlSave, gu.mutation, gu.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -142,17 +118,8 @@ func (gu *GaugeUpdate) ExecX(ctx context.Context) { } func (gu *GaugeUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: gauge.Table, - Columns: gauge.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, - }, - } - if ps := gu.predicates; len(ps) > 0 { + _spec := sqlgraph.NewUpdateSpec(gauge.Table, gauge.Columns, sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt)) + if ps := gu.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -160,39 +127,19 @@ func (gu *GaugeUpdate) sqlSave(ctx context.Context) (n int, err error) { } } if value, ok := gu.mutation.Time(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldTime, - }) + _spec.SetField(gauge.FieldTime, field.TypeInt64, value) } if value, ok := gu.mutation.AddedTime(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldTime, - }) + _spec.AddField(gauge.FieldTime, field.TypeInt64, value) } if value, ok := gu.mutation.Value(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldValue, - }) + _spec.SetField(gauge.FieldValue, field.TypeInt64, value) } if value, ok := gu.mutation.AddedValue(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldValue, - }) + _spec.AddField(gauge.FieldValue, field.TypeInt64, value) } if value, ok := gu.mutation.WID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: gauge.FieldWID, - }) + _spec.SetField(gauge.FieldWID, field.TypeString, value) } if gu.mutation.MetricCleared() { edge := &sqlgraph.EdgeSpec{ @@ -202,10 +149,7 @@ func (gu *GaugeUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{gauge.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -218,10 +162,7 @@ func (gu *GaugeUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{gauge.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -232,60 +173,62 @@ func (gu *GaugeUpdate) sqlSave(ctx context.Context) (n int, err error) { if n, err = sqlgraph.UpdateNodes(ctx, gu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{gauge.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } + gu.mutation.done = true return n, nil } // GaugeUpdateOne is the builder for updating a single Gauge entity. type GaugeUpdateOne struct { config + fields []string hooks []Hook mutation *GaugeMutation } -// SetTime sets the time field. +// SetTime sets the "time" field. func (guo *GaugeUpdateOne) SetTime(i int64) *GaugeUpdateOne { guo.mutation.ResetTime() guo.mutation.SetTime(i) return guo } -// AddTime adds i to time. +// AddTime adds i to the "time" field. func (guo *GaugeUpdateOne) AddTime(i int64) *GaugeUpdateOne { guo.mutation.AddTime(i) return guo } -// SetValue sets the value field. +// SetValue sets the "value" field. func (guo *GaugeUpdateOne) SetValue(i int64) *GaugeUpdateOne { guo.mutation.ResetValue() guo.mutation.SetValue(i) return guo } -// AddValue adds i to value. +// AddValue adds i to the "value" field. func (guo *GaugeUpdateOne) AddValue(i int64) *GaugeUpdateOne { guo.mutation.AddValue(i) return guo } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (guo *GaugeUpdateOne) SetWID(s string) *GaugeUpdateOne { guo.mutation.SetWID(s) return guo } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by ID. func (guo *GaugeUpdateOne) SetMetricID(id int) *GaugeUpdateOne { guo.mutation.SetMetricID(id) return guo } -// SetNillableMetricID sets the metric edge to Metric by id if the given value is not nil. +// SetNillableMetricID sets the "metric" edge to the Metric entity by ID if the given value is not nil. func (guo *GaugeUpdateOne) SetNillableMetricID(id *int) *GaugeUpdateOne { if id != nil { guo = guo.SetMetricID(*id) @@ -293,7 +236,7 @@ func (guo *GaugeUpdateOne) SetNillableMetricID(id *int) *GaugeUpdateOne { return guo } -// SetMetric sets the metric edge to Metric. +// SetMetric sets the "metric" edge to the Metric entity. func (guo *GaugeUpdateOne) SetMetric(m *Metric) *GaugeUpdateOne { return guo.SetMetricID(m.ID) } @@ -303,39 +246,28 @@ func (guo *GaugeUpdateOne) Mutation() *GaugeMutation { return guo.mutation } -// ClearMetric clears the "metric" edge to type Metric. +// ClearMetric clears the "metric" edge to the Metric entity. func (guo *GaugeUpdateOne) ClearMetric() *GaugeUpdateOne { guo.mutation.ClearMetric() return guo } -// Save executes the query and returns the updated entity. +// Where appends a list predicates to the GaugeUpdate builder. +func (guo *GaugeUpdateOne) Where(ps ...predicate.Gauge) *GaugeUpdateOne { + guo.mutation.Where(ps...) + return guo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (guo *GaugeUpdateOne) Select(field string, fields ...string) *GaugeUpdateOne { + guo.fields = append([]string{field}, fields...) + return guo +} + +// Save executes the query and returns the updated Gauge entity. func (guo *GaugeUpdateOne) Save(ctx context.Context) (*Gauge, error) { - var ( - err error - node *Gauge - ) - if len(guo.hooks) == 0 { - node, err = guo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GaugeMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - guo.mutation = mutation - node, err = guo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(guo.hooks) - 1; i >= 0; i-- { - mut = guo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, guo.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, guo.sqlSave, guo.mutation, guo.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -361,55 +293,45 @@ func (guo *GaugeUpdateOne) ExecX(ctx context.Context) { } func (guo *GaugeUpdateOne) sqlSave(ctx context.Context) (_node *Gauge, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: gauge.Table, - Columns: gauge.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, - }, - } + _spec := sqlgraph.NewUpdateSpec(gauge.Table, gauge.Columns, sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt)) id, ok := guo.mutation.ID() if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Gauge.ID for update")} + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Gauge.id" for update`)} } _spec.Node.ID.Value = id + if fields := guo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, gauge.FieldID) + for _, f := range fields { + if !gauge.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != gauge.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := guo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } if value, ok := guo.mutation.Time(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldTime, - }) + _spec.SetField(gauge.FieldTime, field.TypeInt64, value) } if value, ok := guo.mutation.AddedTime(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldTime, - }) + _spec.AddField(gauge.FieldTime, field.TypeInt64, value) } if value, ok := guo.mutation.Value(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldValue, - }) + _spec.SetField(gauge.FieldValue, field.TypeInt64, value) } if value, ok := guo.mutation.AddedValue(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: gauge.FieldValue, - }) + _spec.AddField(gauge.FieldValue, field.TypeInt64, value) } if value, ok := guo.mutation.WID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: gauge.FieldWID, - }) + _spec.SetField(gauge.FieldWID, field.TypeString, value) } if guo.mutation.MetricCleared() { edge := &sqlgraph.EdgeSpec{ @@ -419,10 +341,7 @@ func (guo *GaugeUpdateOne) sqlSave(ctx context.Context) (_node *Gauge, err error Columns: []string{gauge.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -435,10 +354,7 @@ func (guo *GaugeUpdateOne) sqlSave(ctx context.Context) (_node *Gauge, err error Columns: []string{gauge.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -448,14 +364,15 @@ func (guo *GaugeUpdateOne) sqlSave(ctx context.Context) (_node *Gauge, err error } _node = &Gauge{config: guo.config} _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues() + _spec.ScanValues = _node.scanValues if err = sqlgraph.UpdateNode(ctx, guo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{gauge.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } + guo.mutation.done = true return _node, nil } diff --git a/ent/generate.go b/ent/generate.go new file mode 100644 index 00000000..45a6e70c --- /dev/null +++ b/ent/generate.go @@ -0,0 +1,3 @@ +package ent + +//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema \ No newline at end of file diff --git a/ent/graph.go b/ent/graph.go index 17ff114d..a5d31704 100644 --- a/ent/graph.go +++ b/ent/graph.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -6,7 +6,8 @@ import ( "fmt" "strings" - "github.com/facebook/ent/dialect/sql" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/gobench-io/gobench/v2/ent/graph" "github.com/gobench-io/gobench/v2/ent/group" ) @@ -24,14 +25,15 @@ type Graph struct { // The values are being populated by the GraphQuery when eager-loading is set. Edges GraphEdges `json:"edges"` group_graphs *int + selectValues sql.SelectValues } // GraphEdges holds the relations/edges for other nodes in the graph. type GraphEdges struct { // Group holds the value of the group edge. - Group *Group + Group *Group `json:"group,omitempty"` // Metrics holds the value of the metrics edge. - Metrics []*Metric + Metrics []*Metric `json:"metrics,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [2]bool @@ -42,8 +44,7 @@ type GraphEdges struct { func (e GraphEdges) GroupOrErr() (*Group, error) { if e.loadedTypes[0] { if e.Group == nil { - // The edge group was loaded in eager-loading, - // but was not found. + // Edge was loaded but was not found. return nil, &NotFoundError{label: group.Label} } return e.Group, nil @@ -61,80 +62,94 @@ func (e GraphEdges) MetricsOrErr() ([]*Metric, error) { } // scanValues returns the types for scanning values from sql.Rows. -func (*Graph) scanValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // id - &sql.NullString{}, // title - &sql.NullString{}, // unit - } -} - -// fkValues returns the types for scanning foreign-keys values from sql.Rows. -func (*Graph) fkValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // group_graphs +func (*Graph) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case graph.FieldID: + values[i] = new(sql.NullInt64) + case graph.FieldTitle, graph.FieldUnit: + values[i] = new(sql.NullString) + case graph.ForeignKeys[0]: // group_graphs + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } } + return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Graph fields. -func (gr *Graph) assignValues(values ...interface{}) error { - if m, n := len(values), len(graph.Columns); m < n { +func (gr *Graph) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } - value, ok := values[0].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - gr.ID = int(value.Int64) - values = values[1:] - if value, ok := values[0].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field title", values[0]) - } else if value.Valid { - gr.Title = value.String - } - if value, ok := values[1].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field unit", values[1]) - } else if value.Valid { - gr.Unit = value.String - } - values = values[2:] - if len(values) == len(graph.ForeignKeys) { - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field group_graphs", value) - } else if value.Valid { - gr.group_graphs = new(int) - *gr.group_graphs = int(value.Int64) + for i := range columns { + switch columns[i] { + case graph.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + gr.ID = int(value.Int64) + case graph.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + gr.Title = value.String + } + case graph.FieldUnit: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field unit", values[i]) + } else if value.Valid { + gr.Unit = value.String + } + case graph.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field group_graphs", value) + } else if value.Valid { + gr.group_graphs = new(int) + *gr.group_graphs = int(value.Int64) + } + default: + gr.selectValues.Set(columns[i], values[i]) } } return nil } -// QueryGroup queries the group edge of the Graph. +// Value returns the ent.Value that was dynamically selected and assigned to the Graph. +// This includes values selected through modifiers, order, etc. +func (gr *Graph) Value(name string) (ent.Value, error) { + return gr.selectValues.Get(name) +} + +// QueryGroup queries the "group" edge of the Graph entity. func (gr *Graph) QueryGroup() *GroupQuery { - return (&GraphClient{config: gr.config}).QueryGroup(gr) + return NewGraphClient(gr.config).QueryGroup(gr) } -// QueryMetrics queries the metrics edge of the Graph. +// QueryMetrics queries the "metrics" edge of the Graph entity. func (gr *Graph) QueryMetrics() *MetricQuery { - return (&GraphClient{config: gr.config}).QueryMetrics(gr) + return NewGraphClient(gr.config).QueryMetrics(gr) } // Update returns a builder for updating this Graph. -// Note that, you need to call Graph.Unwrap() before calling this method, if this Graph +// Note that you need to call Graph.Unwrap() before calling this method if this Graph // was returned from a transaction, and the transaction was committed or rolled back. func (gr *Graph) Update() *GraphUpdateOne { - return (&GraphClient{config: gr.config}).UpdateOne(gr) + return NewGraphClient(gr.config).UpdateOne(gr) } -// Unwrap unwraps the entity that was returned from a transaction after it was closed, -// so that all next queries will be executed through the driver which created the transaction. +// Unwrap unwraps the Graph entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. func (gr *Graph) Unwrap() *Graph { - tx, ok := gr.config.driver.(*txDriver) + _tx, ok := gr.config.driver.(*txDriver) if !ok { panic("ent: Graph is not a transactional entity") } - gr.config.driver = tx.drv + gr.config.driver = _tx.drv return gr } @@ -142,10 +157,11 @@ func (gr *Graph) Unwrap() *Graph { func (gr *Graph) String() string { var builder strings.Builder builder.WriteString("Graph(") - builder.WriteString(fmt.Sprintf("id=%v", gr.ID)) - builder.WriteString(", title=") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("title=") builder.WriteString(gr.Title) - builder.WriteString(", unit=") + builder.WriteString(", ") + builder.WriteString("unit=") builder.WriteString(gr.Unit) builder.WriteByte(')') return builder.String() @@ -153,9 +169,3 @@ func (gr *Graph) String() string { // Graphs is a parsable slice of Graph. type Graphs []*Graph - -func (gr Graphs) config(cfg config) { - for _i := range gr { - gr[_i].config = cfg - } -} diff --git a/ent/graph/graph.go b/ent/graph/graph.go index ef25387d..dc5f8d81 100644 --- a/ent/graph/graph.go +++ b/ent/graph/graph.go @@ -1,7 +1,12 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package graph +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + const ( // Label holds the string label denoting the graph type in the database. Label = "graph" @@ -11,22 +16,20 @@ const ( FieldTitle = "title" // FieldUnit holds the string denoting the unit field in the database. FieldUnit = "unit" - // EdgeGroup holds the string denoting the group edge name in mutations. EdgeGroup = "group" // EdgeMetrics holds the string denoting the metrics edge name in mutations. EdgeMetrics = "metrics" - // Table holds the table name of the graph in the database. Table = "graphs" - // GroupTable is the table the holds the group relation/edge. + // GroupTable is the table that holds the group relation/edge. GroupTable = "graphs" // GroupInverseTable is the table name for the Group entity. // It exists in this package in order to avoid circular dependency with the "group" package. GroupInverseTable = "groups" // GroupColumn is the table column denoting the group relation/edge. GroupColumn = "group_graphs" - // MetricsTable is the table the holds the metrics relation/edge. + // MetricsTable is the table that holds the metrics relation/edge. MetricsTable = "metrics" // MetricsInverseTable is the table name for the Metric entity. // It exists in this package in order to avoid circular dependency with the "metric" package. @@ -42,7 +45,8 @@ var Columns = []string{ FieldUnit, } -// ForeignKeys holds the SQL foreign-keys that are owned by the Graph type. +// ForeignKeys holds the SQL foreign-keys that are owned by the "graphs" +// table and are not defined as standalone fields in the schema. var ForeignKeys = []string{ "group_graphs", } @@ -61,3 +65,56 @@ func ValidColumn(column string) bool { } return false } + +// OrderOption defines the ordering options for the Graph queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByTitle orders the results by the title field. +func ByTitle(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTitle, opts...).ToFunc() +} + +// ByUnit orders the results by the unit field. +func ByUnit(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUnit, opts...).ToFunc() +} + +// ByGroupField orders the results by group field. +func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...)) + } +} + +// ByMetricsCount orders the results by metrics count. +func ByMetricsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newMetricsStep(), opts...) + } +} + +// ByMetrics orders the results by metrics terms. +func ByMetrics(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newMetricsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newGroupStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn), + ) +} +func newMetricsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(MetricsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, MetricsTable, MetricsColumn), + ) +} diff --git a/ent/graph/where.go b/ent/graph/where.go index 34072d9d..f367c5f2 100644 --- a/ent/graph/where.go +++ b/ent/graph/where.go @@ -1,330 +1,196 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package graph import ( - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" "github.com/gobench-io/gobench/v2/ent/predicate" ) -// ID filters vertices based on their identifier. +// ID filters vertices based on their ID field. func ID(id int) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Graph(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Graph(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) + return predicate.Graph(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) + return predicate.Graph(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) + return predicate.Graph(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) + return predicate.Graph(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) + return predicate.Graph(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) + return predicate.Graph(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) + return predicate.Graph(sql.FieldLTE(FieldID, id)) } // Title applies equality check predicate on the "title" field. It's identical to TitleEQ. func Title(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldEQ(FieldTitle, v)) } // Unit applies equality check predicate on the "unit" field. It's identical to UnitEQ. func Unit(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldEQ(FieldUnit, v)) } // TitleEQ applies the EQ predicate on the "title" field. func TitleEQ(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldEQ(FieldTitle, v)) } // TitleNEQ applies the NEQ predicate on the "title" field. func TitleNEQ(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldNEQ(FieldTitle, v)) } // TitleIn applies the In predicate on the "title" field. func TitleIn(vs ...string) predicate.Graph { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Graph(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldTitle), v...)) - }) + return predicate.Graph(sql.FieldIn(FieldTitle, vs...)) } // TitleNotIn applies the NotIn predicate on the "title" field. func TitleNotIn(vs ...string) predicate.Graph { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Graph(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldTitle), v...)) - }) + return predicate.Graph(sql.FieldNotIn(FieldTitle, vs...)) } // TitleGT applies the GT predicate on the "title" field. func TitleGT(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldGT(FieldTitle, v)) } // TitleGTE applies the GTE predicate on the "title" field. func TitleGTE(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldGTE(FieldTitle, v)) } // TitleLT applies the LT predicate on the "title" field. func TitleLT(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldLT(FieldTitle, v)) } // TitleLTE applies the LTE predicate on the "title" field. func TitleLTE(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldLTE(FieldTitle, v)) } // TitleContains applies the Contains predicate on the "title" field. func TitleContains(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldContains(FieldTitle, v)) } // TitleHasPrefix applies the HasPrefix predicate on the "title" field. func TitleHasPrefix(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldHasPrefix(FieldTitle, v)) } // TitleHasSuffix applies the HasSuffix predicate on the "title" field. func TitleHasSuffix(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldHasSuffix(FieldTitle, v)) } // TitleEqualFold applies the EqualFold predicate on the "title" field. func TitleEqualFold(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldEqualFold(FieldTitle, v)) } // TitleContainsFold applies the ContainsFold predicate on the "title" field. func TitleContainsFold(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldTitle), v)) - }) + return predicate.Graph(sql.FieldContainsFold(FieldTitle, v)) } // UnitEQ applies the EQ predicate on the "unit" field. func UnitEQ(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldEQ(FieldUnit, v)) } // UnitNEQ applies the NEQ predicate on the "unit" field. func UnitNEQ(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldNEQ(FieldUnit, v)) } // UnitIn applies the In predicate on the "unit" field. func UnitIn(vs ...string) predicate.Graph { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Graph(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldUnit), v...)) - }) + return predicate.Graph(sql.FieldIn(FieldUnit, vs...)) } // UnitNotIn applies the NotIn predicate on the "unit" field. func UnitNotIn(vs ...string) predicate.Graph { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Graph(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldUnit), v...)) - }) + return predicate.Graph(sql.FieldNotIn(FieldUnit, vs...)) } // UnitGT applies the GT predicate on the "unit" field. func UnitGT(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldGT(FieldUnit, v)) } // UnitGTE applies the GTE predicate on the "unit" field. func UnitGTE(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldGTE(FieldUnit, v)) } // UnitLT applies the LT predicate on the "unit" field. func UnitLT(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldLT(FieldUnit, v)) } // UnitLTE applies the LTE predicate on the "unit" field. func UnitLTE(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldLTE(FieldUnit, v)) } // UnitContains applies the Contains predicate on the "unit" field. func UnitContains(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldContains(FieldUnit, v)) } // UnitHasPrefix applies the HasPrefix predicate on the "unit" field. func UnitHasPrefix(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldHasPrefix(FieldUnit, v)) } // UnitHasSuffix applies the HasSuffix predicate on the "unit" field. func UnitHasSuffix(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldHasSuffix(FieldUnit, v)) } // UnitEqualFold applies the EqualFold predicate on the "unit" field. func UnitEqualFold(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldEqualFold(FieldUnit, v)) } // UnitContainsFold applies the ContainsFold predicate on the "unit" field. func UnitContainsFold(v string) predicate.Graph { - return predicate.Graph(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldUnit), v)) - }) + return predicate.Graph(sql.FieldContainsFold(FieldUnit, v)) } // HasGroup applies the HasEdge predicate on the "group" edge. @@ -332,7 +198,6 @@ func HasGroup() predicate.Graph { return predicate.Graph(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(GroupTable, FieldID), sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn), ) sqlgraph.HasNeighbors(s, step) @@ -342,11 +207,7 @@ func HasGroup() predicate.Graph { // HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates). func HasGroupWith(preds ...predicate.Group) predicate.Graph { return predicate.Graph(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(GroupInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn), - ) + step := newGroupStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -360,7 +221,6 @@ func HasMetrics() predicate.Graph { return predicate.Graph(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(MetricsTable, FieldID), sqlgraph.Edge(sqlgraph.O2M, false, MetricsTable, MetricsColumn), ) sqlgraph.HasNeighbors(s, step) @@ -370,11 +230,7 @@ func HasMetrics() predicate.Graph { // HasMetricsWith applies the HasEdge predicate on the "metrics" edge with a given conditions (other predicates). func HasMetricsWith(preds ...predicate.Metric) predicate.Graph { return predicate.Graph(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(MetricsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, MetricsTable, MetricsColumn), - ) + step := newMetricsStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -383,7 +239,7 @@ func HasMetricsWith(preds ...predicate.Metric) predicate.Graph { }) } -// And groups list of predicates with the AND operator between them. +// And groups predicates with the AND operator between them. func And(predicates ...predicate.Graph) predicate.Graph { return predicate.Graph(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) @@ -394,7 +250,7 @@ func And(predicates ...predicate.Graph) predicate.Graph { }) } -// Or groups list of predicates with the OR operator between them. +// Or groups predicates with the OR operator between them. func Or(predicates ...predicate.Graph) predicate.Graph { return predicate.Graph(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) diff --git a/ent/graph_create.go b/ent/graph_create.go index 2737cc3b..f22151d2 100644 --- a/ent/graph_create.go +++ b/ent/graph_create.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -7,8 +7,8 @@ import ( "errors" "fmt" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/graph" "github.com/gobench-io/gobench/v2/ent/group" "github.com/gobench-io/gobench/v2/ent/metric" @@ -21,25 +21,25 @@ type GraphCreate struct { hooks []Hook } -// SetTitle sets the title field. +// SetTitle sets the "title" field. func (gc *GraphCreate) SetTitle(s string) *GraphCreate { gc.mutation.SetTitle(s) return gc } -// SetUnit sets the unit field. +// SetUnit sets the "unit" field. func (gc *GraphCreate) SetUnit(s string) *GraphCreate { gc.mutation.SetUnit(s) return gc } -// SetGroupID sets the group edge to Group by id. +// SetGroupID sets the "group" edge to the Group entity by ID. func (gc *GraphCreate) SetGroupID(id int) *GraphCreate { gc.mutation.SetGroupID(id) return gc } -// SetNillableGroupID sets the group edge to Group by id if the given value is not nil. +// SetNillableGroupID sets the "group" edge to the Group entity by ID if the given value is not nil. func (gc *GraphCreate) SetNillableGroupID(id *int) *GraphCreate { if id != nil { gc = gc.SetGroupID(*id) @@ -47,18 +47,18 @@ func (gc *GraphCreate) SetNillableGroupID(id *int) *GraphCreate { return gc } -// SetGroup sets the group edge to Group. +// SetGroup sets the "group" edge to the Group entity. func (gc *GraphCreate) SetGroup(g *Group) *GraphCreate { return gc.SetGroupID(g.ID) } -// AddMetricIDs adds the metrics edge to Metric by ids. +// AddMetricIDs adds the "metrics" edge to the Metric entity by IDs. func (gc *GraphCreate) AddMetricIDs(ids ...int) *GraphCreate { gc.mutation.AddMetricIDs(ids...) return gc } -// AddMetrics adds the metrics edges to Metric. +// AddMetrics adds the "metrics" edges to the Metric entity. func (gc *GraphCreate) AddMetrics(m ...*Metric) *GraphCreate { ids := make([]int, len(m)) for i := range m { @@ -74,37 +74,7 @@ func (gc *GraphCreate) Mutation() *GraphMutation { // Save creates the Graph in the database. func (gc *GraphCreate) Save(ctx context.Context) (*Graph, error) { - var ( - err error - node *Graph - ) - if len(gc.hooks) == 0 { - if err = gc.check(); err != nil { - return nil, err - } - node, err = gc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GraphMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = gc.check(); err != nil { - return nil, err - } - gc.mutation = mutation - node, err = gc.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(gc.hooks) - 1; i >= 0; i-- { - mut = gc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, gc.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, gc.sqlSave, gc.mutation, gc.hooks) } // SaveX calls Save and panics if Save returns an error. @@ -116,55 +86,59 @@ func (gc *GraphCreate) SaveX(ctx context.Context) *Graph { return v } +// Exec executes the query. +func (gc *GraphCreate) Exec(ctx context.Context) error { + _, err := gc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gc *GraphCreate) ExecX(ctx context.Context) { + if err := gc.Exec(ctx); err != nil { + panic(err) + } +} + // check runs all checks and user-defined validators on the builder. func (gc *GraphCreate) check() error { if _, ok := gc.mutation.Title(); !ok { - return &ValidationError{Name: "title", err: errors.New("ent: missing required field \"title\"")} + return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Graph.title"`)} } if _, ok := gc.mutation.Unit(); !ok { - return &ValidationError{Name: "unit", err: errors.New("ent: missing required field \"unit\"")} + return &ValidationError{Name: "unit", err: errors.New(`ent: missing required field "Graph.unit"`)} } return nil } func (gc *GraphCreate) sqlSave(ctx context.Context) (*Graph, error) { + if err := gc.check(); err != nil { + return nil, err + } _node, _spec := gc.createSpec() if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } id := _spec.ID.Value.(int64) _node.ID = int(id) + gc.mutation.id = &_node.ID + gc.mutation.done = true return _node, nil } func (gc *GraphCreate) createSpec() (*Graph, *sqlgraph.CreateSpec) { var ( _node = &Graph{config: gc.config} - _spec = &sqlgraph.CreateSpec{ - Table: graph.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, - } + _spec = sqlgraph.NewCreateSpec(graph.Table, sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt)) ) if value, ok := gc.mutation.Title(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: graph.FieldTitle, - }) + _spec.SetField(graph.FieldTitle, field.TypeString, value) _node.Title = value } if value, ok := gc.mutation.Unit(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: graph.FieldUnit, - }) + _spec.SetField(graph.FieldUnit, field.TypeString, value) _node.Unit = value } if nodes := gc.mutation.GroupIDs(); len(nodes) > 0 { @@ -175,15 +149,13 @@ func (gc *GraphCreate) createSpec() (*Graph, *sqlgraph.CreateSpec) { Columns: []string{graph.GroupColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } + _node.group_graphs = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } if nodes := gc.mutation.MetricsIDs(); len(nodes) > 0 { @@ -194,10 +166,7 @@ func (gc *GraphCreate) createSpec() (*Graph, *sqlgraph.CreateSpec) { Columns: []string{graph.MetricsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -208,7 +177,7 @@ func (gc *GraphCreate) createSpec() (*Graph, *sqlgraph.CreateSpec) { return _node, _spec } -// GraphCreateBulk is the builder for creating a bulk of Graph entities. +// GraphCreateBulk is the builder for creating many Graph entities in bulk. type GraphCreateBulk struct { config builders []*GraphCreate @@ -231,24 +200,28 @@ func (gcb *GraphCreateBulk) Save(ctx context.Context) ([]*Graph, error) { return nil, err } builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() var err error + nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, gcb.builders[i+1].mutation) } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, gcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if err = sqlgraph.BatchCreate(ctx, gcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } } } - mutation.done = true if err != nil { return nil, err } - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { @@ -265,7 +238,7 @@ func (gcb *GraphCreateBulk) Save(ctx context.Context) ([]*Graph, error) { return nodes, nil } -// SaveX calls Save and panics if Save returns an error. +// SaveX is like Save, but panics if an error occurs. func (gcb *GraphCreateBulk) SaveX(ctx context.Context) []*Graph { v, err := gcb.Save(ctx) if err != nil { @@ -273,3 +246,16 @@ func (gcb *GraphCreateBulk) SaveX(ctx context.Context) []*Graph { } return v } + +// Exec executes the query. +func (gcb *GraphCreateBulk) Exec(ctx context.Context) error { + _, err := gcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcb *GraphCreateBulk) ExecX(ctx context.Context) { + if err := gcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/graph_delete.go b/ent/graph_delete.go index 62f9fe8c..f08bf59c 100644 --- a/ent/graph_delete.go +++ b/ent/graph_delete.go @@ -1,14 +1,13 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/graph" "github.com/gobench-io/gobench/v2/ent/predicate" ) @@ -16,44 +15,19 @@ import ( // GraphDelete is the builder for deleting a Graph entity. type GraphDelete struct { config - hooks []Hook - mutation *GraphMutation - predicates []predicate.Graph + hooks []Hook + mutation *GraphMutation } -// Where adds a new predicate to the delete builder. +// Where appends a list predicates to the GraphDelete builder. func (gd *GraphDelete) Where(ps ...predicate.Graph) *GraphDelete { - gd.predicates = append(gd.predicates, ps...) + gd.mutation.Where(ps...) return gd } // Exec executes the deletion query and returns how many vertices were deleted. func (gd *GraphDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(gd.hooks) == 0 { - affected, err = gd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GraphMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - gd.mutation = mutation - affected, err = gd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(gd.hooks) - 1; i >= 0; i-- { - mut = gd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, gd.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, gd.sqlExec, gd.mutation, gd.hooks) } // ExecX is like Exec, but panics if an error occurs. @@ -66,23 +40,20 @@ func (gd *GraphDelete) ExecX(ctx context.Context) int { } func (gd *GraphDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: graph.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, - }, - } - if ps := gd.predicates; len(ps) > 0 { + _spec := sqlgraph.NewDeleteSpec(graph.Table, sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt)) + if ps := gd.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - return sqlgraph.DeleteNodes(ctx, gd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, gd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + gd.mutation.done = true + return affected, err } // GraphDeleteOne is the builder for deleting a single Graph entity. @@ -90,6 +61,12 @@ type GraphDeleteOne struct { gd *GraphDelete } +// Where appends a list predicates to the GraphDelete builder. +func (gdo *GraphDeleteOne) Where(ps ...predicate.Graph) *GraphDeleteOne { + gdo.gd.mutation.Where(ps...) + return gdo +} + // Exec executes the deletion query. func (gdo *GraphDeleteOne) Exec(ctx context.Context) error { n, err := gdo.gd.Exec(ctx) @@ -105,5 +82,7 @@ func (gdo *GraphDeleteOne) Exec(ctx context.Context) error { // ExecX is like Exec, but panics if an error occurs. func (gdo *GraphDeleteOne) ExecX(ctx context.Context) { - gdo.gd.ExecX(ctx) + if err := gdo.Exec(ctx); err != nil { + panic(err) + } } diff --git a/ent/graph_query.go b/ent/graph_query.go index ecdcc68e..e91dbf87 100644 --- a/ent/graph_query.go +++ b/ent/graph_query.go @@ -1,17 +1,16 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" "database/sql/driver" - "errors" "fmt" "math" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/graph" "github.com/gobench-io/gobench/v2/ent/group" "github.com/gobench-io/gobench/v2/ent/metric" @@ -21,12 +20,10 @@ import ( // GraphQuery is the builder for querying Graph entities. type GraphQuery struct { config - limit *int - offset *int - order []OrderFunc - unique []string - predicates []predicate.Graph - // eager-loading edges. + ctx *QueryContext + order []graph.OrderOption + inters []Interceptor + predicates []predicate.Graph withGroup *GroupQuery withMetrics *MetricQuery withFKs bool @@ -35,38 +32,45 @@ type GraphQuery struct { path func(context.Context) (*sql.Selector, error) } -// Where adds a new predicate for the builder. +// Where adds a new predicate for the GraphQuery builder. func (gq *GraphQuery) Where(ps ...predicate.Graph) *GraphQuery { gq.predicates = append(gq.predicates, ps...) return gq } -// Limit adds a limit step to the query. +// Limit the number of records to be returned by this query. func (gq *GraphQuery) Limit(limit int) *GraphQuery { - gq.limit = &limit + gq.ctx.Limit = &limit return gq } -// Offset adds an offset step to the query. +// Offset to start from. func (gq *GraphQuery) Offset(offset int) *GraphQuery { - gq.offset = &offset + gq.ctx.Offset = &offset return gq } -// Order adds an order step to the query. -func (gq *GraphQuery) Order(o ...OrderFunc) *GraphQuery { +// 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 (gq *GraphQuery) Unique(unique bool) *GraphQuery { + gq.ctx.Unique = &unique + return gq +} + +// Order specifies how the records should be ordered. +func (gq *GraphQuery) Order(o ...graph.OrderOption) *GraphQuery { gq.order = append(gq.order, o...) return gq } -// QueryGroup chains the current query on the group edge. +// QueryGroup chains the current query on the "group" edge. func (gq *GraphQuery) QueryGroup() *GroupQuery { - query := &GroupQuery{config: gq.config} + query := (&GroupClient{config: gq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := gq.prepareQuery(ctx); err != nil { return nil, err } - selector := gq.sqlQuery() + selector := gq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -81,14 +85,14 @@ func (gq *GraphQuery) QueryGroup() *GroupQuery { return query } -// QueryMetrics chains the current query on the metrics edge. +// QueryMetrics chains the current query on the "metrics" edge. func (gq *GraphQuery) QueryMetrics() *MetricQuery { - query := &MetricQuery{config: gq.config} + query := (&MetricClient{config: gq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := gq.prepareQuery(ctx); err != nil { return nil, err } - selector := gq.sqlQuery() + selector := gq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -103,9 +107,10 @@ func (gq *GraphQuery) QueryMetrics() *MetricQuery { return query } -// First returns the first Graph entity in the query. Returns *NotFoundError when no graph was found. +// First returns the first Graph entity from the query. +// Returns a *NotFoundError when no Graph was found. func (gq *GraphQuery) First(ctx context.Context) (*Graph, error) { - nodes, err := gq.Limit(1).All(ctx) + nodes, err := gq.Limit(1).All(setContextOp(ctx, gq.ctx, "First")) if err != nil { return nil, err } @@ -124,10 +129,11 @@ func (gq *GraphQuery) FirstX(ctx context.Context) *Graph { return node } -// FirstID returns the first Graph id in the query. Returns *NotFoundError when no id was found. +// FirstID returns the first Graph ID from the query. +// Returns a *NotFoundError when no Graph ID was found. func (gq *GraphQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = gq.Limit(1).IDs(ctx); err != nil { + if ids, err = gq.Limit(1).IDs(setContextOp(ctx, gq.ctx, "FirstID")); err != nil { return } if len(ids) == 0 { @@ -137,8 +143,8 @@ func (gq *GraphQuery) FirstID(ctx context.Context) (id int, err error) { return ids[0], nil } -// FirstXID is like FirstID, but panics if an error occurs. -func (gq *GraphQuery) FirstXID(ctx context.Context) int { +// FirstIDX is like FirstID, but panics if an error occurs. +func (gq *GraphQuery) FirstIDX(ctx context.Context) int { id, err := gq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -146,9 +152,11 @@ func (gq *GraphQuery) FirstXID(ctx context.Context) int { return id } -// Only returns the only Graph entity in the query, returns an error if not exactly one entity was returned. +// Only returns a single Graph entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Graph entity is found. +// Returns a *NotFoundError when no Graph entities are found. func (gq *GraphQuery) Only(ctx context.Context) (*Graph, error) { - nodes, err := gq.Limit(2).All(ctx) + nodes, err := gq.Limit(2).All(setContextOp(ctx, gq.ctx, "Only")) if err != nil { return nil, err } @@ -171,10 +179,12 @@ func (gq *GraphQuery) OnlyX(ctx context.Context) *Graph { return node } -// OnlyID returns the only Graph id in the query, returns an error if not exactly one id was returned. +// OnlyID is like Only, but returns the only Graph ID in the query. +// Returns a *NotSingularError when more than one Graph ID is found. +// Returns a *NotFoundError when no entities are found. func (gq *GraphQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = gq.Limit(2).IDs(ctx); err != nil { + if ids, err = gq.Limit(2).IDs(setContextOp(ctx, gq.ctx, "OnlyID")); err != nil { return } switch len(ids) { @@ -199,10 +209,12 @@ func (gq *GraphQuery) OnlyIDX(ctx context.Context) int { // All executes the query and returns a list of Graphs. func (gq *GraphQuery) All(ctx context.Context) ([]*Graph, error) { + ctx = setContextOp(ctx, gq.ctx, "All") if err := gq.prepareQuery(ctx); err != nil { return nil, err } - return gq.sqlAll(ctx) + qr := querierAll[[]*Graph, *GraphQuery]() + return withInterceptors[[]*Graph](ctx, gq, qr, gq.inters) } // AllX is like All, but panics if an error occurs. @@ -214,10 +226,13 @@ func (gq *GraphQuery) AllX(ctx context.Context) []*Graph { return nodes } -// IDs executes the query and returns a list of Graph ids. -func (gq *GraphQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := gq.Select(graph.FieldID).Scan(ctx, &ids); err != nil { +// IDs executes the query and returns a list of Graph IDs. +func (gq *GraphQuery) IDs(ctx context.Context) (ids []int, err error) { + if gq.ctx.Unique == nil && gq.path != nil { + gq.Unique(true) + } + ctx = setContextOp(ctx, gq.ctx, "IDs") + if err = gq.Select(graph.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil @@ -234,10 +249,11 @@ func (gq *GraphQuery) IDsX(ctx context.Context) []int { // Count returns the count of the given query. func (gq *GraphQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, gq.ctx, "Count") if err := gq.prepareQuery(ctx); err != nil { return 0, err } - return gq.sqlCount(ctx) + return withInterceptors[int](ctx, gq, querierCount[*GraphQuery](), gq.inters) } // CountX is like Count, but panics if an error occurs. @@ -251,10 +267,15 @@ func (gq *GraphQuery) CountX(ctx context.Context) int { // Exist returns true if the query has elements in the graph. func (gq *GraphQuery) Exist(ctx context.Context) (bool, error) { - if err := gq.prepareQuery(ctx); err != nil { - return false, err + ctx = setContextOp(ctx, gq.ctx, "Exist") + switch _, err := gq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil } - return gq.sqlExist(ctx) } // ExistX is like Exist, but panics if an error occurs. @@ -266,26 +287,30 @@ func (gq *GraphQuery) ExistX(ctx context.Context) bool { return exist } -// Clone returns a duplicate of the query builder, including all associated steps. It can be +// Clone returns a duplicate of the GraphQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. func (gq *GraphQuery) Clone() *GraphQuery { + if gq == nil { + return nil + } return &GraphQuery{ - config: gq.config, - limit: gq.limit, - offset: gq.offset, - order: append([]OrderFunc{}, gq.order...), - unique: append([]string{}, gq.unique...), - predicates: append([]predicate.Graph{}, gq.predicates...), + config: gq.config, + ctx: gq.ctx.Clone(), + order: append([]graph.OrderOption{}, gq.order...), + inters: append([]Interceptor{}, gq.inters...), + predicates: append([]predicate.Graph{}, gq.predicates...), + withGroup: gq.withGroup.Clone(), + withMetrics: gq.withMetrics.Clone(), // clone intermediate query. sql: gq.sql.Clone(), path: gq.path, } } -// WithGroup tells the query-builder to eager-loads the nodes that are connected to -// the "group" edge. The optional arguments used to configure the query builder of the edge. +// WithGroup tells the query-builder to eager-load the nodes that are connected to +// the "group" edge. The optional arguments are used to configure the query builder of the edge. func (gq *GraphQuery) WithGroup(opts ...func(*GroupQuery)) *GraphQuery { - query := &GroupQuery{config: gq.config} + query := (&GroupClient{config: gq.config}).Query() for _, opt := range opts { opt(query) } @@ -293,10 +318,10 @@ func (gq *GraphQuery) WithGroup(opts ...func(*GroupQuery)) *GraphQuery { return gq } -// WithMetrics tells the query-builder to eager-loads the nodes that are connected to -// the "metrics" edge. The optional arguments used to configure the query builder of the edge. +// WithMetrics tells the query-builder to eager-load the nodes that are connected to +// the "metrics" edge. The optional arguments are used to configure the query builder of the edge. func (gq *GraphQuery) WithMetrics(opts ...func(*MetricQuery)) *GraphQuery { - query := &MetricQuery{config: gq.config} + query := (&MetricClient{config: gq.config}).Query() for _, opt := range opts { opt(query) } @@ -304,7 +329,7 @@ func (gq *GraphQuery) WithMetrics(opts ...func(*MetricQuery)) *GraphQuery { return gq } -// GroupBy used to group vertices by one or more fields/columns. +// 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: @@ -318,20 +343,17 @@ func (gq *GraphQuery) WithMetrics(opts ...func(*MetricQuery)) *GraphQuery { // GroupBy(graph.FieldTitle). // Aggregate(ent.Count()). // Scan(ctx, &v) -// func (gq *GraphQuery) GroupBy(field string, fields ...string) *GraphGroupBy { - group := &GraphGroupBy{config: gq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := gq.prepareQuery(ctx); err != nil { - return nil, err - } - return gq.sqlQuery(), nil - } - return group + gq.ctx.Fields = append([]string{field}, fields...) + grbuild := &GraphGroupBy{build: gq} + grbuild.flds = &gq.ctx.Fields + grbuild.label = graph.Label + grbuild.scan = grbuild.Scan + return grbuild } -// Select one or more fields from the given query. +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. // // Example: // @@ -342,20 +364,35 @@ func (gq *GraphQuery) GroupBy(field string, fields ...string) *GraphGroupBy { // client.Graph.Query(). // Select(graph.FieldTitle). // Scan(ctx, &v) -// -func (gq *GraphQuery) Select(field string, fields ...string) *GraphSelect { - selector := &GraphSelect{config: gq.config} - selector.fields = append([]string{field}, fields...) - selector.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := gq.prepareQuery(ctx); err != nil { - return nil, err - } - return gq.sqlQuery(), nil - } - return selector +func (gq *GraphQuery) Select(fields ...string) *GraphSelect { + gq.ctx.Fields = append(gq.ctx.Fields, fields...) + sbuild := &GraphSelect{GraphQuery: gq} + sbuild.label = graph.Label + sbuild.flds, sbuild.scan = &gq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a GraphSelect configured with the given aggregations. +func (gq *GraphQuery) Aggregate(fns ...AggregateFunc) *GraphSelect { + return gq.Select().Aggregate(fns...) } func (gq *GraphQuery) prepareQuery(ctx context.Context) error { + for _, inter := range gq.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, gq); err != nil { + return err + } + } + } + for _, f := range gq.ctx.Fields { + if !graph.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } if gq.path != nil { prev, err := gq.path(ctx) if err != nil { @@ -366,7 +403,7 @@ func (gq *GraphQuery) prepareQuery(ctx context.Context) error { return nil } -func (gq *GraphQuery) sqlAll(ctx context.Context) ([]*Graph, error) { +func (gq *GraphQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Graph, error) { var ( nodes = []*Graph{} withFKs = gq.withFKs @@ -382,22 +419,17 @@ func (gq *GraphQuery) sqlAll(ctx context.Context) ([]*Graph, error) { if withFKs { _spec.Node.Columns = append(_spec.Node.Columns, graph.ForeignKeys...) } - _spec.ScanValues = func() []interface{} { + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Graph).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { node := &Graph{config: gq.config} nodes = append(nodes, node) - values := node.scanValues() - if withFKs { - values = append(values, node.fkValues()...) - } - return values - } - _spec.Assign = func(values ...interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("ent: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] node.Edges.loadedTypes = loadedTypes - return node.assignValues(values...) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) } if err := sqlgraph.QueryNodes(ctx, gq.driver, _spec); err != nil { return nil, err @@ -405,88 +437,111 @@ func (gq *GraphQuery) sqlAll(ctx context.Context) ([]*Graph, error) { if len(nodes) == 0 { return nodes, nil } - if query := gq.withGroup; query != nil { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*Graph) - for i := range nodes { - if fk := nodes[i].group_graphs; fk != nil { - ids = append(ids, *fk) - nodeids[*fk] = append(nodeids[*fk], nodes[i]) - } - } - query.Where(group.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { + if err := gq.loadGroup(ctx, query, nodes, nil, + func(n *Graph, e *Group) { n.Edges.Group = e }); err != nil { return nil, err } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "group_graphs" returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.Group = n - } + } + if query := gq.withMetrics; query != nil { + if err := gq.loadMetrics(ctx, query, nodes, + func(n *Graph) { n.Edges.Metrics = []*Metric{} }, + func(n *Graph, e *Metric) { n.Edges.Metrics = append(n.Edges.Metrics, e) }); err != nil { + return nil, err } } + return nodes, nil +} - if query := gq.withMetrics; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*Graph) +func (gq *GraphQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*Graph, init func(*Graph), assign func(*Graph, *Group)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Graph) + for i := range nodes { + if nodes[i].group_graphs == nil { + continue + } + fk := *nodes[i].group_graphs + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(group.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 "group_graphs" returned %v`, n.ID) + } for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] + assign(nodes[i], n) } - query.withFKs = true - query.Where(predicate.Metric(func(s *sql.Selector) { - s.Where(sql.InValues(graph.MetricsColumn, fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err + } + return nil +} +func (gq *GraphQuery) loadMetrics(ctx context.Context, query *MetricQuery, nodes []*Graph, init func(*Graph), assign func(*Graph, *Metric)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Graph) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) } - for _, n := range neighbors { - fk := n.graph_metrics - if fk == nil { - return nil, fmt.Errorf(`foreign-key "graph_metrics" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "graph_metrics" returned %v for node %v`, *fk, n.ID) - } - node.Edges.Metrics = append(node.Edges.Metrics, n) + } + query.withFKs = true + query.Where(predicate.Metric(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(graph.MetricsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.graph_metrics + if fk == nil { + return fmt.Errorf(`foreign-key "graph_metrics" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "graph_metrics" returned %v for node %v`, *fk, n.ID) } + assign(node, n) } - - return nodes, nil + return nil } func (gq *GraphQuery) sqlCount(ctx context.Context) (int, error) { _spec := gq.querySpec() - return sqlgraph.CountNodes(ctx, gq.driver, _spec) -} - -func (gq *GraphQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := gq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("ent: check existence: %v", err) + _spec.Node.Columns = gq.ctx.Fields + if len(gq.ctx.Fields) > 0 { + _spec.Unique = gq.ctx.Unique != nil && *gq.ctx.Unique } - return n > 0, nil + return sqlgraph.CountNodes(ctx, gq.driver, _spec) } func (gq *GraphQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: graph.Table, - Columns: graph.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, - }, - From: gq.sql, - Unique: true, + _spec := sqlgraph.NewQuerySpec(graph.Table, graph.Columns, sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt)) + _spec.From = gq.sql + if unique := gq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if gq.path != nil { + _spec.Unique = true + } + if fields := gq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, graph.FieldID) + for i := range fields { + if fields[i] != graph.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } } if ps := gq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -495,55 +550,58 @@ func (gq *GraphQuery) querySpec() *sqlgraph.QuerySpec { } } } - if limit := gq.limit; limit != nil { + if limit := gq.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := gq.offset; offset != nil { + if offset := gq.ctx.Offset; offset != nil { _spec.Offset = *offset } if ps := gq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector, graph.ValidColumn) + ps[i](selector) } } } return _spec } -func (gq *GraphQuery) sqlQuery() *sql.Selector { +func (gq *GraphQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(gq.driver.Dialect()) t1 := builder.Table(graph.Table) - selector := builder.Select(t1.Columns(graph.Columns...)...).From(t1) + columns := gq.ctx.Fields + if len(columns) == 0 { + columns = graph.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) if gq.sql != nil { selector = gq.sql - selector.Select(selector.Columns(graph.Columns...)...) + selector.Select(selector.Columns(columns...)...) + } + if gq.ctx.Unique != nil && *gq.ctx.Unique { + selector.Distinct() } for _, p := range gq.predicates { p(selector) } for _, p := range gq.order { - p(selector, graph.ValidColumn) + p(selector) } - if offset := gq.offset; offset != nil { + if offset := gq.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 := gq.limit; limit != nil { + if limit := gq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector } -// GraphGroupBy is the builder for group-by Graph entities. +// GraphGroupBy is the group-by builder for Graph entities. type GraphGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) + selector + build *GraphQuery } // Aggregate adds the given aggregation functions to the group-by query. @@ -552,471 +610,80 @@ func (ggb *GraphGroupBy) Aggregate(fns ...AggregateFunc) *GraphGroupBy { return ggb } -// Scan applies the group-by query and scan the result into the given value. -func (ggb *GraphGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := ggb.path(ctx) - if err != nil { +// Scan applies the selector query and scans the result into the given value. +func (ggb *GraphGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ggb.build.ctx, "GroupBy") + if err := ggb.build.prepareQuery(ctx); err != nil { return err } - ggb.sql = query - return ggb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (ggb *GraphGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := ggb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field. -func (ggb *GraphGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GraphGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil + return scanWithInterceptors[*GraphQuery, *GraphGroupBy](ctx, ggb.build, ggb, ggb.build.inters, v) } -// StringsX is like Strings, but panics if an error occurs. -func (ggb *GraphGroupBy) StringsX(ctx context.Context) []string { - v, err := ggb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from group-by. It is only allowed when querying group-by with one field. -func (ggb *GraphGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = ggb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{graph.Label} - default: - err = fmt.Errorf("ent: GraphGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (ggb *GraphGroupBy) StringX(ctx context.Context) string { - v, err := ggb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field. -func (ggb *GraphGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GraphGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (ggb *GraphGroupBy) IntsX(ctx context.Context) []int { - v, err := ggb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from group-by. It is only allowed when querying group-by with one field. -func (ggb *GraphGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = ggb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{graph.Label} - default: - err = fmt.Errorf("ent: GraphGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (ggb *GraphGroupBy) IntX(ctx context.Context) int { - v, err := ggb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field. -func (ggb *GraphGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GraphGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (ggb *GraphGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := ggb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field. -func (ggb *GraphGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = ggb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{graph.Label} - default: - err = fmt.Errorf("ent: GraphGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (ggb *GraphGroupBy) Float64X(ctx context.Context) float64 { - v, err := ggb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field. -func (ggb *GraphGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GraphGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (ggb *GraphGroupBy) BoolsX(ctx context.Context) []bool { - v, err := ggb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field. -func (ggb *GraphGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = ggb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{graph.Label} - default: - err = fmt.Errorf("ent: GraphGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (ggb *GraphGroupBy) BoolX(ctx context.Context) bool { - v, err := ggb.Bool(ctx) - if err != nil { - panic(err) +func (ggb *GraphGroupBy) sqlScan(ctx context.Context, root *GraphQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ggb.fns)) + for _, fn := range ggb.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (ggb *GraphGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range ggb.fields { - if !graph.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ggb.flds)+len(ggb.fns)) + for _, f := range *ggb.flds { + columns = append(columns, selector.C(f)) } + columns = append(columns, aggregation...) + selector.Select(columns...) } - selector := ggb.sqlQuery() + selector.GroupBy(selector.Columns(*ggb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := ggb.driver.Query(ctx, query, args, rows); err != nil { + if err := ggb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } -func (ggb *GraphGroupBy) sqlQuery() *sql.Selector { - selector := ggb.sql - columns := make([]string, 0, len(ggb.fields)+len(ggb.fns)) - columns = append(columns, ggb.fields...) - for _, fn := range ggb.fns { - columns = append(columns, fn(selector, graph.ValidColumn)) - } - return selector.Select(columns...).GroupBy(ggb.fields...) -} - -// GraphSelect is the builder for select fields of Graph entities. +// GraphSelect is the builder for selecting fields of Graph entities. type GraphSelect struct { - config - fields []string - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Scan applies the selector query and scan the result into the given value. -func (gs *GraphSelect) Scan(ctx context.Context, v interface{}) error { - query, err := gs.path(ctx) - if err != nil { - return err - } - gs.sql = query - return gs.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (gs *GraphSelect) ScanX(ctx context.Context, v interface{}) { - if err := gs.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from selector. It is only allowed when selecting one field. -func (gs *GraphSelect) Strings(ctx context.Context) ([]string, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GraphSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (gs *GraphSelect) StringsX(ctx context.Context) []string { - v, err := gs.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from selector. It is only allowed when selecting one field. -func (gs *GraphSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = gs.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{graph.Label} - default: - err = fmt.Errorf("ent: GraphSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (gs *GraphSelect) StringX(ctx context.Context) string { - v, err := gs.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from selector. It is only allowed when selecting one field. -func (gs *GraphSelect) Ints(ctx context.Context) ([]int, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GraphSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (gs *GraphSelect) IntsX(ctx context.Context) []int { - v, err := gs.Ints(ctx) - if err != nil { - panic(err) - } - return v + *GraphQuery + selector } -// Int returns a single int from selector. It is only allowed when selecting one field. -func (gs *GraphSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = gs.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{graph.Label} - default: - err = fmt.Errorf("ent: GraphSelect.Ints returned %d results when one was expected", len(v)) - } - return +// Aggregate adds the given aggregation functions to the selector query. +func (gs *GraphSelect) Aggregate(fns ...AggregateFunc) *GraphSelect { + gs.fns = append(gs.fns, fns...) + return gs } -// IntX is like Int, but panics if an error occurs. -func (gs *GraphSelect) IntX(ctx context.Context) int { - v, err := gs.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from selector. It is only allowed when selecting one field. -func (gs *GraphSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GraphSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (gs *GraphSelect) Float64sX(ctx context.Context) []float64 { - v, err := gs.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from selector. It is only allowed when selecting one field. -func (gs *GraphSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = gs.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{graph.Label} - default: - err = fmt.Errorf("ent: GraphSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (gs *GraphSelect) Float64X(ctx context.Context) float64 { - v, err := gs.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from selector. It is only allowed when selecting one field. -func (gs *GraphSelect) Bools(ctx context.Context) ([]bool, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GraphSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (gs *GraphSelect) BoolsX(ctx context.Context) []bool { - v, err := gs.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from selector. It is only allowed when selecting one field. -func (gs *GraphSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = gs.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{graph.Label} - default: - err = fmt.Errorf("ent: GraphSelect.Bools returned %d results when one was expected", len(v)) +// Scan applies the selector query and scans the result into the given value. +func (gs *GraphSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, gs.ctx, "Select") + if err := gs.prepareQuery(ctx); err != nil { + return err } - return + return scanWithInterceptors[*GraphQuery, *GraphSelect](ctx, gs.GraphQuery, gs, gs.inters, v) } -// BoolX is like Bool, but panics if an error occurs. -func (gs *GraphSelect) BoolX(ctx context.Context) bool { - v, err := gs.Bool(ctx) - if err != nil { - panic(err) +func (gs *GraphSelect) sqlScan(ctx context.Context, root *GraphQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(gs.fns)) + for _, fn := range gs.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (gs *GraphSelect) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range gs.fields { - if !graph.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} - } + switch n := len(*gs.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 := gs.sqlQuery().Query() + query, args := selector.Query() if err := gs.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } - -func (gs *GraphSelect) sqlQuery() sql.Querier { - selector := gs.sql - selector.Select(selector.Columns(gs.fields...)...) - return selector -} diff --git a/ent/graph_update.go b/ent/graph_update.go index 501f2ca9..26014c46 100644 --- a/ent/graph_update.go +++ b/ent/graph_update.go @@ -1,14 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/graph" "github.com/gobench-io/gobench/v2/ent/group" "github.com/gobench-io/gobench/v2/ent/metric" @@ -18,30 +19,29 @@ import ( // GraphUpdate is the builder for updating Graph entities. type GraphUpdate struct { config - hooks []Hook - mutation *GraphMutation - predicates []predicate.Graph + hooks []Hook + mutation *GraphMutation } -// Where adds a new predicate for the builder. +// Where appends a list predicates to the GraphUpdate builder. func (gu *GraphUpdate) Where(ps ...predicate.Graph) *GraphUpdate { - gu.predicates = append(gu.predicates, ps...) + gu.mutation.Where(ps...) return gu } -// SetUnit sets the unit field. +// SetUnit sets the "unit" field. func (gu *GraphUpdate) SetUnit(s string) *GraphUpdate { gu.mutation.SetUnit(s) return gu } -// SetGroupID sets the group edge to Group by id. +// SetGroupID sets the "group" edge to the Group entity by ID. func (gu *GraphUpdate) SetGroupID(id int) *GraphUpdate { gu.mutation.SetGroupID(id) return gu } -// SetNillableGroupID sets the group edge to Group by id if the given value is not nil. +// SetNillableGroupID sets the "group" edge to the Group entity by ID if the given value is not nil. func (gu *GraphUpdate) SetNillableGroupID(id *int) *GraphUpdate { if id != nil { gu = gu.SetGroupID(*id) @@ -49,18 +49,18 @@ func (gu *GraphUpdate) SetNillableGroupID(id *int) *GraphUpdate { return gu } -// SetGroup sets the group edge to Group. +// SetGroup sets the "group" edge to the Group entity. func (gu *GraphUpdate) SetGroup(g *Group) *GraphUpdate { return gu.SetGroupID(g.ID) } -// AddMetricIDs adds the metrics edge to Metric by ids. +// AddMetricIDs adds the "metrics" edge to the Metric entity by IDs. func (gu *GraphUpdate) AddMetricIDs(ids ...int) *GraphUpdate { gu.mutation.AddMetricIDs(ids...) return gu } -// AddMetrics adds the metrics edges to Metric. +// AddMetrics adds the "metrics" edges to the Metric entity. func (gu *GraphUpdate) AddMetrics(m ...*Metric) *GraphUpdate { ids := make([]int, len(m)) for i := range m { @@ -74,25 +74,25 @@ func (gu *GraphUpdate) Mutation() *GraphMutation { return gu.mutation } -// ClearGroup clears the "group" edge to type Group. +// ClearGroup clears the "group" edge to the Group entity. func (gu *GraphUpdate) ClearGroup() *GraphUpdate { gu.mutation.ClearGroup() return gu } -// ClearMetrics clears all "metrics" edges to type Metric. +// ClearMetrics clears all "metrics" edges to the Metric entity. func (gu *GraphUpdate) ClearMetrics() *GraphUpdate { gu.mutation.ClearMetrics() return gu } -// RemoveMetricIDs removes the metrics edge to Metric by ids. +// RemoveMetricIDs removes the "metrics" edge to Metric entities by IDs. func (gu *GraphUpdate) RemoveMetricIDs(ids ...int) *GraphUpdate { gu.mutation.RemoveMetricIDs(ids...) return gu } -// RemoveMetrics removes metrics edges to Metric. +// RemoveMetrics removes "metrics" edges to Metric entities. func (gu *GraphUpdate) RemoveMetrics(m ...*Metric) *GraphUpdate { ids := make([]int, len(m)) for i := range m { @@ -101,33 +101,9 @@ func (gu *GraphUpdate) RemoveMetrics(m ...*Metric) *GraphUpdate { return gu.RemoveMetricIDs(ids...) } -// Save executes the query and returns the number of rows/vertices matched by this operation. +// Save executes the query and returns the number of nodes affected by the update operation. func (gu *GraphUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(gu.hooks) == 0 { - affected, err = gu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GraphMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - gu.mutation = mutation - affected, err = gu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(gu.hooks) - 1; i >= 0; i-- { - mut = gu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, gu.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, gu.sqlSave, gu.mutation, gu.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -153,17 +129,8 @@ func (gu *GraphUpdate) ExecX(ctx context.Context) { } func (gu *GraphUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: graph.Table, - Columns: graph.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, - }, - } - if ps := gu.predicates; len(ps) > 0 { + _spec := sqlgraph.NewUpdateSpec(graph.Table, graph.Columns, sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt)) + if ps := gu.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -171,11 +138,7 @@ func (gu *GraphUpdate) sqlSave(ctx context.Context) (n int, err error) { } } if value, ok := gu.mutation.Unit(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: graph.FieldUnit, - }) + _spec.SetField(graph.FieldUnit, field.TypeString, value) } if gu.mutation.GroupCleared() { edge := &sqlgraph.EdgeSpec{ @@ -185,10 +148,7 @@ func (gu *GraphUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{graph.GroupColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -201,10 +161,7 @@ func (gu *GraphUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{graph.GroupColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -220,10 +177,7 @@ func (gu *GraphUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{graph.MetricsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -236,10 +190,7 @@ func (gu *GraphUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{graph.MetricsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -255,10 +206,7 @@ func (gu *GraphUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{graph.MetricsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -269,34 +217,36 @@ func (gu *GraphUpdate) sqlSave(ctx context.Context) (n int, err error) { if n, err = sqlgraph.UpdateNodes(ctx, gu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{graph.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } + gu.mutation.done = true return n, nil } // GraphUpdateOne is the builder for updating a single Graph entity. type GraphUpdateOne struct { config + fields []string hooks []Hook mutation *GraphMutation } -// SetUnit sets the unit field. +// SetUnit sets the "unit" field. func (guo *GraphUpdateOne) SetUnit(s string) *GraphUpdateOne { guo.mutation.SetUnit(s) return guo } -// SetGroupID sets the group edge to Group by id. +// SetGroupID sets the "group" edge to the Group entity by ID. func (guo *GraphUpdateOne) SetGroupID(id int) *GraphUpdateOne { guo.mutation.SetGroupID(id) return guo } -// SetNillableGroupID sets the group edge to Group by id if the given value is not nil. +// SetNillableGroupID sets the "group" edge to the Group entity by ID if the given value is not nil. func (guo *GraphUpdateOne) SetNillableGroupID(id *int) *GraphUpdateOne { if id != nil { guo = guo.SetGroupID(*id) @@ -304,18 +254,18 @@ func (guo *GraphUpdateOne) SetNillableGroupID(id *int) *GraphUpdateOne { return guo } -// SetGroup sets the group edge to Group. +// SetGroup sets the "group" edge to the Group entity. func (guo *GraphUpdateOne) SetGroup(g *Group) *GraphUpdateOne { return guo.SetGroupID(g.ID) } -// AddMetricIDs adds the metrics edge to Metric by ids. +// AddMetricIDs adds the "metrics" edge to the Metric entity by IDs. func (guo *GraphUpdateOne) AddMetricIDs(ids ...int) *GraphUpdateOne { guo.mutation.AddMetricIDs(ids...) return guo } -// AddMetrics adds the metrics edges to Metric. +// AddMetrics adds the "metrics" edges to the Metric entity. func (guo *GraphUpdateOne) AddMetrics(m ...*Metric) *GraphUpdateOne { ids := make([]int, len(m)) for i := range m { @@ -329,25 +279,25 @@ func (guo *GraphUpdateOne) Mutation() *GraphMutation { return guo.mutation } -// ClearGroup clears the "group" edge to type Group. +// ClearGroup clears the "group" edge to the Group entity. func (guo *GraphUpdateOne) ClearGroup() *GraphUpdateOne { guo.mutation.ClearGroup() return guo } -// ClearMetrics clears all "metrics" edges to type Metric. +// ClearMetrics clears all "metrics" edges to the Metric entity. func (guo *GraphUpdateOne) ClearMetrics() *GraphUpdateOne { guo.mutation.ClearMetrics() return guo } -// RemoveMetricIDs removes the metrics edge to Metric by ids. +// RemoveMetricIDs removes the "metrics" edge to Metric entities by IDs. func (guo *GraphUpdateOne) RemoveMetricIDs(ids ...int) *GraphUpdateOne { guo.mutation.RemoveMetricIDs(ids...) return guo } -// RemoveMetrics removes metrics edges to Metric. +// RemoveMetrics removes "metrics" edges to Metric entities. func (guo *GraphUpdateOne) RemoveMetrics(m ...*Metric) *GraphUpdateOne { ids := make([]int, len(m)) for i := range m { @@ -356,33 +306,22 @@ func (guo *GraphUpdateOne) RemoveMetrics(m ...*Metric) *GraphUpdateOne { return guo.RemoveMetricIDs(ids...) } -// Save executes the query and returns the updated entity. +// Where appends a list predicates to the GraphUpdate builder. +func (guo *GraphUpdateOne) Where(ps ...predicate.Graph) *GraphUpdateOne { + guo.mutation.Where(ps...) + return guo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (guo *GraphUpdateOne) Select(field string, fields ...string) *GraphUpdateOne { + guo.fields = append([]string{field}, fields...) + return guo +} + +// Save executes the query and returns the updated Graph entity. func (guo *GraphUpdateOne) Save(ctx context.Context) (*Graph, error) { - var ( - err error - node *Graph - ) - if len(guo.hooks) == 0 { - node, err = guo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GraphMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - guo.mutation = mutation - node, err = guo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(guo.hooks) - 1; i >= 0; i-- { - mut = guo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, guo.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, guo.sqlSave, guo.mutation, guo.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -408,27 +347,33 @@ func (guo *GraphUpdateOne) ExecX(ctx context.Context) { } func (guo *GraphUpdateOne) sqlSave(ctx context.Context) (_node *Graph, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: graph.Table, - Columns: graph.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, - }, - } + _spec := sqlgraph.NewUpdateSpec(graph.Table, graph.Columns, sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt)) id, ok := guo.mutation.ID() if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Graph.ID for update")} + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Graph.id" for update`)} } _spec.Node.ID.Value = id + if fields := guo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, graph.FieldID) + for _, f := range fields { + if !graph.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != graph.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := guo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } if value, ok := guo.mutation.Unit(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: graph.FieldUnit, - }) + _spec.SetField(graph.FieldUnit, field.TypeString, value) } if guo.mutation.GroupCleared() { edge := &sqlgraph.EdgeSpec{ @@ -438,10 +383,7 @@ func (guo *GraphUpdateOne) sqlSave(ctx context.Context) (_node *Graph, err error Columns: []string{graph.GroupColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -454,10 +396,7 @@ func (guo *GraphUpdateOne) sqlSave(ctx context.Context) (_node *Graph, err error Columns: []string{graph.GroupColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -473,10 +412,7 @@ func (guo *GraphUpdateOne) sqlSave(ctx context.Context) (_node *Graph, err error Columns: []string{graph.MetricsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -489,10 +425,7 @@ func (guo *GraphUpdateOne) sqlSave(ctx context.Context) (_node *Graph, err error Columns: []string{graph.MetricsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -508,10 +441,7 @@ func (guo *GraphUpdateOne) sqlSave(ctx context.Context) (_node *Graph, err error Columns: []string{graph.MetricsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -521,14 +451,15 @@ func (guo *GraphUpdateOne) sqlSave(ctx context.Context) (_node *Graph, err error } _node = &Graph{config: guo.config} _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues() + _spec.ScanValues = _node.scanValues if err = sqlgraph.UpdateNode(ctx, guo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{graph.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } + guo.mutation.done = true return _node, nil } diff --git a/ent/group.go b/ent/group.go index a3a04f8d..dc359121 100644 --- a/ent/group.go +++ b/ent/group.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -6,7 +6,8 @@ import ( "fmt" "strings" - "github.com/facebook/ent/dialect/sql" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/group" ) @@ -22,14 +23,15 @@ type Group struct { // The values are being populated by the GroupQuery when eager-loading is set. Edges GroupEdges `json:"edges"` application_groups *int + selectValues sql.SelectValues } // GroupEdges holds the relations/edges for other nodes in the graph. type GroupEdges struct { // Application holds the value of the application edge. - Application *Application + Application *Application `json:"application,omitempty"` // Graphs holds the value of the graphs edge. - Graphs []*Graph + Graphs []*Graph `json:"graphs,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [2]bool @@ -40,8 +42,7 @@ type GroupEdges struct { func (e GroupEdges) ApplicationOrErr() (*Application, error) { if e.loadedTypes[0] { if e.Application == nil { - // The edge application was loaded in eager-loading, - // but was not found. + // Edge was loaded but was not found. return nil, &NotFoundError{label: application.Label} } return e.Application, nil @@ -59,74 +60,88 @@ func (e GroupEdges) GraphsOrErr() ([]*Graph, error) { } // scanValues returns the types for scanning values from sql.Rows. -func (*Group) scanValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // id - &sql.NullString{}, // name - } -} - -// fkValues returns the types for scanning foreign-keys values from sql.Rows. -func (*Group) fkValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // application_groups +func (*Group) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case group.FieldID: + values[i] = new(sql.NullInt64) + case group.FieldName: + values[i] = new(sql.NullString) + case group.ForeignKeys[0]: // application_groups + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } } + return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Group fields. -func (gr *Group) assignValues(values ...interface{}) error { - if m, n := len(values), len(group.Columns); m < n { +func (gr *Group) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } - value, ok := values[0].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - gr.ID = int(value.Int64) - values = values[1:] - if value, ok := values[0].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field name", values[0]) - } else if value.Valid { - gr.Name = value.String - } - values = values[1:] - if len(values) == len(group.ForeignKeys) { - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field application_groups", value) - } else if value.Valid { - gr.application_groups = new(int) - *gr.application_groups = int(value.Int64) + for i := range columns { + switch columns[i] { + case group.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + gr.ID = int(value.Int64) + case group.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + gr.Name = value.String + } + case group.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field application_groups", value) + } else if value.Valid { + gr.application_groups = new(int) + *gr.application_groups = int(value.Int64) + } + default: + gr.selectValues.Set(columns[i], values[i]) } } return nil } -// QueryApplication queries the application edge of the Group. +// Value returns the ent.Value that was dynamically selected and assigned to the Group. +// This includes values selected through modifiers, order, etc. +func (gr *Group) Value(name string) (ent.Value, error) { + return gr.selectValues.Get(name) +} + +// QueryApplication queries the "application" edge of the Group entity. func (gr *Group) QueryApplication() *ApplicationQuery { - return (&GroupClient{config: gr.config}).QueryApplication(gr) + return NewGroupClient(gr.config).QueryApplication(gr) } -// QueryGraphs queries the graphs edge of the Group. +// QueryGraphs queries the "graphs" edge of the Group entity. func (gr *Group) QueryGraphs() *GraphQuery { - return (&GroupClient{config: gr.config}).QueryGraphs(gr) + return NewGroupClient(gr.config).QueryGraphs(gr) } // Update returns a builder for updating this Group. -// Note that, you need to call Group.Unwrap() before calling this method, if this Group +// Note that you need to call Group.Unwrap() before calling this method if this Group // was returned from a transaction, and the transaction was committed or rolled back. func (gr *Group) Update() *GroupUpdateOne { - return (&GroupClient{config: gr.config}).UpdateOne(gr) + return NewGroupClient(gr.config).UpdateOne(gr) } -// Unwrap unwraps the entity that was returned from a transaction after it was closed, -// so that all next queries will be executed through the driver which created the transaction. +// Unwrap unwraps the Group entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. func (gr *Group) Unwrap() *Group { - tx, ok := gr.config.driver.(*txDriver) + _tx, ok := gr.config.driver.(*txDriver) if !ok { panic("ent: Group is not a transactional entity") } - gr.config.driver = tx.drv + gr.config.driver = _tx.drv return gr } @@ -134,8 +149,8 @@ func (gr *Group) Unwrap() *Group { func (gr *Group) String() string { var builder strings.Builder builder.WriteString("Group(") - builder.WriteString(fmt.Sprintf("id=%v", gr.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("name=") builder.WriteString(gr.Name) builder.WriteByte(')') return builder.String() @@ -143,9 +158,3 @@ func (gr *Group) String() string { // Groups is a parsable slice of Group. type Groups []*Group - -func (gr Groups) config(cfg config) { - for _i := range gr { - gr[_i].config = cfg - } -} diff --git a/ent/group/group.go b/ent/group/group.go index 61388ba2..809e11ae 100644 --- a/ent/group/group.go +++ b/ent/group/group.go @@ -1,7 +1,12 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package group +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + const ( // Label holds the string label denoting the group type in the database. Label = "group" @@ -9,22 +14,20 @@ const ( FieldID = "id" // FieldName holds the string denoting the name field in the database. FieldName = "name" - // EdgeApplication holds the string denoting the application edge name in mutations. EdgeApplication = "application" // EdgeGraphs holds the string denoting the graphs edge name in mutations. EdgeGraphs = "graphs" - // Table holds the table name of the group in the database. Table = "groups" - // ApplicationTable is the table the holds the application relation/edge. + // ApplicationTable is the table that holds the application relation/edge. ApplicationTable = "groups" // ApplicationInverseTable is the table name for the Application entity. // It exists in this package in order to avoid circular dependency with the "application" package. ApplicationInverseTable = "applications" // ApplicationColumn is the table column denoting the application relation/edge. ApplicationColumn = "application_groups" - // GraphsTable is the table the holds the graphs relation/edge. + // GraphsTable is the table that holds the graphs relation/edge. GraphsTable = "graphs" // GraphsInverseTable is the table name for the Graph entity. // It exists in this package in order to avoid circular dependency with the "graph" package. @@ -39,7 +42,8 @@ var Columns = []string{ FieldName, } -// ForeignKeys holds the SQL foreign-keys that are owned by the Group type. +// ForeignKeys holds the SQL foreign-keys that are owned by the "groups" +// table and are not defined as standalone fields in the schema. var ForeignKeys = []string{ "application_groups", } @@ -58,3 +62,51 @@ func ValidColumn(column string) bool { } return false } + +// OrderOption defines the ordering options for the Group queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByApplicationField orders the results by application field. +func ByApplicationField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newApplicationStep(), sql.OrderByField(field, opts...)) + } +} + +// ByGraphsCount orders the results by graphs count. +func ByGraphsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newGraphsStep(), opts...) + } +} + +// ByGraphs orders the results by graphs terms. +func ByGraphs(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGraphsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newApplicationStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ApplicationInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ApplicationTable, ApplicationColumn), + ) +} +func newGraphsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GraphsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, GraphsTable, GraphsColumn), + ) +} diff --git a/ent/group/where.go b/ent/group/where.go index c78ef3e7..dcfd8317 100644 --- a/ent/group/where.go +++ b/ent/group/where.go @@ -1,212 +1,126 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package group import ( - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" "github.com/gobench-io/gobench/v2/ent/predicate" ) -// ID filters vertices based on their identifier. +// ID filters vertices based on their ID field. func ID(id int) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Group(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Group(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) + return predicate.Group(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) + return predicate.Group(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) + return predicate.Group(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) + return predicate.Group(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) + return predicate.Group(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) + return predicate.Group(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) + return predicate.Group(sql.FieldLTE(FieldID, id)) } // Name applies equality check predicate on the "name" field. It's identical to NameEQ. func Name(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldEQ(FieldName, v)) } // NameEQ applies the EQ predicate on the "name" field. func NameEQ(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldEQ(FieldName, v)) } // NameNEQ applies the NEQ predicate on the "name" field. func NameNEQ(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldNEQ(FieldName, v)) } // NameIn applies the In predicate on the "name" field. func NameIn(vs ...string) predicate.Group { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Group(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldName), v...)) - }) + return predicate.Group(sql.FieldIn(FieldName, vs...)) } // NameNotIn applies the NotIn predicate on the "name" field. func NameNotIn(vs ...string) predicate.Group { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Group(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldName), v...)) - }) + return predicate.Group(sql.FieldNotIn(FieldName, vs...)) } // NameGT applies the GT predicate on the "name" field. func NameGT(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldGT(FieldName, v)) } // NameGTE applies the GTE predicate on the "name" field. func NameGTE(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldGTE(FieldName, v)) } // NameLT applies the LT predicate on the "name" field. func NameLT(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldLT(FieldName, v)) } // NameLTE applies the LTE predicate on the "name" field. func NameLTE(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldLTE(FieldName, v)) } // NameContains applies the Contains predicate on the "name" field. func NameContains(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldContains(FieldName, v)) } // NameHasPrefix applies the HasPrefix predicate on the "name" field. func NameHasPrefix(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldHasPrefix(FieldName, v)) } // NameHasSuffix applies the HasSuffix predicate on the "name" field. func NameHasSuffix(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldHasSuffix(FieldName, v)) } // NameEqualFold applies the EqualFold predicate on the "name" field. func NameEqualFold(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldEqualFold(FieldName, v)) } // NameContainsFold applies the ContainsFold predicate on the "name" field. func NameContainsFold(v string) predicate.Group { - return predicate.Group(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldName), v)) - }) + return predicate.Group(sql.FieldContainsFold(FieldName, v)) } // HasApplication applies the HasEdge predicate on the "application" edge. @@ -214,7 +128,6 @@ func HasApplication() predicate.Group { return predicate.Group(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(ApplicationTable, FieldID), sqlgraph.Edge(sqlgraph.M2O, true, ApplicationTable, ApplicationColumn), ) sqlgraph.HasNeighbors(s, step) @@ -224,11 +137,7 @@ func HasApplication() predicate.Group { // HasApplicationWith applies the HasEdge predicate on the "application" edge with a given conditions (other predicates). func HasApplicationWith(preds ...predicate.Application) predicate.Group { return predicate.Group(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(ApplicationInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, ApplicationTable, ApplicationColumn), - ) + step := newApplicationStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -242,7 +151,6 @@ func HasGraphs() predicate.Group { return predicate.Group(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(GraphsTable, FieldID), sqlgraph.Edge(sqlgraph.O2M, false, GraphsTable, GraphsColumn), ) sqlgraph.HasNeighbors(s, step) @@ -252,11 +160,7 @@ func HasGraphs() predicate.Group { // HasGraphsWith applies the HasEdge predicate on the "graphs" edge with a given conditions (other predicates). func HasGraphsWith(preds ...predicate.Graph) predicate.Group { return predicate.Group(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(GraphsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, GraphsTable, GraphsColumn), - ) + step := newGraphsStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -265,7 +169,7 @@ func HasGraphsWith(preds ...predicate.Graph) predicate.Group { }) } -// And groups list of predicates with the AND operator between them. +// And groups predicates with the AND operator between them. func And(predicates ...predicate.Group) predicate.Group { return predicate.Group(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) @@ -276,7 +180,7 @@ func And(predicates ...predicate.Group) predicate.Group { }) } -// Or groups list of predicates with the OR operator between them. +// Or groups predicates with the OR operator between them. func Or(predicates ...predicate.Group) predicate.Group { return predicate.Group(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) diff --git a/ent/group_create.go b/ent/group_create.go index 2747ccc3..bd98b566 100644 --- a/ent/group_create.go +++ b/ent/group_create.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -7,8 +7,8 @@ import ( "errors" "fmt" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/graph" "github.com/gobench-io/gobench/v2/ent/group" @@ -21,19 +21,19 @@ type GroupCreate struct { hooks []Hook } -// SetName sets the name field. +// SetName sets the "name" field. func (gc *GroupCreate) SetName(s string) *GroupCreate { gc.mutation.SetName(s) return gc } -// SetApplicationID sets the application edge to Application by id. +// SetApplicationID sets the "application" edge to the Application entity by ID. func (gc *GroupCreate) SetApplicationID(id int) *GroupCreate { gc.mutation.SetApplicationID(id) return gc } -// SetNillableApplicationID sets the application edge to Application by id if the given value is not nil. +// SetNillableApplicationID sets the "application" edge to the Application entity by ID if the given value is not nil. func (gc *GroupCreate) SetNillableApplicationID(id *int) *GroupCreate { if id != nil { gc = gc.SetApplicationID(*id) @@ -41,18 +41,18 @@ func (gc *GroupCreate) SetNillableApplicationID(id *int) *GroupCreate { return gc } -// SetApplication sets the application edge to Application. +// SetApplication sets the "application" edge to the Application entity. func (gc *GroupCreate) SetApplication(a *Application) *GroupCreate { return gc.SetApplicationID(a.ID) } -// AddGraphIDs adds the graphs edge to Graph by ids. +// AddGraphIDs adds the "graphs" edge to the Graph entity by IDs. func (gc *GroupCreate) AddGraphIDs(ids ...int) *GroupCreate { gc.mutation.AddGraphIDs(ids...) return gc } -// AddGraphs adds the graphs edges to Graph. +// AddGraphs adds the "graphs" edges to the Graph entity. func (gc *GroupCreate) AddGraphs(g ...*Graph) *GroupCreate { ids := make([]int, len(g)) for i := range g { @@ -68,37 +68,7 @@ func (gc *GroupCreate) Mutation() *GroupMutation { // Save creates the Group in the database. func (gc *GroupCreate) Save(ctx context.Context) (*Group, error) { - var ( - err error - node *Group - ) - if len(gc.hooks) == 0 { - if err = gc.check(); err != nil { - return nil, err - } - node, err = gc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = gc.check(); err != nil { - return nil, err - } - gc.mutation = mutation - node, err = gc.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(gc.hooks) - 1; i >= 0; i-- { - mut = gc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, gc.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, gc.sqlSave, gc.mutation, gc.hooks) } // SaveX calls Save and panics if Save returns an error. @@ -110,44 +80,52 @@ func (gc *GroupCreate) SaveX(ctx context.Context) *Group { return v } +// Exec executes the query. +func (gc *GroupCreate) Exec(ctx context.Context) error { + _, err := gc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gc *GroupCreate) ExecX(ctx context.Context) { + if err := gc.Exec(ctx); err != nil { + panic(err) + } +} + // check runs all checks and user-defined validators on the builder. func (gc *GroupCreate) check() error { if _, ok := gc.mutation.Name(); !ok { - return &ValidationError{Name: "name", err: errors.New("ent: missing required field \"name\"")} + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Group.name"`)} } return nil } func (gc *GroupCreate) sqlSave(ctx context.Context) (*Group, error) { + if err := gc.check(); err != nil { + return nil, err + } _node, _spec := gc.createSpec() if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } id := _spec.ID.Value.(int64) _node.ID = int(id) + gc.mutation.id = &_node.ID + gc.mutation.done = true return _node, nil } func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) { var ( _node = &Group{config: gc.config} - _spec = &sqlgraph.CreateSpec{ - Table: group.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, - } + _spec = sqlgraph.NewCreateSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) ) if value, ok := gc.mutation.Name(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: group.FieldName, - }) + _spec.SetField(group.FieldName, field.TypeString, value) _node.Name = value } if nodes := gc.mutation.ApplicationIDs(); len(nodes) > 0 { @@ -158,15 +136,13 @@ func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) { Columns: []string{group.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } + _node.application_groups = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } if nodes := gc.mutation.GraphsIDs(); len(nodes) > 0 { @@ -177,10 +153,7 @@ func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) { Columns: []string{group.GraphsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -191,7 +164,7 @@ func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) { return _node, _spec } -// GroupCreateBulk is the builder for creating a bulk of Group entities. +// GroupCreateBulk is the builder for creating many Group entities in bulk. type GroupCreateBulk struct { config builders []*GroupCreate @@ -214,24 +187,28 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nil, err } builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() var err error + nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, gcb.builders[i+1].mutation) } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, gcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if err = sqlgraph.BatchCreate(ctx, gcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } } } - mutation.done = true if err != nil { return nil, err } - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { @@ -248,7 +225,7 @@ func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { return nodes, nil } -// SaveX calls Save and panics if Save returns an error. +// SaveX is like Save, but panics if an error occurs. func (gcb *GroupCreateBulk) SaveX(ctx context.Context) []*Group { v, err := gcb.Save(ctx) if err != nil { @@ -256,3 +233,16 @@ func (gcb *GroupCreateBulk) SaveX(ctx context.Context) []*Group { } return v } + +// Exec executes the query. +func (gcb *GroupCreateBulk) Exec(ctx context.Context) error { + _, err := gcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcb *GroupCreateBulk) ExecX(ctx context.Context) { + if err := gcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/group_delete.go b/ent/group_delete.go index 790b2fe0..a1de1160 100644 --- a/ent/group_delete.go +++ b/ent/group_delete.go @@ -1,14 +1,13 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/group" "github.com/gobench-io/gobench/v2/ent/predicate" ) @@ -16,44 +15,19 @@ import ( // GroupDelete is the builder for deleting a Group entity. type GroupDelete struct { config - hooks []Hook - mutation *GroupMutation - predicates []predicate.Group + hooks []Hook + mutation *GroupMutation } -// Where adds a new predicate to the delete builder. +// Where appends a list predicates to the GroupDelete builder. func (gd *GroupDelete) Where(ps ...predicate.Group) *GroupDelete { - gd.predicates = append(gd.predicates, ps...) + gd.mutation.Where(ps...) return gd } // Exec executes the deletion query and returns how many vertices were deleted. func (gd *GroupDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(gd.hooks) == 0 { - affected, err = gd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - gd.mutation = mutation - affected, err = gd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(gd.hooks) - 1; i >= 0; i-- { - mut = gd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, gd.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, gd.sqlExec, gd.mutation, gd.hooks) } // ExecX is like Exec, but panics if an error occurs. @@ -66,23 +40,20 @@ func (gd *GroupDelete) ExecX(ctx context.Context) int { } func (gd *GroupDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: group.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, - }, - } - if ps := gd.predicates; len(ps) > 0 { + _spec := sqlgraph.NewDeleteSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) + if ps := gd.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - return sqlgraph.DeleteNodes(ctx, gd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, gd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + gd.mutation.done = true + return affected, err } // GroupDeleteOne is the builder for deleting a single Group entity. @@ -90,6 +61,12 @@ type GroupDeleteOne struct { gd *GroupDelete } +// Where appends a list predicates to the GroupDelete builder. +func (gdo *GroupDeleteOne) Where(ps ...predicate.Group) *GroupDeleteOne { + gdo.gd.mutation.Where(ps...) + return gdo +} + // Exec executes the deletion query. func (gdo *GroupDeleteOne) Exec(ctx context.Context) error { n, err := gdo.gd.Exec(ctx) @@ -105,5 +82,7 @@ func (gdo *GroupDeleteOne) Exec(ctx context.Context) error { // ExecX is like Exec, but panics if an error occurs. func (gdo *GroupDeleteOne) ExecX(ctx context.Context) { - gdo.gd.ExecX(ctx) + if err := gdo.Exec(ctx); err != nil { + panic(err) + } } diff --git a/ent/group_query.go b/ent/group_query.go index 2f66cae3..e3c6095c 100644 --- a/ent/group_query.go +++ b/ent/group_query.go @@ -1,17 +1,16 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" "database/sql/driver" - "errors" "fmt" "math" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/graph" "github.com/gobench-io/gobench/v2/ent/group" @@ -21,12 +20,10 @@ import ( // GroupQuery is the builder for querying Group entities. type GroupQuery struct { config - limit *int - offset *int - order []OrderFunc - unique []string - predicates []predicate.Group - // eager-loading edges. + ctx *QueryContext + order []group.OrderOption + inters []Interceptor + predicates []predicate.Group withApplication *ApplicationQuery withGraphs *GraphQuery withFKs bool @@ -35,38 +32,45 @@ type GroupQuery struct { path func(context.Context) (*sql.Selector, error) } -// Where adds a new predicate for the builder. +// Where adds a new predicate for the GroupQuery builder. func (gq *GroupQuery) Where(ps ...predicate.Group) *GroupQuery { gq.predicates = append(gq.predicates, ps...) return gq } -// Limit adds a limit step to the query. +// Limit the number of records to be returned by this query. func (gq *GroupQuery) Limit(limit int) *GroupQuery { - gq.limit = &limit + gq.ctx.Limit = &limit return gq } -// Offset adds an offset step to the query. +// Offset to start from. func (gq *GroupQuery) Offset(offset int) *GroupQuery { - gq.offset = &offset + gq.ctx.Offset = &offset return gq } -// Order adds an order step to the query. -func (gq *GroupQuery) Order(o ...OrderFunc) *GroupQuery { +// 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 (gq *GroupQuery) Unique(unique bool) *GroupQuery { + gq.ctx.Unique = &unique + return gq +} + +// Order specifies how the records should be ordered. +func (gq *GroupQuery) Order(o ...group.OrderOption) *GroupQuery { gq.order = append(gq.order, o...) return gq } -// QueryApplication chains the current query on the application edge. +// QueryApplication chains the current query on the "application" edge. func (gq *GroupQuery) QueryApplication() *ApplicationQuery { - query := &ApplicationQuery{config: gq.config} + query := (&ApplicationClient{config: gq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := gq.prepareQuery(ctx); err != nil { return nil, err } - selector := gq.sqlQuery() + selector := gq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -81,14 +85,14 @@ func (gq *GroupQuery) QueryApplication() *ApplicationQuery { return query } -// QueryGraphs chains the current query on the graphs edge. +// QueryGraphs chains the current query on the "graphs" edge. func (gq *GroupQuery) QueryGraphs() *GraphQuery { - query := &GraphQuery{config: gq.config} + query := (&GraphClient{config: gq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := gq.prepareQuery(ctx); err != nil { return nil, err } - selector := gq.sqlQuery() + selector := gq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -103,9 +107,10 @@ func (gq *GroupQuery) QueryGraphs() *GraphQuery { return query } -// First returns the first Group entity in the query. Returns *NotFoundError when no group was found. +// First returns the first Group entity from the query. +// Returns a *NotFoundError when no Group was found. func (gq *GroupQuery) First(ctx context.Context) (*Group, error) { - nodes, err := gq.Limit(1).All(ctx) + nodes, err := gq.Limit(1).All(setContextOp(ctx, gq.ctx, "First")) if err != nil { return nil, err } @@ -124,10 +129,11 @@ func (gq *GroupQuery) FirstX(ctx context.Context) *Group { return node } -// FirstID returns the first Group id in the query. Returns *NotFoundError when no id was found. +// FirstID returns the first Group ID from the query. +// Returns a *NotFoundError when no Group ID was found. func (gq *GroupQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = gq.Limit(1).IDs(ctx); err != nil { + if ids, err = gq.Limit(1).IDs(setContextOp(ctx, gq.ctx, "FirstID")); err != nil { return } if len(ids) == 0 { @@ -137,8 +143,8 @@ func (gq *GroupQuery) FirstID(ctx context.Context) (id int, err error) { return ids[0], nil } -// FirstXID is like FirstID, but panics if an error occurs. -func (gq *GroupQuery) FirstXID(ctx context.Context) int { +// FirstIDX is like FirstID, but panics if an error occurs. +func (gq *GroupQuery) FirstIDX(ctx context.Context) int { id, err := gq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -146,9 +152,11 @@ func (gq *GroupQuery) FirstXID(ctx context.Context) int { return id } -// Only returns the only Group entity in the query, returns an error if not exactly one entity was returned. +// Only returns a single Group entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Group entity is found. +// Returns a *NotFoundError when no Group entities are found. func (gq *GroupQuery) Only(ctx context.Context) (*Group, error) { - nodes, err := gq.Limit(2).All(ctx) + nodes, err := gq.Limit(2).All(setContextOp(ctx, gq.ctx, "Only")) if err != nil { return nil, err } @@ -171,10 +179,12 @@ func (gq *GroupQuery) OnlyX(ctx context.Context) *Group { return node } -// OnlyID returns the only Group id in the query, returns an error if not exactly one id was returned. +// OnlyID is like Only, but returns the only Group ID in the query. +// Returns a *NotSingularError when more than one Group ID is found. +// Returns a *NotFoundError when no entities are found. func (gq *GroupQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = gq.Limit(2).IDs(ctx); err != nil { + if ids, err = gq.Limit(2).IDs(setContextOp(ctx, gq.ctx, "OnlyID")); err != nil { return } switch len(ids) { @@ -199,10 +209,12 @@ func (gq *GroupQuery) OnlyIDX(ctx context.Context) int { // All executes the query and returns a list of Groups. func (gq *GroupQuery) All(ctx context.Context) ([]*Group, error) { + ctx = setContextOp(ctx, gq.ctx, "All") if err := gq.prepareQuery(ctx); err != nil { return nil, err } - return gq.sqlAll(ctx) + qr := querierAll[[]*Group, *GroupQuery]() + return withInterceptors[[]*Group](ctx, gq, qr, gq.inters) } // AllX is like All, but panics if an error occurs. @@ -214,10 +226,13 @@ func (gq *GroupQuery) AllX(ctx context.Context) []*Group { return nodes } -// IDs executes the query and returns a list of Group ids. -func (gq *GroupQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := gq.Select(group.FieldID).Scan(ctx, &ids); err != nil { +// IDs executes the query and returns a list of Group IDs. +func (gq *GroupQuery) IDs(ctx context.Context) (ids []int, err error) { + if gq.ctx.Unique == nil && gq.path != nil { + gq.Unique(true) + } + ctx = setContextOp(ctx, gq.ctx, "IDs") + if err = gq.Select(group.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil @@ -234,10 +249,11 @@ func (gq *GroupQuery) IDsX(ctx context.Context) []int { // Count returns the count of the given query. func (gq *GroupQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, gq.ctx, "Count") if err := gq.prepareQuery(ctx); err != nil { return 0, err } - return gq.sqlCount(ctx) + return withInterceptors[int](ctx, gq, querierCount[*GroupQuery](), gq.inters) } // CountX is like Count, but panics if an error occurs. @@ -251,10 +267,15 @@ func (gq *GroupQuery) CountX(ctx context.Context) int { // Exist returns true if the query has elements in the graph. func (gq *GroupQuery) Exist(ctx context.Context) (bool, error) { - if err := gq.prepareQuery(ctx); err != nil { - return false, err + ctx = setContextOp(ctx, gq.ctx, "Exist") + switch _, err := gq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil } - return gq.sqlExist(ctx) } // ExistX is like Exist, but panics if an error occurs. @@ -266,26 +287,30 @@ func (gq *GroupQuery) ExistX(ctx context.Context) bool { return exist } -// Clone returns a duplicate of the query builder, including all associated steps. It can be +// Clone returns a duplicate of the GroupQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. func (gq *GroupQuery) Clone() *GroupQuery { + if gq == nil { + return nil + } return &GroupQuery{ - config: gq.config, - limit: gq.limit, - offset: gq.offset, - order: append([]OrderFunc{}, gq.order...), - unique: append([]string{}, gq.unique...), - predicates: append([]predicate.Group{}, gq.predicates...), + config: gq.config, + ctx: gq.ctx.Clone(), + order: append([]group.OrderOption{}, gq.order...), + inters: append([]Interceptor{}, gq.inters...), + predicates: append([]predicate.Group{}, gq.predicates...), + withApplication: gq.withApplication.Clone(), + withGraphs: gq.withGraphs.Clone(), // clone intermediate query. sql: gq.sql.Clone(), path: gq.path, } } -// WithApplication tells the query-builder to eager-loads the nodes that are connected to -// the "application" edge. The optional arguments used to configure the query builder of the edge. +// WithApplication tells the query-builder to eager-load the nodes that are connected to +// the "application" edge. The optional arguments are used to configure the query builder of the edge. func (gq *GroupQuery) WithApplication(opts ...func(*ApplicationQuery)) *GroupQuery { - query := &ApplicationQuery{config: gq.config} + query := (&ApplicationClient{config: gq.config}).Query() for _, opt := range opts { opt(query) } @@ -293,10 +318,10 @@ func (gq *GroupQuery) WithApplication(opts ...func(*ApplicationQuery)) *GroupQue return gq } -// WithGraphs tells the query-builder to eager-loads the nodes that are connected to -// the "graphs" edge. The optional arguments used to configure the query builder of the edge. +// WithGraphs tells the query-builder to eager-load the nodes that are connected to +// the "graphs" edge. The optional arguments are used to configure the query builder of the edge. func (gq *GroupQuery) WithGraphs(opts ...func(*GraphQuery)) *GroupQuery { - query := &GraphQuery{config: gq.config} + query := (&GraphClient{config: gq.config}).Query() for _, opt := range opts { opt(query) } @@ -304,7 +329,7 @@ func (gq *GroupQuery) WithGraphs(opts ...func(*GraphQuery)) *GroupQuery { return gq } -// GroupBy used to group vertices by one or more fields/columns. +// 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: @@ -318,20 +343,17 @@ func (gq *GroupQuery) WithGraphs(opts ...func(*GraphQuery)) *GroupQuery { // GroupBy(group.FieldName). // Aggregate(ent.Count()). // Scan(ctx, &v) -// func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy { - group := &GroupGroupBy{config: gq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := gq.prepareQuery(ctx); err != nil { - return nil, err - } - return gq.sqlQuery(), nil - } - return group + gq.ctx.Fields = append([]string{field}, fields...) + grbuild := &GroupGroupBy{build: gq} + grbuild.flds = &gq.ctx.Fields + grbuild.label = group.Label + grbuild.scan = grbuild.Scan + return grbuild } -// Select one or more fields from the given query. +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. // // Example: // @@ -342,20 +364,35 @@ func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy { // client.Group.Query(). // Select(group.FieldName). // Scan(ctx, &v) -// -func (gq *GroupQuery) Select(field string, fields ...string) *GroupSelect { - selector := &GroupSelect{config: gq.config} - selector.fields = append([]string{field}, fields...) - selector.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := gq.prepareQuery(ctx); err != nil { - return nil, err - } - return gq.sqlQuery(), nil - } - return selector +func (gq *GroupQuery) Select(fields ...string) *GroupSelect { + gq.ctx.Fields = append(gq.ctx.Fields, fields...) + sbuild := &GroupSelect{GroupQuery: gq} + sbuild.label = group.Label + sbuild.flds, sbuild.scan = &gq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a GroupSelect configured with the given aggregations. +func (gq *GroupQuery) Aggregate(fns ...AggregateFunc) *GroupSelect { + return gq.Select().Aggregate(fns...) } func (gq *GroupQuery) prepareQuery(ctx context.Context) error { + for _, inter := range gq.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, gq); err != nil { + return err + } + } + } + for _, f := range gq.ctx.Fields { + if !group.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } if gq.path != nil { prev, err := gq.path(ctx) if err != nil { @@ -366,7 +403,7 @@ func (gq *GroupQuery) prepareQuery(ctx context.Context) error { return nil } -func (gq *GroupQuery) sqlAll(ctx context.Context) ([]*Group, error) { +func (gq *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) { var ( nodes = []*Group{} withFKs = gq.withFKs @@ -382,22 +419,17 @@ func (gq *GroupQuery) sqlAll(ctx context.Context) ([]*Group, error) { if withFKs { _spec.Node.Columns = append(_spec.Node.Columns, group.ForeignKeys...) } - _spec.ScanValues = func() []interface{} { + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Group).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { node := &Group{config: gq.config} nodes = append(nodes, node) - values := node.scanValues() - if withFKs { - values = append(values, node.fkValues()...) - } - return values - } - _spec.Assign = func(values ...interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("ent: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] node.Edges.loadedTypes = loadedTypes - return node.assignValues(values...) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) } if err := sqlgraph.QueryNodes(ctx, gq.driver, _spec); err != nil { return nil, err @@ -405,88 +437,111 @@ func (gq *GroupQuery) sqlAll(ctx context.Context) ([]*Group, error) { if len(nodes) == 0 { return nodes, nil } - if query := gq.withApplication; query != nil { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*Group) - for i := range nodes { - if fk := nodes[i].application_groups; fk != nil { - ids = append(ids, *fk) - nodeids[*fk] = append(nodeids[*fk], nodes[i]) - } - } - query.Where(application.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { + if err := gq.loadApplication(ctx, query, nodes, nil, + func(n *Group, e *Application) { n.Edges.Application = e }); err != nil { return nil, err } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "application_groups" returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.Application = n - } + } + if query := gq.withGraphs; query != nil { + if err := gq.loadGraphs(ctx, query, nodes, + func(n *Group) { n.Edges.Graphs = []*Graph{} }, + func(n *Group, e *Graph) { n.Edges.Graphs = append(n.Edges.Graphs, e) }); err != nil { + return nil, err } } + return nodes, nil +} - if query := gq.withGraphs; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*Group) +func (gq *GroupQuery) loadApplication(ctx context.Context, query *ApplicationQuery, nodes []*Group, init func(*Group), assign func(*Group, *Application)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Group) + for i := range nodes { + if nodes[i].application_groups == nil { + continue + } + fk := *nodes[i].application_groups + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(application.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 "application_groups" returned %v`, n.ID) + } for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] + assign(nodes[i], n) } - query.withFKs = true - query.Where(predicate.Graph(func(s *sql.Selector) { - s.Where(sql.InValues(group.GraphsColumn, fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err + } + return nil +} +func (gq *GroupQuery) loadGraphs(ctx context.Context, query *GraphQuery, nodes []*Group, init func(*Group), assign func(*Group, *Graph)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Group) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) } - for _, n := range neighbors { - fk := n.group_graphs - if fk == nil { - return nil, fmt.Errorf(`foreign-key "group_graphs" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "group_graphs" returned %v for node %v`, *fk, n.ID) - } - node.Edges.Graphs = append(node.Edges.Graphs, n) + } + query.withFKs = true + query.Where(predicate.Graph(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(group.GraphsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.group_graphs + if fk == nil { + return fmt.Errorf(`foreign-key "group_graphs" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "group_graphs" returned %v for node %v`, *fk, n.ID) } + assign(node, n) } - - return nodes, nil + return nil } func (gq *GroupQuery) sqlCount(ctx context.Context) (int, error) { _spec := gq.querySpec() - return sqlgraph.CountNodes(ctx, gq.driver, _spec) -} - -func (gq *GroupQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := gq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("ent: check existence: %v", err) + _spec.Node.Columns = gq.ctx.Fields + if len(gq.ctx.Fields) > 0 { + _spec.Unique = gq.ctx.Unique != nil && *gq.ctx.Unique } - return n > 0, nil + return sqlgraph.CountNodes(ctx, gq.driver, _spec) } func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: group.Table, - Columns: group.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, - }, - From: gq.sql, - Unique: true, + _spec := sqlgraph.NewQuerySpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) + _spec.From = gq.sql + if unique := gq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if gq.path != nil { + _spec.Unique = true + } + if fields := gq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, group.FieldID) + for i := range fields { + if fields[i] != group.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } } if ps := gq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -495,55 +550,58 @@ func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec { } } } - if limit := gq.limit; limit != nil { + if limit := gq.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := gq.offset; offset != nil { + if offset := gq.ctx.Offset; offset != nil { _spec.Offset = *offset } if ps := gq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector, group.ValidColumn) + ps[i](selector) } } } return _spec } -func (gq *GroupQuery) sqlQuery() *sql.Selector { +func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(gq.driver.Dialect()) t1 := builder.Table(group.Table) - selector := builder.Select(t1.Columns(group.Columns...)...).From(t1) + columns := gq.ctx.Fields + if len(columns) == 0 { + columns = group.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) if gq.sql != nil { selector = gq.sql - selector.Select(selector.Columns(group.Columns...)...) + selector.Select(selector.Columns(columns...)...) + } + if gq.ctx.Unique != nil && *gq.ctx.Unique { + selector.Distinct() } for _, p := range gq.predicates { p(selector) } for _, p := range gq.order { - p(selector, group.ValidColumn) + p(selector) } - if offset := gq.offset; offset != nil { + if offset := gq.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 := gq.limit; limit != nil { + if limit := gq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector } -// GroupGroupBy is the builder for group-by Group entities. +// GroupGroupBy is the group-by builder for Group entities. type GroupGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) + selector + build *GroupQuery } // Aggregate adds the given aggregation functions to the group-by query. @@ -552,471 +610,80 @@ func (ggb *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy { return ggb } -// Scan applies the group-by query and scan the result into the given value. -func (ggb *GroupGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := ggb.path(ctx) - if err != nil { +// Scan applies the selector query and scans the result into the given value. +func (ggb *GroupGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ggb.build.ctx, "GroupBy") + if err := ggb.build.prepareQuery(ctx); err != nil { return err } - ggb.sql = query - return ggb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (ggb *GroupGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := ggb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field. -func (ggb *GroupGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GroupGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil + return scanWithInterceptors[*GroupQuery, *GroupGroupBy](ctx, ggb.build, ggb, ggb.build.inters, v) } -// StringsX is like Strings, but panics if an error occurs. -func (ggb *GroupGroupBy) StringsX(ctx context.Context) []string { - v, err := ggb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from group-by. It is only allowed when querying group-by with one field. -func (ggb *GroupGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = ggb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{group.Label} - default: - err = fmt.Errorf("ent: GroupGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (ggb *GroupGroupBy) StringX(ctx context.Context) string { - v, err := ggb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field. -func (ggb *GroupGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GroupGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (ggb *GroupGroupBy) IntsX(ctx context.Context) []int { - v, err := ggb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from group-by. It is only allowed when querying group-by with one field. -func (ggb *GroupGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = ggb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{group.Label} - default: - err = fmt.Errorf("ent: GroupGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (ggb *GroupGroupBy) IntX(ctx context.Context) int { - v, err := ggb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field. -func (ggb *GroupGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GroupGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (ggb *GroupGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := ggb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field. -func (ggb *GroupGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = ggb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{group.Label} - default: - err = fmt.Errorf("ent: GroupGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (ggb *GroupGroupBy) Float64X(ctx context.Context) float64 { - v, err := ggb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field. -func (ggb *GroupGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(ggb.fields) > 1 { - return nil, errors.New("ent: GroupGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := ggb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (ggb *GroupGroupBy) BoolsX(ctx context.Context) []bool { - v, err := ggb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field. -func (ggb *GroupGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = ggb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{group.Label} - default: - err = fmt.Errorf("ent: GroupGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (ggb *GroupGroupBy) BoolX(ctx context.Context) bool { - v, err := ggb.Bool(ctx) - if err != nil { - panic(err) +func (ggb *GroupGroupBy) sqlScan(ctx context.Context, root *GroupQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ggb.fns)) + for _, fn := range ggb.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (ggb *GroupGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range ggb.fields { - if !group.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ggb.flds)+len(ggb.fns)) + for _, f := range *ggb.flds { + columns = append(columns, selector.C(f)) } + columns = append(columns, aggregation...) + selector.Select(columns...) } - selector := ggb.sqlQuery() + selector.GroupBy(selector.Columns(*ggb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := ggb.driver.Query(ctx, query, args, rows); err != nil { + if err := ggb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } -func (ggb *GroupGroupBy) sqlQuery() *sql.Selector { - selector := ggb.sql - columns := make([]string, 0, len(ggb.fields)+len(ggb.fns)) - columns = append(columns, ggb.fields...) - for _, fn := range ggb.fns { - columns = append(columns, fn(selector, group.ValidColumn)) - } - return selector.Select(columns...).GroupBy(ggb.fields...) -} - -// GroupSelect is the builder for select fields of Group entities. +// GroupSelect is the builder for selecting fields of Group entities. type GroupSelect struct { - config - fields []string - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Scan applies the selector query and scan the result into the given value. -func (gs *GroupSelect) Scan(ctx context.Context, v interface{}) error { - query, err := gs.path(ctx) - if err != nil { - return err - } - gs.sql = query - return gs.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (gs *GroupSelect) ScanX(ctx context.Context, v interface{}) { - if err := gs.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from selector. It is only allowed when selecting one field. -func (gs *GroupSelect) Strings(ctx context.Context) ([]string, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GroupSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (gs *GroupSelect) StringsX(ctx context.Context) []string { - v, err := gs.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from selector. It is only allowed when selecting one field. -func (gs *GroupSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = gs.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{group.Label} - default: - err = fmt.Errorf("ent: GroupSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (gs *GroupSelect) StringX(ctx context.Context) string { - v, err := gs.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from selector. It is only allowed when selecting one field. -func (gs *GroupSelect) Ints(ctx context.Context) ([]int, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GroupSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (gs *GroupSelect) IntsX(ctx context.Context) []int { - v, err := gs.Ints(ctx) - if err != nil { - panic(err) - } - return v + *GroupQuery + selector } -// Int returns a single int from selector. It is only allowed when selecting one field. -func (gs *GroupSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = gs.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{group.Label} - default: - err = fmt.Errorf("ent: GroupSelect.Ints returned %d results when one was expected", len(v)) - } - return +// Aggregate adds the given aggregation functions to the selector query. +func (gs *GroupSelect) Aggregate(fns ...AggregateFunc) *GroupSelect { + gs.fns = append(gs.fns, fns...) + return gs } -// IntX is like Int, but panics if an error occurs. -func (gs *GroupSelect) IntX(ctx context.Context) int { - v, err := gs.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from selector. It is only allowed when selecting one field. -func (gs *GroupSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GroupSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (gs *GroupSelect) Float64sX(ctx context.Context) []float64 { - v, err := gs.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from selector. It is only allowed when selecting one field. -func (gs *GroupSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = gs.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{group.Label} - default: - err = fmt.Errorf("ent: GroupSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (gs *GroupSelect) Float64X(ctx context.Context) float64 { - v, err := gs.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from selector. It is only allowed when selecting one field. -func (gs *GroupSelect) Bools(ctx context.Context) ([]bool, error) { - if len(gs.fields) > 1 { - return nil, errors.New("ent: GroupSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := gs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (gs *GroupSelect) BoolsX(ctx context.Context) []bool { - v, err := gs.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from selector. It is only allowed when selecting one field. -func (gs *GroupSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = gs.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{group.Label} - default: - err = fmt.Errorf("ent: GroupSelect.Bools returned %d results when one was expected", len(v)) +// Scan applies the selector query and scans the result into the given value. +func (gs *GroupSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, gs.ctx, "Select") + if err := gs.prepareQuery(ctx); err != nil { + return err } - return + return scanWithInterceptors[*GroupQuery, *GroupSelect](ctx, gs.GroupQuery, gs, gs.inters, v) } -// BoolX is like Bool, but panics if an error occurs. -func (gs *GroupSelect) BoolX(ctx context.Context) bool { - v, err := gs.Bool(ctx) - if err != nil { - panic(err) +func (gs *GroupSelect) sqlScan(ctx context.Context, root *GroupQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(gs.fns)) + for _, fn := range gs.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (gs *GroupSelect) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range gs.fields { - if !group.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} - } + switch n := len(*gs.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 := gs.sqlQuery().Query() + query, args := selector.Query() if err := gs.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } - -func (gs *GroupSelect) sqlQuery() sql.Querier { - selector := gs.sql - selector.Select(selector.Columns(gs.fields...)...) - return selector -} diff --git a/ent/group_update.go b/ent/group_update.go index ce527a5e..68658155 100644 --- a/ent/group_update.go +++ b/ent/group_update.go @@ -1,14 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/graph" "github.com/gobench-io/gobench/v2/ent/group" @@ -18,24 +19,23 @@ import ( // GroupUpdate is the builder for updating Group entities. type GroupUpdate struct { config - hooks []Hook - mutation *GroupMutation - predicates []predicate.Group + hooks []Hook + mutation *GroupMutation } -// Where adds a new predicate for the builder. +// Where appends a list predicates to the GroupUpdate builder. func (gu *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate { - gu.predicates = append(gu.predicates, ps...) + gu.mutation.Where(ps...) return gu } -// SetApplicationID sets the application edge to Application by id. +// SetApplicationID sets the "application" edge to the Application entity by ID. func (gu *GroupUpdate) SetApplicationID(id int) *GroupUpdate { gu.mutation.SetApplicationID(id) return gu } -// SetNillableApplicationID sets the application edge to Application by id if the given value is not nil. +// SetNillableApplicationID sets the "application" edge to the Application entity by ID if the given value is not nil. func (gu *GroupUpdate) SetNillableApplicationID(id *int) *GroupUpdate { if id != nil { gu = gu.SetApplicationID(*id) @@ -43,18 +43,18 @@ func (gu *GroupUpdate) SetNillableApplicationID(id *int) *GroupUpdate { return gu } -// SetApplication sets the application edge to Application. +// SetApplication sets the "application" edge to the Application entity. func (gu *GroupUpdate) SetApplication(a *Application) *GroupUpdate { return gu.SetApplicationID(a.ID) } -// AddGraphIDs adds the graphs edge to Graph by ids. +// AddGraphIDs adds the "graphs" edge to the Graph entity by IDs. func (gu *GroupUpdate) AddGraphIDs(ids ...int) *GroupUpdate { gu.mutation.AddGraphIDs(ids...) return gu } -// AddGraphs adds the graphs edges to Graph. +// AddGraphs adds the "graphs" edges to the Graph entity. func (gu *GroupUpdate) AddGraphs(g ...*Graph) *GroupUpdate { ids := make([]int, len(g)) for i := range g { @@ -68,25 +68,25 @@ func (gu *GroupUpdate) Mutation() *GroupMutation { return gu.mutation } -// ClearApplication clears the "application" edge to type Application. +// ClearApplication clears the "application" edge to the Application entity. func (gu *GroupUpdate) ClearApplication() *GroupUpdate { gu.mutation.ClearApplication() return gu } -// ClearGraphs clears all "graphs" edges to type Graph. +// ClearGraphs clears all "graphs" edges to the Graph entity. func (gu *GroupUpdate) ClearGraphs() *GroupUpdate { gu.mutation.ClearGraphs() return gu } -// RemoveGraphIDs removes the graphs edge to Graph by ids. +// RemoveGraphIDs removes the "graphs" edge to Graph entities by IDs. func (gu *GroupUpdate) RemoveGraphIDs(ids ...int) *GroupUpdate { gu.mutation.RemoveGraphIDs(ids...) return gu } -// RemoveGraphs removes graphs edges to Graph. +// RemoveGraphs removes "graphs" edges to Graph entities. func (gu *GroupUpdate) RemoveGraphs(g ...*Graph) *GroupUpdate { ids := make([]int, len(g)) for i := range g { @@ -95,33 +95,9 @@ func (gu *GroupUpdate) RemoveGraphs(g ...*Graph) *GroupUpdate { return gu.RemoveGraphIDs(ids...) } -// Save executes the query and returns the number of rows/vertices matched by this operation. +// Save executes the query and returns the number of nodes affected by the update operation. func (gu *GroupUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(gu.hooks) == 0 { - affected, err = gu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - gu.mutation = mutation - affected, err = gu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(gu.hooks) - 1; i >= 0; i-- { - mut = gu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, gu.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, gu.sqlSave, gu.mutation, gu.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -147,17 +123,8 @@ func (gu *GroupUpdate) ExecX(ctx context.Context) { } func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: group.Table, - Columns: group.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, - }, - } - if ps := gu.predicates; len(ps) > 0 { + _spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) + if ps := gu.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -172,10 +139,7 @@ func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{group.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -188,10 +152,7 @@ func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{group.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -207,10 +168,7 @@ func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{group.GraphsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -223,10 +181,7 @@ func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{group.GraphsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -242,10 +197,7 @@ func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{group.GraphsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -256,28 +208,30 @@ func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) { if n, err = sqlgraph.UpdateNodes(ctx, gu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{group.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } + gu.mutation.done = true return n, nil } // GroupUpdateOne is the builder for updating a single Group entity. type GroupUpdateOne struct { config + fields []string hooks []Hook mutation *GroupMutation } -// SetApplicationID sets the application edge to Application by id. +// SetApplicationID sets the "application" edge to the Application entity by ID. func (guo *GroupUpdateOne) SetApplicationID(id int) *GroupUpdateOne { guo.mutation.SetApplicationID(id) return guo } -// SetNillableApplicationID sets the application edge to Application by id if the given value is not nil. +// SetNillableApplicationID sets the "application" edge to the Application entity by ID if the given value is not nil. func (guo *GroupUpdateOne) SetNillableApplicationID(id *int) *GroupUpdateOne { if id != nil { guo = guo.SetApplicationID(*id) @@ -285,18 +239,18 @@ func (guo *GroupUpdateOne) SetNillableApplicationID(id *int) *GroupUpdateOne { return guo } -// SetApplication sets the application edge to Application. +// SetApplication sets the "application" edge to the Application entity. func (guo *GroupUpdateOne) SetApplication(a *Application) *GroupUpdateOne { return guo.SetApplicationID(a.ID) } -// AddGraphIDs adds the graphs edge to Graph by ids. +// AddGraphIDs adds the "graphs" edge to the Graph entity by IDs. func (guo *GroupUpdateOne) AddGraphIDs(ids ...int) *GroupUpdateOne { guo.mutation.AddGraphIDs(ids...) return guo } -// AddGraphs adds the graphs edges to Graph. +// AddGraphs adds the "graphs" edges to the Graph entity. func (guo *GroupUpdateOne) AddGraphs(g ...*Graph) *GroupUpdateOne { ids := make([]int, len(g)) for i := range g { @@ -310,25 +264,25 @@ func (guo *GroupUpdateOne) Mutation() *GroupMutation { return guo.mutation } -// ClearApplication clears the "application" edge to type Application. +// ClearApplication clears the "application" edge to the Application entity. func (guo *GroupUpdateOne) ClearApplication() *GroupUpdateOne { guo.mutation.ClearApplication() return guo } -// ClearGraphs clears all "graphs" edges to type Graph. +// ClearGraphs clears all "graphs" edges to the Graph entity. func (guo *GroupUpdateOne) ClearGraphs() *GroupUpdateOne { guo.mutation.ClearGraphs() return guo } -// RemoveGraphIDs removes the graphs edge to Graph by ids. +// RemoveGraphIDs removes the "graphs" edge to Graph entities by IDs. func (guo *GroupUpdateOne) RemoveGraphIDs(ids ...int) *GroupUpdateOne { guo.mutation.RemoveGraphIDs(ids...) return guo } -// RemoveGraphs removes graphs edges to Graph. +// RemoveGraphs removes "graphs" edges to Graph entities. func (guo *GroupUpdateOne) RemoveGraphs(g ...*Graph) *GroupUpdateOne { ids := make([]int, len(g)) for i := range g { @@ -337,33 +291,22 @@ func (guo *GroupUpdateOne) RemoveGraphs(g ...*Graph) *GroupUpdateOne { return guo.RemoveGraphIDs(ids...) } -// Save executes the query and returns the updated entity. +// Where appends a list predicates to the GroupUpdate builder. +func (guo *GroupUpdateOne) Where(ps ...predicate.Group) *GroupUpdateOne { + guo.mutation.Where(ps...) + return guo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (guo *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne { + guo.fields = append([]string{field}, fields...) + return guo +} + +// Save executes the query and returns the updated Group entity. func (guo *GroupUpdateOne) Save(ctx context.Context) (*Group, error) { - var ( - err error - node *Group - ) - if len(guo.hooks) == 0 { - node, err = guo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*GroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - guo.mutation = mutation - node, err = guo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(guo.hooks) - 1; i >= 0; i-- { - mut = guo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, guo.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, guo.sqlSave, guo.mutation, guo.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -389,21 +332,31 @@ func (guo *GroupUpdateOne) ExecX(ctx context.Context) { } func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: group.Table, - Columns: group.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: group.FieldID, - }, - }, - } + _spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) id, ok := guo.mutation.ID() if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Group.ID for update")} + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Group.id" for update`)} } _spec.Node.ID.Value = id + if fields := guo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, group.FieldID) + for _, f := range fields { + if !group.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != group.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := guo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } if guo.mutation.ApplicationCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -412,10 +365,7 @@ func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error Columns: []string{group.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -428,10 +378,7 @@ func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error Columns: []string{group.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -447,10 +394,7 @@ func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error Columns: []string{group.GraphsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -463,10 +407,7 @@ func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error Columns: []string{group.GraphsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -482,10 +423,7 @@ func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error Columns: []string{group.GraphsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -495,14 +433,15 @@ func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error } _node = &Group{config: guo.config} _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues() + _spec.ScanValues = _node.scanValues if err = sqlgraph.UpdateNode(ctx, guo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{group.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } + guo.mutation.done = true return _node, nil } diff --git a/ent/histogram.go b/ent/histogram.go index a5454a26..a2ac961b 100644 --- a/ent/histogram.go +++ b/ent/histogram.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -6,7 +6,8 @@ import ( "fmt" "strings" - "github.com/facebook/ent/dialect/sql" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/gobench-io/gobench/v2/ent/histogram" "github.com/gobench-io/gobench/v2/ent/metric" ) @@ -44,12 +45,13 @@ type Histogram struct { // The values are being populated by the HistogramQuery when eager-loading is set. Edges HistogramEdges `json:"edges"` metric_histograms *int + selectValues sql.SelectValues } // HistogramEdges holds the relations/edges for other nodes in the graph. type HistogramEdges struct { // Metric holds the value of the metric edge. - Metric *Metric + Metric *Metric `json:"metric,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [1]bool @@ -60,8 +62,7 @@ type HistogramEdges struct { func (e HistogramEdges) MetricOrErr() (*Metric, error) { if e.loadedTypes[0] { if e.Metric == nil { - // The edge metric was loaded in eager-loading, - // but was not found. + // Edge was loaded but was not found. return nil, &NotFoundError{label: metric.Label} } return e.Metric, nil @@ -70,135 +71,151 @@ func (e HistogramEdges) MetricOrErr() (*Metric, error) { } // scanValues returns the types for scanning values from sql.Rows. -func (*Histogram) scanValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // id - &sql.NullInt64{}, // time - &sql.NullInt64{}, // count - &sql.NullInt64{}, // min - &sql.NullInt64{}, // max - &sql.NullFloat64{}, // mean - &sql.NullFloat64{}, // stddev - &sql.NullFloat64{}, // median - &sql.NullFloat64{}, // p75 - &sql.NullFloat64{}, // p95 - &sql.NullFloat64{}, // p99 - &sql.NullFloat64{}, // p999 - &sql.NullString{}, // wID - } -} - -// fkValues returns the types for scanning foreign-keys values from sql.Rows. -func (*Histogram) fkValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // metric_histograms +func (*Histogram) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case histogram.FieldMean, histogram.FieldStddev, histogram.FieldMedian, histogram.FieldP75, histogram.FieldP95, histogram.FieldP99, histogram.FieldP999: + values[i] = new(sql.NullFloat64) + case histogram.FieldID, histogram.FieldTime, histogram.FieldCount, histogram.FieldMin, histogram.FieldMax: + values[i] = new(sql.NullInt64) + case histogram.FieldWID: + values[i] = new(sql.NullString) + case histogram.ForeignKeys[0]: // metric_histograms + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } } + return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Histogram fields. -func (h *Histogram) assignValues(values ...interface{}) error { - if m, n := len(values), len(histogram.Columns); m < n { +func (h *Histogram) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } - value, ok := values[0].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - h.ID = int(value.Int64) - values = values[1:] - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field time", values[0]) - } else if value.Valid { - h.Time = value.Int64 - } - if value, ok := values[1].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field count", values[1]) - } else if value.Valid { - h.Count = value.Int64 - } - if value, ok := values[2].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field min", values[2]) - } else if value.Valid { - h.Min = value.Int64 - } - if value, ok := values[3].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for field max", values[3]) - } else if value.Valid { - h.Max = value.Int64 - } - if value, ok := values[4].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field mean", values[4]) - } else if value.Valid { - h.Mean = value.Float64 - } - if value, ok := values[5].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field stddev", values[5]) - } else if value.Valid { - h.Stddev = value.Float64 - } - if value, ok := values[6].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field median", values[6]) - } else if value.Valid { - h.Median = value.Float64 - } - if value, ok := values[7].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field p75", values[7]) - } else if value.Valid { - h.P75 = value.Float64 - } - if value, ok := values[8].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field p95", values[8]) - } else if value.Valid { - h.P95 = value.Float64 - } - if value, ok := values[9].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field p99", values[9]) - } else if value.Valid { - h.P99 = value.Float64 - } - if value, ok := values[10].(*sql.NullFloat64); !ok { - return fmt.Errorf("unexpected type %T for field p999", values[10]) - } else if value.Valid { - h.P999 = value.Float64 - } - if value, ok := values[11].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field wID", values[11]) - } else if value.Valid { - h.WID = value.String - } - values = values[12:] - if len(values) == len(histogram.ForeignKeys) { - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field metric_histograms", value) - } else if value.Valid { - h.metric_histograms = new(int) - *h.metric_histograms = int(value.Int64) + for i := range columns { + switch columns[i] { + case histogram.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + h.ID = int(value.Int64) + case histogram.FieldTime: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field time", values[i]) + } else if value.Valid { + h.Time = value.Int64 + } + case histogram.FieldCount: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field count", values[i]) + } else if value.Valid { + h.Count = value.Int64 + } + case histogram.FieldMin: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field min", values[i]) + } else if value.Valid { + h.Min = value.Int64 + } + case histogram.FieldMax: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field max", values[i]) + } else if value.Valid { + h.Max = value.Int64 + } + case histogram.FieldMean: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field mean", values[i]) + } else if value.Valid { + h.Mean = value.Float64 + } + case histogram.FieldStddev: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field stddev", values[i]) + } else if value.Valid { + h.Stddev = value.Float64 + } + case histogram.FieldMedian: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field median", values[i]) + } else if value.Valid { + h.Median = value.Float64 + } + case histogram.FieldP75: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field p75", values[i]) + } else if value.Valid { + h.P75 = value.Float64 + } + case histogram.FieldP95: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field p95", values[i]) + } else if value.Valid { + h.P95 = value.Float64 + } + case histogram.FieldP99: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field p99", values[i]) + } else if value.Valid { + h.P99 = value.Float64 + } + case histogram.FieldP999: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field p999", values[i]) + } else if value.Valid { + h.P999 = value.Float64 + } + case histogram.FieldWID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field wID", values[i]) + } else if value.Valid { + h.WID = value.String + } + case histogram.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field metric_histograms", value) + } else if value.Valid { + h.metric_histograms = new(int) + *h.metric_histograms = int(value.Int64) + } + default: + h.selectValues.Set(columns[i], values[i]) } } return nil } -// QueryMetric queries the metric edge of the Histogram. +// Value returns the ent.Value that was dynamically selected and assigned to the Histogram. +// This includes values selected through modifiers, order, etc. +func (h *Histogram) Value(name string) (ent.Value, error) { + return h.selectValues.Get(name) +} + +// QueryMetric queries the "metric" edge of the Histogram entity. func (h *Histogram) QueryMetric() *MetricQuery { - return (&HistogramClient{config: h.config}).QueryMetric(h) + return NewHistogramClient(h.config).QueryMetric(h) } // Update returns a builder for updating this Histogram. -// Note that, you need to call Histogram.Unwrap() before calling this method, if this Histogram +// Note that you need to call Histogram.Unwrap() before calling this method if this Histogram // was returned from a transaction, and the transaction was committed or rolled back. func (h *Histogram) Update() *HistogramUpdateOne { - return (&HistogramClient{config: h.config}).UpdateOne(h) + return NewHistogramClient(h.config).UpdateOne(h) } -// Unwrap unwraps the entity that was returned from a transaction after it was closed, -// so that all next queries will be executed through the driver which created the transaction. +// Unwrap unwraps the Histogram entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. func (h *Histogram) Unwrap() *Histogram { - tx, ok := h.config.driver.(*txDriver) + _tx, ok := h.config.driver.(*txDriver) if !ok { panic("ent: Histogram is not a transactional entity") } - h.config.driver = tx.drv + h.config.driver = _tx.drv return h } @@ -206,30 +223,41 @@ func (h *Histogram) Unwrap() *Histogram { func (h *Histogram) String() string { var builder strings.Builder builder.WriteString("Histogram(") - builder.WriteString(fmt.Sprintf("id=%v", h.ID)) - builder.WriteString(", time=") + builder.WriteString(fmt.Sprintf("id=%v, ", h.ID)) + builder.WriteString("time=") builder.WriteString(fmt.Sprintf("%v", h.Time)) - builder.WriteString(", count=") + builder.WriteString(", ") + builder.WriteString("count=") builder.WriteString(fmt.Sprintf("%v", h.Count)) - builder.WriteString(", min=") + builder.WriteString(", ") + builder.WriteString("min=") builder.WriteString(fmt.Sprintf("%v", h.Min)) - builder.WriteString(", max=") + builder.WriteString(", ") + builder.WriteString("max=") builder.WriteString(fmt.Sprintf("%v", h.Max)) - builder.WriteString(", mean=") + builder.WriteString(", ") + builder.WriteString("mean=") builder.WriteString(fmt.Sprintf("%v", h.Mean)) - builder.WriteString(", stddev=") + builder.WriteString(", ") + builder.WriteString("stddev=") builder.WriteString(fmt.Sprintf("%v", h.Stddev)) - builder.WriteString(", median=") + builder.WriteString(", ") + builder.WriteString("median=") builder.WriteString(fmt.Sprintf("%v", h.Median)) - builder.WriteString(", p75=") + builder.WriteString(", ") + builder.WriteString("p75=") builder.WriteString(fmt.Sprintf("%v", h.P75)) - builder.WriteString(", p95=") + builder.WriteString(", ") + builder.WriteString("p95=") builder.WriteString(fmt.Sprintf("%v", h.P95)) - builder.WriteString(", p99=") + builder.WriteString(", ") + builder.WriteString("p99=") builder.WriteString(fmt.Sprintf("%v", h.P99)) - builder.WriteString(", p999=") + builder.WriteString(", ") + builder.WriteString("p999=") builder.WriteString(fmt.Sprintf("%v", h.P999)) - builder.WriteString(", wID=") + builder.WriteString(", ") + builder.WriteString("wID=") builder.WriteString(h.WID) builder.WriteByte(')') return builder.String() @@ -237,9 +265,3 @@ func (h *Histogram) String() string { // Histograms is a parsable slice of Histogram. type Histograms []*Histogram - -func (h Histograms) config(cfg config) { - for _i := range h { - h[_i].config = cfg - } -} diff --git a/ent/histogram/histogram.go b/ent/histogram/histogram.go index b4521011..33dc2511 100644 --- a/ent/histogram/histogram.go +++ b/ent/histogram/histogram.go @@ -1,7 +1,12 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package histogram +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + const ( // Label holds the string label denoting the histogram type in the database. Label = "histogram" @@ -31,13 +36,11 @@ const ( FieldP999 = "p999" // FieldWID holds the string denoting the wid field in the database. FieldWID = "w_id" - // EdgeMetric holds the string denoting the metric edge name in mutations. EdgeMetric = "metric" - // Table holds the table name of the histogram in the database. Table = "histograms" - // MetricTable is the table the holds the metric relation/edge. + // MetricTable is the table that holds the metric relation/edge. MetricTable = "histograms" // MetricInverseTable is the table name for the Metric entity. // It exists in this package in order to avoid circular dependency with the "metric" package. @@ -63,7 +66,8 @@ var Columns = []string{ FieldWID, } -// ForeignKeys holds the SQL foreign-keys that are owned by the Histogram type. +// ForeignKeys holds the SQL foreign-keys that are owned by the "histograms" +// table and are not defined as standalone fields in the schema. var ForeignKeys = []string{ "metric_histograms", } @@ -82,3 +86,85 @@ func ValidColumn(column string) bool { } return false } + +// OrderOption defines the ordering options for the Histogram queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByTime orders the results by the time field. +func ByTime(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTime, opts...).ToFunc() +} + +// ByCount orders the results by the count field. +func ByCount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCount, opts...).ToFunc() +} + +// ByMin orders the results by the min field. +func ByMin(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMin, opts...).ToFunc() +} + +// ByMax orders the results by the max field. +func ByMax(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMax, opts...).ToFunc() +} + +// ByMean orders the results by the mean field. +func ByMean(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMean, opts...).ToFunc() +} + +// ByStddev orders the results by the stddev field. +func ByStddev(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStddev, opts...).ToFunc() +} + +// ByMedian orders the results by the median field. +func ByMedian(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMedian, opts...).ToFunc() +} + +// ByP75 orders the results by the p75 field. +func ByP75(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldP75, opts...).ToFunc() +} + +// ByP95 orders the results by the p95 field. +func ByP95(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldP95, opts...).ToFunc() +} + +// ByP99 orders the results by the p99 field. +func ByP99(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldP99, opts...).ToFunc() +} + +// ByP999 orders the results by the p999 field. +func ByP999(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldP999, opts...).ToFunc() +} + +// ByWID orders the results by the wID field. +func ByWID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWID, opts...).ToFunc() +} + +// ByMetricField orders the results by metric field. +func ByMetricField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newMetricStep(), sql.OrderByField(field, opts...)) + } +} +func newMetricStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(MetricInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, MetricTable, MetricColumn), + ) +} diff --git a/ent/histogram/where.go b/ent/histogram/where.go index 0971b0e8..13aacb00 100644 --- a/ent/histogram/where.go +++ b/ent/histogram/where.go @@ -1,1125 +1,621 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package histogram import ( - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" "github.com/gobench-io/gobench/v2/ent/predicate" ) -// ID filters vertices based on their identifier. +// ID filters vertices based on their ID field. func ID(id int) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Histogram(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Histogram(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) + return predicate.Histogram(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) + return predicate.Histogram(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) + return predicate.Histogram(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) + return predicate.Histogram(sql.FieldLTE(FieldID, id)) } // Time applies equality check predicate on the "time" field. It's identical to TimeEQ. func Time(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTime), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldTime, v)) } // Count applies equality check predicate on the "count" field. It's identical to CountEQ. func Count(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCount), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldCount, v)) } // Min applies equality check predicate on the "min" field. It's identical to MinEQ. func Min(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMin), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldMin, v)) } // Max applies equality check predicate on the "max" field. It's identical to MaxEQ. func Max(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMax), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldMax, v)) } // Mean applies equality check predicate on the "mean" field. It's identical to MeanEQ. func Mean(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMean), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldMean, v)) } // Stddev applies equality check predicate on the "stddev" field. It's identical to StddevEQ. func Stddev(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldStddev), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldStddev, v)) } // Median applies equality check predicate on the "median" field. It's identical to MedianEQ. func Median(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMedian), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldMedian, v)) } // P75 applies equality check predicate on the "p75" field. It's identical to P75EQ. func P75(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldP75), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldP75, v)) } // P95 applies equality check predicate on the "p95" field. It's identical to P95EQ. func P95(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldP95), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldP95, v)) } // P99 applies equality check predicate on the "p99" field. It's identical to P99EQ. func P99(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldP99), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldP99, v)) } // P999 applies equality check predicate on the "p999" field. It's identical to P999EQ. func P999(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldP999), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldP999, v)) } // WID applies equality check predicate on the "wID" field. It's identical to WIDEQ. func WID(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldWID, v)) } // TimeEQ applies the EQ predicate on the "time" field. func TimeEQ(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTime), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldTime, v)) } // TimeNEQ applies the NEQ predicate on the "time" field. func TimeNEQ(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldTime), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldTime, v)) } // TimeIn applies the In predicate on the "time" field. func TimeIn(vs ...int64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldTime), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldTime, vs...)) } // TimeNotIn applies the NotIn predicate on the "time" field. func TimeNotIn(vs ...int64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldTime), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldTime, vs...)) } // TimeGT applies the GT predicate on the "time" field. func TimeGT(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldTime), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldTime, v)) } // TimeGTE applies the GTE predicate on the "time" field. func TimeGTE(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldTime), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldTime, v)) } // TimeLT applies the LT predicate on the "time" field. func TimeLT(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldTime), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldTime, v)) } // TimeLTE applies the LTE predicate on the "time" field. func TimeLTE(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldTime), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldTime, v)) } // CountEQ applies the EQ predicate on the "count" field. func CountEQ(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldCount), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldCount, v)) } // CountNEQ applies the NEQ predicate on the "count" field. func CountNEQ(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldCount), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldCount, v)) } // CountIn applies the In predicate on the "count" field. func CountIn(vs ...int64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldCount), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldCount, vs...)) } // CountNotIn applies the NotIn predicate on the "count" field. func CountNotIn(vs ...int64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldCount), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldCount, vs...)) } // CountGT applies the GT predicate on the "count" field. func CountGT(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldCount), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldCount, v)) } // CountGTE applies the GTE predicate on the "count" field. func CountGTE(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldCount), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldCount, v)) } // CountLT applies the LT predicate on the "count" field. func CountLT(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldCount), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldCount, v)) } // CountLTE applies the LTE predicate on the "count" field. func CountLTE(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldCount), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldCount, v)) } // MinEQ applies the EQ predicate on the "min" field. func MinEQ(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMin), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldMin, v)) } // MinNEQ applies the NEQ predicate on the "min" field. func MinNEQ(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldMin), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldMin, v)) } // MinIn applies the In predicate on the "min" field. func MinIn(vs ...int64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldMin), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldMin, vs...)) } // MinNotIn applies the NotIn predicate on the "min" field. func MinNotIn(vs ...int64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldMin), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldMin, vs...)) } // MinGT applies the GT predicate on the "min" field. func MinGT(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldMin), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldMin, v)) } // MinGTE applies the GTE predicate on the "min" field. func MinGTE(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldMin), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldMin, v)) } // MinLT applies the LT predicate on the "min" field. func MinLT(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldMin), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldMin, v)) } // MinLTE applies the LTE predicate on the "min" field. func MinLTE(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldMin), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldMin, v)) } // MaxEQ applies the EQ predicate on the "max" field. func MaxEQ(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMax), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldMax, v)) } // MaxNEQ applies the NEQ predicate on the "max" field. func MaxNEQ(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldMax), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldMax, v)) } // MaxIn applies the In predicate on the "max" field. func MaxIn(vs ...int64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldMax), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldMax, vs...)) } // MaxNotIn applies the NotIn predicate on the "max" field. func MaxNotIn(vs ...int64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldMax), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldMax, vs...)) } // MaxGT applies the GT predicate on the "max" field. func MaxGT(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldMax), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldMax, v)) } // MaxGTE applies the GTE predicate on the "max" field. func MaxGTE(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldMax), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldMax, v)) } // MaxLT applies the LT predicate on the "max" field. func MaxLT(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldMax), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldMax, v)) } // MaxLTE applies the LTE predicate on the "max" field. func MaxLTE(v int64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldMax), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldMax, v)) } // MeanEQ applies the EQ predicate on the "mean" field. func MeanEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMean), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldMean, v)) } // MeanNEQ applies the NEQ predicate on the "mean" field. func MeanNEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldMean), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldMean, v)) } // MeanIn applies the In predicate on the "mean" field. func MeanIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldMean), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldMean, vs...)) } // MeanNotIn applies the NotIn predicate on the "mean" field. func MeanNotIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldMean), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldMean, vs...)) } // MeanGT applies the GT predicate on the "mean" field. func MeanGT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldMean), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldMean, v)) } // MeanGTE applies the GTE predicate on the "mean" field. func MeanGTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldMean), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldMean, v)) } // MeanLT applies the LT predicate on the "mean" field. func MeanLT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldMean), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldMean, v)) } // MeanLTE applies the LTE predicate on the "mean" field. func MeanLTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldMean), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldMean, v)) } // StddevEQ applies the EQ predicate on the "stddev" field. func StddevEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldStddev), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldStddev, v)) } // StddevNEQ applies the NEQ predicate on the "stddev" field. func StddevNEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldStddev), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldStddev, v)) } // StddevIn applies the In predicate on the "stddev" field. func StddevIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldStddev), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldStddev, vs...)) } // StddevNotIn applies the NotIn predicate on the "stddev" field. func StddevNotIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldStddev), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldStddev, vs...)) } // StddevGT applies the GT predicate on the "stddev" field. func StddevGT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldStddev), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldStddev, v)) } // StddevGTE applies the GTE predicate on the "stddev" field. func StddevGTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldStddev), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldStddev, v)) } // StddevLT applies the LT predicate on the "stddev" field. func StddevLT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldStddev), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldStddev, v)) } // StddevLTE applies the LTE predicate on the "stddev" field. func StddevLTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldStddev), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldStddev, v)) } // MedianEQ applies the EQ predicate on the "median" field. func MedianEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldMedian), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldMedian, v)) } // MedianNEQ applies the NEQ predicate on the "median" field. func MedianNEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldMedian), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldMedian, v)) } // MedianIn applies the In predicate on the "median" field. func MedianIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldMedian), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldMedian, vs...)) } // MedianNotIn applies the NotIn predicate on the "median" field. func MedianNotIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldMedian), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldMedian, vs...)) } // MedianGT applies the GT predicate on the "median" field. func MedianGT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldMedian), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldMedian, v)) } // MedianGTE applies the GTE predicate on the "median" field. func MedianGTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldMedian), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldMedian, v)) } // MedianLT applies the LT predicate on the "median" field. func MedianLT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldMedian), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldMedian, v)) } // MedianLTE applies the LTE predicate on the "median" field. func MedianLTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldMedian), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldMedian, v)) } // P75EQ applies the EQ predicate on the "p75" field. func P75EQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldP75), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldP75, v)) } // P75NEQ applies the NEQ predicate on the "p75" field. func P75NEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldP75), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldP75, v)) } // P75In applies the In predicate on the "p75" field. func P75In(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldP75), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldP75, vs...)) } // P75NotIn applies the NotIn predicate on the "p75" field. func P75NotIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldP75), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldP75, vs...)) } // P75GT applies the GT predicate on the "p75" field. func P75GT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldP75), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldP75, v)) } // P75GTE applies the GTE predicate on the "p75" field. func P75GTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldP75), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldP75, v)) } // P75LT applies the LT predicate on the "p75" field. func P75LT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldP75), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldP75, v)) } // P75LTE applies the LTE predicate on the "p75" field. func P75LTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldP75), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldP75, v)) } // P95EQ applies the EQ predicate on the "p95" field. func P95EQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldP95), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldP95, v)) } // P95NEQ applies the NEQ predicate on the "p95" field. func P95NEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldP95), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldP95, v)) } // P95In applies the In predicate on the "p95" field. func P95In(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldP95), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldP95, vs...)) } // P95NotIn applies the NotIn predicate on the "p95" field. func P95NotIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldP95), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldP95, vs...)) } // P95GT applies the GT predicate on the "p95" field. func P95GT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldP95), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldP95, v)) } // P95GTE applies the GTE predicate on the "p95" field. func P95GTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldP95), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldP95, v)) } // P95LT applies the LT predicate on the "p95" field. func P95LT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldP95), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldP95, v)) } // P95LTE applies the LTE predicate on the "p95" field. func P95LTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldP95), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldP95, v)) } // P99EQ applies the EQ predicate on the "p99" field. func P99EQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldP99), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldP99, v)) } // P99NEQ applies the NEQ predicate on the "p99" field. func P99NEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldP99), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldP99, v)) } // P99In applies the In predicate on the "p99" field. func P99In(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldP99), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldP99, vs...)) } // P99NotIn applies the NotIn predicate on the "p99" field. func P99NotIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldP99), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldP99, vs...)) } // P99GT applies the GT predicate on the "p99" field. func P99GT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldP99), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldP99, v)) } // P99GTE applies the GTE predicate on the "p99" field. func P99GTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldP99), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldP99, v)) } // P99LT applies the LT predicate on the "p99" field. func P99LT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldP99), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldP99, v)) } // P99LTE applies the LTE predicate on the "p99" field. func P99LTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldP99), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldP99, v)) } // P999EQ applies the EQ predicate on the "p999" field. func P999EQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldP999), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldP999, v)) } // P999NEQ applies the NEQ predicate on the "p999" field. func P999NEQ(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldP999), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldP999, v)) } // P999In applies the In predicate on the "p999" field. func P999In(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldP999), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldP999, vs...)) } // P999NotIn applies the NotIn predicate on the "p999" field. func P999NotIn(vs ...float64) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldP999), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldP999, vs...)) } // P999GT applies the GT predicate on the "p999" field. func P999GT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldP999), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldP999, v)) } // P999GTE applies the GTE predicate on the "p999" field. func P999GTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldP999), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldP999, v)) } // P999LT applies the LT predicate on the "p999" field. func P999LT(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldP999), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldP999, v)) } // P999LTE applies the LTE predicate on the "p999" field. func P999LTE(v float64) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldP999), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldP999, v)) } // WIDEQ applies the EQ predicate on the "wID" field. func WIDEQ(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldEQ(FieldWID, v)) } // WIDNEQ applies the NEQ predicate on the "wID" field. func WIDNEQ(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldNEQ(FieldWID, v)) } // WIDIn applies the In predicate on the "wID" field. func WIDIn(vs ...string) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldWID), v...)) - }) + return predicate.Histogram(sql.FieldIn(FieldWID, vs...)) } // WIDNotIn applies the NotIn predicate on the "wID" field. func WIDNotIn(vs ...string) predicate.Histogram { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Histogram(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldWID), v...)) - }) + return predicate.Histogram(sql.FieldNotIn(FieldWID, vs...)) } // WIDGT applies the GT predicate on the "wID" field. func WIDGT(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldGT(FieldWID, v)) } // WIDGTE applies the GTE predicate on the "wID" field. func WIDGTE(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldGTE(FieldWID, v)) } // WIDLT applies the LT predicate on the "wID" field. func WIDLT(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldLT(FieldWID, v)) } // WIDLTE applies the LTE predicate on the "wID" field. func WIDLTE(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldLTE(FieldWID, v)) } // WIDContains applies the Contains predicate on the "wID" field. func WIDContains(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldContains(FieldWID, v)) } // WIDHasPrefix applies the HasPrefix predicate on the "wID" field. func WIDHasPrefix(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldHasPrefix(FieldWID, v)) } // WIDHasSuffix applies the HasSuffix predicate on the "wID" field. func WIDHasSuffix(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldHasSuffix(FieldWID, v)) } // WIDEqualFold applies the EqualFold predicate on the "wID" field. func WIDEqualFold(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldEqualFold(FieldWID, v)) } // WIDContainsFold applies the ContainsFold predicate on the "wID" field. func WIDContainsFold(v string) predicate.Histogram { - return predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldWID), v)) - }) + return predicate.Histogram(sql.FieldContainsFold(FieldWID, v)) } // HasMetric applies the HasEdge predicate on the "metric" edge. @@ -1127,7 +623,6 @@ func HasMetric() predicate.Histogram { return predicate.Histogram(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(MetricTable, FieldID), sqlgraph.Edge(sqlgraph.M2O, true, MetricTable, MetricColumn), ) sqlgraph.HasNeighbors(s, step) @@ -1137,11 +632,7 @@ func HasMetric() predicate.Histogram { // HasMetricWith applies the HasEdge predicate on the "metric" edge with a given conditions (other predicates). func HasMetricWith(preds ...predicate.Metric) predicate.Histogram { return predicate.Histogram(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(MetricInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, MetricTable, MetricColumn), - ) + step := newMetricStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -1150,7 +641,7 @@ func HasMetricWith(preds ...predicate.Metric) predicate.Histogram { }) } -// And groups list of predicates with the AND operator between them. +// And groups predicates with the AND operator between them. func And(predicates ...predicate.Histogram) predicate.Histogram { return predicate.Histogram(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) @@ -1161,7 +652,7 @@ func And(predicates ...predicate.Histogram) predicate.Histogram { }) } -// Or groups list of predicates with the OR operator between them. +// Or groups predicates with the OR operator between them. func Or(predicates ...predicate.Histogram) predicate.Histogram { return predicate.Histogram(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) diff --git a/ent/histogram_create.go b/ent/histogram_create.go index d4bc87c7..94ce3400 100644 --- a/ent/histogram_create.go +++ b/ent/histogram_create.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -7,8 +7,8 @@ import ( "errors" "fmt" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/histogram" "github.com/gobench-io/gobench/v2/ent/metric" ) @@ -20,85 +20,85 @@ type HistogramCreate struct { hooks []Hook } -// SetTime sets the time field. +// SetTime sets the "time" field. func (hc *HistogramCreate) SetTime(i int64) *HistogramCreate { hc.mutation.SetTime(i) return hc } -// SetCount sets the count field. +// SetCount sets the "count" field. func (hc *HistogramCreate) SetCount(i int64) *HistogramCreate { hc.mutation.SetCount(i) return hc } -// SetMin sets the min field. +// SetMin sets the "min" field. func (hc *HistogramCreate) SetMin(i int64) *HistogramCreate { hc.mutation.SetMin(i) return hc } -// SetMax sets the max field. +// SetMax sets the "max" field. func (hc *HistogramCreate) SetMax(i int64) *HistogramCreate { hc.mutation.SetMax(i) return hc } -// SetMean sets the mean field. +// SetMean sets the "mean" field. func (hc *HistogramCreate) SetMean(f float64) *HistogramCreate { hc.mutation.SetMean(f) return hc } -// SetStddev sets the stddev field. +// SetStddev sets the "stddev" field. func (hc *HistogramCreate) SetStddev(f float64) *HistogramCreate { hc.mutation.SetStddev(f) return hc } -// SetMedian sets the median field. +// SetMedian sets the "median" field. func (hc *HistogramCreate) SetMedian(f float64) *HistogramCreate { hc.mutation.SetMedian(f) return hc } -// SetP75 sets the p75 field. +// SetP75 sets the "p75" field. func (hc *HistogramCreate) SetP75(f float64) *HistogramCreate { hc.mutation.SetP75(f) return hc } -// SetP95 sets the p95 field. +// SetP95 sets the "p95" field. func (hc *HistogramCreate) SetP95(f float64) *HistogramCreate { hc.mutation.SetP95(f) return hc } -// SetP99 sets the p99 field. +// SetP99 sets the "p99" field. func (hc *HistogramCreate) SetP99(f float64) *HistogramCreate { hc.mutation.SetP99(f) return hc } -// SetP999 sets the p999 field. +// SetP999 sets the "p999" field. func (hc *HistogramCreate) SetP999(f float64) *HistogramCreate { hc.mutation.SetP999(f) return hc } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (hc *HistogramCreate) SetWID(s string) *HistogramCreate { hc.mutation.SetWID(s) return hc } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by ID. func (hc *HistogramCreate) SetMetricID(id int) *HistogramCreate { hc.mutation.SetMetricID(id) return hc } -// SetNillableMetricID sets the metric edge to Metric by id if the given value is not nil. +// SetNillableMetricID sets the "metric" edge to the Metric entity by ID if the given value is not nil. func (hc *HistogramCreate) SetNillableMetricID(id *int) *HistogramCreate { if id != nil { hc = hc.SetMetricID(*id) @@ -106,7 +106,7 @@ func (hc *HistogramCreate) SetNillableMetricID(id *int) *HistogramCreate { return hc } -// SetMetric sets the metric edge to Metric. +// SetMetric sets the "metric" edge to the Metric entity. func (hc *HistogramCreate) SetMetric(m *Metric) *HistogramCreate { return hc.SetMetricID(m.ID) } @@ -118,37 +118,7 @@ func (hc *HistogramCreate) Mutation() *HistogramMutation { // Save creates the Histogram in the database. func (hc *HistogramCreate) Save(ctx context.Context) (*Histogram, error) { - var ( - err error - node *Histogram - ) - if len(hc.hooks) == 0 { - if err = hc.check(); err != nil { - return nil, err - } - node, err = hc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*HistogramMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = hc.check(); err != nil { - return nil, err - } - hc.mutation = mutation - node, err = hc.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(hc.hooks) - 1; i >= 0; i-- { - mut = hc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, hc.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, hc.sqlSave, hc.mutation, hc.hooks) } // SaveX calls Save and panics if Save returns an error. @@ -160,165 +130,129 @@ func (hc *HistogramCreate) SaveX(ctx context.Context) *Histogram { return v } +// Exec executes the query. +func (hc *HistogramCreate) Exec(ctx context.Context) error { + _, err := hc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (hc *HistogramCreate) ExecX(ctx context.Context) { + if err := hc.Exec(ctx); err != nil { + panic(err) + } +} + // check runs all checks and user-defined validators on the builder. func (hc *HistogramCreate) check() error { if _, ok := hc.mutation.Time(); !ok { - return &ValidationError{Name: "time", err: errors.New("ent: missing required field \"time\"")} + return &ValidationError{Name: "time", err: errors.New(`ent: missing required field "Histogram.time"`)} } if _, ok := hc.mutation.Count(); !ok { - return &ValidationError{Name: "count", err: errors.New("ent: missing required field \"count\"")} + return &ValidationError{Name: "count", err: errors.New(`ent: missing required field "Histogram.count"`)} } if _, ok := hc.mutation.Min(); !ok { - return &ValidationError{Name: "min", err: errors.New("ent: missing required field \"min\"")} + return &ValidationError{Name: "min", err: errors.New(`ent: missing required field "Histogram.min"`)} } if _, ok := hc.mutation.Max(); !ok { - return &ValidationError{Name: "max", err: errors.New("ent: missing required field \"max\"")} + return &ValidationError{Name: "max", err: errors.New(`ent: missing required field "Histogram.max"`)} } if _, ok := hc.mutation.Mean(); !ok { - return &ValidationError{Name: "mean", err: errors.New("ent: missing required field \"mean\"")} + return &ValidationError{Name: "mean", err: errors.New(`ent: missing required field "Histogram.mean"`)} } if _, ok := hc.mutation.Stddev(); !ok { - return &ValidationError{Name: "stddev", err: errors.New("ent: missing required field \"stddev\"")} + return &ValidationError{Name: "stddev", err: errors.New(`ent: missing required field "Histogram.stddev"`)} } if _, ok := hc.mutation.Median(); !ok { - return &ValidationError{Name: "median", err: errors.New("ent: missing required field \"median\"")} + return &ValidationError{Name: "median", err: errors.New(`ent: missing required field "Histogram.median"`)} } if _, ok := hc.mutation.P75(); !ok { - return &ValidationError{Name: "p75", err: errors.New("ent: missing required field \"p75\"")} + return &ValidationError{Name: "p75", err: errors.New(`ent: missing required field "Histogram.p75"`)} } if _, ok := hc.mutation.P95(); !ok { - return &ValidationError{Name: "p95", err: errors.New("ent: missing required field \"p95\"")} + return &ValidationError{Name: "p95", err: errors.New(`ent: missing required field "Histogram.p95"`)} } if _, ok := hc.mutation.P99(); !ok { - return &ValidationError{Name: "p99", err: errors.New("ent: missing required field \"p99\"")} + return &ValidationError{Name: "p99", err: errors.New(`ent: missing required field "Histogram.p99"`)} } if _, ok := hc.mutation.P999(); !ok { - return &ValidationError{Name: "p999", err: errors.New("ent: missing required field \"p999\"")} + return &ValidationError{Name: "p999", err: errors.New(`ent: missing required field "Histogram.p999"`)} } if _, ok := hc.mutation.WID(); !ok { - return &ValidationError{Name: "wID", err: errors.New("ent: missing required field \"wID\"")} + return &ValidationError{Name: "wID", err: errors.New(`ent: missing required field "Histogram.wID"`)} } return nil } func (hc *HistogramCreate) sqlSave(ctx context.Context) (*Histogram, error) { + if err := hc.check(); err != nil { + return nil, err + } _node, _spec := hc.createSpec() if err := sqlgraph.CreateNode(ctx, hc.driver, _spec); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } id := _spec.ID.Value.(int64) _node.ID = int(id) + hc.mutation.id = &_node.ID + hc.mutation.done = true return _node, nil } func (hc *HistogramCreate) createSpec() (*Histogram, *sqlgraph.CreateSpec) { var ( _node = &Histogram{config: hc.config} - _spec = &sqlgraph.CreateSpec{ - Table: histogram.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, - } + _spec = sqlgraph.NewCreateSpec(histogram.Table, sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt)) ) if value, ok := hc.mutation.Time(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldTime, - }) + _spec.SetField(histogram.FieldTime, field.TypeInt64, value) _node.Time = value } if value, ok := hc.mutation.Count(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldCount, - }) + _spec.SetField(histogram.FieldCount, field.TypeInt64, value) _node.Count = value } if value, ok := hc.mutation.Min(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMin, - }) + _spec.SetField(histogram.FieldMin, field.TypeInt64, value) _node.Min = value } if value, ok := hc.mutation.Max(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMax, - }) + _spec.SetField(histogram.FieldMax, field.TypeInt64, value) _node.Max = value } if value, ok := hc.mutation.Mean(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMean, - }) + _spec.SetField(histogram.FieldMean, field.TypeFloat64, value) _node.Mean = value } if value, ok := hc.mutation.Stddev(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldStddev, - }) + _spec.SetField(histogram.FieldStddev, field.TypeFloat64, value) _node.Stddev = value } if value, ok := hc.mutation.Median(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMedian, - }) + _spec.SetField(histogram.FieldMedian, field.TypeFloat64, value) _node.Median = value } if value, ok := hc.mutation.P75(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP75, - }) + _spec.SetField(histogram.FieldP75, field.TypeFloat64, value) _node.P75 = value } if value, ok := hc.mutation.P95(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP95, - }) + _spec.SetField(histogram.FieldP95, field.TypeFloat64, value) _node.P95 = value } if value, ok := hc.mutation.P99(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP99, - }) + _spec.SetField(histogram.FieldP99, field.TypeFloat64, value) _node.P99 = value } if value, ok := hc.mutation.P999(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP999, - }) + _spec.SetField(histogram.FieldP999, field.TypeFloat64, value) _node.P999 = value } if value, ok := hc.mutation.WID(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: histogram.FieldWID, - }) + _spec.SetField(histogram.FieldWID, field.TypeString, value) _node.WID = value } if nodes := hc.mutation.MetricIDs(); len(nodes) > 0 { @@ -329,21 +263,19 @@ func (hc *HistogramCreate) createSpec() (*Histogram, *sqlgraph.CreateSpec) { Columns: []string{histogram.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } + _node.metric_histograms = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } return _node, _spec } -// HistogramCreateBulk is the builder for creating a bulk of Histogram entities. +// HistogramCreateBulk is the builder for creating many Histogram entities in bulk. type HistogramCreateBulk struct { config builders []*HistogramCreate @@ -366,24 +298,28 @@ func (hcb *HistogramCreateBulk) Save(ctx context.Context) ([]*Histogram, error) return nil, err } builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() var err error + nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, hcb.builders[i+1].mutation) } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, hcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if err = sqlgraph.BatchCreate(ctx, hcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } } } - mutation.done = true if err != nil { return nil, err } - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { @@ -400,7 +336,7 @@ func (hcb *HistogramCreateBulk) Save(ctx context.Context) ([]*Histogram, error) return nodes, nil } -// SaveX calls Save and panics if Save returns an error. +// SaveX is like Save, but panics if an error occurs. func (hcb *HistogramCreateBulk) SaveX(ctx context.Context) []*Histogram { v, err := hcb.Save(ctx) if err != nil { @@ -408,3 +344,16 @@ func (hcb *HistogramCreateBulk) SaveX(ctx context.Context) []*Histogram { } return v } + +// Exec executes the query. +func (hcb *HistogramCreateBulk) Exec(ctx context.Context) error { + _, err := hcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (hcb *HistogramCreateBulk) ExecX(ctx context.Context) { + if err := hcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/histogram_delete.go b/ent/histogram_delete.go index 623fc547..4ea9beb8 100644 --- a/ent/histogram_delete.go +++ b/ent/histogram_delete.go @@ -1,14 +1,13 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/histogram" "github.com/gobench-io/gobench/v2/ent/predicate" ) @@ -16,44 +15,19 @@ import ( // HistogramDelete is the builder for deleting a Histogram entity. type HistogramDelete struct { config - hooks []Hook - mutation *HistogramMutation - predicates []predicate.Histogram + hooks []Hook + mutation *HistogramMutation } -// Where adds a new predicate to the delete builder. +// Where appends a list predicates to the HistogramDelete builder. func (hd *HistogramDelete) Where(ps ...predicate.Histogram) *HistogramDelete { - hd.predicates = append(hd.predicates, ps...) + hd.mutation.Where(ps...) return hd } // Exec executes the deletion query and returns how many vertices were deleted. func (hd *HistogramDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(hd.hooks) == 0 { - affected, err = hd.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*HistogramMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - hd.mutation = mutation - affected, err = hd.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(hd.hooks) - 1; i >= 0; i-- { - mut = hd.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, hd.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, hd.sqlExec, hd.mutation, hd.hooks) } // ExecX is like Exec, but panics if an error occurs. @@ -66,23 +40,20 @@ func (hd *HistogramDelete) ExecX(ctx context.Context) int { } func (hd *HistogramDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: histogram.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, - }, - } - if ps := hd.predicates; len(ps) > 0 { + _spec := sqlgraph.NewDeleteSpec(histogram.Table, sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt)) + if ps := hd.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - return sqlgraph.DeleteNodes(ctx, hd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, hd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + hd.mutation.done = true + return affected, err } // HistogramDeleteOne is the builder for deleting a single Histogram entity. @@ -90,6 +61,12 @@ type HistogramDeleteOne struct { hd *HistogramDelete } +// Where appends a list predicates to the HistogramDelete builder. +func (hdo *HistogramDeleteOne) Where(ps ...predicate.Histogram) *HistogramDeleteOne { + hdo.hd.mutation.Where(ps...) + return hdo +} + // Exec executes the deletion query. func (hdo *HistogramDeleteOne) Exec(ctx context.Context) error { n, err := hdo.hd.Exec(ctx) @@ -105,5 +82,7 @@ func (hdo *HistogramDeleteOne) Exec(ctx context.Context) error { // ExecX is like Exec, but panics if an error occurs. func (hdo *HistogramDeleteOne) ExecX(ctx context.Context) { - hdo.hd.ExecX(ctx) + if err := hdo.Exec(ctx); err != nil { + panic(err) + } } diff --git a/ent/histogram_query.go b/ent/histogram_query.go index 82451e64..abc0ad17 100644 --- a/ent/histogram_query.go +++ b/ent/histogram_query.go @@ -1,16 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "errors" "fmt" "math" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/histogram" "github.com/gobench-io/gobench/v2/ent/metric" "github.com/gobench-io/gobench/v2/ent/predicate" @@ -19,12 +18,10 @@ import ( // HistogramQuery is the builder for querying Histogram entities. type HistogramQuery struct { config - limit *int - offset *int - order []OrderFunc - unique []string + ctx *QueryContext + order []histogram.OrderOption + inters []Interceptor predicates []predicate.Histogram - // eager-loading edges. withMetric *MetricQuery withFKs bool // intermediate query (i.e. traversal path). @@ -32,38 +29,45 @@ type HistogramQuery struct { path func(context.Context) (*sql.Selector, error) } -// Where adds a new predicate for the builder. +// Where adds a new predicate for the HistogramQuery builder. func (hq *HistogramQuery) Where(ps ...predicate.Histogram) *HistogramQuery { hq.predicates = append(hq.predicates, ps...) return hq } -// Limit adds a limit step to the query. +// Limit the number of records to be returned by this query. func (hq *HistogramQuery) Limit(limit int) *HistogramQuery { - hq.limit = &limit + hq.ctx.Limit = &limit return hq } -// Offset adds an offset step to the query. +// Offset to start from. func (hq *HistogramQuery) Offset(offset int) *HistogramQuery { - hq.offset = &offset + hq.ctx.Offset = &offset return hq } -// Order adds an order step to the query. -func (hq *HistogramQuery) Order(o ...OrderFunc) *HistogramQuery { +// 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 *HistogramQuery) Unique(unique bool) *HistogramQuery { + hq.ctx.Unique = &unique + return hq +} + +// Order specifies how the records should be ordered. +func (hq *HistogramQuery) Order(o ...histogram.OrderOption) *HistogramQuery { hq.order = append(hq.order, o...) return hq } -// QueryMetric chains the current query on the metric edge. +// QueryMetric chains the current query on the "metric" edge. func (hq *HistogramQuery) QueryMetric() *MetricQuery { - query := &MetricQuery{config: hq.config} + query := (&MetricClient{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() + selector := hq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -78,9 +82,10 @@ func (hq *HistogramQuery) QueryMetric() *MetricQuery { return query } -// First returns the first Histogram entity in the query. Returns *NotFoundError when no histogram was found. +// First returns the first Histogram entity from the query. +// Returns a *NotFoundError when no Histogram was found. func (hq *HistogramQuery) First(ctx context.Context) (*Histogram, error) { - nodes, err := hq.Limit(1).All(ctx) + nodes, err := hq.Limit(1).All(setContextOp(ctx, hq.ctx, "First")) if err != nil { return nil, err } @@ -99,10 +104,11 @@ func (hq *HistogramQuery) FirstX(ctx context.Context) *Histogram { return node } -// FirstID returns the first Histogram id in the query. Returns *NotFoundError when no id was found. +// FirstID returns the first Histogram ID from the query. +// Returns a *NotFoundError when no Histogram ID was found. func (hq *HistogramQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = hq.Limit(1).IDs(ctx); err != nil { + if ids, err = hq.Limit(1).IDs(setContextOp(ctx, hq.ctx, "FirstID")); err != nil { return } if len(ids) == 0 { @@ -112,8 +118,8 @@ func (hq *HistogramQuery) FirstID(ctx context.Context) (id int, err error) { return ids[0], nil } -// FirstXID is like FirstID, but panics if an error occurs. -func (hq *HistogramQuery) FirstXID(ctx context.Context) int { +// FirstIDX is like FirstID, but panics if an error occurs. +func (hq *HistogramQuery) FirstIDX(ctx context.Context) int { id, err := hq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -121,9 +127,11 @@ func (hq *HistogramQuery) FirstXID(ctx context.Context) int { return id } -// Only returns the only Histogram entity in the query, returns an error if not exactly one entity was returned. +// Only returns a single Histogram entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Histogram entity is found. +// Returns a *NotFoundError when no Histogram entities are found. func (hq *HistogramQuery) Only(ctx context.Context) (*Histogram, error) { - nodes, err := hq.Limit(2).All(ctx) + nodes, err := hq.Limit(2).All(setContextOp(ctx, hq.ctx, "Only")) if err != nil { return nil, err } @@ -146,10 +154,12 @@ func (hq *HistogramQuery) OnlyX(ctx context.Context) *Histogram { return node } -// OnlyID returns the only Histogram id in the query, returns an error if not exactly one id was returned. +// OnlyID is like Only, but returns the only Histogram ID in the query. +// Returns a *NotSingularError when more than one Histogram ID is found. +// Returns a *NotFoundError when no entities are found. func (hq *HistogramQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = hq.Limit(2).IDs(ctx); err != nil { + if ids, err = hq.Limit(2).IDs(setContextOp(ctx, hq.ctx, "OnlyID")); err != nil { return } switch len(ids) { @@ -174,10 +184,12 @@ func (hq *HistogramQuery) OnlyIDX(ctx context.Context) int { // All executes the query and returns a list of Histograms. func (hq *HistogramQuery) All(ctx context.Context) ([]*Histogram, error) { + ctx = setContextOp(ctx, hq.ctx, "All") if err := hq.prepareQuery(ctx); err != nil { return nil, err } - return hq.sqlAll(ctx) + qr := querierAll[[]*Histogram, *HistogramQuery]() + return withInterceptors[[]*Histogram](ctx, hq, qr, hq.inters) } // AllX is like All, but panics if an error occurs. @@ -189,10 +201,13 @@ func (hq *HistogramQuery) AllX(ctx context.Context) []*Histogram { return nodes } -// IDs executes the query and returns a list of Histogram ids. -func (hq *HistogramQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := hq.Select(histogram.FieldID).Scan(ctx, &ids); err != nil { +// IDs executes the query and returns a list of Histogram IDs. +func (hq *HistogramQuery) IDs(ctx context.Context) (ids []int, err error) { + if hq.ctx.Unique == nil && hq.path != nil { + hq.Unique(true) + } + ctx = setContextOp(ctx, hq.ctx, "IDs") + if err = hq.Select(histogram.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil @@ -209,10 +224,11 @@ func (hq *HistogramQuery) IDsX(ctx context.Context) []int { // Count returns the count of the given query. func (hq *HistogramQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, hq.ctx, "Count") if err := hq.prepareQuery(ctx); err != nil { return 0, err } - return hq.sqlCount(ctx) + return withInterceptors[int](ctx, hq, querierCount[*HistogramQuery](), hq.inters) } // CountX is like Count, but panics if an error occurs. @@ -226,10 +242,15 @@ func (hq *HistogramQuery) CountX(ctx context.Context) int { // Exist returns true if the query has elements in the graph. func (hq *HistogramQuery) Exist(ctx context.Context) (bool, error) { - if err := hq.prepareQuery(ctx); err != nil { - return false, err + 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 } - return hq.sqlExist(ctx) } // ExistX is like Exist, but panics if an error occurs. @@ -241,26 +262,29 @@ func (hq *HistogramQuery) ExistX(ctx context.Context) bool { return exist } -// Clone returns a duplicate of the query builder, including all associated steps. It can be +// Clone returns a duplicate of the HistogramQuery 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 *HistogramQuery) Clone() *HistogramQuery { + if hq == nil { + return nil + } return &HistogramQuery{ config: hq.config, - limit: hq.limit, - offset: hq.offset, - order: append([]OrderFunc{}, hq.order...), - unique: append([]string{}, hq.unique...), + ctx: hq.ctx.Clone(), + order: append([]histogram.OrderOption{}, hq.order...), + inters: append([]Interceptor{}, hq.inters...), predicates: append([]predicate.Histogram{}, hq.predicates...), + withMetric: hq.withMetric.Clone(), // clone intermediate query. sql: hq.sql.Clone(), path: hq.path, } } -// WithMetric tells the query-builder to eager-loads the nodes that are connected to -// the "metric" edge. The optional arguments used to configure the query builder of the edge. +// WithMetric tells the query-builder to eager-load the nodes that are connected to +// the "metric" edge. The optional arguments are used to configure the query builder of the edge. func (hq *HistogramQuery) WithMetric(opts ...func(*MetricQuery)) *HistogramQuery { - query := &MetricQuery{config: hq.config} + query := (&MetricClient{config: hq.config}).Query() for _, opt := range opts { opt(query) } @@ -268,7 +292,7 @@ func (hq *HistogramQuery) WithMetric(opts ...func(*MetricQuery)) *HistogramQuery return hq } -// GroupBy used to group vertices by one or more fields/columns. +// 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: @@ -282,20 +306,17 @@ func (hq *HistogramQuery) WithMetric(opts ...func(*MetricQuery)) *HistogramQuery // GroupBy(histogram.FieldTime). // Aggregate(ent.Count()). // Scan(ctx, &v) -// func (hq *HistogramQuery) GroupBy(field string, fields ...string) *HistogramGroupBy { - group := &HistogramGroupBy{config: hq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := hq.prepareQuery(ctx); err != nil { - return nil, err - } - return hq.sqlQuery(), nil - } - return group + hq.ctx.Fields = append([]string{field}, fields...) + grbuild := &HistogramGroupBy{build: hq} + grbuild.flds = &hq.ctx.Fields + grbuild.label = histogram.Label + grbuild.scan = grbuild.Scan + return grbuild } -// Select one or more fields from the given query. +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. // // Example: // @@ -306,20 +327,35 @@ func (hq *HistogramQuery) GroupBy(field string, fields ...string) *HistogramGrou // client.Histogram.Query(). // Select(histogram.FieldTime). // Scan(ctx, &v) -// -func (hq *HistogramQuery) Select(field string, fields ...string) *HistogramSelect { - selector := &HistogramSelect{config: hq.config} - selector.fields = append([]string{field}, fields...) - selector.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := hq.prepareQuery(ctx); err != nil { - return nil, err - } - return hq.sqlQuery(), nil - } - return selector +func (hq *HistogramQuery) Select(fields ...string) *HistogramSelect { + hq.ctx.Fields = append(hq.ctx.Fields, fields...) + sbuild := &HistogramSelect{HistogramQuery: hq} + sbuild.label = histogram.Label + sbuild.flds, sbuild.scan = &hq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a HistogramSelect configured with the given aggregations. +func (hq *HistogramQuery) Aggregate(fns ...AggregateFunc) *HistogramSelect { + return hq.Select().Aggregate(fns...) } func (hq *HistogramQuery) 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 !histogram.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 { @@ -330,7 +366,7 @@ func (hq *HistogramQuery) prepareQuery(ctx context.Context) error { return nil } -func (hq *HistogramQuery) sqlAll(ctx context.Context) ([]*Histogram, error) { +func (hq *HistogramQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Histogram, error) { var ( nodes = []*Histogram{} withFKs = hq.withFKs @@ -345,22 +381,17 @@ func (hq *HistogramQuery) sqlAll(ctx context.Context) ([]*Histogram, error) { if withFKs { _spec.Node.Columns = append(_spec.Node.Columns, histogram.ForeignKeys...) } - _spec.ScanValues = func() []interface{} { + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Histogram).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { node := &Histogram{config: hq.config} nodes = append(nodes, node) - values := node.scanValues() - if withFKs { - values = append(values, node.fkValues()...) - } - return values - } - _spec.Assign = func(values ...interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("ent: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] node.Edges.loadedTypes = loadedTypes - return node.assignValues(values...) + 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 @@ -368,60 +399,73 @@ func (hq *HistogramQuery) sqlAll(ctx context.Context) ([]*Histogram, error) { if len(nodes) == 0 { return nodes, nil } - if query := hq.withMetric; query != nil { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*Histogram) - for i := range nodes { - if fk := nodes[i].metric_histograms; fk != nil { - ids = append(ids, *fk) - nodeids[*fk] = append(nodeids[*fk], nodes[i]) - } - } - query.Where(metric.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { + if err := hq.loadMetric(ctx, query, nodes, nil, + func(n *Histogram, e *Metric) { n.Edges.Metric = e }); err != nil { return nil, err } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "metric_histograms" returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.Metric = n - } - } } - return nodes, nil } -func (hq *HistogramQuery) sqlCount(ctx context.Context) (int, error) { - _spec := hq.querySpec() - return sqlgraph.CountNodes(ctx, hq.driver, _spec) +func (hq *HistogramQuery) loadMetric(ctx context.Context, query *MetricQuery, nodes []*Histogram, init func(*Histogram), assign func(*Histogram, *Metric)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Histogram) + for i := range nodes { + if nodes[i].metric_histograms == nil { + continue + } + fk := *nodes[i].metric_histograms + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(metric.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 "metric_histograms" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil } -func (hq *HistogramQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := hq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("ent: check existence: %v", err) +func (hq *HistogramQuery) 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 n > 0, nil + return sqlgraph.CountNodes(ctx, hq.driver, _spec) } func (hq *HistogramQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: histogram.Table, - Columns: histogram.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, - }, - From: hq.sql, - Unique: true, + _spec := sqlgraph.NewQuerySpec(histogram.Table, histogram.Columns, sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt)) + _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, histogram.FieldID) + for i := range fields { + if fields[i] != histogram.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } } if ps := hq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -430,55 +474,58 @@ func (hq *HistogramQuery) querySpec() *sqlgraph.QuerySpec { } } } - if limit := hq.limit; limit != nil { + if limit := hq.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := hq.offset; offset != nil { + 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, histogram.ValidColumn) + ps[i](selector) } } } return _spec } -func (hq *HistogramQuery) sqlQuery() *sql.Selector { +func (hq *HistogramQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(hq.driver.Dialect()) t1 := builder.Table(histogram.Table) - selector := builder.Select(t1.Columns(histogram.Columns...)...).From(t1) + columns := hq.ctx.Fields + if len(columns) == 0 { + columns = histogram.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) if hq.sql != nil { selector = hq.sql - selector.Select(selector.Columns(histogram.Columns...)...) + 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, histogram.ValidColumn) + p(selector) } - if offset := hq.offset; offset != nil { + 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.limit; limit != nil { + if limit := hq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector } -// HistogramGroupBy is the builder for group-by Histogram entities. +// HistogramGroupBy is the group-by builder for Histogram entities. type HistogramGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) + selector + build *HistogramQuery } // Aggregate adds the given aggregation functions to the group-by query. @@ -487,471 +534,80 @@ func (hgb *HistogramGroupBy) Aggregate(fns ...AggregateFunc) *HistogramGroupBy { return hgb } -// Scan applies the group-by query and scan the result into the given value. -func (hgb *HistogramGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := hgb.path(ctx) - if err != nil { +// Scan applies the selector query and scans the result into the given value. +func (hgb *HistogramGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, hgb.build.ctx, "GroupBy") + if err := hgb.build.prepareQuery(ctx); err != nil { return err } - hgb.sql = query - return hgb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (hgb *HistogramGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := hgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field. -func (hgb *HistogramGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(hgb.fields) > 1 { - return nil, errors.New("ent: HistogramGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := hgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (hgb *HistogramGroupBy) StringsX(ctx context.Context) []string { - v, err := hgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from group-by. It is only allowed when querying group-by with one field. -func (hgb *HistogramGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = hgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{histogram.Label} - default: - err = fmt.Errorf("ent: HistogramGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (hgb *HistogramGroupBy) StringX(ctx context.Context) string { - v, err := hgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field. -func (hgb *HistogramGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(hgb.fields) > 1 { - return nil, errors.New("ent: HistogramGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := hgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (hgb *HistogramGroupBy) IntsX(ctx context.Context) []int { - v, err := hgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from group-by. It is only allowed when querying group-by with one field. -func (hgb *HistogramGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = hgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{histogram.Label} - default: - err = fmt.Errorf("ent: HistogramGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (hgb *HistogramGroupBy) IntX(ctx context.Context) int { - v, err := hgb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field. -func (hgb *HistogramGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(hgb.fields) > 1 { - return nil, errors.New("ent: HistogramGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := hgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (hgb *HistogramGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := hgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field. -func (hgb *HistogramGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = hgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{histogram.Label} - default: - err = fmt.Errorf("ent: HistogramGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (hgb *HistogramGroupBy) Float64X(ctx context.Context) float64 { - v, err := hgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field. -func (hgb *HistogramGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(hgb.fields) > 1 { - return nil, errors.New("ent: HistogramGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := hgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil + return scanWithInterceptors[*HistogramQuery, *HistogramGroupBy](ctx, hgb.build, hgb, hgb.build.inters, v) } -// BoolsX is like Bools, but panics if an error occurs. -func (hgb *HistogramGroupBy) BoolsX(ctx context.Context) []bool { - v, err := hgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field. -func (hgb *HistogramGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = hgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{histogram.Label} - default: - err = fmt.Errorf("ent: HistogramGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (hgb *HistogramGroupBy) BoolX(ctx context.Context) bool { - v, err := hgb.Bool(ctx) - if err != nil { - panic(err) +func (hgb *HistogramGroupBy) sqlScan(ctx context.Context, root *HistogramQuery, 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)) } - return v -} - -func (hgb *HistogramGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range hgb.fields { - if !histogram.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + 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 := hgb.sqlQuery() + selector.GroupBy(selector.Columns(*hgb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := hgb.driver.Query(ctx, query, args, rows); err != nil { + if err := hgb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } -func (hgb *HistogramGroupBy) sqlQuery() *sql.Selector { - selector := hgb.sql - columns := make([]string, 0, len(hgb.fields)+len(hgb.fns)) - columns = append(columns, hgb.fields...) - for _, fn := range hgb.fns { - columns = append(columns, fn(selector, histogram.ValidColumn)) - } - return selector.Select(columns...).GroupBy(hgb.fields...) -} - -// HistogramSelect is the builder for select fields of Histogram entities. +// HistogramSelect is the builder for selecting fields of Histogram entities. type HistogramSelect struct { - config - fields []string - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Scan applies the selector query and scan the result into the given value. -func (hs *HistogramSelect) Scan(ctx context.Context, v interface{}) error { - query, err := hs.path(ctx) - if err != nil { - return err - } - hs.sql = query - return hs.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (hs *HistogramSelect) ScanX(ctx context.Context, v interface{}) { - if err := hs.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from selector. It is only allowed when selecting one field. -func (hs *HistogramSelect) Strings(ctx context.Context) ([]string, error) { - if len(hs.fields) > 1 { - return nil, errors.New("ent: HistogramSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := hs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (hs *HistogramSelect) StringsX(ctx context.Context) []string { - v, err := hs.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from selector. It is only allowed when selecting one field. -func (hs *HistogramSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = hs.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{histogram.Label} - default: - err = fmt.Errorf("ent: HistogramSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (hs *HistogramSelect) StringX(ctx context.Context) string { - v, err := hs.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from selector. It is only allowed when selecting one field. -func (hs *HistogramSelect) Ints(ctx context.Context) ([]int, error) { - if len(hs.fields) > 1 { - return nil, errors.New("ent: HistogramSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := hs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (hs *HistogramSelect) IntsX(ctx context.Context) []int { - v, err := hs.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from selector. It is only allowed when selecting one field. -func (hs *HistogramSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = hs.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{histogram.Label} - default: - err = fmt.Errorf("ent: HistogramSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (hs *HistogramSelect) IntX(ctx context.Context) int { - v, err := hs.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from selector. It is only allowed when selecting one field. -func (hs *HistogramSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(hs.fields) > 1 { - return nil, errors.New("ent: HistogramSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := hs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (hs *HistogramSelect) Float64sX(ctx context.Context) []float64 { - v, err := hs.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from selector. It is only allowed when selecting one field. -func (hs *HistogramSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = hs.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{histogram.Label} - default: - err = fmt.Errorf("ent: HistogramSelect.Float64s returned %d results when one was expected", len(v)) - } - return + *HistogramQuery + selector } -// Float64X is like Float64, but panics if an error occurs. -func (hs *HistogramSelect) Float64X(ctx context.Context) float64 { - v, err := hs.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from selector. It is only allowed when selecting one field. -func (hs *HistogramSelect) Bools(ctx context.Context) ([]bool, error) { - if len(hs.fields) > 1 { - return nil, errors.New("ent: HistogramSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := hs.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (hs *HistogramSelect) BoolsX(ctx context.Context) []bool { - v, err := hs.Bools(ctx) - if err != nil { - panic(err) - } - return v +// Aggregate adds the given aggregation functions to the selector query. +func (hs *HistogramSelect) Aggregate(fns ...AggregateFunc) *HistogramSelect { + hs.fns = append(hs.fns, fns...) + return hs } -// Bool returns a single bool from selector. It is only allowed when selecting one field. -func (hs *HistogramSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = hs.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{histogram.Label} - default: - err = fmt.Errorf("ent: HistogramSelect.Bools returned %d results when one was expected", len(v)) +// Scan applies the selector query and scans the result into the given value. +func (hs *HistogramSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, hs.ctx, "Select") + if err := hs.prepareQuery(ctx); err != nil { + return err } - return + return scanWithInterceptors[*HistogramQuery, *HistogramSelect](ctx, hs.HistogramQuery, hs, hs.inters, v) } -// BoolX is like Bool, but panics if an error occurs. -func (hs *HistogramSelect) BoolX(ctx context.Context) bool { - v, err := hs.Bool(ctx) - if err != nil { - panic(err) +func (hs *HistogramSelect) sqlScan(ctx context.Context, root *HistogramQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(hs.fns)) + for _, fn := range hs.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (hs *HistogramSelect) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range hs.fields { - if !histogram.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} - } + 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 := hs.sqlQuery().Query() + 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) } - -func (hs *HistogramSelect) sqlQuery() sql.Querier { - selector := hs.sql - selector.Select(selector.Columns(hs.fields...)...) - return selector -} diff --git a/ent/histogram_update.go b/ent/histogram_update.go index 4f3624ba..d3d4172d 100644 --- a/ent/histogram_update.go +++ b/ent/histogram_update.go @@ -1,14 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/histogram" "github.com/gobench-io/gobench/v2/ent/metric" "github.com/gobench-io/gobench/v2/ent/predicate" @@ -17,173 +18,172 @@ import ( // HistogramUpdate is the builder for updating Histogram entities. type HistogramUpdate struct { config - hooks []Hook - mutation *HistogramMutation - predicates []predicate.Histogram + hooks []Hook + mutation *HistogramMutation } -// Where adds a new predicate for the builder. +// Where appends a list predicates to the HistogramUpdate builder. func (hu *HistogramUpdate) Where(ps ...predicate.Histogram) *HistogramUpdate { - hu.predicates = append(hu.predicates, ps...) + hu.mutation.Where(ps...) return hu } -// SetTime sets the time field. +// SetTime sets the "time" field. func (hu *HistogramUpdate) SetTime(i int64) *HistogramUpdate { hu.mutation.ResetTime() hu.mutation.SetTime(i) return hu } -// AddTime adds i to time. +// AddTime adds i to the "time" field. func (hu *HistogramUpdate) AddTime(i int64) *HistogramUpdate { hu.mutation.AddTime(i) return hu } -// SetCount sets the count field. +// SetCount sets the "count" field. func (hu *HistogramUpdate) SetCount(i int64) *HistogramUpdate { hu.mutation.ResetCount() hu.mutation.SetCount(i) return hu } -// AddCount adds i to count. +// AddCount adds i to the "count" field. func (hu *HistogramUpdate) AddCount(i int64) *HistogramUpdate { hu.mutation.AddCount(i) return hu } -// SetMin sets the min field. +// SetMin sets the "min" field. func (hu *HistogramUpdate) SetMin(i int64) *HistogramUpdate { hu.mutation.ResetMin() hu.mutation.SetMin(i) return hu } -// AddMin adds i to min. +// AddMin adds i to the "min" field. func (hu *HistogramUpdate) AddMin(i int64) *HistogramUpdate { hu.mutation.AddMin(i) return hu } -// SetMax sets the max field. +// SetMax sets the "max" field. func (hu *HistogramUpdate) SetMax(i int64) *HistogramUpdate { hu.mutation.ResetMax() hu.mutation.SetMax(i) return hu } -// AddMax adds i to max. +// AddMax adds i to the "max" field. func (hu *HistogramUpdate) AddMax(i int64) *HistogramUpdate { hu.mutation.AddMax(i) return hu } -// SetMean sets the mean field. +// SetMean sets the "mean" field. func (hu *HistogramUpdate) SetMean(f float64) *HistogramUpdate { hu.mutation.ResetMean() hu.mutation.SetMean(f) return hu } -// AddMean adds f to mean. +// AddMean adds f to the "mean" field. func (hu *HistogramUpdate) AddMean(f float64) *HistogramUpdate { hu.mutation.AddMean(f) return hu } -// SetStddev sets the stddev field. +// SetStddev sets the "stddev" field. func (hu *HistogramUpdate) SetStddev(f float64) *HistogramUpdate { hu.mutation.ResetStddev() hu.mutation.SetStddev(f) return hu } -// AddStddev adds f to stddev. +// AddStddev adds f to the "stddev" field. func (hu *HistogramUpdate) AddStddev(f float64) *HistogramUpdate { hu.mutation.AddStddev(f) return hu } -// SetMedian sets the median field. +// SetMedian sets the "median" field. func (hu *HistogramUpdate) SetMedian(f float64) *HistogramUpdate { hu.mutation.ResetMedian() hu.mutation.SetMedian(f) return hu } -// AddMedian adds f to median. +// AddMedian adds f to the "median" field. func (hu *HistogramUpdate) AddMedian(f float64) *HistogramUpdate { hu.mutation.AddMedian(f) return hu } -// SetP75 sets the p75 field. +// SetP75 sets the "p75" field. func (hu *HistogramUpdate) SetP75(f float64) *HistogramUpdate { hu.mutation.ResetP75() hu.mutation.SetP75(f) return hu } -// AddP75 adds f to p75. +// AddP75 adds f to the "p75" field. func (hu *HistogramUpdate) AddP75(f float64) *HistogramUpdate { hu.mutation.AddP75(f) return hu } -// SetP95 sets the p95 field. +// SetP95 sets the "p95" field. func (hu *HistogramUpdate) SetP95(f float64) *HistogramUpdate { hu.mutation.ResetP95() hu.mutation.SetP95(f) return hu } -// AddP95 adds f to p95. +// AddP95 adds f to the "p95" field. func (hu *HistogramUpdate) AddP95(f float64) *HistogramUpdate { hu.mutation.AddP95(f) return hu } -// SetP99 sets the p99 field. +// SetP99 sets the "p99" field. func (hu *HistogramUpdate) SetP99(f float64) *HistogramUpdate { hu.mutation.ResetP99() hu.mutation.SetP99(f) return hu } -// AddP99 adds f to p99. +// AddP99 adds f to the "p99" field. func (hu *HistogramUpdate) AddP99(f float64) *HistogramUpdate { hu.mutation.AddP99(f) return hu } -// SetP999 sets the p999 field. +// SetP999 sets the "p999" field. func (hu *HistogramUpdate) SetP999(f float64) *HistogramUpdate { hu.mutation.ResetP999() hu.mutation.SetP999(f) return hu } -// AddP999 adds f to p999. +// AddP999 adds f to the "p999" field. func (hu *HistogramUpdate) AddP999(f float64) *HistogramUpdate { hu.mutation.AddP999(f) return hu } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (hu *HistogramUpdate) SetWID(s string) *HistogramUpdate { hu.mutation.SetWID(s) return hu } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by ID. func (hu *HistogramUpdate) SetMetricID(id int) *HistogramUpdate { hu.mutation.SetMetricID(id) return hu } -// SetNillableMetricID sets the metric edge to Metric by id if the given value is not nil. +// SetNillableMetricID sets the "metric" edge to the Metric entity by ID if the given value is not nil. func (hu *HistogramUpdate) SetNillableMetricID(id *int) *HistogramUpdate { if id != nil { hu = hu.SetMetricID(*id) @@ -191,7 +191,7 @@ func (hu *HistogramUpdate) SetNillableMetricID(id *int) *HistogramUpdate { return hu } -// SetMetric sets the metric edge to Metric. +// SetMetric sets the "metric" edge to the Metric entity. func (hu *HistogramUpdate) SetMetric(m *Metric) *HistogramUpdate { return hu.SetMetricID(m.ID) } @@ -201,39 +201,15 @@ func (hu *HistogramUpdate) Mutation() *HistogramMutation { return hu.mutation } -// ClearMetric clears the "metric" edge to type Metric. +// ClearMetric clears the "metric" edge to the Metric entity. func (hu *HistogramUpdate) ClearMetric() *HistogramUpdate { hu.mutation.ClearMetric() return hu } -// Save executes the query and returns the number of rows/vertices matched by this operation. +// Save executes the query and returns the number of nodes affected by the update operation. func (hu *HistogramUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(hu.hooks) == 0 { - affected, err = hu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*HistogramMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - hu.mutation = mutation - affected, err = hu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(hu.hooks) - 1; i >= 0; i-- { - mut = hu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, hu.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, hu.sqlSave, hu.mutation, hu.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -259,17 +235,8 @@ func (hu *HistogramUpdate) ExecX(ctx context.Context) { } func (hu *HistogramUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: histogram.Table, - Columns: histogram.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, - }, - } - if ps := hu.predicates; len(ps) > 0 { + _spec := sqlgraph.NewUpdateSpec(histogram.Table, histogram.Columns, sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt)) + if ps := hu.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -277,165 +244,73 @@ func (hu *HistogramUpdate) sqlSave(ctx context.Context) (n int, err error) { } } if value, ok := hu.mutation.Time(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldTime, - }) + _spec.SetField(histogram.FieldTime, field.TypeInt64, value) } if value, ok := hu.mutation.AddedTime(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldTime, - }) + _spec.AddField(histogram.FieldTime, field.TypeInt64, value) } if value, ok := hu.mutation.Count(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldCount, - }) + _spec.SetField(histogram.FieldCount, field.TypeInt64, value) } if value, ok := hu.mutation.AddedCount(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldCount, - }) + _spec.AddField(histogram.FieldCount, field.TypeInt64, value) } if value, ok := hu.mutation.Min(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMin, - }) + _spec.SetField(histogram.FieldMin, field.TypeInt64, value) } if value, ok := hu.mutation.AddedMin(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMin, - }) + _spec.AddField(histogram.FieldMin, field.TypeInt64, value) } if value, ok := hu.mutation.Max(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMax, - }) + _spec.SetField(histogram.FieldMax, field.TypeInt64, value) } if value, ok := hu.mutation.AddedMax(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMax, - }) + _spec.AddField(histogram.FieldMax, field.TypeInt64, value) } if value, ok := hu.mutation.Mean(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMean, - }) + _spec.SetField(histogram.FieldMean, field.TypeFloat64, value) } if value, ok := hu.mutation.AddedMean(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMean, - }) + _spec.AddField(histogram.FieldMean, field.TypeFloat64, value) } if value, ok := hu.mutation.Stddev(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldStddev, - }) + _spec.SetField(histogram.FieldStddev, field.TypeFloat64, value) } if value, ok := hu.mutation.AddedStddev(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldStddev, - }) + _spec.AddField(histogram.FieldStddev, field.TypeFloat64, value) } if value, ok := hu.mutation.Median(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMedian, - }) + _spec.SetField(histogram.FieldMedian, field.TypeFloat64, value) } if value, ok := hu.mutation.AddedMedian(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMedian, - }) + _spec.AddField(histogram.FieldMedian, field.TypeFloat64, value) } if value, ok := hu.mutation.P75(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP75, - }) + _spec.SetField(histogram.FieldP75, field.TypeFloat64, value) } if value, ok := hu.mutation.AddedP75(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP75, - }) + _spec.AddField(histogram.FieldP75, field.TypeFloat64, value) } if value, ok := hu.mutation.P95(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP95, - }) + _spec.SetField(histogram.FieldP95, field.TypeFloat64, value) } if value, ok := hu.mutation.AddedP95(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP95, - }) + _spec.AddField(histogram.FieldP95, field.TypeFloat64, value) } if value, ok := hu.mutation.P99(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP99, - }) + _spec.SetField(histogram.FieldP99, field.TypeFloat64, value) } if value, ok := hu.mutation.AddedP99(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP99, - }) + _spec.AddField(histogram.FieldP99, field.TypeFloat64, value) } if value, ok := hu.mutation.P999(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP999, - }) + _spec.SetField(histogram.FieldP999, field.TypeFloat64, value) } if value, ok := hu.mutation.AddedP999(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP999, - }) + _spec.AddField(histogram.FieldP999, field.TypeFloat64, value) } if value, ok := hu.mutation.WID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: histogram.FieldWID, - }) + _spec.SetField(histogram.FieldWID, field.TypeString, value) } if hu.mutation.MetricCleared() { edge := &sqlgraph.EdgeSpec{ @@ -445,10 +320,7 @@ func (hu *HistogramUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{histogram.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -461,10 +333,7 @@ func (hu *HistogramUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{histogram.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -475,177 +344,179 @@ func (hu *HistogramUpdate) sqlSave(ctx context.Context) (n int, err error) { if n, err = sqlgraph.UpdateNodes(ctx, hu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{histogram.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } + hu.mutation.done = true return n, nil } // HistogramUpdateOne is the builder for updating a single Histogram entity. type HistogramUpdateOne struct { config + fields []string hooks []Hook mutation *HistogramMutation } -// SetTime sets the time field. +// SetTime sets the "time" field. func (huo *HistogramUpdateOne) SetTime(i int64) *HistogramUpdateOne { huo.mutation.ResetTime() huo.mutation.SetTime(i) return huo } -// AddTime adds i to time. +// AddTime adds i to the "time" field. func (huo *HistogramUpdateOne) AddTime(i int64) *HistogramUpdateOne { huo.mutation.AddTime(i) return huo } -// SetCount sets the count field. +// SetCount sets the "count" field. func (huo *HistogramUpdateOne) SetCount(i int64) *HistogramUpdateOne { huo.mutation.ResetCount() huo.mutation.SetCount(i) return huo } -// AddCount adds i to count. +// AddCount adds i to the "count" field. func (huo *HistogramUpdateOne) AddCount(i int64) *HistogramUpdateOne { huo.mutation.AddCount(i) return huo } -// SetMin sets the min field. +// SetMin sets the "min" field. func (huo *HistogramUpdateOne) SetMin(i int64) *HistogramUpdateOne { huo.mutation.ResetMin() huo.mutation.SetMin(i) return huo } -// AddMin adds i to min. +// AddMin adds i to the "min" field. func (huo *HistogramUpdateOne) AddMin(i int64) *HistogramUpdateOne { huo.mutation.AddMin(i) return huo } -// SetMax sets the max field. +// SetMax sets the "max" field. func (huo *HistogramUpdateOne) SetMax(i int64) *HistogramUpdateOne { huo.mutation.ResetMax() huo.mutation.SetMax(i) return huo } -// AddMax adds i to max. +// AddMax adds i to the "max" field. func (huo *HistogramUpdateOne) AddMax(i int64) *HistogramUpdateOne { huo.mutation.AddMax(i) return huo } -// SetMean sets the mean field. +// SetMean sets the "mean" field. func (huo *HistogramUpdateOne) SetMean(f float64) *HistogramUpdateOne { huo.mutation.ResetMean() huo.mutation.SetMean(f) return huo } -// AddMean adds f to mean. +// AddMean adds f to the "mean" field. func (huo *HistogramUpdateOne) AddMean(f float64) *HistogramUpdateOne { huo.mutation.AddMean(f) return huo } -// SetStddev sets the stddev field. +// SetStddev sets the "stddev" field. func (huo *HistogramUpdateOne) SetStddev(f float64) *HistogramUpdateOne { huo.mutation.ResetStddev() huo.mutation.SetStddev(f) return huo } -// AddStddev adds f to stddev. +// AddStddev adds f to the "stddev" field. func (huo *HistogramUpdateOne) AddStddev(f float64) *HistogramUpdateOne { huo.mutation.AddStddev(f) return huo } -// SetMedian sets the median field. +// SetMedian sets the "median" field. func (huo *HistogramUpdateOne) SetMedian(f float64) *HistogramUpdateOne { huo.mutation.ResetMedian() huo.mutation.SetMedian(f) return huo } -// AddMedian adds f to median. +// AddMedian adds f to the "median" field. func (huo *HistogramUpdateOne) AddMedian(f float64) *HistogramUpdateOne { huo.mutation.AddMedian(f) return huo } -// SetP75 sets the p75 field. +// SetP75 sets the "p75" field. func (huo *HistogramUpdateOne) SetP75(f float64) *HistogramUpdateOne { huo.mutation.ResetP75() huo.mutation.SetP75(f) return huo } -// AddP75 adds f to p75. +// AddP75 adds f to the "p75" field. func (huo *HistogramUpdateOne) AddP75(f float64) *HistogramUpdateOne { huo.mutation.AddP75(f) return huo } -// SetP95 sets the p95 field. +// SetP95 sets the "p95" field. func (huo *HistogramUpdateOne) SetP95(f float64) *HistogramUpdateOne { huo.mutation.ResetP95() huo.mutation.SetP95(f) return huo } -// AddP95 adds f to p95. +// AddP95 adds f to the "p95" field. func (huo *HistogramUpdateOne) AddP95(f float64) *HistogramUpdateOne { huo.mutation.AddP95(f) return huo } -// SetP99 sets the p99 field. +// SetP99 sets the "p99" field. func (huo *HistogramUpdateOne) SetP99(f float64) *HistogramUpdateOne { huo.mutation.ResetP99() huo.mutation.SetP99(f) return huo } -// AddP99 adds f to p99. +// AddP99 adds f to the "p99" field. func (huo *HistogramUpdateOne) AddP99(f float64) *HistogramUpdateOne { huo.mutation.AddP99(f) return huo } -// SetP999 sets the p999 field. +// SetP999 sets the "p999" field. func (huo *HistogramUpdateOne) SetP999(f float64) *HistogramUpdateOne { huo.mutation.ResetP999() huo.mutation.SetP999(f) return huo } -// AddP999 adds f to p999. +// AddP999 adds f to the "p999" field. func (huo *HistogramUpdateOne) AddP999(f float64) *HistogramUpdateOne { huo.mutation.AddP999(f) return huo } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (huo *HistogramUpdateOne) SetWID(s string) *HistogramUpdateOne { huo.mutation.SetWID(s) return huo } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by ID. func (huo *HistogramUpdateOne) SetMetricID(id int) *HistogramUpdateOne { huo.mutation.SetMetricID(id) return huo } -// SetNillableMetricID sets the metric edge to Metric by id if the given value is not nil. +// SetNillableMetricID sets the "metric" edge to the Metric entity by ID if the given value is not nil. func (huo *HistogramUpdateOne) SetNillableMetricID(id *int) *HistogramUpdateOne { if id != nil { huo = huo.SetMetricID(*id) @@ -653,7 +524,7 @@ func (huo *HistogramUpdateOne) SetNillableMetricID(id *int) *HistogramUpdateOne return huo } -// SetMetric sets the metric edge to Metric. +// SetMetric sets the "metric" edge to the Metric entity. func (huo *HistogramUpdateOne) SetMetric(m *Metric) *HistogramUpdateOne { return huo.SetMetricID(m.ID) } @@ -663,39 +534,28 @@ func (huo *HistogramUpdateOne) Mutation() *HistogramMutation { return huo.mutation } -// ClearMetric clears the "metric" edge to type Metric. +// ClearMetric clears the "metric" edge to the Metric entity. func (huo *HistogramUpdateOne) ClearMetric() *HistogramUpdateOne { huo.mutation.ClearMetric() return huo } -// Save executes the query and returns the updated entity. +// Where appends a list predicates to the HistogramUpdate builder. +func (huo *HistogramUpdateOne) Where(ps ...predicate.Histogram) *HistogramUpdateOne { + huo.mutation.Where(ps...) + return huo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (huo *HistogramUpdateOne) Select(field string, fields ...string) *HistogramUpdateOne { + huo.fields = append([]string{field}, fields...) + return huo +} + +// Save executes the query and returns the updated Histogram entity. func (huo *HistogramUpdateOne) Save(ctx context.Context) (*Histogram, error) { - var ( - err error - node *Histogram - ) - if len(huo.hooks) == 0 { - node, err = huo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*HistogramMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - huo.mutation = mutation - node, err = huo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(huo.hooks) - 1; i >= 0; i-- { - mut = huo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, huo.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, huo.sqlSave, huo.mutation, huo.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -721,181 +581,99 @@ func (huo *HistogramUpdateOne) ExecX(ctx context.Context) { } func (huo *HistogramUpdateOne) sqlSave(ctx context.Context) (_node *Histogram, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: histogram.Table, - Columns: histogram.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, - }, - } + _spec := sqlgraph.NewUpdateSpec(histogram.Table, histogram.Columns, sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt)) id, ok := huo.mutation.ID() if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Histogram.ID for update")} + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Histogram.id" for update`)} } _spec.Node.ID.Value = id + if fields := huo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, histogram.FieldID) + for _, f := range fields { + if !histogram.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != histogram.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := huo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } if value, ok := huo.mutation.Time(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldTime, - }) + _spec.SetField(histogram.FieldTime, field.TypeInt64, value) } if value, ok := huo.mutation.AddedTime(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldTime, - }) + _spec.AddField(histogram.FieldTime, field.TypeInt64, value) } if value, ok := huo.mutation.Count(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldCount, - }) + _spec.SetField(histogram.FieldCount, field.TypeInt64, value) } if value, ok := huo.mutation.AddedCount(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldCount, - }) + _spec.AddField(histogram.FieldCount, field.TypeInt64, value) } if value, ok := huo.mutation.Min(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMin, - }) + _spec.SetField(histogram.FieldMin, field.TypeInt64, value) } if value, ok := huo.mutation.AddedMin(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMin, - }) + _spec.AddField(histogram.FieldMin, field.TypeInt64, value) } if value, ok := huo.mutation.Max(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMax, - }) + _spec.SetField(histogram.FieldMax, field.TypeInt64, value) } if value, ok := huo.mutation.AddedMax(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeInt64, - Value: value, - Column: histogram.FieldMax, - }) + _spec.AddField(histogram.FieldMax, field.TypeInt64, value) } if value, ok := huo.mutation.Mean(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMean, - }) + _spec.SetField(histogram.FieldMean, field.TypeFloat64, value) } if value, ok := huo.mutation.AddedMean(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMean, - }) + _spec.AddField(histogram.FieldMean, field.TypeFloat64, value) } if value, ok := huo.mutation.Stddev(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldStddev, - }) + _spec.SetField(histogram.FieldStddev, field.TypeFloat64, value) } if value, ok := huo.mutation.AddedStddev(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldStddev, - }) + _spec.AddField(histogram.FieldStddev, field.TypeFloat64, value) } if value, ok := huo.mutation.Median(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMedian, - }) + _spec.SetField(histogram.FieldMedian, field.TypeFloat64, value) } if value, ok := huo.mutation.AddedMedian(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldMedian, - }) + _spec.AddField(histogram.FieldMedian, field.TypeFloat64, value) } if value, ok := huo.mutation.P75(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP75, - }) + _spec.SetField(histogram.FieldP75, field.TypeFloat64, value) } if value, ok := huo.mutation.AddedP75(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP75, - }) + _spec.AddField(histogram.FieldP75, field.TypeFloat64, value) } if value, ok := huo.mutation.P95(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP95, - }) + _spec.SetField(histogram.FieldP95, field.TypeFloat64, value) } if value, ok := huo.mutation.AddedP95(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP95, - }) + _spec.AddField(histogram.FieldP95, field.TypeFloat64, value) } if value, ok := huo.mutation.P99(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP99, - }) + _spec.SetField(histogram.FieldP99, field.TypeFloat64, value) } if value, ok := huo.mutation.AddedP99(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP99, - }) + _spec.AddField(histogram.FieldP99, field.TypeFloat64, value) } if value, ok := huo.mutation.P999(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP999, - }) + _spec.SetField(histogram.FieldP999, field.TypeFloat64, value) } if value, ok := huo.mutation.AddedP999(); ok { - _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ - Type: field.TypeFloat64, - Value: value, - Column: histogram.FieldP999, - }) + _spec.AddField(histogram.FieldP999, field.TypeFloat64, value) } if value, ok := huo.mutation.WID(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: histogram.FieldWID, - }) + _spec.SetField(histogram.FieldWID, field.TypeString, value) } if huo.mutation.MetricCleared() { edge := &sqlgraph.EdgeSpec{ @@ -905,10 +683,7 @@ func (huo *HistogramUpdateOne) sqlSave(ctx context.Context) (_node *Histogram, e Columns: []string{histogram.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -921,10 +696,7 @@ func (huo *HistogramUpdateOne) sqlSave(ctx context.Context) (_node *Histogram, e Columns: []string{histogram.MetricColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -934,14 +706,15 @@ func (huo *HistogramUpdateOne) sqlSave(ctx context.Context) (_node *Histogram, e } _node = &Histogram{config: huo.config} _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues() + _spec.ScanValues = _node.scanValues if err = sqlgraph.UpdateNode(ctx, huo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{histogram.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } + huo.mutation.done = true return _node, nil } diff --git a/ent/hook/hook.go b/ent/hook/hook.go index a24590a3..275b65dd 100644 --- a/ent/hook/hook.go +++ b/ent/hook/hook.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package hook @@ -15,11 +15,10 @@ type ApplicationFunc func(context.Context, *ent.ApplicationMutation) (ent.Value, // Mutate calls f(ctx, m). func (f ApplicationFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - mv, ok := m.(*ent.ApplicationMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ApplicationMutation", m) + if mv, ok := m.(*ent.ApplicationMutation); ok { + return f(ctx, mv) } - return f(ctx, mv) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ApplicationMutation", m) } // The CounterFunc type is an adapter to allow the use of ordinary @@ -28,11 +27,10 @@ type CounterFunc func(context.Context, *ent.CounterMutation) (ent.Value, error) // Mutate calls f(ctx, m). func (f CounterFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - mv, ok := m.(*ent.CounterMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CounterMutation", m) + if mv, ok := m.(*ent.CounterMutation); ok { + return f(ctx, mv) } - return f(ctx, mv) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CounterMutation", m) } // The GaugeFunc type is an adapter to allow the use of ordinary @@ -41,11 +39,10 @@ type GaugeFunc func(context.Context, *ent.GaugeMutation) (ent.Value, error) // Mutate calls f(ctx, m). func (f GaugeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - mv, ok := m.(*ent.GaugeMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GaugeMutation", m) + if mv, ok := m.(*ent.GaugeMutation); ok { + return f(ctx, mv) } - return f(ctx, mv) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GaugeMutation", m) } // The GraphFunc type is an adapter to allow the use of ordinary @@ -54,11 +51,10 @@ type GraphFunc func(context.Context, *ent.GraphMutation) (ent.Value, error) // Mutate calls f(ctx, m). func (f GraphFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - mv, ok := m.(*ent.GraphMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GraphMutation", m) + if mv, ok := m.(*ent.GraphMutation); ok { + return f(ctx, mv) } - return f(ctx, mv) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GraphMutation", m) } // The GroupFunc type is an adapter to allow the use of ordinary @@ -67,11 +63,10 @@ type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error) // Mutate calls f(ctx, m). func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - mv, ok := m.(*ent.GroupMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m) + if mv, ok := m.(*ent.GroupMutation); ok { + return f(ctx, mv) } - return f(ctx, mv) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m) } // The HistogramFunc type is an adapter to allow the use of ordinary @@ -80,11 +75,10 @@ type HistogramFunc func(context.Context, *ent.HistogramMutation) (ent.Value, err // Mutate calls f(ctx, m). func (f HistogramFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - mv, ok := m.(*ent.HistogramMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.HistogramMutation", m) + if mv, ok := m.(*ent.HistogramMutation); ok { + return f(ctx, mv) } - return f(ctx, mv) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.HistogramMutation", m) } // The MetricFunc type is an adapter to allow the use of ordinary @@ -93,11 +87,10 @@ type MetricFunc func(context.Context, *ent.MetricMutation) (ent.Value, error) // Mutate calls f(ctx, m). func (f MetricFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - mv, ok := m.(*ent.MetricMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.MetricMutation", m) + if mv, ok := m.(*ent.MetricMutation); ok { + return f(ctx, mv) } - return f(ctx, mv) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.MetricMutation", m) } // The TagFunc type is an adapter to allow the use of ordinary @@ -106,11 +99,10 @@ type TagFunc func(context.Context, *ent.TagMutation) (ent.Value, error) // Mutate calls f(ctx, m). func (f TagFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - mv, ok := m.(*ent.TagMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TagMutation", m) + if mv, ok := m.(*ent.TagMutation); ok { + return f(ctx, mv) } - return f(ctx, mv) + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TagMutation", m) } // Condition is a hook condition function. @@ -208,7 +200,6 @@ func HasFields(field string, fields ...string) Condition { // If executes the given hook under condition. // // hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) -// func If(hk ent.Hook, cond Condition) ent.Hook { return func(next ent.Mutator) ent.Mutator { return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { @@ -223,7 +214,6 @@ func If(hk ent.Hook, cond Condition) ent.Hook { // On executes the given hook only for the given operation. // // hook.On(Log, ent.Delete|ent.Create) -// func On(hk ent.Hook, op ent.Op) ent.Hook { return If(hk, HasOp(op)) } @@ -231,11 +221,19 @@ func On(hk ent.Hook, op ent.Op) ent.Hook { // Unless skips the given hook only for the given operation. // // hook.Unless(Log, ent.Update|ent.UpdateOne) -// func Unless(hk ent.Hook, op ent.Op) ent.Hook { return If(hk, Not(HasOp(op))) } +// FixedError is a hook returning a fixed error. +func FixedError(err error) ent.Hook { + return func(ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { + return nil, err + }) + } +} + // Reject returns a hook that rejects all operations that match op. // // func (T) Hooks() []ent.Hook { @@ -243,13 +241,8 @@ func Unless(hk ent.Hook, op ent.Op) ent.Hook { // Reject(ent.Delete|ent.Update), // } // } -// func Reject(op ent.Op) ent.Hook { - hk := func(ent.Mutator) ent.Mutator { - return ent.MutateFunc(func(_ context.Context, m ent.Mutation) (ent.Value, error) { - return nil, fmt.Errorf("%s operation is not allowed", m.Op()) - }) - } + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) return On(hk, op) } diff --git a/ent/metric.go b/ent/metric.go index 1e87ef30..6e0b9878 100644 --- a/ent/metric.go +++ b/ent/metric.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -6,7 +6,8 @@ import ( "fmt" "strings" - "github.com/facebook/ent/dialect/sql" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/gobench-io/gobench/v2/ent/graph" "github.com/gobench-io/gobench/v2/ent/metric" ) @@ -24,18 +25,19 @@ type Metric struct { // The values are being populated by the MetricQuery when eager-loading is set. Edges MetricEdges `json:"edges"` graph_metrics *int + selectValues sql.SelectValues } // MetricEdges holds the relations/edges for other nodes in the graph. type MetricEdges struct { // Graph holds the value of the graph edge. - Graph *Graph + Graph *Graph `json:"graph,omitempty"` // Histograms holds the value of the histograms edge. - Histograms []*Histogram + Histograms []*Histogram `json:"histograms,omitempty"` // Counters holds the value of the counters edge. - Counters []*Counter + Counters []*Counter `json:"counters,omitempty"` // Gauges holds the value of the gauges edge. - Gauges []*Gauge + Gauges []*Gauge `json:"gauges,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [4]bool @@ -46,8 +48,7 @@ type MetricEdges struct { func (e MetricEdges) GraphOrErr() (*Graph, error) { if e.loadedTypes[0] { if e.Graph == nil { - // The edge graph was loaded in eager-loading, - // but was not found. + // Edge was loaded but was not found. return nil, &NotFoundError{label: graph.Label} } return e.Graph, nil @@ -83,90 +84,104 @@ func (e MetricEdges) GaugesOrErr() ([]*Gauge, error) { } // scanValues returns the types for scanning values from sql.Rows. -func (*Metric) scanValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // id - &sql.NullString{}, // title - &sql.NullString{}, // type - } -} - -// fkValues returns the types for scanning foreign-keys values from sql.Rows. -func (*Metric) fkValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // graph_metrics +func (*Metric) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case metric.FieldID: + values[i] = new(sql.NullInt64) + case metric.FieldTitle, metric.FieldType: + values[i] = new(sql.NullString) + case metric.ForeignKeys[0]: // graph_metrics + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } } + return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Metric fields. -func (m *Metric) assignValues(values ...interface{}) error { - if m, n := len(values), len(metric.Columns); m < n { +func (m *Metric) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } - value, ok := values[0].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - m.ID = int(value.Int64) - values = values[1:] - if value, ok := values[0].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field title", values[0]) - } else if value.Valid { - m.Title = value.String - } - if value, ok := values[1].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field type", values[1]) - } else if value.Valid { - m.Type = value.String - } - values = values[2:] - if len(values) == len(metric.ForeignKeys) { - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field graph_metrics", value) - } else if value.Valid { - m.graph_metrics = new(int) - *m.graph_metrics = int(value.Int64) + for i := range columns { + switch columns[i] { + case metric.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + m.ID = int(value.Int64) + case metric.FieldTitle: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field title", values[i]) + } else if value.Valid { + m.Title = value.String + } + case metric.FieldType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field type", values[i]) + } else if value.Valid { + m.Type = value.String + } + case metric.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field graph_metrics", value) + } else if value.Valid { + m.graph_metrics = new(int) + *m.graph_metrics = int(value.Int64) + } + default: + m.selectValues.Set(columns[i], values[i]) } } return nil } -// QueryGraph queries the graph edge of the Metric. +// Value returns the ent.Value that was dynamically selected and assigned to the Metric. +// This includes values selected through modifiers, order, etc. +func (m *Metric) Value(name string) (ent.Value, error) { + return m.selectValues.Get(name) +} + +// QueryGraph queries the "graph" edge of the Metric entity. func (m *Metric) QueryGraph() *GraphQuery { - return (&MetricClient{config: m.config}).QueryGraph(m) + return NewMetricClient(m.config).QueryGraph(m) } -// QueryHistograms queries the histograms edge of the Metric. +// QueryHistograms queries the "histograms" edge of the Metric entity. func (m *Metric) QueryHistograms() *HistogramQuery { - return (&MetricClient{config: m.config}).QueryHistograms(m) + return NewMetricClient(m.config).QueryHistograms(m) } -// QueryCounters queries the counters edge of the Metric. +// QueryCounters queries the "counters" edge of the Metric entity. func (m *Metric) QueryCounters() *CounterQuery { - return (&MetricClient{config: m.config}).QueryCounters(m) + return NewMetricClient(m.config).QueryCounters(m) } -// QueryGauges queries the gauges edge of the Metric. +// QueryGauges queries the "gauges" edge of the Metric entity. func (m *Metric) QueryGauges() *GaugeQuery { - return (&MetricClient{config: m.config}).QueryGauges(m) + return NewMetricClient(m.config).QueryGauges(m) } // Update returns a builder for updating this Metric. -// Note that, you need to call Metric.Unwrap() before calling this method, if this Metric +// Note that you need to call Metric.Unwrap() before calling this method if this Metric // was returned from a transaction, and the transaction was committed or rolled back. func (m *Metric) Update() *MetricUpdateOne { - return (&MetricClient{config: m.config}).UpdateOne(m) + return NewMetricClient(m.config).UpdateOne(m) } -// Unwrap unwraps the entity that was returned from a transaction after it was closed, -// so that all next queries will be executed through the driver which created the transaction. +// Unwrap unwraps the Metric entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. func (m *Metric) Unwrap() *Metric { - tx, ok := m.config.driver.(*txDriver) + _tx, ok := m.config.driver.(*txDriver) if !ok { panic("ent: Metric is not a transactional entity") } - m.config.driver = tx.drv + m.config.driver = _tx.drv return m } @@ -174,10 +189,11 @@ func (m *Metric) Unwrap() *Metric { func (m *Metric) String() string { var builder strings.Builder builder.WriteString("Metric(") - builder.WriteString(fmt.Sprintf("id=%v", m.ID)) - builder.WriteString(", title=") + builder.WriteString(fmt.Sprintf("id=%v, ", m.ID)) + builder.WriteString("title=") builder.WriteString(m.Title) - builder.WriteString(", type=") + builder.WriteString(", ") + builder.WriteString("type=") builder.WriteString(m.Type) builder.WriteByte(')') return builder.String() @@ -185,9 +201,3 @@ func (m *Metric) String() string { // Metrics is a parsable slice of Metric. type Metrics []*Metric - -func (m Metrics) config(cfg config) { - for _i := range m { - m[_i].config = cfg - } -} diff --git a/ent/metric/metric.go b/ent/metric/metric.go index a0d2e3e8..ed67e0da 100644 --- a/ent/metric/metric.go +++ b/ent/metric/metric.go @@ -1,7 +1,12 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package metric +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + const ( // Label holds the string label denoting the metric type in the database. Label = "metric" @@ -11,7 +16,6 @@ const ( FieldTitle = "title" // FieldType holds the string denoting the type field in the database. FieldType = "type" - // EdgeGraph holds the string denoting the graph edge name in mutations. EdgeGraph = "graph" // EdgeHistograms holds the string denoting the histograms edge name in mutations. @@ -20,31 +24,30 @@ const ( EdgeCounters = "counters" // EdgeGauges holds the string denoting the gauges edge name in mutations. EdgeGauges = "gauges" - // Table holds the table name of the metric in the database. Table = "metrics" - // GraphTable is the table the holds the graph relation/edge. + // GraphTable is the table that holds the graph relation/edge. GraphTable = "metrics" // GraphInverseTable is the table name for the Graph entity. // It exists in this package in order to avoid circular dependency with the "graph" package. GraphInverseTable = "graphs" // GraphColumn is the table column denoting the graph relation/edge. GraphColumn = "graph_metrics" - // HistogramsTable is the table the holds the histograms relation/edge. + // HistogramsTable is the table that holds the histograms relation/edge. HistogramsTable = "histograms" // HistogramsInverseTable is the table name for the Histogram entity. // It exists in this package in order to avoid circular dependency with the "histogram" package. HistogramsInverseTable = "histograms" // HistogramsColumn is the table column denoting the histograms relation/edge. HistogramsColumn = "metric_histograms" - // CountersTable is the table the holds the counters relation/edge. + // CountersTable is the table that holds the counters relation/edge. CountersTable = "counters" // CountersInverseTable is the table name for the Counter entity. // It exists in this package in order to avoid circular dependency with the "counter" package. CountersInverseTable = "counters" // CountersColumn is the table column denoting the counters relation/edge. CountersColumn = "metric_counters" - // GaugesTable is the table the holds the gauges relation/edge. + // GaugesTable is the table that holds the gauges relation/edge. GaugesTable = "gauges" // GaugesInverseTable is the table name for the Gauge entity. // It exists in this package in order to avoid circular dependency with the "gauge" package. @@ -60,7 +63,8 @@ var Columns = []string{ FieldType, } -// ForeignKeys holds the SQL foreign-keys that are owned by the Metric type. +// ForeignKeys holds the SQL foreign-keys that are owned by the "metrics" +// table and are not defined as standalone fields in the schema. var ForeignKeys = []string{ "graph_metrics", } @@ -79,3 +83,98 @@ func ValidColumn(column string) bool { } return false } + +// OrderOption defines the ordering options for the Metric queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByTitle orders the results by the title field. +func ByTitle(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTitle, opts...).ToFunc() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByGraphField orders the results by graph field. +func ByGraphField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGraphStep(), sql.OrderByField(field, opts...)) + } +} + +// ByHistogramsCount orders the results by histograms count. +func ByHistogramsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newHistogramsStep(), opts...) + } +} + +// ByHistograms orders the results by histograms terms. +func ByHistograms(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newHistogramsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByCountersCount orders the results by counters count. +func ByCountersCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newCountersStep(), opts...) + } +} + +// ByCounters orders the results by counters terms. +func ByCounters(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCountersStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByGaugesCount orders the results by gauges count. +func ByGaugesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newGaugesStep(), opts...) + } +} + +// ByGauges orders the results by gauges terms. +func ByGauges(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGaugesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newGraphStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GraphInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, GraphTable, GraphColumn), + ) +} +func newHistogramsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(HistogramsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, HistogramsTable, HistogramsColumn), + ) +} +func newCountersStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CountersInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CountersTable, CountersColumn), + ) +} +func newGaugesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GaugesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, GaugesTable, GaugesColumn), + ) +} diff --git a/ent/metric/where.go b/ent/metric/where.go index fa8e8ee1..c098d63b 100644 --- a/ent/metric/where.go +++ b/ent/metric/where.go @@ -1,330 +1,196 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package metric import ( - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" "github.com/gobench-io/gobench/v2/ent/predicate" ) -// ID filters vertices based on their identifier. +// ID filters vertices based on their ID field. func ID(id int) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Metric(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Metric(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) + return predicate.Metric(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) + return predicate.Metric(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) + return predicate.Metric(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) + return predicate.Metric(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) + return predicate.Metric(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) + return predicate.Metric(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) + return predicate.Metric(sql.FieldLTE(FieldID, id)) } // Title applies equality check predicate on the "title" field. It's identical to TitleEQ. func Title(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldEQ(FieldTitle, v)) } // Type applies equality check predicate on the "type" field. It's identical to TypeEQ. func Type(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldEQ(FieldType, v)) } // TitleEQ applies the EQ predicate on the "title" field. func TitleEQ(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldEQ(FieldTitle, v)) } // TitleNEQ applies the NEQ predicate on the "title" field. func TitleNEQ(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldNEQ(FieldTitle, v)) } // TitleIn applies the In predicate on the "title" field. func TitleIn(vs ...string) predicate.Metric { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Metric(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldTitle), v...)) - }) + return predicate.Metric(sql.FieldIn(FieldTitle, vs...)) } // TitleNotIn applies the NotIn predicate on the "title" field. func TitleNotIn(vs ...string) predicate.Metric { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Metric(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldTitle), v...)) - }) + return predicate.Metric(sql.FieldNotIn(FieldTitle, vs...)) } // TitleGT applies the GT predicate on the "title" field. func TitleGT(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldGT(FieldTitle, v)) } // TitleGTE applies the GTE predicate on the "title" field. func TitleGTE(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldGTE(FieldTitle, v)) } // TitleLT applies the LT predicate on the "title" field. func TitleLT(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldLT(FieldTitle, v)) } // TitleLTE applies the LTE predicate on the "title" field. func TitleLTE(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldLTE(FieldTitle, v)) } // TitleContains applies the Contains predicate on the "title" field. func TitleContains(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldContains(FieldTitle, v)) } // TitleHasPrefix applies the HasPrefix predicate on the "title" field. func TitleHasPrefix(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldHasPrefix(FieldTitle, v)) } // TitleHasSuffix applies the HasSuffix predicate on the "title" field. func TitleHasSuffix(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldHasSuffix(FieldTitle, v)) } // TitleEqualFold applies the EqualFold predicate on the "title" field. func TitleEqualFold(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldEqualFold(FieldTitle, v)) } // TitleContainsFold applies the ContainsFold predicate on the "title" field. func TitleContainsFold(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldTitle), v)) - }) + return predicate.Metric(sql.FieldContainsFold(FieldTitle, v)) } // TypeEQ applies the EQ predicate on the "type" field. func TypeEQ(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldEQ(FieldType, v)) } // TypeNEQ applies the NEQ predicate on the "type" field. func TypeNEQ(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldNEQ(FieldType, v)) } // TypeIn applies the In predicate on the "type" field. func TypeIn(vs ...string) predicate.Metric { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Metric(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldType), v...)) - }) + return predicate.Metric(sql.FieldIn(FieldType, vs...)) } // TypeNotIn applies the NotIn predicate on the "type" field. func TypeNotIn(vs ...string) predicate.Metric { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Metric(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldType), v...)) - }) + return predicate.Metric(sql.FieldNotIn(FieldType, vs...)) } // TypeGT applies the GT predicate on the "type" field. func TypeGT(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldGT(FieldType, v)) } // TypeGTE applies the GTE predicate on the "type" field. func TypeGTE(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldGTE(FieldType, v)) } // TypeLT applies the LT predicate on the "type" field. func TypeLT(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldLT(FieldType, v)) } // TypeLTE applies the LTE predicate on the "type" field. func TypeLTE(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldLTE(FieldType, v)) } // TypeContains applies the Contains predicate on the "type" field. func TypeContains(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldContains(FieldType, v)) } // TypeHasPrefix applies the HasPrefix predicate on the "type" field. func TypeHasPrefix(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldHasPrefix(FieldType, v)) } // TypeHasSuffix applies the HasSuffix predicate on the "type" field. func TypeHasSuffix(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldHasSuffix(FieldType, v)) } // TypeEqualFold applies the EqualFold predicate on the "type" field. func TypeEqualFold(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldEqualFold(FieldType, v)) } // TypeContainsFold applies the ContainsFold predicate on the "type" field. func TypeContainsFold(v string) predicate.Metric { - return predicate.Metric(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldType), v)) - }) + return predicate.Metric(sql.FieldContainsFold(FieldType, v)) } // HasGraph applies the HasEdge predicate on the "graph" edge. @@ -332,7 +198,6 @@ func HasGraph() predicate.Metric { return predicate.Metric(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(GraphTable, FieldID), sqlgraph.Edge(sqlgraph.M2O, true, GraphTable, GraphColumn), ) sqlgraph.HasNeighbors(s, step) @@ -342,11 +207,7 @@ func HasGraph() predicate.Metric { // HasGraphWith applies the HasEdge predicate on the "graph" edge with a given conditions (other predicates). func HasGraphWith(preds ...predicate.Graph) predicate.Metric { return predicate.Metric(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(GraphInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, GraphTable, GraphColumn), - ) + step := newGraphStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -360,7 +221,6 @@ func HasHistograms() predicate.Metric { return predicate.Metric(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(HistogramsTable, FieldID), sqlgraph.Edge(sqlgraph.O2M, false, HistogramsTable, HistogramsColumn), ) sqlgraph.HasNeighbors(s, step) @@ -370,11 +230,7 @@ func HasHistograms() predicate.Metric { // HasHistogramsWith applies the HasEdge predicate on the "histograms" edge with a given conditions (other predicates). func HasHistogramsWith(preds ...predicate.Histogram) predicate.Metric { return predicate.Metric(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(HistogramsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, HistogramsTable, HistogramsColumn), - ) + step := newHistogramsStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -388,7 +244,6 @@ func HasCounters() predicate.Metric { return predicate.Metric(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(CountersTable, FieldID), sqlgraph.Edge(sqlgraph.O2M, false, CountersTable, CountersColumn), ) sqlgraph.HasNeighbors(s, step) @@ -398,11 +253,7 @@ func HasCounters() predicate.Metric { // HasCountersWith applies the HasEdge predicate on the "counters" edge with a given conditions (other predicates). func HasCountersWith(preds ...predicate.Counter) predicate.Metric { return predicate.Metric(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(CountersInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, CountersTable, CountersColumn), - ) + step := newCountersStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -416,7 +267,6 @@ func HasGauges() predicate.Metric { return predicate.Metric(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(GaugesTable, FieldID), sqlgraph.Edge(sqlgraph.O2M, false, GaugesTable, GaugesColumn), ) sqlgraph.HasNeighbors(s, step) @@ -426,11 +276,7 @@ func HasGauges() predicate.Metric { // HasGaugesWith applies the HasEdge predicate on the "gauges" edge with a given conditions (other predicates). func HasGaugesWith(preds ...predicate.Gauge) predicate.Metric { return predicate.Metric(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(GaugesInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, GaugesTable, GaugesColumn), - ) + step := newGaugesStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -439,7 +285,7 @@ func HasGaugesWith(preds ...predicate.Gauge) predicate.Metric { }) } -// And groups list of predicates with the AND operator between them. +// And groups predicates with the AND operator between them. func And(predicates ...predicate.Metric) predicate.Metric { return predicate.Metric(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) @@ -450,7 +296,7 @@ func And(predicates ...predicate.Metric) predicate.Metric { }) } -// Or groups list of predicates with the OR operator between them. +// Or groups predicates with the OR operator between them. func Or(predicates ...predicate.Metric) predicate.Metric { return predicate.Metric(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) diff --git a/ent/metric_create.go b/ent/metric_create.go index 59abfc3d..d1f84783 100644 --- a/ent/metric_create.go +++ b/ent/metric_create.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -7,8 +7,8 @@ import ( "errors" "fmt" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/gauge" "github.com/gobench-io/gobench/v2/ent/graph" @@ -23,25 +23,25 @@ type MetricCreate struct { hooks []Hook } -// SetTitle sets the title field. +// SetTitle sets the "title" field. func (mc *MetricCreate) SetTitle(s string) *MetricCreate { mc.mutation.SetTitle(s) return mc } -// SetType sets the type field. +// SetType sets the "type" field. func (mc *MetricCreate) SetType(s string) *MetricCreate { mc.mutation.SetType(s) return mc } -// SetGraphID sets the graph edge to Graph by id. +// SetGraphID sets the "graph" edge to the Graph entity by ID. func (mc *MetricCreate) SetGraphID(id int) *MetricCreate { mc.mutation.SetGraphID(id) return mc } -// SetNillableGraphID sets the graph edge to Graph by id if the given value is not nil. +// SetNillableGraphID sets the "graph" edge to the Graph entity by ID if the given value is not nil. func (mc *MetricCreate) SetNillableGraphID(id *int) *MetricCreate { if id != nil { mc = mc.SetGraphID(*id) @@ -49,18 +49,18 @@ func (mc *MetricCreate) SetNillableGraphID(id *int) *MetricCreate { return mc } -// SetGraph sets the graph edge to Graph. +// SetGraph sets the "graph" edge to the Graph entity. func (mc *MetricCreate) SetGraph(g *Graph) *MetricCreate { return mc.SetGraphID(g.ID) } -// AddHistogramIDs adds the histograms edge to Histogram by ids. +// AddHistogramIDs adds the "histograms" edge to the Histogram entity by IDs. func (mc *MetricCreate) AddHistogramIDs(ids ...int) *MetricCreate { mc.mutation.AddHistogramIDs(ids...) return mc } -// AddHistograms adds the histograms edges to Histogram. +// AddHistograms adds the "histograms" edges to the Histogram entity. func (mc *MetricCreate) AddHistograms(h ...*Histogram) *MetricCreate { ids := make([]int, len(h)) for i := range h { @@ -69,13 +69,13 @@ func (mc *MetricCreate) AddHistograms(h ...*Histogram) *MetricCreate { return mc.AddHistogramIDs(ids...) } -// AddCounterIDs adds the counters edge to Counter by ids. +// AddCounterIDs adds the "counters" edge to the Counter entity by IDs. func (mc *MetricCreate) AddCounterIDs(ids ...int) *MetricCreate { mc.mutation.AddCounterIDs(ids...) return mc } -// AddCounters adds the counters edges to Counter. +// AddCounters adds the "counters" edges to the Counter entity. func (mc *MetricCreate) AddCounters(c ...*Counter) *MetricCreate { ids := make([]int, len(c)) for i := range c { @@ -84,13 +84,13 @@ func (mc *MetricCreate) AddCounters(c ...*Counter) *MetricCreate { return mc.AddCounterIDs(ids...) } -// AddGaugeIDs adds the gauges edge to Gauge by ids. +// AddGaugeIDs adds the "gauges" edge to the Gauge entity by IDs. func (mc *MetricCreate) AddGaugeIDs(ids ...int) *MetricCreate { mc.mutation.AddGaugeIDs(ids...) return mc } -// AddGauges adds the gauges edges to Gauge. +// AddGauges adds the "gauges" edges to the Gauge entity. func (mc *MetricCreate) AddGauges(g ...*Gauge) *MetricCreate { ids := make([]int, len(g)) for i := range g { @@ -106,37 +106,7 @@ func (mc *MetricCreate) Mutation() *MetricMutation { // Save creates the Metric in the database. func (mc *MetricCreate) Save(ctx context.Context) (*Metric, error) { - var ( - err error - node *Metric - ) - if len(mc.hooks) == 0 { - if err = mc.check(); err != nil { - return nil, err - } - node, err = mc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*MetricMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = mc.check(); err != nil { - return nil, err - } - mc.mutation = mutation - node, err = mc.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(mc.hooks) - 1; i >= 0; i-- { - mut = mc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, mc.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, mc.sqlSave, mc.mutation, mc.hooks) } // SaveX calls Save and panics if Save returns an error. @@ -148,55 +118,59 @@ func (mc *MetricCreate) SaveX(ctx context.Context) *Metric { return v } +// Exec executes the query. +func (mc *MetricCreate) Exec(ctx context.Context) error { + _, err := mc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (mc *MetricCreate) ExecX(ctx context.Context) { + if err := mc.Exec(ctx); err != nil { + panic(err) + } +} + // check runs all checks and user-defined validators on the builder. func (mc *MetricCreate) check() error { if _, ok := mc.mutation.Title(); !ok { - return &ValidationError{Name: "title", err: errors.New("ent: missing required field \"title\"")} + return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Metric.title"`)} } if _, ok := mc.mutation.GetType(); !ok { - return &ValidationError{Name: "type", err: errors.New("ent: missing required field \"type\"")} + return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "Metric.type"`)} } return nil } func (mc *MetricCreate) sqlSave(ctx context.Context) (*Metric, error) { + if err := mc.check(); err != nil { + return nil, err + } _node, _spec := mc.createSpec() if err := sqlgraph.CreateNode(ctx, mc.driver, _spec); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } id := _spec.ID.Value.(int64) _node.ID = int(id) + mc.mutation.id = &_node.ID + mc.mutation.done = true return _node, nil } func (mc *MetricCreate) createSpec() (*Metric, *sqlgraph.CreateSpec) { var ( _node = &Metric{config: mc.config} - _spec = &sqlgraph.CreateSpec{ - Table: metric.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, - } + _spec = sqlgraph.NewCreateSpec(metric.Table, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt)) ) if value, ok := mc.mutation.Title(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: metric.FieldTitle, - }) + _spec.SetField(metric.FieldTitle, field.TypeString, value) _node.Title = value } if value, ok := mc.mutation.GetType(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: metric.FieldType, - }) + _spec.SetField(metric.FieldType, field.TypeString, value) _node.Type = value } if nodes := mc.mutation.GraphIDs(); len(nodes) > 0 { @@ -207,15 +181,13 @@ func (mc *MetricCreate) createSpec() (*Metric, *sqlgraph.CreateSpec) { Columns: []string{metric.GraphColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } + _node.graph_metrics = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } if nodes := mc.mutation.HistogramsIDs(); len(nodes) > 0 { @@ -226,10 +198,7 @@ func (mc *MetricCreate) createSpec() (*Metric, *sqlgraph.CreateSpec) { Columns: []string{metric.HistogramsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -245,10 +214,7 @@ func (mc *MetricCreate) createSpec() (*Metric, *sqlgraph.CreateSpec) { Columns: []string{metric.CountersColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -264,10 +230,7 @@ func (mc *MetricCreate) createSpec() (*Metric, *sqlgraph.CreateSpec) { Columns: []string{metric.GaugesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -278,7 +241,7 @@ func (mc *MetricCreate) createSpec() (*Metric, *sqlgraph.CreateSpec) { return _node, _spec } -// MetricCreateBulk is the builder for creating a bulk of Metric entities. +// MetricCreateBulk is the builder for creating many Metric entities in bulk. type MetricCreateBulk struct { config builders []*MetricCreate @@ -301,24 +264,28 @@ func (mcb *MetricCreateBulk) Save(ctx context.Context) ([]*Metric, error) { return nil, err } builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() var err error + nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, mcb.builders[i+1].mutation) } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, mcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if err = sqlgraph.BatchCreate(ctx, mcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } } } - mutation.done = true if err != nil { return nil, err } - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { @@ -335,7 +302,7 @@ func (mcb *MetricCreateBulk) Save(ctx context.Context) ([]*Metric, error) { return nodes, nil } -// SaveX calls Save and panics if Save returns an error. +// SaveX is like Save, but panics if an error occurs. func (mcb *MetricCreateBulk) SaveX(ctx context.Context) []*Metric { v, err := mcb.Save(ctx) if err != nil { @@ -343,3 +310,16 @@ func (mcb *MetricCreateBulk) SaveX(ctx context.Context) []*Metric { } return v } + +// Exec executes the query. +func (mcb *MetricCreateBulk) Exec(ctx context.Context) error { + _, err := mcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (mcb *MetricCreateBulk) ExecX(ctx context.Context) { + if err := mcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/metric_delete.go b/ent/metric_delete.go index 1ca2ffa8..a7fd8d12 100644 --- a/ent/metric_delete.go +++ b/ent/metric_delete.go @@ -1,14 +1,13 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/metric" "github.com/gobench-io/gobench/v2/ent/predicate" ) @@ -16,44 +15,19 @@ import ( // MetricDelete is the builder for deleting a Metric entity. type MetricDelete struct { config - hooks []Hook - mutation *MetricMutation - predicates []predicate.Metric + hooks []Hook + mutation *MetricMutation } -// Where adds a new predicate to the delete builder. +// Where appends a list predicates to the MetricDelete builder. func (md *MetricDelete) Where(ps ...predicate.Metric) *MetricDelete { - md.predicates = append(md.predicates, ps...) + md.mutation.Where(ps...) return md } // Exec executes the deletion query and returns how many vertices were deleted. func (md *MetricDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(md.hooks) == 0 { - affected, err = md.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*MetricMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - md.mutation = mutation - affected, err = md.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(md.hooks) - 1; i >= 0; i-- { - mut = md.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, md.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, md.sqlExec, md.mutation, md.hooks) } // ExecX is like Exec, but panics if an error occurs. @@ -66,23 +40,20 @@ func (md *MetricDelete) ExecX(ctx context.Context) int { } func (md *MetricDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: metric.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, - }, - } - if ps := md.predicates; len(ps) > 0 { + _spec := sqlgraph.NewDeleteSpec(metric.Table, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt)) + if ps := md.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - return sqlgraph.DeleteNodes(ctx, md.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, md.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + md.mutation.done = true + return affected, err } // MetricDeleteOne is the builder for deleting a single Metric entity. @@ -90,6 +61,12 @@ type MetricDeleteOne struct { md *MetricDelete } +// Where appends a list predicates to the MetricDelete builder. +func (mdo *MetricDeleteOne) Where(ps ...predicate.Metric) *MetricDeleteOne { + mdo.md.mutation.Where(ps...) + return mdo +} + // Exec executes the deletion query. func (mdo *MetricDeleteOne) Exec(ctx context.Context) error { n, err := mdo.md.Exec(ctx) @@ -105,5 +82,7 @@ func (mdo *MetricDeleteOne) Exec(ctx context.Context) error { // ExecX is like Exec, but panics if an error occurs. func (mdo *MetricDeleteOne) ExecX(ctx context.Context) { - mdo.md.ExecX(ctx) + if err := mdo.Exec(ctx); err != nil { + panic(err) + } } diff --git a/ent/metric_query.go b/ent/metric_query.go index 4464a283..47d2f1ee 100644 --- a/ent/metric_query.go +++ b/ent/metric_query.go @@ -1,17 +1,16 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" "database/sql/driver" - "errors" "fmt" "math" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/gauge" "github.com/gobench-io/gobench/v2/ent/graph" @@ -23,12 +22,10 @@ import ( // MetricQuery is the builder for querying Metric entities. type MetricQuery struct { config - limit *int - offset *int - order []OrderFunc - unique []string - predicates []predicate.Metric - // eager-loading edges. + ctx *QueryContext + order []metric.OrderOption + inters []Interceptor + predicates []predicate.Metric withGraph *GraphQuery withHistograms *HistogramQuery withCounters *CounterQuery @@ -39,38 +36,45 @@ type MetricQuery struct { path func(context.Context) (*sql.Selector, error) } -// Where adds a new predicate for the builder. +// Where adds a new predicate for the MetricQuery builder. func (mq *MetricQuery) Where(ps ...predicate.Metric) *MetricQuery { mq.predicates = append(mq.predicates, ps...) return mq } -// Limit adds a limit step to the query. +// Limit the number of records to be returned by this query. func (mq *MetricQuery) Limit(limit int) *MetricQuery { - mq.limit = &limit + mq.ctx.Limit = &limit return mq } -// Offset adds an offset step to the query. +// Offset to start from. func (mq *MetricQuery) Offset(offset int) *MetricQuery { - mq.offset = &offset + mq.ctx.Offset = &offset return mq } -// Order adds an order step to the query. -func (mq *MetricQuery) Order(o ...OrderFunc) *MetricQuery { +// 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 (mq *MetricQuery) Unique(unique bool) *MetricQuery { + mq.ctx.Unique = &unique + return mq +} + +// Order specifies how the records should be ordered. +func (mq *MetricQuery) Order(o ...metric.OrderOption) *MetricQuery { mq.order = append(mq.order, o...) return mq } -// QueryGraph chains the current query on the graph edge. +// QueryGraph chains the current query on the "graph" edge. func (mq *MetricQuery) QueryGraph() *GraphQuery { - query := &GraphQuery{config: mq.config} + query := (&GraphClient{config: mq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := mq.prepareQuery(ctx); err != nil { return nil, err } - selector := mq.sqlQuery() + selector := mq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -85,14 +89,14 @@ func (mq *MetricQuery) QueryGraph() *GraphQuery { return query } -// QueryHistograms chains the current query on the histograms edge. +// QueryHistograms chains the current query on the "histograms" edge. func (mq *MetricQuery) QueryHistograms() *HistogramQuery { - query := &HistogramQuery{config: mq.config} + query := (&HistogramClient{config: mq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := mq.prepareQuery(ctx); err != nil { return nil, err } - selector := mq.sqlQuery() + selector := mq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -107,14 +111,14 @@ func (mq *MetricQuery) QueryHistograms() *HistogramQuery { return query } -// QueryCounters chains the current query on the counters edge. +// QueryCounters chains the current query on the "counters" edge. func (mq *MetricQuery) QueryCounters() *CounterQuery { - query := &CounterQuery{config: mq.config} + query := (&CounterClient{config: mq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := mq.prepareQuery(ctx); err != nil { return nil, err } - selector := mq.sqlQuery() + selector := mq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -129,14 +133,14 @@ func (mq *MetricQuery) QueryCounters() *CounterQuery { return query } -// QueryGauges chains the current query on the gauges edge. +// QueryGauges chains the current query on the "gauges" edge. func (mq *MetricQuery) QueryGauges() *GaugeQuery { - query := &GaugeQuery{config: mq.config} + query := (&GaugeClient{config: mq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := mq.prepareQuery(ctx); err != nil { return nil, err } - selector := mq.sqlQuery() + selector := mq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -151,9 +155,10 @@ func (mq *MetricQuery) QueryGauges() *GaugeQuery { return query } -// First returns the first Metric entity in the query. Returns *NotFoundError when no metric was found. +// First returns the first Metric entity from the query. +// Returns a *NotFoundError when no Metric was found. func (mq *MetricQuery) First(ctx context.Context) (*Metric, error) { - nodes, err := mq.Limit(1).All(ctx) + nodes, err := mq.Limit(1).All(setContextOp(ctx, mq.ctx, "First")) if err != nil { return nil, err } @@ -172,10 +177,11 @@ func (mq *MetricQuery) FirstX(ctx context.Context) *Metric { return node } -// FirstID returns the first Metric id in the query. Returns *NotFoundError when no id was found. +// FirstID returns the first Metric ID from the query. +// Returns a *NotFoundError when no Metric ID was found. func (mq *MetricQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = mq.Limit(1).IDs(ctx); err != nil { + if ids, err = mq.Limit(1).IDs(setContextOp(ctx, mq.ctx, "FirstID")); err != nil { return } if len(ids) == 0 { @@ -185,8 +191,8 @@ func (mq *MetricQuery) FirstID(ctx context.Context) (id int, err error) { return ids[0], nil } -// FirstXID is like FirstID, but panics if an error occurs. -func (mq *MetricQuery) FirstXID(ctx context.Context) int { +// FirstIDX is like FirstID, but panics if an error occurs. +func (mq *MetricQuery) FirstIDX(ctx context.Context) int { id, err := mq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -194,9 +200,11 @@ func (mq *MetricQuery) FirstXID(ctx context.Context) int { return id } -// Only returns the only Metric entity in the query, returns an error if not exactly one entity was returned. +// Only returns a single Metric entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Metric entity is found. +// Returns a *NotFoundError when no Metric entities are found. func (mq *MetricQuery) Only(ctx context.Context) (*Metric, error) { - nodes, err := mq.Limit(2).All(ctx) + nodes, err := mq.Limit(2).All(setContextOp(ctx, mq.ctx, "Only")) if err != nil { return nil, err } @@ -219,10 +227,12 @@ func (mq *MetricQuery) OnlyX(ctx context.Context) *Metric { return node } -// OnlyID returns the only Metric id in the query, returns an error if not exactly one id was returned. +// OnlyID is like Only, but returns the only Metric ID in the query. +// Returns a *NotSingularError when more than one Metric ID is found. +// Returns a *NotFoundError when no entities are found. func (mq *MetricQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = mq.Limit(2).IDs(ctx); err != nil { + if ids, err = mq.Limit(2).IDs(setContextOp(ctx, mq.ctx, "OnlyID")); err != nil { return } switch len(ids) { @@ -247,10 +257,12 @@ func (mq *MetricQuery) OnlyIDX(ctx context.Context) int { // All executes the query and returns a list of Metrics. func (mq *MetricQuery) All(ctx context.Context) ([]*Metric, error) { + ctx = setContextOp(ctx, mq.ctx, "All") if err := mq.prepareQuery(ctx); err != nil { return nil, err } - return mq.sqlAll(ctx) + qr := querierAll[[]*Metric, *MetricQuery]() + return withInterceptors[[]*Metric](ctx, mq, qr, mq.inters) } // AllX is like All, but panics if an error occurs. @@ -262,10 +274,13 @@ func (mq *MetricQuery) AllX(ctx context.Context) []*Metric { return nodes } -// IDs executes the query and returns a list of Metric ids. -func (mq *MetricQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := mq.Select(metric.FieldID).Scan(ctx, &ids); err != nil { +// IDs executes the query and returns a list of Metric IDs. +func (mq *MetricQuery) IDs(ctx context.Context) (ids []int, err error) { + if mq.ctx.Unique == nil && mq.path != nil { + mq.Unique(true) + } + ctx = setContextOp(ctx, mq.ctx, "IDs") + if err = mq.Select(metric.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil @@ -282,10 +297,11 @@ func (mq *MetricQuery) IDsX(ctx context.Context) []int { // Count returns the count of the given query. func (mq *MetricQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, mq.ctx, "Count") if err := mq.prepareQuery(ctx); err != nil { return 0, err } - return mq.sqlCount(ctx) + return withInterceptors[int](ctx, mq, querierCount[*MetricQuery](), mq.inters) } // CountX is like Count, but panics if an error occurs. @@ -299,10 +315,15 @@ func (mq *MetricQuery) CountX(ctx context.Context) int { // Exist returns true if the query has elements in the graph. func (mq *MetricQuery) Exist(ctx context.Context) (bool, error) { - if err := mq.prepareQuery(ctx); err != nil { - return false, err + ctx = setContextOp(ctx, mq.ctx, "Exist") + switch _, err := mq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil } - return mq.sqlExist(ctx) } // ExistX is like Exist, but panics if an error occurs. @@ -314,26 +335,32 @@ func (mq *MetricQuery) ExistX(ctx context.Context) bool { return exist } -// Clone returns a duplicate of the query builder, including all associated steps. It can be +// Clone returns a duplicate of the MetricQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. func (mq *MetricQuery) Clone() *MetricQuery { + if mq == nil { + return nil + } return &MetricQuery{ - config: mq.config, - limit: mq.limit, - offset: mq.offset, - order: append([]OrderFunc{}, mq.order...), - unique: append([]string{}, mq.unique...), - predicates: append([]predicate.Metric{}, mq.predicates...), + config: mq.config, + ctx: mq.ctx.Clone(), + order: append([]metric.OrderOption{}, mq.order...), + inters: append([]Interceptor{}, mq.inters...), + predicates: append([]predicate.Metric{}, mq.predicates...), + withGraph: mq.withGraph.Clone(), + withHistograms: mq.withHistograms.Clone(), + withCounters: mq.withCounters.Clone(), + withGauges: mq.withGauges.Clone(), // clone intermediate query. sql: mq.sql.Clone(), path: mq.path, } } -// WithGraph tells the query-builder to eager-loads the nodes that are connected to -// the "graph" edge. The optional arguments used to configure the query builder of the edge. +// WithGraph tells the query-builder to eager-load the nodes that are connected to +// the "graph" edge. The optional arguments are used to configure the query builder of the edge. func (mq *MetricQuery) WithGraph(opts ...func(*GraphQuery)) *MetricQuery { - query := &GraphQuery{config: mq.config} + query := (&GraphClient{config: mq.config}).Query() for _, opt := range opts { opt(query) } @@ -341,10 +368,10 @@ func (mq *MetricQuery) WithGraph(opts ...func(*GraphQuery)) *MetricQuery { return mq } -// WithHistograms tells the query-builder to eager-loads the nodes that are connected to -// the "histograms" edge. The optional arguments used to configure the query builder of the edge. +// WithHistograms tells the query-builder to eager-load the nodes that are connected to +// the "histograms" edge. The optional arguments are used to configure the query builder of the edge. func (mq *MetricQuery) WithHistograms(opts ...func(*HistogramQuery)) *MetricQuery { - query := &HistogramQuery{config: mq.config} + query := (&HistogramClient{config: mq.config}).Query() for _, opt := range opts { opt(query) } @@ -352,10 +379,10 @@ func (mq *MetricQuery) WithHistograms(opts ...func(*HistogramQuery)) *MetricQuer return mq } -// WithCounters tells the query-builder to eager-loads the nodes that are connected to -// the "counters" edge. The optional arguments used to configure the query builder of the edge. +// WithCounters tells the query-builder to eager-load the nodes that are connected to +// the "counters" edge. The optional arguments are used to configure the query builder of the edge. func (mq *MetricQuery) WithCounters(opts ...func(*CounterQuery)) *MetricQuery { - query := &CounterQuery{config: mq.config} + query := (&CounterClient{config: mq.config}).Query() for _, opt := range opts { opt(query) } @@ -363,10 +390,10 @@ func (mq *MetricQuery) WithCounters(opts ...func(*CounterQuery)) *MetricQuery { return mq } -// WithGauges tells the query-builder to eager-loads the nodes that are connected to -// the "gauges" edge. The optional arguments used to configure the query builder of the edge. +// WithGauges tells the query-builder to eager-load the nodes that are connected to +// the "gauges" edge. The optional arguments are used to configure the query builder of the edge. func (mq *MetricQuery) WithGauges(opts ...func(*GaugeQuery)) *MetricQuery { - query := &GaugeQuery{config: mq.config} + query := (&GaugeClient{config: mq.config}).Query() for _, opt := range opts { opt(query) } @@ -374,7 +401,7 @@ func (mq *MetricQuery) WithGauges(opts ...func(*GaugeQuery)) *MetricQuery { return mq } -// GroupBy used to group vertices by one or more fields/columns. +// 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: @@ -388,20 +415,17 @@ func (mq *MetricQuery) WithGauges(opts ...func(*GaugeQuery)) *MetricQuery { // GroupBy(metric.FieldTitle). // Aggregate(ent.Count()). // Scan(ctx, &v) -// func (mq *MetricQuery) GroupBy(field string, fields ...string) *MetricGroupBy { - group := &MetricGroupBy{config: mq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := mq.prepareQuery(ctx); err != nil { - return nil, err - } - return mq.sqlQuery(), nil - } - return group + mq.ctx.Fields = append([]string{field}, fields...) + grbuild := &MetricGroupBy{build: mq} + grbuild.flds = &mq.ctx.Fields + grbuild.label = metric.Label + grbuild.scan = grbuild.Scan + return grbuild } -// Select one or more fields from the given query. +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. // // Example: // @@ -412,20 +436,35 @@ func (mq *MetricQuery) GroupBy(field string, fields ...string) *MetricGroupBy { // client.Metric.Query(). // Select(metric.FieldTitle). // Scan(ctx, &v) -// -func (mq *MetricQuery) Select(field string, fields ...string) *MetricSelect { - selector := &MetricSelect{config: mq.config} - selector.fields = append([]string{field}, fields...) - selector.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := mq.prepareQuery(ctx); err != nil { - return nil, err - } - return mq.sqlQuery(), nil - } - return selector +func (mq *MetricQuery) Select(fields ...string) *MetricSelect { + mq.ctx.Fields = append(mq.ctx.Fields, fields...) + sbuild := &MetricSelect{MetricQuery: mq} + sbuild.label = metric.Label + sbuild.flds, sbuild.scan = &mq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a MetricSelect configured with the given aggregations. +func (mq *MetricQuery) Aggregate(fns ...AggregateFunc) *MetricSelect { + return mq.Select().Aggregate(fns...) } func (mq *MetricQuery) prepareQuery(ctx context.Context) error { + for _, inter := range mq.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, mq); err != nil { + return err + } + } + } + for _, f := range mq.ctx.Fields { + if !metric.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } if mq.path != nil { prev, err := mq.path(ctx) if err != nil { @@ -436,7 +475,7 @@ func (mq *MetricQuery) prepareQuery(ctx context.Context) error { return nil } -func (mq *MetricQuery) sqlAll(ctx context.Context) ([]*Metric, error) { +func (mq *MetricQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Metric, error) { var ( nodes = []*Metric{} withFKs = mq.withFKs @@ -454,22 +493,17 @@ func (mq *MetricQuery) sqlAll(ctx context.Context) ([]*Metric, error) { if withFKs { _spec.Node.Columns = append(_spec.Node.Columns, metric.ForeignKeys...) } - _spec.ScanValues = func() []interface{} { + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Metric).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { node := &Metric{config: mq.config} nodes = append(nodes, node) - values := node.scanValues() - if withFKs { - values = append(values, node.fkValues()...) - } - return values - } - _spec.Assign = func(values ...interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("ent: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] node.Edges.loadedTypes = loadedTypes - return node.assignValues(values...) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) } if err := sqlgraph.QueryNodes(ctx, mq.driver, _spec); err != nil { return nil, err @@ -477,144 +511,187 @@ func (mq *MetricQuery) sqlAll(ctx context.Context) ([]*Metric, error) { if len(nodes) == 0 { return nodes, nil } - if query := mq.withGraph; query != nil { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*Metric) - for i := range nodes { - if fk := nodes[i].graph_metrics; fk != nil { - ids = append(ids, *fk) - nodeids[*fk] = append(nodeids[*fk], nodes[i]) - } - } - query.Where(graph.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { + if err := mq.loadGraph(ctx, query, nodes, nil, + func(n *Metric, e *Graph) { n.Edges.Graph = e }); err != nil { return nil, err } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "graph_metrics" returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.Graph = n - } - } } - if query := mq.withHistograms; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*Metric) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] + if err := mq.loadHistograms(ctx, query, nodes, + func(n *Metric) { n.Edges.Histograms = []*Histogram{} }, + func(n *Metric, e *Histogram) { n.Edges.Histograms = append(n.Edges.Histograms, e) }); err != nil { + return nil, err } - query.withFKs = true - query.Where(predicate.Histogram(func(s *sql.Selector) { - s.Where(sql.InValues(metric.HistogramsColumn, fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { + } + if query := mq.withCounters; query != nil { + if err := mq.loadCounters(ctx, query, nodes, + func(n *Metric) { n.Edges.Counters = []*Counter{} }, + func(n *Metric, e *Counter) { n.Edges.Counters = append(n.Edges.Counters, e) }); err != nil { return nil, err } - for _, n := range neighbors { - fk := n.metric_histograms - if fk == nil { - return nil, fmt.Errorf(`foreign-key "metric_histograms" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "metric_histograms" returned %v for node %v`, *fk, n.ID) - } - node.Edges.Histograms = append(node.Edges.Histograms, n) + } + if query := mq.withGauges; query != nil { + if err := mq.loadGauges(ctx, query, nodes, + func(n *Metric) { n.Edges.Gauges = []*Gauge{} }, + func(n *Metric, e *Gauge) { n.Edges.Gauges = append(n.Edges.Gauges, e) }); err != nil { + return nil, err } } + return nodes, nil +} - if query := mq.withCounters; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*Metric) +func (mq *MetricQuery) loadGraph(ctx context.Context, query *GraphQuery, nodes []*Metric, init func(*Metric), assign func(*Metric, *Graph)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Metric) + for i := range nodes { + if nodes[i].graph_metrics == nil { + continue + } + fk := *nodes[i].graph_metrics + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(graph.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 "graph_metrics" returned %v`, n.ID) + } for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] + assign(nodes[i], n) } - query.withFKs = true - query.Where(predicate.Counter(func(s *sql.Selector) { - s.Where(sql.InValues(metric.CountersColumn, fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err + } + return nil +} +func (mq *MetricQuery) loadHistograms(ctx context.Context, query *HistogramQuery, nodes []*Metric, init func(*Metric), assign func(*Metric, *Histogram)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Metric) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) } - for _, n := range neighbors { - fk := n.metric_counters - if fk == nil { - return nil, fmt.Errorf(`foreign-key "metric_counters" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "metric_counters" returned %v for node %v`, *fk, n.ID) - } - node.Edges.Counters = append(node.Edges.Counters, n) + } + query.withFKs = true + query.Where(predicate.Histogram(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(metric.HistogramsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.metric_histograms + if fk == nil { + return fmt.Errorf(`foreign-key "metric_histograms" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "metric_histograms" returned %v for node %v`, *fk, n.ID) } + assign(node, n) } - - if query := mq.withGauges; query != nil { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[int]*Metric) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] + return nil +} +func (mq *MetricQuery) loadCounters(ctx context.Context, query *CounterQuery, nodes []*Metric, init func(*Metric), assign func(*Metric, *Counter)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Metric) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) } - query.withFKs = true - query.Where(predicate.Gauge(func(s *sql.Selector) { - s.Where(sql.InValues(metric.GaugesColumn, fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return nil, err + } + query.withFKs = true + query.Where(predicate.Counter(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(metric.CountersColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.metric_counters + if fk == nil { + return fmt.Errorf(`foreign-key "metric_counters" is nil for node %v`, n.ID) } - for _, n := range neighbors { - fk := n.metric_gauges - if fk == nil { - return nil, fmt.Errorf(`foreign-key "metric_gauges" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "metric_gauges" returned %v for node %v`, *fk, n.ID) - } - node.Edges.Gauges = append(node.Edges.Gauges, n) + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "metric_counters" returned %v for node %v`, *fk, n.ID) } + assign(node, n) } - - return nodes, nil + return nil +} +func (mq *MetricQuery) loadGauges(ctx context.Context, query *GaugeQuery, nodes []*Metric, init func(*Metric), assign func(*Metric, *Gauge)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Metric) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + query.Where(predicate.Gauge(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(metric.GaugesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.metric_gauges + if fk == nil { + return fmt.Errorf(`foreign-key "metric_gauges" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "metric_gauges" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil } func (mq *MetricQuery) sqlCount(ctx context.Context) (int, error) { _spec := mq.querySpec() - return sqlgraph.CountNodes(ctx, mq.driver, _spec) -} - -func (mq *MetricQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := mq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("ent: check existence: %v", err) + _spec.Node.Columns = mq.ctx.Fields + if len(mq.ctx.Fields) > 0 { + _spec.Unique = mq.ctx.Unique != nil && *mq.ctx.Unique } - return n > 0, nil + return sqlgraph.CountNodes(ctx, mq.driver, _spec) } func (mq *MetricQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: metric.Table, - Columns: metric.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, - }, - From: mq.sql, - Unique: true, + _spec := sqlgraph.NewQuerySpec(metric.Table, metric.Columns, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt)) + _spec.From = mq.sql + if unique := mq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if mq.path != nil { + _spec.Unique = true + } + if fields := mq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, metric.FieldID) + for i := range fields { + if fields[i] != metric.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } } if ps := mq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -623,55 +700,58 @@ func (mq *MetricQuery) querySpec() *sqlgraph.QuerySpec { } } } - if limit := mq.limit; limit != nil { + if limit := mq.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := mq.offset; offset != nil { + if offset := mq.ctx.Offset; offset != nil { _spec.Offset = *offset } if ps := mq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector, metric.ValidColumn) + ps[i](selector) } } } return _spec } -func (mq *MetricQuery) sqlQuery() *sql.Selector { +func (mq *MetricQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(mq.driver.Dialect()) t1 := builder.Table(metric.Table) - selector := builder.Select(t1.Columns(metric.Columns...)...).From(t1) + columns := mq.ctx.Fields + if len(columns) == 0 { + columns = metric.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) if mq.sql != nil { selector = mq.sql - selector.Select(selector.Columns(metric.Columns...)...) + selector.Select(selector.Columns(columns...)...) + } + if mq.ctx.Unique != nil && *mq.ctx.Unique { + selector.Distinct() } for _, p := range mq.predicates { p(selector) } for _, p := range mq.order { - p(selector, metric.ValidColumn) + p(selector) } - if offset := mq.offset; offset != nil { + if offset := mq.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 := mq.limit; limit != nil { + if limit := mq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector } -// MetricGroupBy is the builder for group-by Metric entities. +// MetricGroupBy is the group-by builder for Metric entities. type MetricGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) + selector + build *MetricQuery } // Aggregate adds the given aggregation functions to the group-by query. @@ -680,471 +760,80 @@ func (mgb *MetricGroupBy) Aggregate(fns ...AggregateFunc) *MetricGroupBy { return mgb } -// Scan applies the group-by query and scan the result into the given value. -func (mgb *MetricGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := mgb.path(ctx) - if err != nil { +// Scan applies the selector query and scans the result into the given value. +func (mgb *MetricGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, mgb.build.ctx, "GroupBy") + if err := mgb.build.prepareQuery(ctx); err != nil { return err } - mgb.sql = query - return mgb.sqlScan(ctx, v) + return scanWithInterceptors[*MetricQuery, *MetricGroupBy](ctx, mgb.build, mgb, mgb.build.inters, v) } -// ScanX is like Scan, but panics if an error occurs. -func (mgb *MetricGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := mgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field. -func (mgb *MetricGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(mgb.fields) > 1 { - return nil, errors.New("ent: MetricGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := mgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (mgb *MetricGroupBy) StringsX(ctx context.Context) []string { - v, err := mgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from group-by. It is only allowed when querying group-by with one field. -func (mgb *MetricGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = mgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{metric.Label} - default: - err = fmt.Errorf("ent: MetricGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (mgb *MetricGroupBy) StringX(ctx context.Context) string { - v, err := mgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field. -func (mgb *MetricGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(mgb.fields) > 1 { - return nil, errors.New("ent: MetricGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := mgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (mgb *MetricGroupBy) IntsX(ctx context.Context) []int { - v, err := mgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from group-by. It is only allowed when querying group-by with one field. -func (mgb *MetricGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = mgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{metric.Label} - default: - err = fmt.Errorf("ent: MetricGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (mgb *MetricGroupBy) IntX(ctx context.Context) int { - v, err := mgb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field. -func (mgb *MetricGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(mgb.fields) > 1 { - return nil, errors.New("ent: MetricGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := mgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (mgb *MetricGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := mgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field. -func (mgb *MetricGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = mgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{metric.Label} - default: - err = fmt.Errorf("ent: MetricGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (mgb *MetricGroupBy) Float64X(ctx context.Context) float64 { - v, err := mgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field. -func (mgb *MetricGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(mgb.fields) > 1 { - return nil, errors.New("ent: MetricGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := mgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (mgb *MetricGroupBy) BoolsX(ctx context.Context) []bool { - v, err := mgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field. -func (mgb *MetricGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = mgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{metric.Label} - default: - err = fmt.Errorf("ent: MetricGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (mgb *MetricGroupBy) BoolX(ctx context.Context) bool { - v, err := mgb.Bool(ctx) - if err != nil { - panic(err) +func (mgb *MetricGroupBy) sqlScan(ctx context.Context, root *MetricQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(mgb.fns)) + for _, fn := range mgb.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (mgb *MetricGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range mgb.fields { - if !metric.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*mgb.flds)+len(mgb.fns)) + for _, f := range *mgb.flds { + columns = append(columns, selector.C(f)) } + columns = append(columns, aggregation...) + selector.Select(columns...) } - selector := mgb.sqlQuery() + selector.GroupBy(selector.Columns(*mgb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := mgb.driver.Query(ctx, query, args, rows); err != nil { + if err := mgb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } -func (mgb *MetricGroupBy) sqlQuery() *sql.Selector { - selector := mgb.sql - columns := make([]string, 0, len(mgb.fields)+len(mgb.fns)) - columns = append(columns, mgb.fields...) - for _, fn := range mgb.fns { - columns = append(columns, fn(selector, metric.ValidColumn)) - } - return selector.Select(columns...).GroupBy(mgb.fields...) -} - -// MetricSelect is the builder for select fields of Metric entities. +// MetricSelect is the builder for selecting fields of Metric entities. type MetricSelect struct { - config - fields []string - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Scan applies the selector query and scan the result into the given value. -func (ms *MetricSelect) Scan(ctx context.Context, v interface{}) error { - query, err := ms.path(ctx) - if err != nil { - return err - } - ms.sql = query - return ms.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (ms *MetricSelect) ScanX(ctx context.Context, v interface{}) { - if err := ms.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from selector. It is only allowed when selecting one field. -func (ms *MetricSelect) Strings(ctx context.Context) ([]string, error) { - if len(ms.fields) > 1 { - return nil, errors.New("ent: MetricSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := ms.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (ms *MetricSelect) StringsX(ctx context.Context) []string { - v, err := ms.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from selector. It is only allowed when selecting one field. -func (ms *MetricSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = ms.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{metric.Label} - default: - err = fmt.Errorf("ent: MetricSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (ms *MetricSelect) StringX(ctx context.Context) string { - v, err := ms.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from selector. It is only allowed when selecting one field. -func (ms *MetricSelect) Ints(ctx context.Context) ([]int, error) { - if len(ms.fields) > 1 { - return nil, errors.New("ent: MetricSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := ms.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil + *MetricQuery + selector } -// IntsX is like Ints, but panics if an error occurs. -func (ms *MetricSelect) IntsX(ctx context.Context) []int { - v, err := ms.Ints(ctx) - if err != nil { - panic(err) - } - return v +// Aggregate adds the given aggregation functions to the selector query. +func (ms *MetricSelect) Aggregate(fns ...AggregateFunc) *MetricSelect { + ms.fns = append(ms.fns, fns...) + return ms } -// Int returns a single int from selector. It is only allowed when selecting one field. -func (ms *MetricSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = ms.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{metric.Label} - default: - err = fmt.Errorf("ent: MetricSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (ms *MetricSelect) IntX(ctx context.Context) int { - v, err := ms.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from selector. It is only allowed when selecting one field. -func (ms *MetricSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(ms.fields) > 1 { - return nil, errors.New("ent: MetricSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := ms.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (ms *MetricSelect) Float64sX(ctx context.Context) []float64 { - v, err := ms.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from selector. It is only allowed when selecting one field. -func (ms *MetricSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = ms.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{metric.Label} - default: - err = fmt.Errorf("ent: MetricSelect.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (ms *MetricSelect) Float64X(ctx context.Context) float64 { - v, err := ms.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from selector. It is only allowed when selecting one field. -func (ms *MetricSelect) Bools(ctx context.Context) ([]bool, error) { - if len(ms.fields) > 1 { - return nil, errors.New("ent: MetricSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := ms.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (ms *MetricSelect) BoolsX(ctx context.Context) []bool { - v, err := ms.Bools(ctx) - if err != nil { - panic(err) +// Scan applies the selector query and scans the result into the given value. +func (ms *MetricSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ms.ctx, "Select") + if err := ms.prepareQuery(ctx); err != nil { + return err } - return v + return scanWithInterceptors[*MetricQuery, *MetricSelect](ctx, ms.MetricQuery, ms, ms.inters, v) } -// Bool returns a single bool from selector. It is only allowed when selecting one field. -func (ms *MetricSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = ms.Bools(ctx); err != nil { - return +func (ms *MetricSelect) sqlScan(ctx context.Context, root *MetricQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ms.fns)) + for _, fn := range ms.fns { + aggregation = append(aggregation, fn(selector)) } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{metric.Label} - default: - err = fmt.Errorf("ent: MetricSelect.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (ms *MetricSelect) BoolX(ctx context.Context) bool { - v, err := ms.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -func (ms *MetricSelect) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range ms.fields { - if !metric.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} - } + switch n := len(*ms.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 := ms.sqlQuery().Query() + query, args := selector.Query() if err := ms.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } - -func (ms *MetricSelect) sqlQuery() sql.Querier { - selector := ms.sql - selector.Select(selector.Columns(ms.fields...)...) - return selector -} diff --git a/ent/metric_update.go b/ent/metric_update.go index 3c0c4a61..5d66d44d 100644 --- a/ent/metric_update.go +++ b/ent/metric_update.go @@ -1,14 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/gauge" "github.com/gobench-io/gobench/v2/ent/graph" @@ -20,30 +21,29 @@ import ( // MetricUpdate is the builder for updating Metric entities. type MetricUpdate struct { config - hooks []Hook - mutation *MetricMutation - predicates []predicate.Metric + hooks []Hook + mutation *MetricMutation } -// Where adds a new predicate for the builder. +// Where appends a list predicates to the MetricUpdate builder. func (mu *MetricUpdate) Where(ps ...predicate.Metric) *MetricUpdate { - mu.predicates = append(mu.predicates, ps...) + mu.mutation.Where(ps...) return mu } -// SetType sets the type field. +// SetType sets the "type" field. func (mu *MetricUpdate) SetType(s string) *MetricUpdate { mu.mutation.SetType(s) return mu } -// SetGraphID sets the graph edge to Graph by id. +// SetGraphID sets the "graph" edge to the Graph entity by ID. func (mu *MetricUpdate) SetGraphID(id int) *MetricUpdate { mu.mutation.SetGraphID(id) return mu } -// SetNillableGraphID sets the graph edge to Graph by id if the given value is not nil. +// SetNillableGraphID sets the "graph" edge to the Graph entity by ID if the given value is not nil. func (mu *MetricUpdate) SetNillableGraphID(id *int) *MetricUpdate { if id != nil { mu = mu.SetGraphID(*id) @@ -51,18 +51,18 @@ func (mu *MetricUpdate) SetNillableGraphID(id *int) *MetricUpdate { return mu } -// SetGraph sets the graph edge to Graph. +// SetGraph sets the "graph" edge to the Graph entity. func (mu *MetricUpdate) SetGraph(g *Graph) *MetricUpdate { return mu.SetGraphID(g.ID) } -// AddHistogramIDs adds the histograms edge to Histogram by ids. +// AddHistogramIDs adds the "histograms" edge to the Histogram entity by IDs. func (mu *MetricUpdate) AddHistogramIDs(ids ...int) *MetricUpdate { mu.mutation.AddHistogramIDs(ids...) return mu } -// AddHistograms adds the histograms edges to Histogram. +// AddHistograms adds the "histograms" edges to the Histogram entity. func (mu *MetricUpdate) AddHistograms(h ...*Histogram) *MetricUpdate { ids := make([]int, len(h)) for i := range h { @@ -71,13 +71,13 @@ func (mu *MetricUpdate) AddHistograms(h ...*Histogram) *MetricUpdate { return mu.AddHistogramIDs(ids...) } -// AddCounterIDs adds the counters edge to Counter by ids. +// AddCounterIDs adds the "counters" edge to the Counter entity by IDs. func (mu *MetricUpdate) AddCounterIDs(ids ...int) *MetricUpdate { mu.mutation.AddCounterIDs(ids...) return mu } -// AddCounters adds the counters edges to Counter. +// AddCounters adds the "counters" edges to the Counter entity. func (mu *MetricUpdate) AddCounters(c ...*Counter) *MetricUpdate { ids := make([]int, len(c)) for i := range c { @@ -86,13 +86,13 @@ func (mu *MetricUpdate) AddCounters(c ...*Counter) *MetricUpdate { return mu.AddCounterIDs(ids...) } -// AddGaugeIDs adds the gauges edge to Gauge by ids. +// AddGaugeIDs adds the "gauges" edge to the Gauge entity by IDs. func (mu *MetricUpdate) AddGaugeIDs(ids ...int) *MetricUpdate { mu.mutation.AddGaugeIDs(ids...) return mu } -// AddGauges adds the gauges edges to Gauge. +// AddGauges adds the "gauges" edges to the Gauge entity. func (mu *MetricUpdate) AddGauges(g ...*Gauge) *MetricUpdate { ids := make([]int, len(g)) for i := range g { @@ -106,25 +106,25 @@ func (mu *MetricUpdate) Mutation() *MetricMutation { return mu.mutation } -// ClearGraph clears the "graph" edge to type Graph. +// ClearGraph clears the "graph" edge to the Graph entity. func (mu *MetricUpdate) ClearGraph() *MetricUpdate { mu.mutation.ClearGraph() return mu } -// ClearHistograms clears all "histograms" edges to type Histogram. +// ClearHistograms clears all "histograms" edges to the Histogram entity. func (mu *MetricUpdate) ClearHistograms() *MetricUpdate { mu.mutation.ClearHistograms() return mu } -// RemoveHistogramIDs removes the histograms edge to Histogram by ids. +// RemoveHistogramIDs removes the "histograms" edge to Histogram entities by IDs. func (mu *MetricUpdate) RemoveHistogramIDs(ids ...int) *MetricUpdate { mu.mutation.RemoveHistogramIDs(ids...) return mu } -// RemoveHistograms removes histograms edges to Histogram. +// RemoveHistograms removes "histograms" edges to Histogram entities. func (mu *MetricUpdate) RemoveHistograms(h ...*Histogram) *MetricUpdate { ids := make([]int, len(h)) for i := range h { @@ -133,19 +133,19 @@ func (mu *MetricUpdate) RemoveHistograms(h ...*Histogram) *MetricUpdate { return mu.RemoveHistogramIDs(ids...) } -// ClearCounters clears all "counters" edges to type Counter. +// ClearCounters clears all "counters" edges to the Counter entity. func (mu *MetricUpdate) ClearCounters() *MetricUpdate { mu.mutation.ClearCounters() return mu } -// RemoveCounterIDs removes the counters edge to Counter by ids. +// RemoveCounterIDs removes the "counters" edge to Counter entities by IDs. func (mu *MetricUpdate) RemoveCounterIDs(ids ...int) *MetricUpdate { mu.mutation.RemoveCounterIDs(ids...) return mu } -// RemoveCounters removes counters edges to Counter. +// RemoveCounters removes "counters" edges to Counter entities. func (mu *MetricUpdate) RemoveCounters(c ...*Counter) *MetricUpdate { ids := make([]int, len(c)) for i := range c { @@ -154,19 +154,19 @@ func (mu *MetricUpdate) RemoveCounters(c ...*Counter) *MetricUpdate { return mu.RemoveCounterIDs(ids...) } -// ClearGauges clears all "gauges" edges to type Gauge. +// ClearGauges clears all "gauges" edges to the Gauge entity. func (mu *MetricUpdate) ClearGauges() *MetricUpdate { mu.mutation.ClearGauges() return mu } -// RemoveGaugeIDs removes the gauges edge to Gauge by ids. +// RemoveGaugeIDs removes the "gauges" edge to Gauge entities by IDs. func (mu *MetricUpdate) RemoveGaugeIDs(ids ...int) *MetricUpdate { mu.mutation.RemoveGaugeIDs(ids...) return mu } -// RemoveGauges removes gauges edges to Gauge. +// RemoveGauges removes "gauges" edges to Gauge entities. func (mu *MetricUpdate) RemoveGauges(g ...*Gauge) *MetricUpdate { ids := make([]int, len(g)) for i := range g { @@ -175,33 +175,9 @@ func (mu *MetricUpdate) RemoveGauges(g ...*Gauge) *MetricUpdate { return mu.RemoveGaugeIDs(ids...) } -// Save executes the query and returns the number of rows/vertices matched by this operation. +// Save executes the query and returns the number of nodes affected by the update operation. func (mu *MetricUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(mu.hooks) == 0 { - affected, err = mu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*MetricMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - mu.mutation = mutation - affected, err = mu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(mu.hooks) - 1; i >= 0; i-- { - mut = mu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, mu.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, mu.sqlSave, mu.mutation, mu.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -227,17 +203,8 @@ func (mu *MetricUpdate) ExecX(ctx context.Context) { } func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: metric.Table, - Columns: metric.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, - }, - } - if ps := mu.predicates; len(ps) > 0 { + _spec := sqlgraph.NewUpdateSpec(metric.Table, metric.Columns, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt)) + if ps := mu.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -245,11 +212,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { } } if value, ok := mu.mutation.GetType(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: metric.FieldType, - }) + _spec.SetField(metric.FieldType, field.TypeString, value) } if mu.mutation.GraphCleared() { edge := &sqlgraph.EdgeSpec{ @@ -259,10 +222,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.GraphColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -275,10 +235,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.GraphColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -294,10 +251,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.HistogramsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -310,10 +264,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.HistogramsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -329,10 +280,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.HistogramsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -348,10 +296,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.CountersColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -364,10 +309,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.CountersColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -383,10 +325,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.CountersColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -402,10 +341,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.GaugesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -418,10 +354,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.GaugesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -437,10 +370,7 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{metric.GaugesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -451,34 +381,36 @@ func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) { if n, err = sqlgraph.UpdateNodes(ctx, mu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{metric.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } + mu.mutation.done = true return n, nil } // MetricUpdateOne is the builder for updating a single Metric entity. type MetricUpdateOne struct { config + fields []string hooks []Hook mutation *MetricMutation } -// SetType sets the type field. +// SetType sets the "type" field. func (muo *MetricUpdateOne) SetType(s string) *MetricUpdateOne { muo.mutation.SetType(s) return muo } -// SetGraphID sets the graph edge to Graph by id. +// SetGraphID sets the "graph" edge to the Graph entity by ID. func (muo *MetricUpdateOne) SetGraphID(id int) *MetricUpdateOne { muo.mutation.SetGraphID(id) return muo } -// SetNillableGraphID sets the graph edge to Graph by id if the given value is not nil. +// SetNillableGraphID sets the "graph" edge to the Graph entity by ID if the given value is not nil. func (muo *MetricUpdateOne) SetNillableGraphID(id *int) *MetricUpdateOne { if id != nil { muo = muo.SetGraphID(*id) @@ -486,18 +418,18 @@ func (muo *MetricUpdateOne) SetNillableGraphID(id *int) *MetricUpdateOne { return muo } -// SetGraph sets the graph edge to Graph. +// SetGraph sets the "graph" edge to the Graph entity. func (muo *MetricUpdateOne) SetGraph(g *Graph) *MetricUpdateOne { return muo.SetGraphID(g.ID) } -// AddHistogramIDs adds the histograms edge to Histogram by ids. +// AddHistogramIDs adds the "histograms" edge to the Histogram entity by IDs. func (muo *MetricUpdateOne) AddHistogramIDs(ids ...int) *MetricUpdateOne { muo.mutation.AddHistogramIDs(ids...) return muo } -// AddHistograms adds the histograms edges to Histogram. +// AddHistograms adds the "histograms" edges to the Histogram entity. func (muo *MetricUpdateOne) AddHistograms(h ...*Histogram) *MetricUpdateOne { ids := make([]int, len(h)) for i := range h { @@ -506,13 +438,13 @@ func (muo *MetricUpdateOne) AddHistograms(h ...*Histogram) *MetricUpdateOne { return muo.AddHistogramIDs(ids...) } -// AddCounterIDs adds the counters edge to Counter by ids. +// AddCounterIDs adds the "counters" edge to the Counter entity by IDs. func (muo *MetricUpdateOne) AddCounterIDs(ids ...int) *MetricUpdateOne { muo.mutation.AddCounterIDs(ids...) return muo } -// AddCounters adds the counters edges to Counter. +// AddCounters adds the "counters" edges to the Counter entity. func (muo *MetricUpdateOne) AddCounters(c ...*Counter) *MetricUpdateOne { ids := make([]int, len(c)) for i := range c { @@ -521,13 +453,13 @@ func (muo *MetricUpdateOne) AddCounters(c ...*Counter) *MetricUpdateOne { return muo.AddCounterIDs(ids...) } -// AddGaugeIDs adds the gauges edge to Gauge by ids. +// AddGaugeIDs adds the "gauges" edge to the Gauge entity by IDs. func (muo *MetricUpdateOne) AddGaugeIDs(ids ...int) *MetricUpdateOne { muo.mutation.AddGaugeIDs(ids...) return muo } -// AddGauges adds the gauges edges to Gauge. +// AddGauges adds the "gauges" edges to the Gauge entity. func (muo *MetricUpdateOne) AddGauges(g ...*Gauge) *MetricUpdateOne { ids := make([]int, len(g)) for i := range g { @@ -541,25 +473,25 @@ func (muo *MetricUpdateOne) Mutation() *MetricMutation { return muo.mutation } -// ClearGraph clears the "graph" edge to type Graph. +// ClearGraph clears the "graph" edge to the Graph entity. func (muo *MetricUpdateOne) ClearGraph() *MetricUpdateOne { muo.mutation.ClearGraph() return muo } -// ClearHistograms clears all "histograms" edges to type Histogram. +// ClearHistograms clears all "histograms" edges to the Histogram entity. func (muo *MetricUpdateOne) ClearHistograms() *MetricUpdateOne { muo.mutation.ClearHistograms() return muo } -// RemoveHistogramIDs removes the histograms edge to Histogram by ids. +// RemoveHistogramIDs removes the "histograms" edge to Histogram entities by IDs. func (muo *MetricUpdateOne) RemoveHistogramIDs(ids ...int) *MetricUpdateOne { muo.mutation.RemoveHistogramIDs(ids...) return muo } -// RemoveHistograms removes histograms edges to Histogram. +// RemoveHistograms removes "histograms" edges to Histogram entities. func (muo *MetricUpdateOne) RemoveHistograms(h ...*Histogram) *MetricUpdateOne { ids := make([]int, len(h)) for i := range h { @@ -568,19 +500,19 @@ func (muo *MetricUpdateOne) RemoveHistograms(h ...*Histogram) *MetricUpdateOne { return muo.RemoveHistogramIDs(ids...) } -// ClearCounters clears all "counters" edges to type Counter. +// ClearCounters clears all "counters" edges to the Counter entity. func (muo *MetricUpdateOne) ClearCounters() *MetricUpdateOne { muo.mutation.ClearCounters() return muo } -// RemoveCounterIDs removes the counters edge to Counter by ids. +// RemoveCounterIDs removes the "counters" edge to Counter entities by IDs. func (muo *MetricUpdateOne) RemoveCounterIDs(ids ...int) *MetricUpdateOne { muo.mutation.RemoveCounterIDs(ids...) return muo } -// RemoveCounters removes counters edges to Counter. +// RemoveCounters removes "counters" edges to Counter entities. func (muo *MetricUpdateOne) RemoveCounters(c ...*Counter) *MetricUpdateOne { ids := make([]int, len(c)) for i := range c { @@ -589,19 +521,19 @@ func (muo *MetricUpdateOne) RemoveCounters(c ...*Counter) *MetricUpdateOne { return muo.RemoveCounterIDs(ids...) } -// ClearGauges clears all "gauges" edges to type Gauge. +// ClearGauges clears all "gauges" edges to the Gauge entity. func (muo *MetricUpdateOne) ClearGauges() *MetricUpdateOne { muo.mutation.ClearGauges() return muo } -// RemoveGaugeIDs removes the gauges edge to Gauge by ids. +// RemoveGaugeIDs removes the "gauges" edge to Gauge entities by IDs. func (muo *MetricUpdateOne) RemoveGaugeIDs(ids ...int) *MetricUpdateOne { muo.mutation.RemoveGaugeIDs(ids...) return muo } -// RemoveGauges removes gauges edges to Gauge. +// RemoveGauges removes "gauges" edges to Gauge entities. func (muo *MetricUpdateOne) RemoveGauges(g ...*Gauge) *MetricUpdateOne { ids := make([]int, len(g)) for i := range g { @@ -610,33 +542,22 @@ func (muo *MetricUpdateOne) RemoveGauges(g ...*Gauge) *MetricUpdateOne { return muo.RemoveGaugeIDs(ids...) } -// Save executes the query and returns the updated entity. +// Where appends a list predicates to the MetricUpdate builder. +func (muo *MetricUpdateOne) Where(ps ...predicate.Metric) *MetricUpdateOne { + muo.mutation.Where(ps...) + return muo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (muo *MetricUpdateOne) Select(field string, fields ...string) *MetricUpdateOne { + muo.fields = append([]string{field}, fields...) + return muo +} + +// Save executes the query and returns the updated Metric entity. func (muo *MetricUpdateOne) Save(ctx context.Context) (*Metric, error) { - var ( - err error - node *Metric - ) - if len(muo.hooks) == 0 { - node, err = muo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*MetricMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - muo.mutation = mutation - node, err = muo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(muo.hooks) - 1; i >= 0; i-- { - mut = muo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, muo.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, muo.sqlSave, muo.mutation, muo.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -662,27 +583,33 @@ func (muo *MetricUpdateOne) ExecX(ctx context.Context) { } func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: metric.Table, - Columns: metric.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: metric.FieldID, - }, - }, - } + _spec := sqlgraph.NewUpdateSpec(metric.Table, metric.Columns, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt)) id, ok := muo.mutation.ID() if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Metric.ID for update")} + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Metric.id" for update`)} } _spec.Node.ID.Value = id + if fields := muo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, metric.FieldID) + for _, f := range fields { + if !metric.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != metric.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := muo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } if value, ok := muo.mutation.GetType(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: metric.FieldType, - }) + _spec.SetField(metric.FieldType, field.TypeString, value) } if muo.mutation.GraphCleared() { edge := &sqlgraph.EdgeSpec{ @@ -692,10 +619,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.GraphColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -708,10 +632,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.GraphColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: graph.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(graph.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -727,10 +648,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.HistogramsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -743,10 +661,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.HistogramsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -762,10 +677,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.HistogramsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: histogram.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(histogram.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -781,10 +693,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.CountersColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -797,10 +706,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.CountersColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -816,10 +722,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.CountersColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: counter.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(counter.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -835,10 +738,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.GaugesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -851,10 +751,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.GaugesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -870,10 +767,7 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err Columns: []string{metric.GaugesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: gauge.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(gauge.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -883,14 +777,15 @@ func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err err } _node = &Metric{config: muo.config} _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues() + _spec.ScanValues = _node.scanValues if err = sqlgraph.UpdateNode(ctx, muo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{metric.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } + muo.mutation.done = true return _node, nil } diff --git a/ent/migrate/migrate.go b/ent/migrate/migrate.go index 7e1d225b..1956a6bf 100644 --- a/ent/migrate/migrate.go +++ b/ent/migrate/migrate.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package migrate @@ -7,8 +7,8 @@ import ( "fmt" "io" - "github.com/facebook/ent/dialect" - "github.com/facebook/ent/dialect/sql/schema" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" ) var ( @@ -28,15 +28,13 @@ var ( // and therefore, it's recommended to enable this option to get more // flexibility in the schema changes. WithDropIndex = schema.WithDropIndex - // WithFixture sets the foreign-key renaming option to the migration when upgrading - // ent from v0.1.0 (issue-#285). Defaults to false. - WithFixture = schema.WithFixture + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys ) // Schema is the API for creating, migrating and dropping a schema. type Schema struct { - drv dialect.Driver - universalID bool + drv dialect.Driver } // NewSchema creates a new schema client. @@ -44,27 +42,23 @@ func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } // Create creates all schema resources. func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { migrate, err := schema.NewMigrate(s.drv, opts...) if err != nil { - return fmt.Errorf("ent/migrate: %v", err) + return fmt.Errorf("ent/migrate: %w", err) } - return migrate.Create(ctx, Tables...) + return migrate.Create(ctx, tables...) } // WriteTo writes the schema changes to w instead of running them against the database. // -// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { // log.Fatal(err) -// } -// +// } func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { - drv := &schema.WriteDriver{ - Writer: w, - Driver: s.drv, - } - migrate, err := schema.NewMigrate(drv, opts...) - if err != nil { - return fmt.Errorf("ent/migrate: %v", err) - } - return migrate.Create(ctx, Tables...) + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) } diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go index bc51aa46..cab91112 100644 --- a/ent/migrate/schema.go +++ b/ent/migrate/schema.go @@ -1,10 +1,10 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package migrate import ( - "github.com/facebook/ent/dialect/sql/schema" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" ) var ( @@ -19,13 +19,13 @@ var ( {Name: "scenario", Type: field.TypeString, Size: 2147483647}, {Name: "gomod", Type: field.TypeString, Size: 2147483647, Default: ""}, {Name: "gosum", Type: field.TypeString, Size: 2147483647, Default: ""}, + {Name: "vu", Type: field.TypeInt, Default: 0}, } // ApplicationsTable holds the schema information for the "applications" table. ApplicationsTable = &schema.Table{ - Name: "applications", - Columns: ApplicationsColumns, - PrimaryKey: []*schema.Column{ApplicationsColumns[0]}, - ForeignKeys: []*schema.ForeignKey{}, + Name: "applications", + Columns: ApplicationsColumns, + PrimaryKey: []*schema.Column{ApplicationsColumns[0]}, } // CountersColumns holds the columns for the "counters" table. CountersColumns = []*schema.Column{ @@ -42,9 +42,8 @@ var ( PrimaryKey: []*schema.Column{CountersColumns[0]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "counters_metrics_counters", - Columns: []*schema.Column{CountersColumns[4]}, - + Symbol: "counters_metrics_counters", + Columns: []*schema.Column{CountersColumns[4]}, RefColumns: []*schema.Column{MetricsColumns[0]}, OnDelete: schema.SetNull, }, @@ -65,9 +64,8 @@ var ( PrimaryKey: []*schema.Column{GaugesColumns[0]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "gauges_metrics_gauges", - Columns: []*schema.Column{GaugesColumns[4]}, - + Symbol: "gauges_metrics_gauges", + Columns: []*schema.Column{GaugesColumns[4]}, RefColumns: []*schema.Column{MetricsColumns[0]}, OnDelete: schema.SetNull, }, @@ -87,9 +85,8 @@ var ( PrimaryKey: []*schema.Column{GraphsColumns[0]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "graphs_groups_graphs", - Columns: []*schema.Column{GraphsColumns[3]}, - + Symbol: "graphs_groups_graphs", + Columns: []*schema.Column{GraphsColumns[3]}, RefColumns: []*schema.Column{GroupsColumns[0]}, OnDelete: schema.SetNull, }, @@ -108,9 +105,8 @@ var ( PrimaryKey: []*schema.Column{GroupsColumns[0]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "groups_applications_groups", - Columns: []*schema.Column{GroupsColumns[2]}, - + Symbol: "groups_applications_groups", + Columns: []*schema.Column{GroupsColumns[2]}, RefColumns: []*schema.Column{ApplicationsColumns[0]}, OnDelete: schema.SetNull, }, @@ -140,9 +136,8 @@ var ( PrimaryKey: []*schema.Column{HistogramsColumns[0]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "histograms_metrics_histograms", - Columns: []*schema.Column{HistogramsColumns[13]}, - + Symbol: "histograms_metrics_histograms", + Columns: []*schema.Column{HistogramsColumns[13]}, RefColumns: []*schema.Column{MetricsColumns[0]}, OnDelete: schema.SetNull, }, @@ -162,9 +157,8 @@ var ( PrimaryKey: []*schema.Column{MetricsColumns[0]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "metrics_graphs_metrics", - Columns: []*schema.Column{MetricsColumns[3]}, - + Symbol: "metrics_graphs_metrics", + Columns: []*schema.Column{MetricsColumns[3]}, RefColumns: []*schema.Column{GraphsColumns[0]}, OnDelete: schema.SetNull, }, @@ -183,9 +177,8 @@ var ( PrimaryKey: []*schema.Column{TagsColumns[0]}, ForeignKeys: []*schema.ForeignKey{ { - Symbol: "tags_applications_tags", - Columns: []*schema.Column{TagsColumns[2]}, - + Symbol: "tags_applications_tags", + Columns: []*schema.Column{TagsColumns[2]}, RefColumns: []*schema.Column{ApplicationsColumns[0]}, OnDelete: schema.SetNull, }, diff --git a/ent/mutation.go b/ent/mutation.go index 4371d868..d85bf031 100644 --- a/ent/mutation.go +++ b/ent/mutation.go @@ -1,13 +1,16 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" "sync" "time" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/counter" "github.com/gobench-io/gobench/v2/ent/gauge" @@ -15,9 +18,8 @@ import ( "github.com/gobench-io/gobench/v2/ent/group" "github.com/gobench-io/gobench/v2/ent/histogram" "github.com/gobench-io/gobench/v2/ent/metric" + "github.com/gobench-io/gobench/v2/ent/predicate" "github.com/gobench-io/gobench/v2/ent/tag" - - "github.com/facebook/ent" ) const ( @@ -39,8 +41,7 @@ const ( TypeTag = "Tag" ) -// ApplicationMutation represents an operation that mutate the Applications -// nodes in the graph. +// ApplicationMutation represents an operation that mutates the Application nodes in the graph. type ApplicationMutation struct { config op Op @@ -54,6 +55,8 @@ type ApplicationMutation struct { scenario *string gomod *string gosum *string + vu *int + addvu *int clearedFields map[string]struct{} groups map[int]struct{} removedgroups map[int]struct{} @@ -63,14 +66,15 @@ type ApplicationMutation struct { clearedtags bool done bool oldValue func(context.Context) (*Application, error) + predicates []predicate.Application } var _ ent.Mutation = (*ApplicationMutation)(nil) -// applicationOption allows to manage the mutation configuration using functional options. +// applicationOption allows management of the mutation configuration using functional options. type applicationOption func(*ApplicationMutation) -// newApplicationMutation creates new mutation for $n.Name. +// newApplicationMutation creates new mutation for the Application entity. func newApplicationMutation(c config, op Op, opts ...applicationOption) *ApplicationMutation { m := &ApplicationMutation{ config: c, @@ -84,7 +88,7 @@ func newApplicationMutation(c config, op Op, opts ...applicationOption) *Applica return m } -// withApplicationID sets the id field of the mutation. +// withApplicationID sets the ID field of the mutation. func withApplicationID(id int) applicationOption { return func(m *ApplicationMutation) { var ( @@ -95,7 +99,7 @@ func withApplicationID(id int) applicationOption { m.oldValue = func(ctx context.Context) (*Application, error) { once.Do(func() { if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") + err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().Application.Get(ctx, id) } @@ -128,15 +132,15 @@ func (m ApplicationMutation) Client() *Client { // it returns an error otherwise. func (m ApplicationMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("ent: mutation is not running in a transaction") + return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } -// ID returns the id value in the mutation. Note that, the id -// is available only if it was provided to the builder. +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. func (m *ApplicationMutation) ID() (id int, exists bool) { if m.id == nil { return @@ -144,12 +148,31 @@ func (m *ApplicationMutation) ID() (id int, exists bool) { return *m.id, true } -// SetName sets the name field. +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *ApplicationMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Application.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. func (m *ApplicationMutation) SetName(s string) { m.name = &s } -// Name returns the name value in the mutation. +// Name returns the value of the "name" field in the mutation. func (m *ApplicationMutation) Name() (r string, exists bool) { v := m.name if v == nil { @@ -158,16 +181,15 @@ func (m *ApplicationMutation) Name() (r string, exists bool) { return *v, true } -// OldName returns the old name value of the Application. -// If the Application object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldName returns the old "name" field's value of the Application entity. +// If the Application object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *ApplicationMutation) OldName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldName is allowed only on UpdateOne operations") + return v, errors.New("OldName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldName requires an ID field in the mutation") + return v, errors.New("OldName requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -176,17 +198,17 @@ func (m *ApplicationMutation) OldName(ctx context.Context) (v string, err error) return oldValue.Name, nil } -// ResetName reset all changes of the "name" field. +// ResetName resets all changes to the "name" field. func (m *ApplicationMutation) ResetName() { m.name = nil } -// SetStatus sets the status field. +// SetStatus sets the "status" field. func (m *ApplicationMutation) SetStatus(s string) { m.status = &s } -// Status returns the status value in the mutation. +// Status returns the value of the "status" field in the mutation. func (m *ApplicationMutation) Status() (r string, exists bool) { v := m.status if v == nil { @@ -195,16 +217,15 @@ func (m *ApplicationMutation) Status() (r string, exists bool) { return *v, true } -// OldStatus returns the old status value of the Application. -// If the Application object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldStatus returns the old "status" field's value of the Application entity. +// If the Application object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *ApplicationMutation) OldStatus(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldStatus is allowed only on UpdateOne operations") + return v, errors.New("OldStatus is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldStatus requires an ID field in the mutation") + return v, errors.New("OldStatus requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -213,17 +234,17 @@ func (m *ApplicationMutation) OldStatus(ctx context.Context) (v string, err erro return oldValue.Status, nil } -// ResetStatus reset all changes of the "status" field. +// ResetStatus resets all changes to the "status" field. func (m *ApplicationMutation) ResetStatus() { m.status = nil } -// SetCreatedAt sets the created_at field. +// SetCreatedAt sets the "created_at" field. func (m *ApplicationMutation) SetCreatedAt(t time.Time) { m.created_at = &t } -// CreatedAt returns the created_at value in the mutation. +// CreatedAt returns the value of the "created_at" field in the mutation. func (m *ApplicationMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { @@ -232,16 +253,15 @@ func (m *ApplicationMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old created_at value of the Application. -// If the Application object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldCreatedAt returns the old "created_at" field's value of the Application entity. +// If the Application object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *ApplicationMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldCreatedAt is allowed only on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldCreatedAt requires an ID field in the mutation") + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -250,17 +270,17 @@ func (m *ApplicationMutation) OldCreatedAt(ctx context.Context) (v time.Time, er return oldValue.CreatedAt, nil } -// ResetCreatedAt reset all changes of the "created_at" field. +// ResetCreatedAt resets all changes to the "created_at" field. func (m *ApplicationMutation) ResetCreatedAt() { m.created_at = nil } -// SetStartedAt sets the started_at field. +// SetStartedAt sets the "started_at" field. func (m *ApplicationMutation) SetStartedAt(t time.Time) { m.started_at = &t } -// StartedAt returns the started_at value in the mutation. +// StartedAt returns the value of the "started_at" field in the mutation. func (m *ApplicationMutation) StartedAt() (r time.Time, exists bool) { v := m.started_at if v == nil { @@ -269,16 +289,15 @@ func (m *ApplicationMutation) StartedAt() (r time.Time, exists bool) { return *v, true } -// OldStartedAt returns the old started_at value of the Application. -// If the Application object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldStartedAt returns the old "started_at" field's value of the Application entity. +// If the Application object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *ApplicationMutation) OldStartedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldStartedAt is allowed only on UpdateOne operations") + return v, errors.New("OldStartedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldStartedAt requires an ID field in the mutation") + return v, errors.New("OldStartedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -287,30 +306,30 @@ func (m *ApplicationMutation) OldStartedAt(ctx context.Context) (v time.Time, er return oldValue.StartedAt, nil } -// ClearStartedAt clears the value of started_at. +// ClearStartedAt clears the value of the "started_at" field. func (m *ApplicationMutation) ClearStartedAt() { m.started_at = nil m.clearedFields[application.FieldStartedAt] = struct{}{} } -// StartedAtCleared returns if the field started_at was cleared in this mutation. +// StartedAtCleared returns if the "started_at" field was cleared in this mutation. func (m *ApplicationMutation) StartedAtCleared() bool { _, ok := m.clearedFields[application.FieldStartedAt] return ok } -// ResetStartedAt reset all changes of the "started_at" field. +// ResetStartedAt resets all changes to the "started_at" field. func (m *ApplicationMutation) ResetStartedAt() { m.started_at = nil delete(m.clearedFields, application.FieldStartedAt) } -// SetUpdatedAt sets the updated_at field. +// SetUpdatedAt sets the "updated_at" field. func (m *ApplicationMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } -// UpdatedAt returns the updated_at value in the mutation. +// UpdatedAt returns the value of the "updated_at" field in the mutation. func (m *ApplicationMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { @@ -319,16 +338,15 @@ func (m *ApplicationMutation) UpdatedAt() (r time.Time, exists bool) { return *v, true } -// OldUpdatedAt returns the old updated_at value of the Application. -// If the Application object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldUpdatedAt returns the old "updated_at" field's value of the Application entity. +// If the Application object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *ApplicationMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldUpdatedAt is allowed only on UpdateOne operations") + return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldUpdatedAt requires an ID field in the mutation") + return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -337,17 +355,17 @@ func (m *ApplicationMutation) OldUpdatedAt(ctx context.Context) (v time.Time, er return oldValue.UpdatedAt, nil } -// ResetUpdatedAt reset all changes of the "updated_at" field. +// ResetUpdatedAt resets all changes to the "updated_at" field. func (m *ApplicationMutation) ResetUpdatedAt() { m.updated_at = nil } -// SetScenario sets the scenario field. +// SetScenario sets the "scenario" field. func (m *ApplicationMutation) SetScenario(s string) { m.scenario = &s } -// Scenario returns the scenario value in the mutation. +// Scenario returns the value of the "scenario" field in the mutation. func (m *ApplicationMutation) Scenario() (r string, exists bool) { v := m.scenario if v == nil { @@ -356,16 +374,15 @@ func (m *ApplicationMutation) Scenario() (r string, exists bool) { return *v, true } -// OldScenario returns the old scenario value of the Application. -// If the Application object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldScenario returns the old "scenario" field's value of the Application entity. +// If the Application object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *ApplicationMutation) OldScenario(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldScenario is allowed only on UpdateOne operations") + return v, errors.New("OldScenario is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldScenario requires an ID field in the mutation") + return v, errors.New("OldScenario requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -374,17 +391,17 @@ func (m *ApplicationMutation) OldScenario(ctx context.Context) (v string, err er return oldValue.Scenario, nil } -// ResetScenario reset all changes of the "scenario" field. +// ResetScenario resets all changes to the "scenario" field. func (m *ApplicationMutation) ResetScenario() { m.scenario = nil } -// SetGomod sets the gomod field. +// SetGomod sets the "gomod" field. func (m *ApplicationMutation) SetGomod(s string) { m.gomod = &s } -// Gomod returns the gomod value in the mutation. +// Gomod returns the value of the "gomod" field in the mutation. func (m *ApplicationMutation) Gomod() (r string, exists bool) { v := m.gomod if v == nil { @@ -393,16 +410,15 @@ func (m *ApplicationMutation) Gomod() (r string, exists bool) { return *v, true } -// OldGomod returns the old gomod value of the Application. -// If the Application object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldGomod returns the old "gomod" field's value of the Application entity. +// If the Application object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *ApplicationMutation) OldGomod(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldGomod is allowed only on UpdateOne operations") + return v, errors.New("OldGomod is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldGomod requires an ID field in the mutation") + return v, errors.New("OldGomod requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -411,17 +427,17 @@ func (m *ApplicationMutation) OldGomod(ctx context.Context) (v string, err error return oldValue.Gomod, nil } -// ResetGomod reset all changes of the "gomod" field. +// ResetGomod resets all changes to the "gomod" field. func (m *ApplicationMutation) ResetGomod() { m.gomod = nil } -// SetGosum sets the gosum field. +// SetGosum sets the "gosum" field. func (m *ApplicationMutation) SetGosum(s string) { m.gosum = &s } -// Gosum returns the gosum value in the mutation. +// Gosum returns the value of the "gosum" field in the mutation. func (m *ApplicationMutation) Gosum() (r string, exists bool) { v := m.gosum if v == nil { @@ -430,16 +446,15 @@ func (m *ApplicationMutation) Gosum() (r string, exists bool) { return *v, true } -// OldGosum returns the old gosum value of the Application. -// If the Application object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldGosum returns the old "gosum" field's value of the Application entity. +// If the Application object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *ApplicationMutation) OldGosum(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldGosum is allowed only on UpdateOne operations") + return v, errors.New("OldGosum is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldGosum requires an ID field in the mutation") + return v, errors.New("OldGosum requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -448,12 +463,68 @@ func (m *ApplicationMutation) OldGosum(ctx context.Context) (v string, err error return oldValue.Gosum, nil } -// ResetGosum reset all changes of the "gosum" field. +// ResetGosum resets all changes to the "gosum" field. func (m *ApplicationMutation) ResetGosum() { m.gosum = nil } -// AddGroupIDs adds the groups edge to Group by ids. +// SetVu sets the "vu" field. +func (m *ApplicationMutation) SetVu(i int) { + m.vu = &i + m.addvu = nil +} + +// Vu returns the value of the "vu" field in the mutation. +func (m *ApplicationMutation) Vu() (r int, exists bool) { + v := m.vu + if v == nil { + return + } + return *v, true +} + +// OldVu returns the old "vu" field's value of the Application entity. +// If the Application object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *ApplicationMutation) OldVu(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVu is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVu requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVu: %w", err) + } + return oldValue.Vu, nil +} + +// AddVu adds i to the "vu" field. +func (m *ApplicationMutation) AddVu(i int) { + if m.addvu != nil { + *m.addvu += i + } else { + m.addvu = &i + } +} + +// AddedVu returns the value that was added to the "vu" field in this mutation. +func (m *ApplicationMutation) AddedVu() (r int, exists bool) { + v := m.addvu + if v == nil { + return + } + return *v, true +} + +// ResetVu resets all changes to the "vu" field. +func (m *ApplicationMutation) ResetVu() { + m.vu = nil + m.addvu = nil +} + +// AddGroupIDs adds the "groups" edge to the Group entity by ids. func (m *ApplicationMutation) AddGroupIDs(ids ...int) { if m.groups == nil { m.groups = make(map[int]struct{}) @@ -463,27 +534,28 @@ func (m *ApplicationMutation) AddGroupIDs(ids ...int) { } } -// ClearGroups clears the groups edge to Group. +// ClearGroups clears the "groups" edge to the Group entity. func (m *ApplicationMutation) ClearGroups() { m.clearedgroups = true } -// GroupsCleared returns if the edge groups was cleared. +// GroupsCleared reports if the "groups" edge to the Group entity was cleared. func (m *ApplicationMutation) GroupsCleared() bool { return m.clearedgroups } -// RemoveGroupIDs removes the groups edge to Group by ids. +// RemoveGroupIDs removes the "groups" edge to the Group entity by IDs. func (m *ApplicationMutation) RemoveGroupIDs(ids ...int) { if m.removedgroups == nil { m.removedgroups = make(map[int]struct{}) } for i := range ids { + delete(m.groups, ids[i]) m.removedgroups[ids[i]] = struct{}{} } } -// RemovedGroups returns the removed ids of groups. +// RemovedGroups returns the removed IDs of the "groups" edge to the Group entity. func (m *ApplicationMutation) RemovedGroupsIDs() (ids []int) { for id := range m.removedgroups { ids = append(ids, id) @@ -491,7 +563,7 @@ func (m *ApplicationMutation) RemovedGroupsIDs() (ids []int) { return } -// GroupsIDs returns the groups ids in the mutation. +// GroupsIDs returns the "groups" edge IDs in the mutation. func (m *ApplicationMutation) GroupsIDs() (ids []int) { for id := range m.groups { ids = append(ids, id) @@ -499,14 +571,14 @@ func (m *ApplicationMutation) GroupsIDs() (ids []int) { return } -// ResetGroups reset all changes of the "groups" edge. +// ResetGroups resets all changes to the "groups" edge. func (m *ApplicationMutation) ResetGroups() { m.groups = nil m.clearedgroups = false m.removedgroups = nil } -// AddTagIDs adds the tags edge to Tag by ids. +// AddTagIDs adds the "tags" edge to the Tag entity by ids. func (m *ApplicationMutation) AddTagIDs(ids ...int) { if m.tags == nil { m.tags = make(map[int]struct{}) @@ -516,27 +588,28 @@ func (m *ApplicationMutation) AddTagIDs(ids ...int) { } } -// ClearTags clears the tags edge to Tag. +// ClearTags clears the "tags" edge to the Tag entity. func (m *ApplicationMutation) ClearTags() { m.clearedtags = true } -// TagsCleared returns if the edge tags was cleared. +// TagsCleared reports if the "tags" edge to the Tag entity was cleared. func (m *ApplicationMutation) TagsCleared() bool { return m.clearedtags } -// RemoveTagIDs removes the tags edge to Tag by ids. +// RemoveTagIDs removes the "tags" edge to the Tag entity by IDs. func (m *ApplicationMutation) RemoveTagIDs(ids ...int) { if m.removedtags == nil { m.removedtags = make(map[int]struct{}) } for i := range ids { + delete(m.tags, ids[i]) m.removedtags[ids[i]] = struct{}{} } } -// RemovedTags returns the removed ids of tags. +// RemovedTags returns the removed IDs of the "tags" edge to the Tag entity. func (m *ApplicationMutation) RemovedTagsIDs() (ids []int) { for id := range m.removedtags { ids = append(ids, id) @@ -544,7 +617,7 @@ func (m *ApplicationMutation) RemovedTagsIDs() (ids []int) { return } -// TagsIDs returns the tags ids in the mutation. +// TagsIDs returns the "tags" edge IDs in the mutation. func (m *ApplicationMutation) TagsIDs() (ids []int) { for id := range m.tags { ids = append(ids, id) @@ -552,28 +625,48 @@ func (m *ApplicationMutation) TagsIDs() (ids []int) { return } -// ResetTags reset all changes of the "tags" edge. +// ResetTags resets all changes to the "tags" edge. func (m *ApplicationMutation) ResetTags() { m.tags = nil m.clearedtags = false m.removedtags = nil } +// Where appends a list predicates to the ApplicationMutation builder. +func (m *ApplicationMutation) Where(ps ...predicate.Application) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ApplicationMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ApplicationMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Application, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + // Op returns the operation name. func (m *ApplicationMutation) Op() Op { return m.op } +// SetOp allows setting the mutation operation. +func (m *ApplicationMutation) SetOp(op Op) { + m.op = op +} + // Type returns the node type of this mutation (Application). func (m *ApplicationMutation) Type() string { return m.typ } -// Fields returns all fields that were changed during -// this mutation. Note that, in order to get all numeric -// fields that were in/decremented, call AddedFields(). +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). func (m *ApplicationMutation) Fields() []string { - fields := make([]string, 0, 8) + fields := make([]string, 0, 9) if m.name != nil { fields = append(fields, application.FieldName) } @@ -598,12 +691,15 @@ func (m *ApplicationMutation) Fields() []string { if m.gosum != nil { fields = append(fields, application.FieldGosum) } + if m.vu != nil { + fields = append(fields, application.FieldVu) + } return fields } -// Field returns the value of a field with the given name. -// The second boolean value indicates that this field was -// not set, or was not define in the schema. +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. func (m *ApplicationMutation) Field(name string) (ent.Value, bool) { switch name { case application.FieldName: @@ -622,13 +718,15 @@ func (m *ApplicationMutation) Field(name string) (ent.Value, bool) { return m.Gomod() case application.FieldGosum: return m.Gosum() + case application.FieldVu: + return m.Vu() } return nil, false } -// OldField returns the old value of the field from the database. -// An error is returned if the mutation operation is not UpdateOne, -// or the query to the database was failed. +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. func (m *ApplicationMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { case application.FieldName: @@ -647,13 +745,15 @@ func (m *ApplicationMutation) OldField(ctx context.Context, name string) (ent.Va return m.OldGomod(ctx) case application.FieldGosum: return m.OldGosum(ctx) + case application.FieldVu: + return m.OldVu(ctx) } return nil, fmt.Errorf("unknown Application field %s", name) } -// SetField sets the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *ApplicationMutation) SetField(name string, value ent.Value) error { switch name { case application.FieldName: @@ -712,34 +812,56 @@ func (m *ApplicationMutation) SetField(name string, value ent.Value) error { } m.SetGosum(v) return nil + case application.FieldVu: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVu(v) + return nil } return fmt.Errorf("unknown Application field %s", name) } -// AddedFields returns all numeric fields that were incremented -// or decremented during this mutation. +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. func (m *ApplicationMutation) AddedFields() []string { - return nil + var fields []string + if m.addvu != nil { + fields = append(fields, application.FieldVu) + } + return fields } -// AddedField returns the numeric value that was in/decremented -// from a field with the given name. The second value indicates -// that this field was not set, or was not define in the schema. +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. func (m *ApplicationMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case application.FieldVu: + return m.AddedVu() + } return nil, false } -// AddField adds the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *ApplicationMutation) AddField(name string, value ent.Value) error { switch name { + case application.FieldVu: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddVu(v) + return nil } return fmt.Errorf("unknown Application numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared -// during this mutation. +// ClearedFields returns all nullable fields that were cleared during this +// mutation. func (m *ApplicationMutation) ClearedFields() []string { var fields []string if m.FieldCleared(application.FieldStartedAt) { @@ -748,14 +870,14 @@ func (m *ApplicationMutation) ClearedFields() []string { return fields } -// FieldCleared returns a boolean indicates if this field was +// FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. func (m *ApplicationMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } -// ClearField clears the value for the given name. It returns an +// ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *ApplicationMutation) ClearField(name string) error { switch name { @@ -766,9 +888,8 @@ func (m *ApplicationMutation) ClearField(name string) error { return fmt.Errorf("unknown Application nullable field %s", name) } -// ResetField resets all changes in the mutation regarding the -// given field name. It returns an error if the field is not -// defined in the schema. +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. func (m *ApplicationMutation) ResetField(name string) error { switch name { case application.FieldName: @@ -795,12 +916,14 @@ func (m *ApplicationMutation) ResetField(name string) error { case application.FieldGosum: m.ResetGosum() return nil + case application.FieldVu: + m.ResetVu() + return nil } return fmt.Errorf("unknown Application field %s", name) } -// AddedEdges returns all edge names that were set/added in this -// mutation. +// AddedEdges returns all edge names that were set/added in this mutation. func (m *ApplicationMutation) AddedEdges() []string { edges := make([]string, 0, 2) if m.groups != nil { @@ -812,8 +935,8 @@ func (m *ApplicationMutation) AddedEdges() []string { return edges } -// AddedIDs returns all ids (to other nodes) that were added for -// the given edge name. +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. func (m *ApplicationMutation) AddedIDs(name string) []ent.Value { switch name { case application.EdgeGroups: @@ -832,8 +955,7 @@ func (m *ApplicationMutation) AddedIDs(name string) []ent.Value { return nil } -// RemovedEdges returns all edge names that were removed in this -// mutation. +// RemovedEdges returns all edge names that were removed in this mutation. func (m *ApplicationMutation) RemovedEdges() []string { edges := make([]string, 0, 2) if m.removedgroups != nil { @@ -845,8 +967,8 @@ func (m *ApplicationMutation) RemovedEdges() []string { return edges } -// RemovedIDs returns all ids (to other nodes) that were removed for -// the given edge name. +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. func (m *ApplicationMutation) RemovedIDs(name string) []ent.Value { switch name { case application.EdgeGroups: @@ -865,8 +987,7 @@ func (m *ApplicationMutation) RemovedIDs(name string) []ent.Value { return nil } -// ClearedEdges returns all edge names that were cleared in this -// mutation. +// ClearedEdges returns all edge names that were cleared in this mutation. func (m *ApplicationMutation) ClearedEdges() []string { edges := make([]string, 0, 2) if m.clearedgroups { @@ -878,8 +999,8 @@ func (m *ApplicationMutation) ClearedEdges() []string { return edges } -// EdgeCleared returns a boolean indicates if this edge was -// cleared in this mutation. +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. func (m *ApplicationMutation) EdgeCleared(name string) bool { switch name { case application.EdgeGroups: @@ -890,17 +1011,16 @@ func (m *ApplicationMutation) EdgeCleared(name string) bool { return false } -// ClearEdge clears the value for the given name. It returns an -// error if the edge name is not defined in the schema. +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. func (m *ApplicationMutation) ClearEdge(name string) error { switch name { } return fmt.Errorf("unknown Application unique edge %s", name) } -// ResetEdge resets all changes in the mutation regarding the -// given edge name. It returns an error if the edge is not -// defined in the schema. +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. func (m *ApplicationMutation) ResetEdge(name string) error { switch name { case application.EdgeGroups: @@ -913,8 +1033,7 @@ func (m *ApplicationMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Application edge %s", name) } -// CounterMutation represents an operation that mutate the Counters -// nodes in the graph. +// CounterMutation represents an operation that mutates the Counter nodes in the graph. type CounterMutation struct { config op Op @@ -930,14 +1049,15 @@ type CounterMutation struct { clearedmetric bool done bool oldValue func(context.Context) (*Counter, error) + predicates []predicate.Counter } var _ ent.Mutation = (*CounterMutation)(nil) -// counterOption allows to manage the mutation configuration using functional options. +// counterOption allows management of the mutation configuration using functional options. type counterOption func(*CounterMutation) -// newCounterMutation creates new mutation for $n.Name. +// newCounterMutation creates new mutation for the Counter entity. func newCounterMutation(c config, op Op, opts ...counterOption) *CounterMutation { m := &CounterMutation{ config: c, @@ -951,7 +1071,7 @@ func newCounterMutation(c config, op Op, opts ...counterOption) *CounterMutation return m } -// withCounterID sets the id field of the mutation. +// withCounterID sets the ID field of the mutation. func withCounterID(id int) counterOption { return func(m *CounterMutation) { var ( @@ -962,7 +1082,7 @@ func withCounterID(id int) counterOption { m.oldValue = func(ctx context.Context) (*Counter, error) { once.Do(func() { if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") + err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().Counter.Get(ctx, id) } @@ -995,15 +1115,15 @@ func (m CounterMutation) Client() *Client { // it returns an error otherwise. func (m CounterMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("ent: mutation is not running in a transaction") + return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } -// ID returns the id value in the mutation. Note that, the id -// is available only if it was provided to the builder. +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. func (m *CounterMutation) ID() (id int, exists bool) { if m.id == nil { return @@ -1011,13 +1131,32 @@ func (m *CounterMutation) ID() (id int, exists bool) { return *m.id, true } -// SetTime sets the time field. +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *CounterMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Counter.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTime sets the "time" field. func (m *CounterMutation) SetTime(i int64) { m.time = &i m.addtime = nil } -// Time returns the time value in the mutation. +// Time returns the value of the "time" field in the mutation. func (m *CounterMutation) Time() (r int64, exists bool) { v := m.time if v == nil { @@ -1026,16 +1165,15 @@ func (m *CounterMutation) Time() (r int64, exists bool) { return *v, true } -// OldTime returns the old time value of the Counter. -// If the Counter object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldTime returns the old "time" field's value of the Counter entity. +// If the Counter object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CounterMutation) OldTime(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldTime is allowed only on UpdateOne operations") + return v, errors.New("OldTime is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldTime requires an ID field in the mutation") + return v, errors.New("OldTime requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -1044,7 +1182,7 @@ func (m *CounterMutation) OldTime(ctx context.Context) (v int64, err error) { return oldValue.Time, nil } -// AddTime adds i to time. +// AddTime adds i to the "time" field. func (m *CounterMutation) AddTime(i int64) { if m.addtime != nil { *m.addtime += i @@ -1053,7 +1191,7 @@ func (m *CounterMutation) AddTime(i int64) { } } -// AddedTime returns the value that was added to the time field in this mutation. +// AddedTime returns the value that was added to the "time" field in this mutation. func (m *CounterMutation) AddedTime() (r int64, exists bool) { v := m.addtime if v == nil { @@ -1062,19 +1200,19 @@ func (m *CounterMutation) AddedTime() (r int64, exists bool) { return *v, true } -// ResetTime reset all changes of the "time" field. +// ResetTime resets all changes to the "time" field. func (m *CounterMutation) ResetTime() { m.time = nil m.addtime = nil } -// SetCount sets the count field. +// SetCount sets the "count" field. func (m *CounterMutation) SetCount(i int64) { m.count = &i m.addcount = nil } -// Count returns the count value in the mutation. +// Count returns the value of the "count" field in the mutation. func (m *CounterMutation) Count() (r int64, exists bool) { v := m.count if v == nil { @@ -1083,16 +1221,15 @@ func (m *CounterMutation) Count() (r int64, exists bool) { return *v, true } -// OldCount returns the old count value of the Counter. -// If the Counter object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldCount returns the old "count" field's value of the Counter entity. +// If the Counter object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CounterMutation) OldCount(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldCount is allowed only on UpdateOne operations") + return v, errors.New("OldCount is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldCount requires an ID field in the mutation") + return v, errors.New("OldCount requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -1101,7 +1238,7 @@ func (m *CounterMutation) OldCount(ctx context.Context) (v int64, err error) { return oldValue.Count, nil } -// AddCount adds i to count. +// AddCount adds i to the "count" field. func (m *CounterMutation) AddCount(i int64) { if m.addcount != nil { *m.addcount += i @@ -1110,7 +1247,7 @@ func (m *CounterMutation) AddCount(i int64) { } } -// AddedCount returns the value that was added to the count field in this mutation. +// AddedCount returns the value that was added to the "count" field in this mutation. func (m *CounterMutation) AddedCount() (r int64, exists bool) { v := m.addcount if v == nil { @@ -1119,18 +1256,18 @@ func (m *CounterMutation) AddedCount() (r int64, exists bool) { return *v, true } -// ResetCount reset all changes of the "count" field. +// ResetCount resets all changes to the "count" field. func (m *CounterMutation) ResetCount() { m.count = nil m.addcount = nil } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (m *CounterMutation) SetWID(s string) { m.wID = &s } -// WID returns the wID value in the mutation. +// WID returns the value of the "wID" field in the mutation. func (m *CounterMutation) WID() (r string, exists bool) { v := m.wID if v == nil { @@ -1139,16 +1276,15 @@ func (m *CounterMutation) WID() (r string, exists bool) { return *v, true } -// OldWID returns the old wID value of the Counter. -// If the Counter object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldWID returns the old "wID" field's value of the Counter entity. +// If the Counter object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *CounterMutation) OldWID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldWID is allowed only on UpdateOne operations") + return v, errors.New("OldWID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldWID requires an ID field in the mutation") + return v, errors.New("OldWID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -1157,27 +1293,27 @@ func (m *CounterMutation) OldWID(ctx context.Context) (v string, err error) { return oldValue.WID, nil } -// ResetWID reset all changes of the "wID" field. +// ResetWID resets all changes to the "wID" field. func (m *CounterMutation) ResetWID() { m.wID = nil } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by id. func (m *CounterMutation) SetMetricID(id int) { m.metric = &id } -// ClearMetric clears the metric edge to Metric. +// ClearMetric clears the "metric" edge to the Metric entity. func (m *CounterMutation) ClearMetric() { m.clearedmetric = true } -// MetricCleared returns if the edge metric was cleared. +// MetricCleared reports if the "metric" edge to the Metric entity was cleared. func (m *CounterMutation) MetricCleared() bool { return m.clearedmetric } -// MetricID returns the metric id in the mutation. +// MetricID returns the "metric" edge ID in the mutation. func (m *CounterMutation) MetricID() (id int, exists bool) { if m.metric != nil { return *m.metric, true @@ -1185,8 +1321,8 @@ func (m *CounterMutation) MetricID() (id int, exists bool) { return } -// MetricIDs returns the metric ids in the mutation. -// Note that ids always returns len(ids) <= 1 for unique edges, and you should use +// MetricIDs returns the "metric" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // MetricID instead. It exists only for internal usage by the builders. func (m *CounterMutation) MetricIDs() (ids []int) { if id := m.metric; id != nil { @@ -1195,25 +1331,45 @@ func (m *CounterMutation) MetricIDs() (ids []int) { return } -// ResetMetric reset all changes of the "metric" edge. +// ResetMetric resets all changes to the "metric" edge. func (m *CounterMutation) ResetMetric() { m.metric = nil m.clearedmetric = false } +// Where appends a list predicates to the CounterMutation builder. +func (m *CounterMutation) Where(ps ...predicate.Counter) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CounterMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CounterMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Counter, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + // Op returns the operation name. func (m *CounterMutation) Op() Op { return m.op } +// SetOp allows setting the mutation operation. +func (m *CounterMutation) SetOp(op Op) { + m.op = op +} + // Type returns the node type of this mutation (Counter). func (m *CounterMutation) Type() string { return m.typ } -// Fields returns all fields that were changed during -// this mutation. Note that, in order to get all numeric -// fields that were in/decremented, call AddedFields(). +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). func (m *CounterMutation) Fields() []string { fields := make([]string, 0, 3) if m.time != nil { @@ -1228,9 +1384,9 @@ func (m *CounterMutation) Fields() []string { return fields } -// Field returns the value of a field with the given name. -// The second boolean value indicates that this field was -// not set, or was not define in the schema. +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. func (m *CounterMutation) Field(name string) (ent.Value, bool) { switch name { case counter.FieldTime: @@ -1243,9 +1399,9 @@ func (m *CounterMutation) Field(name string) (ent.Value, bool) { return nil, false } -// OldField returns the old value of the field from the database. -// An error is returned if the mutation operation is not UpdateOne, -// or the query to the database was failed. +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. func (m *CounterMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { case counter.FieldTime: @@ -1258,9 +1414,9 @@ func (m *CounterMutation) OldField(ctx context.Context, name string) (ent.Value, return nil, fmt.Errorf("unknown Counter field %s", name) } -// SetField sets the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *CounterMutation) SetField(name string, value ent.Value) error { switch name { case counter.FieldTime: @@ -1288,8 +1444,8 @@ func (m *CounterMutation) SetField(name string, value ent.Value) error { return fmt.Errorf("unknown Counter field %s", name) } -// AddedFields returns all numeric fields that were incremented -// or decremented during this mutation. +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. func (m *CounterMutation) AddedFields() []string { var fields []string if m.addtime != nil { @@ -1301,9 +1457,9 @@ func (m *CounterMutation) AddedFields() []string { return fields } -// AddedField returns the numeric value that was in/decremented -// from a field with the given name. The second value indicates -// that this field was not set, or was not define in the schema. +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. func (m *CounterMutation) AddedField(name string) (ent.Value, bool) { switch name { case counter.FieldTime: @@ -1314,9 +1470,9 @@ func (m *CounterMutation) AddedField(name string) (ent.Value, bool) { return nil, false } -// AddField adds the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *CounterMutation) AddField(name string, value ent.Value) error { switch name { case counter.FieldTime: @@ -1337,28 +1493,27 @@ func (m *CounterMutation) AddField(name string, value ent.Value) error { return fmt.Errorf("unknown Counter numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared -// during this mutation. +// ClearedFields returns all nullable fields that were cleared during this +// mutation. func (m *CounterMutation) ClearedFields() []string { return nil } -// FieldCleared returns a boolean indicates if this field was +// FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. func (m *CounterMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } -// ClearField clears the value for the given name. It returns an +// ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *CounterMutation) ClearField(name string) error { return fmt.Errorf("unknown Counter nullable field %s", name) } -// ResetField resets all changes in the mutation regarding the -// given field name. It returns an error if the field is not -// defined in the schema. +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. func (m *CounterMutation) ResetField(name string) error { switch name { case counter.FieldTime: @@ -1374,8 +1529,7 @@ func (m *CounterMutation) ResetField(name string) error { return fmt.Errorf("unknown Counter field %s", name) } -// AddedEdges returns all edge names that were set/added in this -// mutation. +// AddedEdges returns all edge names that were set/added in this mutation. func (m *CounterMutation) AddedEdges() []string { edges := make([]string, 0, 1) if m.metric != nil { @@ -1384,8 +1538,8 @@ func (m *CounterMutation) AddedEdges() []string { return edges } -// AddedIDs returns all ids (to other nodes) that were added for -// the given edge name. +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. func (m *CounterMutation) AddedIDs(name string) []ent.Value { switch name { case counter.EdgeMetric: @@ -1396,23 +1550,19 @@ func (m *CounterMutation) AddedIDs(name string) []ent.Value { return nil } -// RemovedEdges returns all edge names that were removed in this -// mutation. +// RemovedEdges returns all edge names that were removed in this mutation. func (m *CounterMutation) RemovedEdges() []string { edges := make([]string, 0, 1) return edges } -// RemovedIDs returns all ids (to other nodes) that were removed for -// the given edge name. +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. func (m *CounterMutation) RemovedIDs(name string) []ent.Value { - switch name { - } return nil } -// ClearedEdges returns all edge names that were cleared in this -// mutation. +// ClearedEdges returns all edge names that were cleared in this mutation. func (m *CounterMutation) ClearedEdges() []string { edges := make([]string, 0, 1) if m.clearedmetric { @@ -1421,8 +1571,8 @@ func (m *CounterMutation) ClearedEdges() []string { return edges } -// EdgeCleared returns a boolean indicates if this edge was -// cleared in this mutation. +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. func (m *CounterMutation) EdgeCleared(name string) bool { switch name { case counter.EdgeMetric: @@ -1431,8 +1581,8 @@ func (m *CounterMutation) EdgeCleared(name string) bool { return false } -// ClearEdge clears the value for the given name. It returns an -// error if the edge name is not defined in the schema. +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. func (m *CounterMutation) ClearEdge(name string) error { switch name { case counter.EdgeMetric: @@ -1442,9 +1592,8 @@ func (m *CounterMutation) ClearEdge(name string) error { return fmt.Errorf("unknown Counter unique edge %s", name) } -// ResetEdge resets all changes in the mutation regarding the -// given edge name. It returns an error if the edge is not -// defined in the schema. +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. func (m *CounterMutation) ResetEdge(name string) error { switch name { case counter.EdgeMetric: @@ -1454,8 +1603,7 @@ func (m *CounterMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Counter edge %s", name) } -// GaugeMutation represents an operation that mutate the Gauges -// nodes in the graph. +// GaugeMutation represents an operation that mutates the Gauge nodes in the graph. type GaugeMutation struct { config op Op @@ -1471,14 +1619,15 @@ type GaugeMutation struct { clearedmetric bool done bool oldValue func(context.Context) (*Gauge, error) + predicates []predicate.Gauge } var _ ent.Mutation = (*GaugeMutation)(nil) -// gaugeOption allows to manage the mutation configuration using functional options. +// gaugeOption allows management of the mutation configuration using functional options. type gaugeOption func(*GaugeMutation) -// newGaugeMutation creates new mutation for $n.Name. +// newGaugeMutation creates new mutation for the Gauge entity. func newGaugeMutation(c config, op Op, opts ...gaugeOption) *GaugeMutation { m := &GaugeMutation{ config: c, @@ -1492,7 +1641,7 @@ func newGaugeMutation(c config, op Op, opts ...gaugeOption) *GaugeMutation { return m } -// withGaugeID sets the id field of the mutation. +// withGaugeID sets the ID field of the mutation. func withGaugeID(id int) gaugeOption { return func(m *GaugeMutation) { var ( @@ -1503,7 +1652,7 @@ func withGaugeID(id int) gaugeOption { m.oldValue = func(ctx context.Context) (*Gauge, error) { once.Do(func() { if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") + err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().Gauge.Get(ctx, id) } @@ -1536,15 +1685,15 @@ func (m GaugeMutation) Client() *Client { // it returns an error otherwise. func (m GaugeMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("ent: mutation is not running in a transaction") + return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } -// ID returns the id value in the mutation. Note that, the id -// is available only if it was provided to the builder. +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. func (m *GaugeMutation) ID() (id int, exists bool) { if m.id == nil { return @@ -1552,13 +1701,32 @@ func (m *GaugeMutation) ID() (id int, exists bool) { return *m.id, true } -// SetTime sets the time field. +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *GaugeMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Gauge.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTime sets the "time" field. func (m *GaugeMutation) SetTime(i int64) { m.time = &i m.addtime = nil } -// Time returns the time value in the mutation. +// Time returns the value of the "time" field in the mutation. func (m *GaugeMutation) Time() (r int64, exists bool) { v := m.time if v == nil { @@ -1567,16 +1735,15 @@ func (m *GaugeMutation) Time() (r int64, exists bool) { return *v, true } -// OldTime returns the old time value of the Gauge. -// If the Gauge object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldTime returns the old "time" field's value of the Gauge entity. +// If the Gauge object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *GaugeMutation) OldTime(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldTime is allowed only on UpdateOne operations") + return v, errors.New("OldTime is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldTime requires an ID field in the mutation") + return v, errors.New("OldTime requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -1585,7 +1752,7 @@ func (m *GaugeMutation) OldTime(ctx context.Context) (v int64, err error) { return oldValue.Time, nil } -// AddTime adds i to time. +// AddTime adds i to the "time" field. func (m *GaugeMutation) AddTime(i int64) { if m.addtime != nil { *m.addtime += i @@ -1594,7 +1761,7 @@ func (m *GaugeMutation) AddTime(i int64) { } } -// AddedTime returns the value that was added to the time field in this mutation. +// AddedTime returns the value that was added to the "time" field in this mutation. func (m *GaugeMutation) AddedTime() (r int64, exists bool) { v := m.addtime if v == nil { @@ -1603,19 +1770,19 @@ func (m *GaugeMutation) AddedTime() (r int64, exists bool) { return *v, true } -// ResetTime reset all changes of the "time" field. +// ResetTime resets all changes to the "time" field. func (m *GaugeMutation) ResetTime() { m.time = nil m.addtime = nil } -// SetValue sets the value field. +// SetValue sets the "value" field. func (m *GaugeMutation) SetValue(i int64) { m.value = &i m.addvalue = nil } -// Value returns the value value in the mutation. +// Value returns the value of the "value" field in the mutation. func (m *GaugeMutation) Value() (r int64, exists bool) { v := m.value if v == nil { @@ -1624,16 +1791,15 @@ func (m *GaugeMutation) Value() (r int64, exists bool) { return *v, true } -// OldValue returns the old value value of the Gauge. -// If the Gauge object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldValue returns the old "value" field's value of the Gauge entity. +// If the Gauge object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *GaugeMutation) OldValue(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldValue is allowed only on UpdateOne operations") + return v, errors.New("OldValue is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldValue requires an ID field in the mutation") + return v, errors.New("OldValue requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -1642,7 +1808,7 @@ func (m *GaugeMutation) OldValue(ctx context.Context) (v int64, err error) { return oldValue.Value, nil } -// AddValue adds i to value. +// AddValue adds i to the "value" field. func (m *GaugeMutation) AddValue(i int64) { if m.addvalue != nil { *m.addvalue += i @@ -1651,7 +1817,7 @@ func (m *GaugeMutation) AddValue(i int64) { } } -// AddedValue returns the value that was added to the value field in this mutation. +// AddedValue returns the value that was added to the "value" field in this mutation. func (m *GaugeMutation) AddedValue() (r int64, exists bool) { v := m.addvalue if v == nil { @@ -1660,18 +1826,18 @@ func (m *GaugeMutation) AddedValue() (r int64, exists bool) { return *v, true } -// ResetValue reset all changes of the "value" field. +// ResetValue resets all changes to the "value" field. func (m *GaugeMutation) ResetValue() { m.value = nil m.addvalue = nil } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (m *GaugeMutation) SetWID(s string) { m.wID = &s } -// WID returns the wID value in the mutation. +// WID returns the value of the "wID" field in the mutation. func (m *GaugeMutation) WID() (r string, exists bool) { v := m.wID if v == nil { @@ -1680,16 +1846,15 @@ func (m *GaugeMutation) WID() (r string, exists bool) { return *v, true } -// OldWID returns the old wID value of the Gauge. -// If the Gauge object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldWID returns the old "wID" field's value of the Gauge entity. +// If the Gauge object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *GaugeMutation) OldWID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldWID is allowed only on UpdateOne operations") + return v, errors.New("OldWID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldWID requires an ID field in the mutation") + return v, errors.New("OldWID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -1698,27 +1863,27 @@ func (m *GaugeMutation) OldWID(ctx context.Context) (v string, err error) { return oldValue.WID, nil } -// ResetWID reset all changes of the "wID" field. +// ResetWID resets all changes to the "wID" field. func (m *GaugeMutation) ResetWID() { m.wID = nil } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by id. func (m *GaugeMutation) SetMetricID(id int) { m.metric = &id } -// ClearMetric clears the metric edge to Metric. +// ClearMetric clears the "metric" edge to the Metric entity. func (m *GaugeMutation) ClearMetric() { m.clearedmetric = true } -// MetricCleared returns if the edge metric was cleared. +// MetricCleared reports if the "metric" edge to the Metric entity was cleared. func (m *GaugeMutation) MetricCleared() bool { return m.clearedmetric } -// MetricID returns the metric id in the mutation. +// MetricID returns the "metric" edge ID in the mutation. func (m *GaugeMutation) MetricID() (id int, exists bool) { if m.metric != nil { return *m.metric, true @@ -1726,8 +1891,8 @@ func (m *GaugeMutation) MetricID() (id int, exists bool) { return } -// MetricIDs returns the metric ids in the mutation. -// Note that ids always returns len(ids) <= 1 for unique edges, and you should use +// MetricIDs returns the "metric" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // MetricID instead. It exists only for internal usage by the builders. func (m *GaugeMutation) MetricIDs() (ids []int) { if id := m.metric; id != nil { @@ -1736,25 +1901,45 @@ func (m *GaugeMutation) MetricIDs() (ids []int) { return } -// ResetMetric reset all changes of the "metric" edge. +// ResetMetric resets all changes to the "metric" edge. func (m *GaugeMutation) ResetMetric() { m.metric = nil m.clearedmetric = false } +// Where appends a list predicates to the GaugeMutation builder. +func (m *GaugeMutation) Where(ps ...predicate.Gauge) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the GaugeMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *GaugeMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Gauge, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + // Op returns the operation name. func (m *GaugeMutation) Op() Op { return m.op } +// SetOp allows setting the mutation operation. +func (m *GaugeMutation) SetOp(op Op) { + m.op = op +} + // Type returns the node type of this mutation (Gauge). func (m *GaugeMutation) Type() string { return m.typ } -// Fields returns all fields that were changed during -// this mutation. Note that, in order to get all numeric -// fields that were in/decremented, call AddedFields(). +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). func (m *GaugeMutation) Fields() []string { fields := make([]string, 0, 3) if m.time != nil { @@ -1769,9 +1954,9 @@ func (m *GaugeMutation) Fields() []string { return fields } -// Field returns the value of a field with the given name. -// The second boolean value indicates that this field was -// not set, or was not define in the schema. +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. func (m *GaugeMutation) Field(name string) (ent.Value, bool) { switch name { case gauge.FieldTime: @@ -1784,9 +1969,9 @@ func (m *GaugeMutation) Field(name string) (ent.Value, bool) { return nil, false } -// OldField returns the old value of the field from the database. -// An error is returned if the mutation operation is not UpdateOne, -// or the query to the database was failed. +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. func (m *GaugeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { case gauge.FieldTime: @@ -1799,9 +1984,9 @@ func (m *GaugeMutation) OldField(ctx context.Context, name string) (ent.Value, e return nil, fmt.Errorf("unknown Gauge field %s", name) } -// SetField sets the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *GaugeMutation) SetField(name string, value ent.Value) error { switch name { case gauge.FieldTime: @@ -1829,8 +2014,8 @@ func (m *GaugeMutation) SetField(name string, value ent.Value) error { return fmt.Errorf("unknown Gauge field %s", name) } -// AddedFields returns all numeric fields that were incremented -// or decremented during this mutation. +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. func (m *GaugeMutation) AddedFields() []string { var fields []string if m.addtime != nil { @@ -1842,9 +2027,9 @@ func (m *GaugeMutation) AddedFields() []string { return fields } -// AddedField returns the numeric value that was in/decremented -// from a field with the given name. The second value indicates -// that this field was not set, or was not define in the schema. +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. func (m *GaugeMutation) AddedField(name string) (ent.Value, bool) { switch name { case gauge.FieldTime: @@ -1855,9 +2040,9 @@ func (m *GaugeMutation) AddedField(name string) (ent.Value, bool) { return nil, false } -// AddField adds the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *GaugeMutation) AddField(name string, value ent.Value) error { switch name { case gauge.FieldTime: @@ -1878,28 +2063,27 @@ func (m *GaugeMutation) AddField(name string, value ent.Value) error { return fmt.Errorf("unknown Gauge numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared -// during this mutation. +// ClearedFields returns all nullable fields that were cleared during this +// mutation. func (m *GaugeMutation) ClearedFields() []string { return nil } -// FieldCleared returns a boolean indicates if this field was +// FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. func (m *GaugeMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } -// ClearField clears the value for the given name. It returns an +// ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *GaugeMutation) ClearField(name string) error { return fmt.Errorf("unknown Gauge nullable field %s", name) } -// ResetField resets all changes in the mutation regarding the -// given field name. It returns an error if the field is not -// defined in the schema. +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. func (m *GaugeMutation) ResetField(name string) error { switch name { case gauge.FieldTime: @@ -1915,8 +2099,7 @@ func (m *GaugeMutation) ResetField(name string) error { return fmt.Errorf("unknown Gauge field %s", name) } -// AddedEdges returns all edge names that were set/added in this -// mutation. +// AddedEdges returns all edge names that were set/added in this mutation. func (m *GaugeMutation) AddedEdges() []string { edges := make([]string, 0, 1) if m.metric != nil { @@ -1925,8 +2108,8 @@ func (m *GaugeMutation) AddedEdges() []string { return edges } -// AddedIDs returns all ids (to other nodes) that were added for -// the given edge name. +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. func (m *GaugeMutation) AddedIDs(name string) []ent.Value { switch name { case gauge.EdgeMetric: @@ -1937,23 +2120,19 @@ func (m *GaugeMutation) AddedIDs(name string) []ent.Value { return nil } -// RemovedEdges returns all edge names that were removed in this -// mutation. +// RemovedEdges returns all edge names that were removed in this mutation. func (m *GaugeMutation) RemovedEdges() []string { edges := make([]string, 0, 1) return edges } -// RemovedIDs returns all ids (to other nodes) that were removed for -// the given edge name. +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. func (m *GaugeMutation) RemovedIDs(name string) []ent.Value { - switch name { - } return nil } -// ClearedEdges returns all edge names that were cleared in this -// mutation. +// ClearedEdges returns all edge names that were cleared in this mutation. func (m *GaugeMutation) ClearedEdges() []string { edges := make([]string, 0, 1) if m.clearedmetric { @@ -1962,8 +2141,8 @@ func (m *GaugeMutation) ClearedEdges() []string { return edges } -// EdgeCleared returns a boolean indicates if this edge was -// cleared in this mutation. +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. func (m *GaugeMutation) EdgeCleared(name string) bool { switch name { case gauge.EdgeMetric: @@ -1972,8 +2151,8 @@ func (m *GaugeMutation) EdgeCleared(name string) bool { return false } -// ClearEdge clears the value for the given name. It returns an -// error if the edge name is not defined in the schema. +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. func (m *GaugeMutation) ClearEdge(name string) error { switch name { case gauge.EdgeMetric: @@ -1983,9 +2162,8 @@ func (m *GaugeMutation) ClearEdge(name string) error { return fmt.Errorf("unknown Gauge unique edge %s", name) } -// ResetEdge resets all changes in the mutation regarding the -// given edge name. It returns an error if the edge is not -// defined in the schema. +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. func (m *GaugeMutation) ResetEdge(name string) error { switch name { case gauge.EdgeMetric: @@ -1995,8 +2173,7 @@ func (m *GaugeMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Gauge edge %s", name) } -// GraphMutation represents an operation that mutate the Graphs -// nodes in the graph. +// GraphMutation represents an operation that mutates the Graph nodes in the graph. type GraphMutation struct { config op Op @@ -2012,14 +2189,15 @@ type GraphMutation struct { clearedmetrics bool done bool oldValue func(context.Context) (*Graph, error) + predicates []predicate.Graph } var _ ent.Mutation = (*GraphMutation)(nil) -// graphOption allows to manage the mutation configuration using functional options. +// graphOption allows management of the mutation configuration using functional options. type graphOption func(*GraphMutation) -// newGraphMutation creates new mutation for $n.Name. +// newGraphMutation creates new mutation for the Graph entity. func newGraphMutation(c config, op Op, opts ...graphOption) *GraphMutation { m := &GraphMutation{ config: c, @@ -2033,7 +2211,7 @@ func newGraphMutation(c config, op Op, opts ...graphOption) *GraphMutation { return m } -// withGraphID sets the id field of the mutation. +// withGraphID sets the ID field of the mutation. func withGraphID(id int) graphOption { return func(m *GraphMutation) { var ( @@ -2044,7 +2222,7 @@ func withGraphID(id int) graphOption { m.oldValue = func(ctx context.Context) (*Graph, error) { once.Do(func() { if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") + err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().Graph.Get(ctx, id) } @@ -2077,15 +2255,15 @@ func (m GraphMutation) Client() *Client { // it returns an error otherwise. func (m GraphMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("ent: mutation is not running in a transaction") + return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } -// ID returns the id value in the mutation. Note that, the id -// is available only if it was provided to the builder. +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. func (m *GraphMutation) ID() (id int, exists bool) { if m.id == nil { return @@ -2093,12 +2271,31 @@ func (m *GraphMutation) ID() (id int, exists bool) { return *m.id, true } -// SetTitle sets the title field. +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *GraphMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Graph.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTitle sets the "title" field. func (m *GraphMutation) SetTitle(s string) { m.title = &s } -// Title returns the title value in the mutation. +// Title returns the value of the "title" field in the mutation. func (m *GraphMutation) Title() (r string, exists bool) { v := m.title if v == nil { @@ -2107,16 +2304,15 @@ func (m *GraphMutation) Title() (r string, exists bool) { return *v, true } -// OldTitle returns the old title value of the Graph. -// If the Graph object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldTitle returns the old "title" field's value of the Graph entity. +// If the Graph object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *GraphMutation) OldTitle(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldTitle is allowed only on UpdateOne operations") + return v, errors.New("OldTitle is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldTitle requires an ID field in the mutation") + return v, errors.New("OldTitle requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -2125,17 +2321,17 @@ func (m *GraphMutation) OldTitle(ctx context.Context) (v string, err error) { return oldValue.Title, nil } -// ResetTitle reset all changes of the "title" field. +// ResetTitle resets all changes to the "title" field. func (m *GraphMutation) ResetTitle() { m.title = nil } -// SetUnit sets the unit field. +// SetUnit sets the "unit" field. func (m *GraphMutation) SetUnit(s string) { m.unit = &s } -// Unit returns the unit value in the mutation. +// Unit returns the value of the "unit" field in the mutation. func (m *GraphMutation) Unit() (r string, exists bool) { v := m.unit if v == nil { @@ -2144,16 +2340,15 @@ func (m *GraphMutation) Unit() (r string, exists bool) { return *v, true } -// OldUnit returns the old unit value of the Graph. -// If the Graph object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldUnit returns the old "unit" field's value of the Graph entity. +// If the Graph object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *GraphMutation) OldUnit(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldUnit is allowed only on UpdateOne operations") + return v, errors.New("OldUnit is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldUnit requires an ID field in the mutation") + return v, errors.New("OldUnit requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -2162,27 +2357,27 @@ func (m *GraphMutation) OldUnit(ctx context.Context) (v string, err error) { return oldValue.Unit, nil } -// ResetUnit reset all changes of the "unit" field. +// ResetUnit resets all changes to the "unit" field. func (m *GraphMutation) ResetUnit() { m.unit = nil } -// SetGroupID sets the group edge to Group by id. +// SetGroupID sets the "group" edge to the Group entity by id. func (m *GraphMutation) SetGroupID(id int) { m.group = &id } -// ClearGroup clears the group edge to Group. +// ClearGroup clears the "group" edge to the Group entity. func (m *GraphMutation) ClearGroup() { m.clearedgroup = true } -// GroupCleared returns if the edge group was cleared. +// GroupCleared reports if the "group" edge to the Group entity was cleared. func (m *GraphMutation) GroupCleared() bool { return m.clearedgroup } -// GroupID returns the group id in the mutation. +// GroupID returns the "group" edge ID in the mutation. func (m *GraphMutation) GroupID() (id int, exists bool) { if m.group != nil { return *m.group, true @@ -2190,8 +2385,8 @@ func (m *GraphMutation) GroupID() (id int, exists bool) { return } -// GroupIDs returns the group ids in the mutation. -// Note that ids always returns len(ids) <= 1 for unique edges, and you should use +// GroupIDs returns the "group" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // GroupID instead. It exists only for internal usage by the builders. func (m *GraphMutation) GroupIDs() (ids []int) { if id := m.group; id != nil { @@ -2200,13 +2395,13 @@ func (m *GraphMutation) GroupIDs() (ids []int) { return } -// ResetGroup reset all changes of the "group" edge. +// ResetGroup resets all changes to the "group" edge. func (m *GraphMutation) ResetGroup() { m.group = nil m.clearedgroup = false } -// AddMetricIDs adds the metrics edge to Metric by ids. +// AddMetricIDs adds the "metrics" edge to the Metric entity by ids. func (m *GraphMutation) AddMetricIDs(ids ...int) { if m.metrics == nil { m.metrics = make(map[int]struct{}) @@ -2216,27 +2411,28 @@ func (m *GraphMutation) AddMetricIDs(ids ...int) { } } -// ClearMetrics clears the metrics edge to Metric. +// ClearMetrics clears the "metrics" edge to the Metric entity. func (m *GraphMutation) ClearMetrics() { m.clearedmetrics = true } -// MetricsCleared returns if the edge metrics was cleared. +// MetricsCleared reports if the "metrics" edge to the Metric entity was cleared. func (m *GraphMutation) MetricsCleared() bool { return m.clearedmetrics } -// RemoveMetricIDs removes the metrics edge to Metric by ids. +// RemoveMetricIDs removes the "metrics" edge to the Metric entity by IDs. func (m *GraphMutation) RemoveMetricIDs(ids ...int) { if m.removedmetrics == nil { m.removedmetrics = make(map[int]struct{}) } for i := range ids { + delete(m.metrics, ids[i]) m.removedmetrics[ids[i]] = struct{}{} } } -// RemovedMetrics returns the removed ids of metrics. +// RemovedMetrics returns the removed IDs of the "metrics" edge to the Metric entity. func (m *GraphMutation) RemovedMetricsIDs() (ids []int) { for id := range m.removedmetrics { ids = append(ids, id) @@ -2244,7 +2440,7 @@ func (m *GraphMutation) RemovedMetricsIDs() (ids []int) { return } -// MetricsIDs returns the metrics ids in the mutation. +// MetricsIDs returns the "metrics" edge IDs in the mutation. func (m *GraphMutation) MetricsIDs() (ids []int) { for id := range m.metrics { ids = append(ids, id) @@ -2252,26 +2448,46 @@ func (m *GraphMutation) MetricsIDs() (ids []int) { return } -// ResetMetrics reset all changes of the "metrics" edge. +// ResetMetrics resets all changes to the "metrics" edge. func (m *GraphMutation) ResetMetrics() { m.metrics = nil m.clearedmetrics = false m.removedmetrics = nil } +// Where appends a list predicates to the GraphMutation builder. +func (m *GraphMutation) Where(ps ...predicate.Graph) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the GraphMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *GraphMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Graph, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + // Op returns the operation name. func (m *GraphMutation) Op() Op { return m.op } +// SetOp allows setting the mutation operation. +func (m *GraphMutation) SetOp(op Op) { + m.op = op +} + // Type returns the node type of this mutation (Graph). func (m *GraphMutation) Type() string { return m.typ } -// Fields returns all fields that were changed during -// this mutation. Note that, in order to get all numeric -// fields that were in/decremented, call AddedFields(). +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). func (m *GraphMutation) Fields() []string { fields := make([]string, 0, 2) if m.title != nil { @@ -2283,9 +2499,9 @@ func (m *GraphMutation) Fields() []string { return fields } -// Field returns the value of a field with the given name. -// The second boolean value indicates that this field was -// not set, or was not define in the schema. +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. func (m *GraphMutation) Field(name string) (ent.Value, bool) { switch name { case graph.FieldTitle: @@ -2296,9 +2512,9 @@ func (m *GraphMutation) Field(name string) (ent.Value, bool) { return nil, false } -// OldField returns the old value of the field from the database. -// An error is returned if the mutation operation is not UpdateOne, -// or the query to the database was failed. +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. func (m *GraphMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { case graph.FieldTitle: @@ -2309,9 +2525,9 @@ func (m *GraphMutation) OldField(ctx context.Context, name string) (ent.Value, e return nil, fmt.Errorf("unknown Graph field %s", name) } -// SetField sets the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *GraphMutation) SetField(name string, value ent.Value) error { switch name { case graph.FieldTitle: @@ -2332,50 +2548,49 @@ func (m *GraphMutation) SetField(name string, value ent.Value) error { return fmt.Errorf("unknown Graph field %s", name) } -// AddedFields returns all numeric fields that were incremented -// or decremented during this mutation. +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. func (m *GraphMutation) AddedFields() []string { return nil } -// AddedField returns the numeric value that was in/decremented -// from a field with the given name. The second value indicates -// that this field was not set, or was not define in the schema. +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. func (m *GraphMutation) AddedField(name string) (ent.Value, bool) { return nil, false } -// AddField adds the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *GraphMutation) AddField(name string, value ent.Value) error { switch name { } return fmt.Errorf("unknown Graph numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared -// during this mutation. +// ClearedFields returns all nullable fields that were cleared during this +// mutation. func (m *GraphMutation) ClearedFields() []string { return nil } -// FieldCleared returns a boolean indicates if this field was +// FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. func (m *GraphMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } -// ClearField clears the value for the given name. It returns an +// ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *GraphMutation) ClearField(name string) error { return fmt.Errorf("unknown Graph nullable field %s", name) } -// ResetField resets all changes in the mutation regarding the -// given field name. It returns an error if the field is not -// defined in the schema. +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. func (m *GraphMutation) ResetField(name string) error { switch name { case graph.FieldTitle: @@ -2388,8 +2603,7 @@ func (m *GraphMutation) ResetField(name string) error { return fmt.Errorf("unknown Graph field %s", name) } -// AddedEdges returns all edge names that were set/added in this -// mutation. +// AddedEdges returns all edge names that were set/added in this mutation. func (m *GraphMutation) AddedEdges() []string { edges := make([]string, 0, 2) if m.group != nil { @@ -2401,8 +2615,8 @@ func (m *GraphMutation) AddedEdges() []string { return edges } -// AddedIDs returns all ids (to other nodes) that were added for -// the given edge name. +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. func (m *GraphMutation) AddedIDs(name string) []ent.Value { switch name { case graph.EdgeGroup: @@ -2419,8 +2633,7 @@ func (m *GraphMutation) AddedIDs(name string) []ent.Value { return nil } -// RemovedEdges returns all edge names that were removed in this -// mutation. +// RemovedEdges returns all edge names that were removed in this mutation. func (m *GraphMutation) RemovedEdges() []string { edges := make([]string, 0, 2) if m.removedmetrics != nil { @@ -2429,8 +2642,8 @@ func (m *GraphMutation) RemovedEdges() []string { return edges } -// RemovedIDs returns all ids (to other nodes) that were removed for -// the given edge name. +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. func (m *GraphMutation) RemovedIDs(name string) []ent.Value { switch name { case graph.EdgeMetrics: @@ -2443,8 +2656,7 @@ func (m *GraphMutation) RemovedIDs(name string) []ent.Value { return nil } -// ClearedEdges returns all edge names that were cleared in this -// mutation. +// ClearedEdges returns all edge names that were cleared in this mutation. func (m *GraphMutation) ClearedEdges() []string { edges := make([]string, 0, 2) if m.clearedgroup { @@ -2456,8 +2668,8 @@ func (m *GraphMutation) ClearedEdges() []string { return edges } -// EdgeCleared returns a boolean indicates if this edge was -// cleared in this mutation. +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. func (m *GraphMutation) EdgeCleared(name string) bool { switch name { case graph.EdgeGroup: @@ -2468,8 +2680,8 @@ func (m *GraphMutation) EdgeCleared(name string) bool { return false } -// ClearEdge clears the value for the given name. It returns an -// error if the edge name is not defined in the schema. +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. func (m *GraphMutation) ClearEdge(name string) error { switch name { case graph.EdgeGroup: @@ -2479,9 +2691,8 @@ func (m *GraphMutation) ClearEdge(name string) error { return fmt.Errorf("unknown Graph unique edge %s", name) } -// ResetEdge resets all changes in the mutation regarding the -// given edge name. It returns an error if the edge is not -// defined in the schema. +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. func (m *GraphMutation) ResetEdge(name string) error { switch name { case graph.EdgeGroup: @@ -2494,8 +2705,7 @@ func (m *GraphMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Graph edge %s", name) } -// GroupMutation represents an operation that mutate the Groups -// nodes in the graph. +// GroupMutation represents an operation that mutates the Group nodes in the graph. type GroupMutation struct { config op Op @@ -2510,14 +2720,15 @@ type GroupMutation struct { clearedgraphs bool done bool oldValue func(context.Context) (*Group, error) + predicates []predicate.Group } var _ ent.Mutation = (*GroupMutation)(nil) -// groupOption allows to manage the mutation configuration using functional options. +// groupOption allows management of the mutation configuration using functional options. type groupOption func(*GroupMutation) -// newGroupMutation creates new mutation for $n.Name. +// newGroupMutation creates new mutation for the Group entity. func newGroupMutation(c config, op Op, opts ...groupOption) *GroupMutation { m := &GroupMutation{ config: c, @@ -2531,7 +2742,7 @@ func newGroupMutation(c config, op Op, opts ...groupOption) *GroupMutation { return m } -// withGroupID sets the id field of the mutation. +// withGroupID sets the ID field of the mutation. func withGroupID(id int) groupOption { return func(m *GroupMutation) { var ( @@ -2542,7 +2753,7 @@ func withGroupID(id int) groupOption { m.oldValue = func(ctx context.Context) (*Group, error) { once.Do(func() { if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") + err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().Group.Get(ctx, id) } @@ -2575,15 +2786,15 @@ func (m GroupMutation) Client() *Client { // it returns an error otherwise. func (m GroupMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("ent: mutation is not running in a transaction") + return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } -// ID returns the id value in the mutation. Note that, the id -// is available only if it was provided to the builder. +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. func (m *GroupMutation) ID() (id int, exists bool) { if m.id == nil { return @@ -2591,12 +2802,31 @@ func (m *GroupMutation) ID() (id int, exists bool) { return *m.id, true } -// SetName sets the name field. +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *GroupMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Group.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. func (m *GroupMutation) SetName(s string) { m.name = &s } -// Name returns the name value in the mutation. +// Name returns the value of the "name" field in the mutation. func (m *GroupMutation) Name() (r string, exists bool) { v := m.name if v == nil { @@ -2605,16 +2835,15 @@ func (m *GroupMutation) Name() (r string, exists bool) { return *v, true } -// OldName returns the old name value of the Group. -// If the Group object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldName returns the old "name" field's value of the Group entity. +// If the Group object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *GroupMutation) OldName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldName is allowed only on UpdateOne operations") + return v, errors.New("OldName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldName requires an ID field in the mutation") + return v, errors.New("OldName requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -2623,27 +2852,27 @@ func (m *GroupMutation) OldName(ctx context.Context) (v string, err error) { return oldValue.Name, nil } -// ResetName reset all changes of the "name" field. +// ResetName resets all changes to the "name" field. func (m *GroupMutation) ResetName() { m.name = nil } -// SetApplicationID sets the application edge to Application by id. +// SetApplicationID sets the "application" edge to the Application entity by id. func (m *GroupMutation) SetApplicationID(id int) { m.application = &id } -// ClearApplication clears the application edge to Application. +// ClearApplication clears the "application" edge to the Application entity. func (m *GroupMutation) ClearApplication() { m.clearedapplication = true } -// ApplicationCleared returns if the edge application was cleared. +// ApplicationCleared reports if the "application" edge to the Application entity was cleared. func (m *GroupMutation) ApplicationCleared() bool { return m.clearedapplication } -// ApplicationID returns the application id in the mutation. +// ApplicationID returns the "application" edge ID in the mutation. func (m *GroupMutation) ApplicationID() (id int, exists bool) { if m.application != nil { return *m.application, true @@ -2651,8 +2880,8 @@ func (m *GroupMutation) ApplicationID() (id int, exists bool) { return } -// ApplicationIDs returns the application ids in the mutation. -// Note that ids always returns len(ids) <= 1 for unique edges, and you should use +// ApplicationIDs returns the "application" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // ApplicationID instead. It exists only for internal usage by the builders. func (m *GroupMutation) ApplicationIDs() (ids []int) { if id := m.application; id != nil { @@ -2661,13 +2890,13 @@ func (m *GroupMutation) ApplicationIDs() (ids []int) { return } -// ResetApplication reset all changes of the "application" edge. +// ResetApplication resets all changes to the "application" edge. func (m *GroupMutation) ResetApplication() { m.application = nil m.clearedapplication = false } -// AddGraphIDs adds the graphs edge to Graph by ids. +// AddGraphIDs adds the "graphs" edge to the Graph entity by ids. func (m *GroupMutation) AddGraphIDs(ids ...int) { if m.graphs == nil { m.graphs = make(map[int]struct{}) @@ -2677,27 +2906,28 @@ func (m *GroupMutation) AddGraphIDs(ids ...int) { } } -// ClearGraphs clears the graphs edge to Graph. +// ClearGraphs clears the "graphs" edge to the Graph entity. func (m *GroupMutation) ClearGraphs() { m.clearedgraphs = true } -// GraphsCleared returns if the edge graphs was cleared. +// GraphsCleared reports if the "graphs" edge to the Graph entity was cleared. func (m *GroupMutation) GraphsCleared() bool { return m.clearedgraphs } -// RemoveGraphIDs removes the graphs edge to Graph by ids. +// RemoveGraphIDs removes the "graphs" edge to the Graph entity by IDs. func (m *GroupMutation) RemoveGraphIDs(ids ...int) { if m.removedgraphs == nil { m.removedgraphs = make(map[int]struct{}) } for i := range ids { + delete(m.graphs, ids[i]) m.removedgraphs[ids[i]] = struct{}{} } } -// RemovedGraphs returns the removed ids of graphs. +// RemovedGraphs returns the removed IDs of the "graphs" edge to the Graph entity. func (m *GroupMutation) RemovedGraphsIDs() (ids []int) { for id := range m.removedgraphs { ids = append(ids, id) @@ -2705,7 +2935,7 @@ func (m *GroupMutation) RemovedGraphsIDs() (ids []int) { return } -// GraphsIDs returns the graphs ids in the mutation. +// GraphsIDs returns the "graphs" edge IDs in the mutation. func (m *GroupMutation) GraphsIDs() (ids []int) { for id := range m.graphs { ids = append(ids, id) @@ -2713,26 +2943,46 @@ func (m *GroupMutation) GraphsIDs() (ids []int) { return } -// ResetGraphs reset all changes of the "graphs" edge. +// ResetGraphs resets all changes to the "graphs" edge. func (m *GroupMutation) ResetGraphs() { m.graphs = nil m.clearedgraphs = false m.removedgraphs = nil } +// Where appends a list predicates to the GroupMutation builder. +func (m *GroupMutation) Where(ps ...predicate.Group) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the GroupMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *GroupMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Group, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + // Op returns the operation name. func (m *GroupMutation) Op() Op { return m.op } +// SetOp allows setting the mutation operation. +func (m *GroupMutation) SetOp(op Op) { + m.op = op +} + // Type returns the node type of this mutation (Group). func (m *GroupMutation) Type() string { return m.typ } -// Fields returns all fields that were changed during -// this mutation. Note that, in order to get all numeric -// fields that were in/decremented, call AddedFields(). +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). func (m *GroupMutation) Fields() []string { fields := make([]string, 0, 1) if m.name != nil { @@ -2741,9 +2991,9 @@ func (m *GroupMutation) Fields() []string { return fields } -// Field returns the value of a field with the given name. -// The second boolean value indicates that this field was -// not set, or was not define in the schema. +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. func (m *GroupMutation) Field(name string) (ent.Value, bool) { switch name { case group.FieldName: @@ -2752,9 +3002,9 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) { return nil, false } -// OldField returns the old value of the field from the database. -// An error is returned if the mutation operation is not UpdateOne, -// or the query to the database was failed. +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { case group.FieldName: @@ -2763,9 +3013,9 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e return nil, fmt.Errorf("unknown Group field %s", name) } -// SetField sets the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *GroupMutation) SetField(name string, value ent.Value) error { switch name { case group.FieldName: @@ -2779,50 +3029,49 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error { return fmt.Errorf("unknown Group field %s", name) } -// AddedFields returns all numeric fields that were incremented -// or decremented during this mutation. +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. func (m *GroupMutation) AddedFields() []string { return nil } -// AddedField returns the numeric value that was in/decremented -// from a field with the given name. The second value indicates -// that this field was not set, or was not define in the schema. +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. func (m *GroupMutation) AddedField(name string) (ent.Value, bool) { return nil, false } -// AddField adds the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *GroupMutation) AddField(name string, value ent.Value) error { switch name { } return fmt.Errorf("unknown Group numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared -// during this mutation. +// ClearedFields returns all nullable fields that were cleared during this +// mutation. func (m *GroupMutation) ClearedFields() []string { return nil } -// FieldCleared returns a boolean indicates if this field was +// FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. func (m *GroupMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } -// ClearField clears the value for the given name. It returns an +// ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *GroupMutation) ClearField(name string) error { return fmt.Errorf("unknown Group nullable field %s", name) } -// ResetField resets all changes in the mutation regarding the -// given field name. It returns an error if the field is not -// defined in the schema. +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. func (m *GroupMutation) ResetField(name string) error { switch name { case group.FieldName: @@ -2832,8 +3081,7 @@ func (m *GroupMutation) ResetField(name string) error { return fmt.Errorf("unknown Group field %s", name) } -// AddedEdges returns all edge names that were set/added in this -// mutation. +// AddedEdges returns all edge names that were set/added in this mutation. func (m *GroupMutation) AddedEdges() []string { edges := make([]string, 0, 2) if m.application != nil { @@ -2845,8 +3093,8 @@ func (m *GroupMutation) AddedEdges() []string { return edges } -// AddedIDs returns all ids (to other nodes) that were added for -// the given edge name. +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. func (m *GroupMutation) AddedIDs(name string) []ent.Value { switch name { case group.EdgeApplication: @@ -2863,8 +3111,7 @@ func (m *GroupMutation) AddedIDs(name string) []ent.Value { return nil } -// RemovedEdges returns all edge names that were removed in this -// mutation. +// RemovedEdges returns all edge names that were removed in this mutation. func (m *GroupMutation) RemovedEdges() []string { edges := make([]string, 0, 2) if m.removedgraphs != nil { @@ -2873,8 +3120,8 @@ func (m *GroupMutation) RemovedEdges() []string { return edges } -// RemovedIDs returns all ids (to other nodes) that were removed for -// the given edge name. +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. func (m *GroupMutation) RemovedIDs(name string) []ent.Value { switch name { case group.EdgeGraphs: @@ -2887,8 +3134,7 @@ func (m *GroupMutation) RemovedIDs(name string) []ent.Value { return nil } -// ClearedEdges returns all edge names that were cleared in this -// mutation. +// ClearedEdges returns all edge names that were cleared in this mutation. func (m *GroupMutation) ClearedEdges() []string { edges := make([]string, 0, 2) if m.clearedapplication { @@ -2900,8 +3146,8 @@ func (m *GroupMutation) ClearedEdges() []string { return edges } -// EdgeCleared returns a boolean indicates if this edge was -// cleared in this mutation. +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. func (m *GroupMutation) EdgeCleared(name string) bool { switch name { case group.EdgeApplication: @@ -2912,8 +3158,8 @@ func (m *GroupMutation) EdgeCleared(name string) bool { return false } -// ClearEdge clears the value for the given name. It returns an -// error if the edge name is not defined in the schema. +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. func (m *GroupMutation) ClearEdge(name string) error { switch name { case group.EdgeApplication: @@ -2923,9 +3169,8 @@ func (m *GroupMutation) ClearEdge(name string) error { return fmt.Errorf("unknown Group unique edge %s", name) } -// ResetEdge resets all changes in the mutation regarding the -// given edge name. It returns an error if the edge is not -// defined in the schema. +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. func (m *GroupMutation) ResetEdge(name string) error { switch name { case group.EdgeApplication: @@ -2938,8 +3183,7 @@ func (m *GroupMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Group edge %s", name) } -// HistogramMutation represents an operation that mutate the Histograms -// nodes in the graph. +// HistogramMutation represents an operation that mutates the Histogram nodes in the graph. type HistogramMutation struct { config op Op @@ -2973,14 +3217,15 @@ type HistogramMutation struct { clearedmetric bool done bool oldValue func(context.Context) (*Histogram, error) + predicates []predicate.Histogram } var _ ent.Mutation = (*HistogramMutation)(nil) -// histogramOption allows to manage the mutation configuration using functional options. +// histogramOption allows management of the mutation configuration using functional options. type histogramOption func(*HistogramMutation) -// newHistogramMutation creates new mutation for $n.Name. +// newHistogramMutation creates new mutation for the Histogram entity. func newHistogramMutation(c config, op Op, opts ...histogramOption) *HistogramMutation { m := &HistogramMutation{ config: c, @@ -2994,7 +3239,7 @@ func newHistogramMutation(c config, op Op, opts ...histogramOption) *HistogramMu return m } -// withHistogramID sets the id field of the mutation. +// withHistogramID sets the ID field of the mutation. func withHistogramID(id int) histogramOption { return func(m *HistogramMutation) { var ( @@ -3005,7 +3250,7 @@ func withHistogramID(id int) histogramOption { m.oldValue = func(ctx context.Context) (*Histogram, error) { once.Do(func() { if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") + err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().Histogram.Get(ctx, id) } @@ -3038,15 +3283,15 @@ func (m HistogramMutation) Client() *Client { // it returns an error otherwise. func (m HistogramMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("ent: mutation is not running in a transaction") + return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } -// ID returns the id value in the mutation. Note that, the id -// is available only if it was provided to the builder. +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. func (m *HistogramMutation) ID() (id int, exists bool) { if m.id == nil { return @@ -3054,13 +3299,32 @@ func (m *HistogramMutation) ID() (id int, exists bool) { return *m.id, true } -// SetTime sets the time field. +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *HistogramMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Histogram.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTime sets the "time" field. func (m *HistogramMutation) SetTime(i int64) { m.time = &i m.addtime = nil } -// Time returns the time value in the mutation. +// Time returns the value of the "time" field in the mutation. func (m *HistogramMutation) Time() (r int64, exists bool) { v := m.time if v == nil { @@ -3069,16 +3333,15 @@ func (m *HistogramMutation) Time() (r int64, exists bool) { return *v, true } -// OldTime returns the old time value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldTime returns the old "time" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldTime(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldTime is allowed only on UpdateOne operations") + return v, errors.New("OldTime is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldTime requires an ID field in the mutation") + return v, errors.New("OldTime requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3087,7 +3350,7 @@ func (m *HistogramMutation) OldTime(ctx context.Context) (v int64, err error) { return oldValue.Time, nil } -// AddTime adds i to time. +// AddTime adds i to the "time" field. func (m *HistogramMutation) AddTime(i int64) { if m.addtime != nil { *m.addtime += i @@ -3096,7 +3359,7 @@ func (m *HistogramMutation) AddTime(i int64) { } } -// AddedTime returns the value that was added to the time field in this mutation. +// AddedTime returns the value that was added to the "time" field in this mutation. func (m *HistogramMutation) AddedTime() (r int64, exists bool) { v := m.addtime if v == nil { @@ -3105,19 +3368,19 @@ func (m *HistogramMutation) AddedTime() (r int64, exists bool) { return *v, true } -// ResetTime reset all changes of the "time" field. +// ResetTime resets all changes to the "time" field. func (m *HistogramMutation) ResetTime() { m.time = nil m.addtime = nil } -// SetCount sets the count field. +// SetCount sets the "count" field. func (m *HistogramMutation) SetCount(i int64) { m.count = &i m.addcount = nil } -// Count returns the count value in the mutation. +// Count returns the value of the "count" field in the mutation. func (m *HistogramMutation) Count() (r int64, exists bool) { v := m.count if v == nil { @@ -3126,16 +3389,15 @@ func (m *HistogramMutation) Count() (r int64, exists bool) { return *v, true } -// OldCount returns the old count value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldCount returns the old "count" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldCount(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldCount is allowed only on UpdateOne operations") + return v, errors.New("OldCount is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldCount requires an ID field in the mutation") + return v, errors.New("OldCount requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3144,7 +3406,7 @@ func (m *HistogramMutation) OldCount(ctx context.Context) (v int64, err error) { return oldValue.Count, nil } -// AddCount adds i to count. +// AddCount adds i to the "count" field. func (m *HistogramMutation) AddCount(i int64) { if m.addcount != nil { *m.addcount += i @@ -3153,7 +3415,7 @@ func (m *HistogramMutation) AddCount(i int64) { } } -// AddedCount returns the value that was added to the count field in this mutation. +// AddedCount returns the value that was added to the "count" field in this mutation. func (m *HistogramMutation) AddedCount() (r int64, exists bool) { v := m.addcount if v == nil { @@ -3162,19 +3424,19 @@ func (m *HistogramMutation) AddedCount() (r int64, exists bool) { return *v, true } -// ResetCount reset all changes of the "count" field. +// ResetCount resets all changes to the "count" field. func (m *HistogramMutation) ResetCount() { m.count = nil m.addcount = nil } -// SetMin sets the min field. +// SetMin sets the "min" field. func (m *HistogramMutation) SetMin(i int64) { m.min = &i m.addmin = nil } -// Min returns the min value in the mutation. +// Min returns the value of the "min" field in the mutation. func (m *HistogramMutation) Min() (r int64, exists bool) { v := m.min if v == nil { @@ -3183,16 +3445,15 @@ func (m *HistogramMutation) Min() (r int64, exists bool) { return *v, true } -// OldMin returns the old min value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldMin returns the old "min" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldMin(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldMin is allowed only on UpdateOne operations") + return v, errors.New("OldMin is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldMin requires an ID field in the mutation") + return v, errors.New("OldMin requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3201,7 +3462,7 @@ func (m *HistogramMutation) OldMin(ctx context.Context) (v int64, err error) { return oldValue.Min, nil } -// AddMin adds i to min. +// AddMin adds i to the "min" field. func (m *HistogramMutation) AddMin(i int64) { if m.addmin != nil { *m.addmin += i @@ -3210,7 +3471,7 @@ func (m *HistogramMutation) AddMin(i int64) { } } -// AddedMin returns the value that was added to the min field in this mutation. +// AddedMin returns the value that was added to the "min" field in this mutation. func (m *HistogramMutation) AddedMin() (r int64, exists bool) { v := m.addmin if v == nil { @@ -3219,19 +3480,19 @@ func (m *HistogramMutation) AddedMin() (r int64, exists bool) { return *v, true } -// ResetMin reset all changes of the "min" field. +// ResetMin resets all changes to the "min" field. func (m *HistogramMutation) ResetMin() { m.min = nil m.addmin = nil } -// SetMax sets the max field. +// SetMax sets the "max" field. func (m *HistogramMutation) SetMax(i int64) { m.max = &i m.addmax = nil } -// Max returns the max value in the mutation. +// Max returns the value of the "max" field in the mutation. func (m *HistogramMutation) Max() (r int64, exists bool) { v := m.max if v == nil { @@ -3240,16 +3501,15 @@ func (m *HistogramMutation) Max() (r int64, exists bool) { return *v, true } -// OldMax returns the old max value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldMax returns the old "max" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldMax(ctx context.Context) (v int64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldMax is allowed only on UpdateOne operations") + return v, errors.New("OldMax is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldMax requires an ID field in the mutation") + return v, errors.New("OldMax requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3258,7 +3518,7 @@ func (m *HistogramMutation) OldMax(ctx context.Context) (v int64, err error) { return oldValue.Max, nil } -// AddMax adds i to max. +// AddMax adds i to the "max" field. func (m *HistogramMutation) AddMax(i int64) { if m.addmax != nil { *m.addmax += i @@ -3267,7 +3527,7 @@ func (m *HistogramMutation) AddMax(i int64) { } } -// AddedMax returns the value that was added to the max field in this mutation. +// AddedMax returns the value that was added to the "max" field in this mutation. func (m *HistogramMutation) AddedMax() (r int64, exists bool) { v := m.addmax if v == nil { @@ -3276,19 +3536,19 @@ func (m *HistogramMutation) AddedMax() (r int64, exists bool) { return *v, true } -// ResetMax reset all changes of the "max" field. +// ResetMax resets all changes to the "max" field. func (m *HistogramMutation) ResetMax() { m.max = nil m.addmax = nil } -// SetMean sets the mean field. +// SetMean sets the "mean" field. func (m *HistogramMutation) SetMean(f float64) { m.mean = &f m.addmean = nil } -// Mean returns the mean value in the mutation. +// Mean returns the value of the "mean" field in the mutation. func (m *HistogramMutation) Mean() (r float64, exists bool) { v := m.mean if v == nil { @@ -3297,16 +3557,15 @@ func (m *HistogramMutation) Mean() (r float64, exists bool) { return *v, true } -// OldMean returns the old mean value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldMean returns the old "mean" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldMean(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldMean is allowed only on UpdateOne operations") + return v, errors.New("OldMean is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldMean requires an ID field in the mutation") + return v, errors.New("OldMean requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3315,7 +3574,7 @@ func (m *HistogramMutation) OldMean(ctx context.Context) (v float64, err error) return oldValue.Mean, nil } -// AddMean adds f to mean. +// AddMean adds f to the "mean" field. func (m *HistogramMutation) AddMean(f float64) { if m.addmean != nil { *m.addmean += f @@ -3324,7 +3583,7 @@ func (m *HistogramMutation) AddMean(f float64) { } } -// AddedMean returns the value that was added to the mean field in this mutation. +// AddedMean returns the value that was added to the "mean" field in this mutation. func (m *HistogramMutation) AddedMean() (r float64, exists bool) { v := m.addmean if v == nil { @@ -3333,19 +3592,19 @@ func (m *HistogramMutation) AddedMean() (r float64, exists bool) { return *v, true } -// ResetMean reset all changes of the "mean" field. +// ResetMean resets all changes to the "mean" field. func (m *HistogramMutation) ResetMean() { m.mean = nil m.addmean = nil } -// SetStddev sets the stddev field. +// SetStddev sets the "stddev" field. func (m *HistogramMutation) SetStddev(f float64) { m.stddev = &f m.addstddev = nil } -// Stddev returns the stddev value in the mutation. +// Stddev returns the value of the "stddev" field in the mutation. func (m *HistogramMutation) Stddev() (r float64, exists bool) { v := m.stddev if v == nil { @@ -3354,16 +3613,15 @@ func (m *HistogramMutation) Stddev() (r float64, exists bool) { return *v, true } -// OldStddev returns the old stddev value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldStddev returns the old "stddev" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldStddev(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldStddev is allowed only on UpdateOne operations") + return v, errors.New("OldStddev is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldStddev requires an ID field in the mutation") + return v, errors.New("OldStddev requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3372,7 +3630,7 @@ func (m *HistogramMutation) OldStddev(ctx context.Context) (v float64, err error return oldValue.Stddev, nil } -// AddStddev adds f to stddev. +// AddStddev adds f to the "stddev" field. func (m *HistogramMutation) AddStddev(f float64) { if m.addstddev != nil { *m.addstddev += f @@ -3381,7 +3639,7 @@ func (m *HistogramMutation) AddStddev(f float64) { } } -// AddedStddev returns the value that was added to the stddev field in this mutation. +// AddedStddev returns the value that was added to the "stddev" field in this mutation. func (m *HistogramMutation) AddedStddev() (r float64, exists bool) { v := m.addstddev if v == nil { @@ -3390,19 +3648,19 @@ func (m *HistogramMutation) AddedStddev() (r float64, exists bool) { return *v, true } -// ResetStddev reset all changes of the "stddev" field. +// ResetStddev resets all changes to the "stddev" field. func (m *HistogramMutation) ResetStddev() { m.stddev = nil m.addstddev = nil } -// SetMedian sets the median field. +// SetMedian sets the "median" field. func (m *HistogramMutation) SetMedian(f float64) { m.median = &f m.addmedian = nil } -// Median returns the median value in the mutation. +// Median returns the value of the "median" field in the mutation. func (m *HistogramMutation) Median() (r float64, exists bool) { v := m.median if v == nil { @@ -3411,16 +3669,15 @@ func (m *HistogramMutation) Median() (r float64, exists bool) { return *v, true } -// OldMedian returns the old median value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldMedian returns the old "median" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldMedian(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldMedian is allowed only on UpdateOne operations") + return v, errors.New("OldMedian is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldMedian requires an ID field in the mutation") + return v, errors.New("OldMedian requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3429,7 +3686,7 @@ func (m *HistogramMutation) OldMedian(ctx context.Context) (v float64, err error return oldValue.Median, nil } -// AddMedian adds f to median. +// AddMedian adds f to the "median" field. func (m *HistogramMutation) AddMedian(f float64) { if m.addmedian != nil { *m.addmedian += f @@ -3438,7 +3695,7 @@ func (m *HistogramMutation) AddMedian(f float64) { } } -// AddedMedian returns the value that was added to the median field in this mutation. +// AddedMedian returns the value that was added to the "median" field in this mutation. func (m *HistogramMutation) AddedMedian() (r float64, exists bool) { v := m.addmedian if v == nil { @@ -3447,19 +3704,19 @@ func (m *HistogramMutation) AddedMedian() (r float64, exists bool) { return *v, true } -// ResetMedian reset all changes of the "median" field. +// ResetMedian resets all changes to the "median" field. func (m *HistogramMutation) ResetMedian() { m.median = nil m.addmedian = nil } -// SetP75 sets the p75 field. +// SetP75 sets the "p75" field. func (m *HistogramMutation) SetP75(f float64) { m.p75 = &f m.addp75 = nil } -// P75 returns the p75 value in the mutation. +// P75 returns the value of the "p75" field in the mutation. func (m *HistogramMutation) P75() (r float64, exists bool) { v := m.p75 if v == nil { @@ -3468,16 +3725,15 @@ func (m *HistogramMutation) P75() (r float64, exists bool) { return *v, true } -// OldP75 returns the old p75 value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldP75 returns the old "p75" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldP75(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldP75 is allowed only on UpdateOne operations") + return v, errors.New("OldP75 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldP75 requires an ID field in the mutation") + return v, errors.New("OldP75 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3486,7 +3742,7 @@ func (m *HistogramMutation) OldP75(ctx context.Context) (v float64, err error) { return oldValue.P75, nil } -// AddP75 adds f to p75. +// AddP75 adds f to the "p75" field. func (m *HistogramMutation) AddP75(f float64) { if m.addp75 != nil { *m.addp75 += f @@ -3495,7 +3751,7 @@ func (m *HistogramMutation) AddP75(f float64) { } } -// AddedP75 returns the value that was added to the p75 field in this mutation. +// AddedP75 returns the value that was added to the "p75" field in this mutation. func (m *HistogramMutation) AddedP75() (r float64, exists bool) { v := m.addp75 if v == nil { @@ -3504,19 +3760,19 @@ func (m *HistogramMutation) AddedP75() (r float64, exists bool) { return *v, true } -// ResetP75 reset all changes of the "p75" field. +// ResetP75 resets all changes to the "p75" field. func (m *HistogramMutation) ResetP75() { m.p75 = nil m.addp75 = nil } -// SetP95 sets the p95 field. +// SetP95 sets the "p95" field. func (m *HistogramMutation) SetP95(f float64) { m.p95 = &f m.addp95 = nil } -// P95 returns the p95 value in the mutation. +// P95 returns the value of the "p95" field in the mutation. func (m *HistogramMutation) P95() (r float64, exists bool) { v := m.p95 if v == nil { @@ -3525,16 +3781,15 @@ func (m *HistogramMutation) P95() (r float64, exists bool) { return *v, true } -// OldP95 returns the old p95 value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldP95 returns the old "p95" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldP95(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldP95 is allowed only on UpdateOne operations") + return v, errors.New("OldP95 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldP95 requires an ID field in the mutation") + return v, errors.New("OldP95 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3543,7 +3798,7 @@ func (m *HistogramMutation) OldP95(ctx context.Context) (v float64, err error) { return oldValue.P95, nil } -// AddP95 adds f to p95. +// AddP95 adds f to the "p95" field. func (m *HistogramMutation) AddP95(f float64) { if m.addp95 != nil { *m.addp95 += f @@ -3552,7 +3807,7 @@ func (m *HistogramMutation) AddP95(f float64) { } } -// AddedP95 returns the value that was added to the p95 field in this mutation. +// AddedP95 returns the value that was added to the "p95" field in this mutation. func (m *HistogramMutation) AddedP95() (r float64, exists bool) { v := m.addp95 if v == nil { @@ -3561,19 +3816,19 @@ func (m *HistogramMutation) AddedP95() (r float64, exists bool) { return *v, true } -// ResetP95 reset all changes of the "p95" field. +// ResetP95 resets all changes to the "p95" field. func (m *HistogramMutation) ResetP95() { m.p95 = nil m.addp95 = nil } -// SetP99 sets the p99 field. +// SetP99 sets the "p99" field. func (m *HistogramMutation) SetP99(f float64) { m.p99 = &f m.addp99 = nil } -// P99 returns the p99 value in the mutation. +// P99 returns the value of the "p99" field in the mutation. func (m *HistogramMutation) P99() (r float64, exists bool) { v := m.p99 if v == nil { @@ -3582,16 +3837,15 @@ func (m *HistogramMutation) P99() (r float64, exists bool) { return *v, true } -// OldP99 returns the old p99 value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldP99 returns the old "p99" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldP99(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldP99 is allowed only on UpdateOne operations") + return v, errors.New("OldP99 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldP99 requires an ID field in the mutation") + return v, errors.New("OldP99 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3600,7 +3854,7 @@ func (m *HistogramMutation) OldP99(ctx context.Context) (v float64, err error) { return oldValue.P99, nil } -// AddP99 adds f to p99. +// AddP99 adds f to the "p99" field. func (m *HistogramMutation) AddP99(f float64) { if m.addp99 != nil { *m.addp99 += f @@ -3609,7 +3863,7 @@ func (m *HistogramMutation) AddP99(f float64) { } } -// AddedP99 returns the value that was added to the p99 field in this mutation. +// AddedP99 returns the value that was added to the "p99" field in this mutation. func (m *HistogramMutation) AddedP99() (r float64, exists bool) { v := m.addp99 if v == nil { @@ -3618,19 +3872,19 @@ func (m *HistogramMutation) AddedP99() (r float64, exists bool) { return *v, true } -// ResetP99 reset all changes of the "p99" field. +// ResetP99 resets all changes to the "p99" field. func (m *HistogramMutation) ResetP99() { m.p99 = nil m.addp99 = nil } -// SetP999 sets the p999 field. +// SetP999 sets the "p999" field. func (m *HistogramMutation) SetP999(f float64) { m.p999 = &f m.addp999 = nil } -// P999 returns the p999 value in the mutation. +// P999 returns the value of the "p999" field in the mutation. func (m *HistogramMutation) P999() (r float64, exists bool) { v := m.p999 if v == nil { @@ -3639,16 +3893,15 @@ func (m *HistogramMutation) P999() (r float64, exists bool) { return *v, true } -// OldP999 returns the old p999 value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldP999 returns the old "p999" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldP999(ctx context.Context) (v float64, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldP999 is allowed only on UpdateOne operations") + return v, errors.New("OldP999 is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldP999 requires an ID field in the mutation") + return v, errors.New("OldP999 requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3657,7 +3910,7 @@ func (m *HistogramMutation) OldP999(ctx context.Context) (v float64, err error) return oldValue.P999, nil } -// AddP999 adds f to p999. +// AddP999 adds f to the "p999" field. func (m *HistogramMutation) AddP999(f float64) { if m.addp999 != nil { *m.addp999 += f @@ -3666,7 +3919,7 @@ func (m *HistogramMutation) AddP999(f float64) { } } -// AddedP999 returns the value that was added to the p999 field in this mutation. +// AddedP999 returns the value that was added to the "p999" field in this mutation. func (m *HistogramMutation) AddedP999() (r float64, exists bool) { v := m.addp999 if v == nil { @@ -3675,18 +3928,18 @@ func (m *HistogramMutation) AddedP999() (r float64, exists bool) { return *v, true } -// ResetP999 reset all changes of the "p999" field. +// ResetP999 resets all changes to the "p999" field. func (m *HistogramMutation) ResetP999() { m.p999 = nil m.addp999 = nil } -// SetWID sets the wID field. +// SetWID sets the "wID" field. func (m *HistogramMutation) SetWID(s string) { m.wID = &s } -// WID returns the wID value in the mutation. +// WID returns the value of the "wID" field in the mutation. func (m *HistogramMutation) WID() (r string, exists bool) { v := m.wID if v == nil { @@ -3695,16 +3948,15 @@ func (m *HistogramMutation) WID() (r string, exists bool) { return *v, true } -// OldWID returns the old wID value of the Histogram. -// If the Histogram object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldWID returns the old "wID" field's value of the Histogram entity. +// If the Histogram object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *HistogramMutation) OldWID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldWID is allowed only on UpdateOne operations") + return v, errors.New("OldWID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldWID requires an ID field in the mutation") + return v, errors.New("OldWID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -3713,27 +3965,27 @@ func (m *HistogramMutation) OldWID(ctx context.Context) (v string, err error) { return oldValue.WID, nil } -// ResetWID reset all changes of the "wID" field. +// ResetWID resets all changes to the "wID" field. func (m *HistogramMutation) ResetWID() { m.wID = nil } -// SetMetricID sets the metric edge to Metric by id. +// SetMetricID sets the "metric" edge to the Metric entity by id. func (m *HistogramMutation) SetMetricID(id int) { m.metric = &id } -// ClearMetric clears the metric edge to Metric. +// ClearMetric clears the "metric" edge to the Metric entity. func (m *HistogramMutation) ClearMetric() { m.clearedmetric = true } -// MetricCleared returns if the edge metric was cleared. +// MetricCleared reports if the "metric" edge to the Metric entity was cleared. func (m *HistogramMutation) MetricCleared() bool { return m.clearedmetric } -// MetricID returns the metric id in the mutation. +// MetricID returns the "metric" edge ID in the mutation. func (m *HistogramMutation) MetricID() (id int, exists bool) { if m.metric != nil { return *m.metric, true @@ -3741,8 +3993,8 @@ func (m *HistogramMutation) MetricID() (id int, exists bool) { return } -// MetricIDs returns the metric ids in the mutation. -// Note that ids always returns len(ids) <= 1 for unique edges, and you should use +// MetricIDs returns the "metric" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // MetricID instead. It exists only for internal usage by the builders. func (m *HistogramMutation) MetricIDs() (ids []int) { if id := m.metric; id != nil { @@ -3751,25 +4003,45 @@ func (m *HistogramMutation) MetricIDs() (ids []int) { return } -// ResetMetric reset all changes of the "metric" edge. +// ResetMetric resets all changes to the "metric" edge. func (m *HistogramMutation) ResetMetric() { m.metric = nil m.clearedmetric = false } +// Where appends a list predicates to the HistogramMutation builder. +func (m *HistogramMutation) Where(ps ...predicate.Histogram) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the HistogramMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *HistogramMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Histogram, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + // Op returns the operation name. func (m *HistogramMutation) Op() Op { return m.op } +// SetOp allows setting the mutation operation. +func (m *HistogramMutation) SetOp(op Op) { + m.op = op +} + // Type returns the node type of this mutation (Histogram). func (m *HistogramMutation) Type() string { return m.typ } -// Fields returns all fields that were changed during -// this mutation. Note that, in order to get all numeric -// fields that were in/decremented, call AddedFields(). +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). func (m *HistogramMutation) Fields() []string { fields := make([]string, 0, 12) if m.time != nil { @@ -3811,9 +4083,9 @@ func (m *HistogramMutation) Fields() []string { return fields } -// Field returns the value of a field with the given name. -// The second boolean value indicates that this field was -// not set, or was not define in the schema. +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. func (m *HistogramMutation) Field(name string) (ent.Value, bool) { switch name { case histogram.FieldTime: @@ -3844,9 +4116,9 @@ func (m *HistogramMutation) Field(name string) (ent.Value, bool) { return nil, false } -// OldField returns the old value of the field from the database. -// An error is returned if the mutation operation is not UpdateOne, -// or the query to the database was failed. +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. func (m *HistogramMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { case histogram.FieldTime: @@ -3877,9 +4149,9 @@ func (m *HistogramMutation) OldField(ctx context.Context, name string) (ent.Valu return nil, fmt.Errorf("unknown Histogram field %s", name) } -// SetField sets the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *HistogramMutation) SetField(name string, value ent.Value) error { switch name { case histogram.FieldTime: @@ -3970,8 +4242,8 @@ func (m *HistogramMutation) SetField(name string, value ent.Value) error { return fmt.Errorf("unknown Histogram field %s", name) } -// AddedFields returns all numeric fields that were incremented -// or decremented during this mutation. +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. func (m *HistogramMutation) AddedFields() []string { var fields []string if m.addtime != nil { @@ -4010,9 +4282,9 @@ func (m *HistogramMutation) AddedFields() []string { return fields } -// AddedField returns the numeric value that was in/decremented -// from a field with the given name. The second value indicates -// that this field was not set, or was not define in the schema. +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. func (m *HistogramMutation) AddedField(name string) (ent.Value, bool) { switch name { case histogram.FieldTime: @@ -4041,9 +4313,9 @@ func (m *HistogramMutation) AddedField(name string) (ent.Value, bool) { return nil, false } -// AddField adds the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *HistogramMutation) AddField(name string, value ent.Value) error { switch name { case histogram.FieldTime: @@ -4127,28 +4399,27 @@ func (m *HistogramMutation) AddField(name string, value ent.Value) error { return fmt.Errorf("unknown Histogram numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared -// during this mutation. +// ClearedFields returns all nullable fields that were cleared during this +// mutation. func (m *HistogramMutation) ClearedFields() []string { return nil } -// FieldCleared returns a boolean indicates if this field was +// FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. func (m *HistogramMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } -// ClearField clears the value for the given name. It returns an +// ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *HistogramMutation) ClearField(name string) error { return fmt.Errorf("unknown Histogram nullable field %s", name) } -// ResetField resets all changes in the mutation regarding the -// given field name. It returns an error if the field is not -// defined in the schema. +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. func (m *HistogramMutation) ResetField(name string) error { switch name { case histogram.FieldTime: @@ -4191,8 +4462,7 @@ func (m *HistogramMutation) ResetField(name string) error { return fmt.Errorf("unknown Histogram field %s", name) } -// AddedEdges returns all edge names that were set/added in this -// mutation. +// AddedEdges returns all edge names that were set/added in this mutation. func (m *HistogramMutation) AddedEdges() []string { edges := make([]string, 0, 1) if m.metric != nil { @@ -4201,8 +4471,8 @@ func (m *HistogramMutation) AddedEdges() []string { return edges } -// AddedIDs returns all ids (to other nodes) that were added for -// the given edge name. +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. func (m *HistogramMutation) AddedIDs(name string) []ent.Value { switch name { case histogram.EdgeMetric: @@ -4213,23 +4483,19 @@ func (m *HistogramMutation) AddedIDs(name string) []ent.Value { return nil } -// RemovedEdges returns all edge names that were removed in this -// mutation. +// RemovedEdges returns all edge names that were removed in this mutation. func (m *HistogramMutation) RemovedEdges() []string { edges := make([]string, 0, 1) return edges } -// RemovedIDs returns all ids (to other nodes) that were removed for -// the given edge name. +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. func (m *HistogramMutation) RemovedIDs(name string) []ent.Value { - switch name { - } return nil } -// ClearedEdges returns all edge names that were cleared in this -// mutation. +// ClearedEdges returns all edge names that were cleared in this mutation. func (m *HistogramMutation) ClearedEdges() []string { edges := make([]string, 0, 1) if m.clearedmetric { @@ -4238,8 +4504,8 @@ func (m *HistogramMutation) ClearedEdges() []string { return edges } -// EdgeCleared returns a boolean indicates if this edge was -// cleared in this mutation. +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. func (m *HistogramMutation) EdgeCleared(name string) bool { switch name { case histogram.EdgeMetric: @@ -4248,8 +4514,8 @@ func (m *HistogramMutation) EdgeCleared(name string) bool { return false } -// ClearEdge clears the value for the given name. It returns an -// error if the edge name is not defined in the schema. +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. func (m *HistogramMutation) ClearEdge(name string) error { switch name { case histogram.EdgeMetric: @@ -4259,9 +4525,8 @@ func (m *HistogramMutation) ClearEdge(name string) error { return fmt.Errorf("unknown Histogram unique edge %s", name) } -// ResetEdge resets all changes in the mutation regarding the -// given edge name. It returns an error if the edge is not -// defined in the schema. +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. func (m *HistogramMutation) ResetEdge(name string) error { switch name { case histogram.EdgeMetric: @@ -4271,8 +4536,7 @@ func (m *HistogramMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Histogram edge %s", name) } -// MetricMutation represents an operation that mutate the Metrics -// nodes in the graph. +// MetricMutation represents an operation that mutates the Metric nodes in the graph. type MetricMutation struct { config op Op @@ -4294,14 +4558,15 @@ type MetricMutation struct { clearedgauges bool done bool oldValue func(context.Context) (*Metric, error) + predicates []predicate.Metric } var _ ent.Mutation = (*MetricMutation)(nil) -// metricOption allows to manage the mutation configuration using functional options. +// metricOption allows management of the mutation configuration using functional options. type metricOption func(*MetricMutation) -// newMetricMutation creates new mutation for $n.Name. +// newMetricMutation creates new mutation for the Metric entity. func newMetricMutation(c config, op Op, opts ...metricOption) *MetricMutation { m := &MetricMutation{ config: c, @@ -4315,7 +4580,7 @@ func newMetricMutation(c config, op Op, opts ...metricOption) *MetricMutation { return m } -// withMetricID sets the id field of the mutation. +// withMetricID sets the ID field of the mutation. func withMetricID(id int) metricOption { return func(m *MetricMutation) { var ( @@ -4326,7 +4591,7 @@ func withMetricID(id int) metricOption { m.oldValue = func(ctx context.Context) (*Metric, error) { once.Do(func() { if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") + err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().Metric.Get(ctx, id) } @@ -4359,15 +4624,15 @@ func (m MetricMutation) Client() *Client { // it returns an error otherwise. func (m MetricMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("ent: mutation is not running in a transaction") + return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } -// ID returns the id value in the mutation. Note that, the id -// is available only if it was provided to the builder. +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. func (m *MetricMutation) ID() (id int, exists bool) { if m.id == nil { return @@ -4375,12 +4640,31 @@ func (m *MetricMutation) ID() (id int, exists bool) { return *m.id, true } -// SetTitle sets the title field. +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *MetricMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Metric.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetTitle sets the "title" field. func (m *MetricMutation) SetTitle(s string) { m.title = &s } -// Title returns the title value in the mutation. +// Title returns the value of the "title" field in the mutation. func (m *MetricMutation) Title() (r string, exists bool) { v := m.title if v == nil { @@ -4389,16 +4673,15 @@ func (m *MetricMutation) Title() (r string, exists bool) { return *v, true } -// OldTitle returns the old title value of the Metric. -// If the Metric object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldTitle returns the old "title" field's value of the Metric entity. +// If the Metric object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *MetricMutation) OldTitle(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldTitle is allowed only on UpdateOne operations") + return v, errors.New("OldTitle is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldTitle requires an ID field in the mutation") + return v, errors.New("OldTitle requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -4407,17 +4690,17 @@ func (m *MetricMutation) OldTitle(ctx context.Context) (v string, err error) { return oldValue.Title, nil } -// ResetTitle reset all changes of the "title" field. +// ResetTitle resets all changes to the "title" field. func (m *MetricMutation) ResetTitle() { m.title = nil } -// SetType sets the type field. +// SetType sets the "type" field. func (m *MetricMutation) SetType(s string) { m._type = &s } -// GetType returns the type value in the mutation. +// GetType returns the value of the "type" field in the mutation. func (m *MetricMutation) GetType() (r string, exists bool) { v := m._type if v == nil { @@ -4426,16 +4709,15 @@ func (m *MetricMutation) GetType() (r string, exists bool) { return *v, true } -// OldType returns the old type value of the Metric. -// If the Metric object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldType returns the old "type" field's value of the Metric entity. +// If the Metric object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *MetricMutation) OldType(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldType is allowed only on UpdateOne operations") + return v, errors.New("OldType is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldType requires an ID field in the mutation") + return v, errors.New("OldType requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -4444,27 +4726,27 @@ func (m *MetricMutation) OldType(ctx context.Context) (v string, err error) { return oldValue.Type, nil } -// ResetType reset all changes of the "type" field. +// ResetType resets all changes to the "type" field. func (m *MetricMutation) ResetType() { m._type = nil } -// SetGraphID sets the graph edge to Graph by id. +// SetGraphID sets the "graph" edge to the Graph entity by id. func (m *MetricMutation) SetGraphID(id int) { m.graph = &id } -// ClearGraph clears the graph edge to Graph. +// ClearGraph clears the "graph" edge to the Graph entity. func (m *MetricMutation) ClearGraph() { m.clearedgraph = true } -// GraphCleared returns if the edge graph was cleared. +// GraphCleared reports if the "graph" edge to the Graph entity was cleared. func (m *MetricMutation) GraphCleared() bool { return m.clearedgraph } -// GraphID returns the graph id in the mutation. +// GraphID returns the "graph" edge ID in the mutation. func (m *MetricMutation) GraphID() (id int, exists bool) { if m.graph != nil { return *m.graph, true @@ -4472,8 +4754,8 @@ func (m *MetricMutation) GraphID() (id int, exists bool) { return } -// GraphIDs returns the graph ids in the mutation. -// Note that ids always returns len(ids) <= 1 for unique edges, and you should use +// GraphIDs returns the "graph" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // GraphID instead. It exists only for internal usage by the builders. func (m *MetricMutation) GraphIDs() (ids []int) { if id := m.graph; id != nil { @@ -4482,13 +4764,13 @@ func (m *MetricMutation) GraphIDs() (ids []int) { return } -// ResetGraph reset all changes of the "graph" edge. +// ResetGraph resets all changes to the "graph" edge. func (m *MetricMutation) ResetGraph() { m.graph = nil m.clearedgraph = false } -// AddHistogramIDs adds the histograms edge to Histogram by ids. +// AddHistogramIDs adds the "histograms" edge to the Histogram entity by ids. func (m *MetricMutation) AddHistogramIDs(ids ...int) { if m.histograms == nil { m.histograms = make(map[int]struct{}) @@ -4498,27 +4780,28 @@ func (m *MetricMutation) AddHistogramIDs(ids ...int) { } } -// ClearHistograms clears the histograms edge to Histogram. +// ClearHistograms clears the "histograms" edge to the Histogram entity. func (m *MetricMutation) ClearHistograms() { m.clearedhistograms = true } -// HistogramsCleared returns if the edge histograms was cleared. +// HistogramsCleared reports if the "histograms" edge to the Histogram entity was cleared. func (m *MetricMutation) HistogramsCleared() bool { return m.clearedhistograms } -// RemoveHistogramIDs removes the histograms edge to Histogram by ids. +// RemoveHistogramIDs removes the "histograms" edge to the Histogram entity by IDs. func (m *MetricMutation) RemoveHistogramIDs(ids ...int) { if m.removedhistograms == nil { m.removedhistograms = make(map[int]struct{}) } for i := range ids { + delete(m.histograms, ids[i]) m.removedhistograms[ids[i]] = struct{}{} } } -// RemovedHistograms returns the removed ids of histograms. +// RemovedHistograms returns the removed IDs of the "histograms" edge to the Histogram entity. func (m *MetricMutation) RemovedHistogramsIDs() (ids []int) { for id := range m.removedhistograms { ids = append(ids, id) @@ -4526,7 +4809,7 @@ func (m *MetricMutation) RemovedHistogramsIDs() (ids []int) { return } -// HistogramsIDs returns the histograms ids in the mutation. +// HistogramsIDs returns the "histograms" edge IDs in the mutation. func (m *MetricMutation) HistogramsIDs() (ids []int) { for id := range m.histograms { ids = append(ids, id) @@ -4534,14 +4817,14 @@ func (m *MetricMutation) HistogramsIDs() (ids []int) { return } -// ResetHistograms reset all changes of the "histograms" edge. +// ResetHistograms resets all changes to the "histograms" edge. func (m *MetricMutation) ResetHistograms() { m.histograms = nil m.clearedhistograms = false m.removedhistograms = nil } -// AddCounterIDs adds the counters edge to Counter by ids. +// AddCounterIDs adds the "counters" edge to the Counter entity by ids. func (m *MetricMutation) AddCounterIDs(ids ...int) { if m.counters == nil { m.counters = make(map[int]struct{}) @@ -4551,27 +4834,28 @@ func (m *MetricMutation) AddCounterIDs(ids ...int) { } } -// ClearCounters clears the counters edge to Counter. +// ClearCounters clears the "counters" edge to the Counter entity. func (m *MetricMutation) ClearCounters() { m.clearedcounters = true } -// CountersCleared returns if the edge counters was cleared. +// CountersCleared reports if the "counters" edge to the Counter entity was cleared. func (m *MetricMutation) CountersCleared() bool { return m.clearedcounters } -// RemoveCounterIDs removes the counters edge to Counter by ids. +// RemoveCounterIDs removes the "counters" edge to the Counter entity by IDs. func (m *MetricMutation) RemoveCounterIDs(ids ...int) { if m.removedcounters == nil { m.removedcounters = make(map[int]struct{}) } for i := range ids { + delete(m.counters, ids[i]) m.removedcounters[ids[i]] = struct{}{} } } -// RemovedCounters returns the removed ids of counters. +// RemovedCounters returns the removed IDs of the "counters" edge to the Counter entity. func (m *MetricMutation) RemovedCountersIDs() (ids []int) { for id := range m.removedcounters { ids = append(ids, id) @@ -4579,7 +4863,7 @@ func (m *MetricMutation) RemovedCountersIDs() (ids []int) { return } -// CountersIDs returns the counters ids in the mutation. +// CountersIDs returns the "counters" edge IDs in the mutation. func (m *MetricMutation) CountersIDs() (ids []int) { for id := range m.counters { ids = append(ids, id) @@ -4587,14 +4871,14 @@ func (m *MetricMutation) CountersIDs() (ids []int) { return } -// ResetCounters reset all changes of the "counters" edge. +// ResetCounters resets all changes to the "counters" edge. func (m *MetricMutation) ResetCounters() { m.counters = nil m.clearedcounters = false m.removedcounters = nil } -// AddGaugeIDs adds the gauges edge to Gauge by ids. +// AddGaugeIDs adds the "gauges" edge to the Gauge entity by ids. func (m *MetricMutation) AddGaugeIDs(ids ...int) { if m.gauges == nil { m.gauges = make(map[int]struct{}) @@ -4604,27 +4888,28 @@ func (m *MetricMutation) AddGaugeIDs(ids ...int) { } } -// ClearGauges clears the gauges edge to Gauge. +// ClearGauges clears the "gauges" edge to the Gauge entity. func (m *MetricMutation) ClearGauges() { m.clearedgauges = true } -// GaugesCleared returns if the edge gauges was cleared. +// GaugesCleared reports if the "gauges" edge to the Gauge entity was cleared. func (m *MetricMutation) GaugesCleared() bool { return m.clearedgauges } -// RemoveGaugeIDs removes the gauges edge to Gauge by ids. +// RemoveGaugeIDs removes the "gauges" edge to the Gauge entity by IDs. func (m *MetricMutation) RemoveGaugeIDs(ids ...int) { if m.removedgauges == nil { m.removedgauges = make(map[int]struct{}) } for i := range ids { + delete(m.gauges, ids[i]) m.removedgauges[ids[i]] = struct{}{} } } -// RemovedGauges returns the removed ids of gauges. +// RemovedGauges returns the removed IDs of the "gauges" edge to the Gauge entity. func (m *MetricMutation) RemovedGaugesIDs() (ids []int) { for id := range m.removedgauges { ids = append(ids, id) @@ -4632,7 +4917,7 @@ func (m *MetricMutation) RemovedGaugesIDs() (ids []int) { return } -// GaugesIDs returns the gauges ids in the mutation. +// GaugesIDs returns the "gauges" edge IDs in the mutation. func (m *MetricMutation) GaugesIDs() (ids []int) { for id := range m.gauges { ids = append(ids, id) @@ -4640,26 +4925,46 @@ func (m *MetricMutation) GaugesIDs() (ids []int) { return } -// ResetGauges reset all changes of the "gauges" edge. +// ResetGauges resets all changes to the "gauges" edge. func (m *MetricMutation) ResetGauges() { m.gauges = nil m.clearedgauges = false m.removedgauges = nil } +// Where appends a list predicates to the MetricMutation builder. +func (m *MetricMutation) Where(ps ...predicate.Metric) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the MetricMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *MetricMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Metric, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + // Op returns the operation name. func (m *MetricMutation) Op() Op { return m.op } +// SetOp allows setting the mutation operation. +func (m *MetricMutation) SetOp(op Op) { + m.op = op +} + // Type returns the node type of this mutation (Metric). func (m *MetricMutation) Type() string { return m.typ } -// Fields returns all fields that were changed during -// this mutation. Note that, in order to get all numeric -// fields that were in/decremented, call AddedFields(). +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). func (m *MetricMutation) Fields() []string { fields := make([]string, 0, 2) if m.title != nil { @@ -4671,9 +4976,9 @@ func (m *MetricMutation) Fields() []string { return fields } -// Field returns the value of a field with the given name. -// The second boolean value indicates that this field was -// not set, or was not define in the schema. +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. func (m *MetricMutation) Field(name string) (ent.Value, bool) { switch name { case metric.FieldTitle: @@ -4684,9 +4989,9 @@ func (m *MetricMutation) Field(name string) (ent.Value, bool) { return nil, false } -// OldField returns the old value of the field from the database. -// An error is returned if the mutation operation is not UpdateOne, -// or the query to the database was failed. +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. func (m *MetricMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { case metric.FieldTitle: @@ -4697,9 +5002,9 @@ func (m *MetricMutation) OldField(ctx context.Context, name string) (ent.Value, return nil, fmt.Errorf("unknown Metric field %s", name) } -// SetField sets the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *MetricMutation) SetField(name string, value ent.Value) error { switch name { case metric.FieldTitle: @@ -4720,50 +5025,49 @@ func (m *MetricMutation) SetField(name string, value ent.Value) error { return fmt.Errorf("unknown Metric field %s", name) } -// AddedFields returns all numeric fields that were incremented -// or decremented during this mutation. +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. func (m *MetricMutation) AddedFields() []string { return nil } -// AddedField returns the numeric value that was in/decremented -// from a field with the given name. The second value indicates -// that this field was not set, or was not define in the schema. +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. func (m *MetricMutation) AddedField(name string) (ent.Value, bool) { return nil, false } -// AddField adds the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *MetricMutation) AddField(name string, value ent.Value) error { switch name { } return fmt.Errorf("unknown Metric numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared -// during this mutation. +// ClearedFields returns all nullable fields that were cleared during this +// mutation. func (m *MetricMutation) ClearedFields() []string { return nil } -// FieldCleared returns a boolean indicates if this field was +// FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. func (m *MetricMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } -// ClearField clears the value for the given name. It returns an +// ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *MetricMutation) ClearField(name string) error { return fmt.Errorf("unknown Metric nullable field %s", name) } -// ResetField resets all changes in the mutation regarding the -// given field name. It returns an error if the field is not -// defined in the schema. +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. func (m *MetricMutation) ResetField(name string) error { switch name { case metric.FieldTitle: @@ -4776,8 +5080,7 @@ func (m *MetricMutation) ResetField(name string) error { return fmt.Errorf("unknown Metric field %s", name) } -// AddedEdges returns all edge names that were set/added in this -// mutation. +// AddedEdges returns all edge names that were set/added in this mutation. func (m *MetricMutation) AddedEdges() []string { edges := make([]string, 0, 4) if m.graph != nil { @@ -4795,8 +5098,8 @@ func (m *MetricMutation) AddedEdges() []string { return edges } -// AddedIDs returns all ids (to other nodes) that were added for -// the given edge name. +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. func (m *MetricMutation) AddedIDs(name string) []ent.Value { switch name { case metric.EdgeGraph: @@ -4825,8 +5128,7 @@ func (m *MetricMutation) AddedIDs(name string) []ent.Value { return nil } -// RemovedEdges returns all edge names that were removed in this -// mutation. +// RemovedEdges returns all edge names that were removed in this mutation. func (m *MetricMutation) RemovedEdges() []string { edges := make([]string, 0, 4) if m.removedhistograms != nil { @@ -4841,8 +5143,8 @@ func (m *MetricMutation) RemovedEdges() []string { return edges } -// RemovedIDs returns all ids (to other nodes) that were removed for -// the given edge name. +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. func (m *MetricMutation) RemovedIDs(name string) []ent.Value { switch name { case metric.EdgeHistograms: @@ -4867,8 +5169,7 @@ func (m *MetricMutation) RemovedIDs(name string) []ent.Value { return nil } -// ClearedEdges returns all edge names that were cleared in this -// mutation. +// ClearedEdges returns all edge names that were cleared in this mutation. func (m *MetricMutation) ClearedEdges() []string { edges := make([]string, 0, 4) if m.clearedgraph { @@ -4886,8 +5187,8 @@ func (m *MetricMutation) ClearedEdges() []string { return edges } -// EdgeCleared returns a boolean indicates if this edge was -// cleared in this mutation. +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. func (m *MetricMutation) EdgeCleared(name string) bool { switch name { case metric.EdgeGraph: @@ -4902,8 +5203,8 @@ func (m *MetricMutation) EdgeCleared(name string) bool { return false } -// ClearEdge clears the value for the given name. It returns an -// error if the edge name is not defined in the schema. +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. func (m *MetricMutation) ClearEdge(name string) error { switch name { case metric.EdgeGraph: @@ -4913,9 +5214,8 @@ func (m *MetricMutation) ClearEdge(name string) error { return fmt.Errorf("unknown Metric unique edge %s", name) } -// ResetEdge resets all changes in the mutation regarding the -// given edge name. It returns an error if the edge is not -// defined in the schema. +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. func (m *MetricMutation) ResetEdge(name string) error { switch name { case metric.EdgeGraph: @@ -4934,8 +5234,7 @@ func (m *MetricMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Metric edge %s", name) } -// TagMutation represents an operation that mutate the Tags -// nodes in the graph. +// TagMutation represents an operation that mutates the Tag nodes in the graph. type TagMutation struct { config op Op @@ -4947,14 +5246,15 @@ type TagMutation struct { clearedapplication bool done bool oldValue func(context.Context) (*Tag, error) + predicates []predicate.Tag } var _ ent.Mutation = (*TagMutation)(nil) -// tagOption allows to manage the mutation configuration using functional options. +// tagOption allows management of the mutation configuration using functional options. type tagOption func(*TagMutation) -// newTagMutation creates new mutation for $n.Name. +// newTagMutation creates new mutation for the Tag entity. func newTagMutation(c config, op Op, opts ...tagOption) *TagMutation { m := &TagMutation{ config: c, @@ -4968,7 +5268,7 @@ func newTagMutation(c config, op Op, opts ...tagOption) *TagMutation { return m } -// withTagID sets the id field of the mutation. +// withTagID sets the ID field of the mutation. func withTagID(id int) tagOption { return func(m *TagMutation) { var ( @@ -4979,7 +5279,7 @@ func withTagID(id int) tagOption { m.oldValue = func(ctx context.Context) (*Tag, error) { once.Do(func() { if m.done { - err = fmt.Errorf("querying old values post mutation is not allowed") + err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().Tag.Get(ctx, id) } @@ -5012,15 +5312,15 @@ func (m TagMutation) Client() *Client { // it returns an error otherwise. func (m TagMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { - return nil, fmt.Errorf("ent: mutation is not running in a transaction") + return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } -// ID returns the id value in the mutation. Note that, the id -// is available only if it was provided to the builder. +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. func (m *TagMutation) ID() (id int, exists bool) { if m.id == nil { return @@ -5028,12 +5328,31 @@ func (m *TagMutation) ID() (id int, exists bool) { return *m.id, true } -// SetName sets the name field. +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *TagMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().Tag.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. func (m *TagMutation) SetName(s string) { m.name = &s } -// Name returns the name value in the mutation. +// Name returns the value of the "name" field in the mutation. func (m *TagMutation) Name() (r string, exists bool) { v := m.name if v == nil { @@ -5042,16 +5361,15 @@ func (m *TagMutation) Name() (r string, exists bool) { return *v, true } -// OldName returns the old name value of the Tag. -// If the Tag object wasn't provided to the builder, the object is fetched -// from the database. -// An error is returned if the mutation operation is not UpdateOne, or database query fails. +// OldName returns the old "name" field's value of the Tag entity. +// If the Tag object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *TagMutation) OldName(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, fmt.Errorf("OldName is allowed only on UpdateOne operations") + return v, errors.New("OldName is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, fmt.Errorf("OldName requires an ID field in the mutation") + return v, errors.New("OldName requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { @@ -5060,27 +5378,27 @@ func (m *TagMutation) OldName(ctx context.Context) (v string, err error) { return oldValue.Name, nil } -// ResetName reset all changes of the "name" field. +// ResetName resets all changes to the "name" field. func (m *TagMutation) ResetName() { m.name = nil } -// SetApplicationID sets the application edge to Application by id. +// SetApplicationID sets the "application" edge to the Application entity by id. func (m *TagMutation) SetApplicationID(id int) { m.application = &id } -// ClearApplication clears the application edge to Application. +// ClearApplication clears the "application" edge to the Application entity. func (m *TagMutation) ClearApplication() { m.clearedapplication = true } -// ApplicationCleared returns if the edge application was cleared. +// ApplicationCleared reports if the "application" edge to the Application entity was cleared. func (m *TagMutation) ApplicationCleared() bool { return m.clearedapplication } -// ApplicationID returns the application id in the mutation. +// ApplicationID returns the "application" edge ID in the mutation. func (m *TagMutation) ApplicationID() (id int, exists bool) { if m.application != nil { return *m.application, true @@ -5088,8 +5406,8 @@ func (m *TagMutation) ApplicationID() (id int, exists bool) { return } -// ApplicationIDs returns the application ids in the mutation. -// Note that ids always returns len(ids) <= 1 for unique edges, and you should use +// ApplicationIDs returns the "application" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // ApplicationID instead. It exists only for internal usage by the builders. func (m *TagMutation) ApplicationIDs() (ids []int) { if id := m.application; id != nil { @@ -5098,25 +5416,45 @@ func (m *TagMutation) ApplicationIDs() (ids []int) { return } -// ResetApplication reset all changes of the "application" edge. +// ResetApplication resets all changes to the "application" edge. func (m *TagMutation) ResetApplication() { m.application = nil m.clearedapplication = false } +// Where appends a list predicates to the TagMutation builder. +func (m *TagMutation) Where(ps ...predicate.Tag) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TagMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TagMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Tag, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + // Op returns the operation name. func (m *TagMutation) Op() Op { return m.op } +// SetOp allows setting the mutation operation. +func (m *TagMutation) SetOp(op Op) { + m.op = op +} + // Type returns the node type of this mutation (Tag). func (m *TagMutation) Type() string { return m.typ } -// Fields returns all fields that were changed during -// this mutation. Note that, in order to get all numeric -// fields that were in/decremented, call AddedFields(). +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). func (m *TagMutation) Fields() []string { fields := make([]string, 0, 1) if m.name != nil { @@ -5125,9 +5463,9 @@ func (m *TagMutation) Fields() []string { return fields } -// Field returns the value of a field with the given name. -// The second boolean value indicates that this field was -// not set, or was not define in the schema. +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. func (m *TagMutation) Field(name string) (ent.Value, bool) { switch name { case tag.FieldName: @@ -5136,9 +5474,9 @@ func (m *TagMutation) Field(name string) (ent.Value, bool) { return nil, false } -// OldField returns the old value of the field from the database. -// An error is returned if the mutation operation is not UpdateOne, -// or the query to the database was failed. +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. func (m *TagMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { case tag.FieldName: @@ -5147,9 +5485,9 @@ func (m *TagMutation) OldField(ctx context.Context, name string) (ent.Value, err return nil, fmt.Errorf("unknown Tag field %s", name) } -// SetField sets the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *TagMutation) SetField(name string, value ent.Value) error { switch name { case tag.FieldName: @@ -5163,50 +5501,49 @@ func (m *TagMutation) SetField(name string, value ent.Value) error { return fmt.Errorf("unknown Tag field %s", name) } -// AddedFields returns all numeric fields that were incremented -// or decremented during this mutation. +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. func (m *TagMutation) AddedFields() []string { return nil } -// AddedField returns the numeric value that was in/decremented -// from a field with the given name. The second value indicates -// that this field was not set, or was not define in the schema. +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. func (m *TagMutation) AddedField(name string) (ent.Value, bool) { return nil, false } -// AddField adds the value for the given name. It returns an -// error if the field is not defined in the schema, or if the -// type mismatch the field type. +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. func (m *TagMutation) AddField(name string, value ent.Value) error { switch name { } return fmt.Errorf("unknown Tag numeric field %s", name) } -// ClearedFields returns all nullable fields that were cleared -// during this mutation. +// ClearedFields returns all nullable fields that were cleared during this +// mutation. func (m *TagMutation) ClearedFields() []string { return nil } -// FieldCleared returns a boolean indicates if this field was +// FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. func (m *TagMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } -// ClearField clears the value for the given name. It returns an +// ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *TagMutation) ClearField(name string) error { return fmt.Errorf("unknown Tag nullable field %s", name) } -// ResetField resets all changes in the mutation regarding the -// given field name. It returns an error if the field is not -// defined in the schema. +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. func (m *TagMutation) ResetField(name string) error { switch name { case tag.FieldName: @@ -5216,8 +5553,7 @@ func (m *TagMutation) ResetField(name string) error { return fmt.Errorf("unknown Tag field %s", name) } -// AddedEdges returns all edge names that were set/added in this -// mutation. +// AddedEdges returns all edge names that were set/added in this mutation. func (m *TagMutation) AddedEdges() []string { edges := make([]string, 0, 1) if m.application != nil { @@ -5226,8 +5562,8 @@ func (m *TagMutation) AddedEdges() []string { return edges } -// AddedIDs returns all ids (to other nodes) that were added for -// the given edge name. +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. func (m *TagMutation) AddedIDs(name string) []ent.Value { switch name { case tag.EdgeApplication: @@ -5238,23 +5574,19 @@ func (m *TagMutation) AddedIDs(name string) []ent.Value { return nil } -// RemovedEdges returns all edge names that were removed in this -// mutation. +// RemovedEdges returns all edge names that were removed in this mutation. func (m *TagMutation) RemovedEdges() []string { edges := make([]string, 0, 1) return edges } -// RemovedIDs returns all ids (to other nodes) that were removed for -// the given edge name. +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. func (m *TagMutation) RemovedIDs(name string) []ent.Value { - switch name { - } return nil } -// ClearedEdges returns all edge names that were cleared in this -// mutation. +// ClearedEdges returns all edge names that were cleared in this mutation. func (m *TagMutation) ClearedEdges() []string { edges := make([]string, 0, 1) if m.clearedapplication { @@ -5263,8 +5595,8 @@ func (m *TagMutation) ClearedEdges() []string { return edges } -// EdgeCleared returns a boolean indicates if this edge was -// cleared in this mutation. +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. func (m *TagMutation) EdgeCleared(name string) bool { switch name { case tag.EdgeApplication: @@ -5273,8 +5605,8 @@ func (m *TagMutation) EdgeCleared(name string) bool { return false } -// ClearEdge clears the value for the given name. It returns an -// error if the edge name is not defined in the schema. +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. func (m *TagMutation) ClearEdge(name string) error { switch name { case tag.EdgeApplication: @@ -5284,9 +5616,8 @@ func (m *TagMutation) ClearEdge(name string) error { return fmt.Errorf("unknown Tag unique edge %s", name) } -// ResetEdge resets all changes in the mutation regarding the -// given edge name. It returns an error if the edge is not -// defined in the schema. +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. func (m *TagMutation) ResetEdge(name string) error { switch name { case tag.EdgeApplication: diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go index b2f948b8..f9c8b1dc 100644 --- a/ent/predicate/predicate.go +++ b/ent/predicate/predicate.go @@ -1,9 +1,9 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package predicate import ( - "github.com/facebook/ent/dialect/sql" + "entgo.io/ent/dialect/sql" ) // Application is the predicate function for application builders. diff --git a/ent/privacy/privacy.go b/ent/privacy/privacy.go deleted file mode 100644 index 9bcb2253..00000000 --- a/ent/privacy/privacy.go +++ /dev/null @@ -1,403 +0,0 @@ -// Code generated by entc, DO NOT EDIT. - -package privacy - -import ( - "context" - "errors" - "fmt" - - "github.com/gobench-io/gobench/v2/ent" -) - -var ( - // Allow may be returned by rules to indicate that the policy - // evaluation should terminate with an allow decision. - Allow = errors.New("ent/privacy: allow rule") - - // Deny may be returned by rules to indicate that the policy - // evaluation should terminate with an deny decision. - Deny = errors.New("ent/privacy: deny rule") - - // Skip may be returned by rules to indicate that the policy - // evaluation should continue to the next rule. - Skip = errors.New("ent/privacy: skip rule") -) - -// Allowf returns an formatted wrapped Allow decision. -func Allowf(format string, a ...interface{}) error { - return fmt.Errorf(format+": %w", append(a, Allow)...) -} - -// Denyf returns an formatted wrapped Deny decision. -func Denyf(format string, a ...interface{}) error { - return fmt.Errorf(format+": %w", append(a, Deny)...) -} - -// Skipf returns an formatted wrapped Skip decision. -func Skipf(format string, a ...interface{}) error { - return fmt.Errorf(format+": %w", append(a, Skip)...) -} - -type decisionCtxKey struct{} - -// DecisionContext creates a decision context. -func DecisionContext(parent context.Context, decision error) context.Context { - if decision == nil || errors.Is(decision, Skip) { - return parent - } - return context.WithValue(parent, decisionCtxKey{}, decision) -} - -func decisionFromContext(ctx context.Context) (error, bool) { - decision, ok := ctx.Value(decisionCtxKey{}).(error) - if ok && errors.Is(decision, Allow) { - decision = nil - } - return decision, ok -} - -type ( - // QueryPolicy combines multiple query rules into a single policy. - QueryPolicy []QueryRule - - // QueryRule defines the interface deciding whether a - // query is allowed and optionally modify it. - QueryRule interface { - EvalQuery(context.Context, ent.Query) error - } -) - -// EvalQuery evaluates a query against a query policy. -func (policy QueryPolicy) EvalQuery(ctx context.Context, q ent.Query) error { - if decision, ok := decisionFromContext(ctx); ok { - return decision - } - for _, rule := range policy { - switch decision := rule.EvalQuery(ctx, q); { - case decision == nil || errors.Is(decision, Skip): - case errors.Is(decision, Allow): - return nil - default: - return decision - } - } - return nil -} - -// QueryRuleFunc type is an adapter to allow the use of -// ordinary functions as query rules. -type QueryRuleFunc func(context.Context, ent.Query) error - -// Eval returns f(ctx, q). -func (f QueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { - return f(ctx, q) -} - -type ( - // MutationPolicy combines multiple mutation rules into a single policy. - MutationPolicy []MutationRule - - // MutationRule defines the interface deciding whether a - // mutation is allowed and optionally modify it. - MutationRule interface { - EvalMutation(context.Context, ent.Mutation) error - } -) - -// EvalMutation evaluates a mutation against a mutation policy. -func (policy MutationPolicy) EvalMutation(ctx context.Context, m ent.Mutation) error { - if decision, ok := decisionFromContext(ctx); ok { - return decision - } - for _, rule := range policy { - switch decision := rule.EvalMutation(ctx, m); { - case decision == nil || errors.Is(decision, Skip): - case errors.Is(decision, Allow): - return nil - default: - return decision - } - } - return nil -} - -// MutationRuleFunc type is an adapter to allow the use of -// ordinary functions as mutation rules. -type MutationRuleFunc func(context.Context, ent.Mutation) error - -// EvalMutation returns f(ctx, m). -func (f MutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { - return f(ctx, m) -} - -// Policy groups query and mutation policies. -type Policy struct { - Query QueryPolicy - Mutation MutationPolicy -} - -// EvalQuery forwards evaluation to query policy. -func (policy Policy) EvalQuery(ctx context.Context, q ent.Query) error { - return policy.Query.EvalQuery(ctx, q) -} - -// EvalMutation forwards evaluation to mutation policy. -func (policy Policy) EvalMutation(ctx context.Context, m ent.Mutation) error { - return policy.Mutation.EvalMutation(ctx, m) -} - -// QueryMutationRule is the interface that groups query and mutation rules. -type QueryMutationRule interface { - QueryRule - MutationRule -} - -// AlwaysAllowRule returns a rule that returns an allow decision. -func AlwaysAllowRule() QueryMutationRule { - return fixedDecision{Allow} -} - -// AlwaysDenyRule returns a rule that returns a deny decision. -func AlwaysDenyRule() QueryMutationRule { - return fixedDecision{Deny} -} - -type fixedDecision struct { - decision error -} - -func (f fixedDecision) EvalQuery(context.Context, ent.Query) error { - return f.decision -} - -func (f fixedDecision) EvalMutation(context.Context, ent.Mutation) error { - return f.decision -} - -type contextDecision struct { - eval func(context.Context) error -} - -// ContextQueryMutationRule creates a query/mutation rule from a context eval func. -func ContextQueryMutationRule(eval func(context.Context) error) QueryMutationRule { - return contextDecision{eval} -} - -func (c contextDecision) EvalQuery(ctx context.Context, _ ent.Query) error { - return c.eval(ctx) -} - -func (c contextDecision) EvalMutation(ctx context.Context, _ ent.Mutation) error { - return c.eval(ctx) -} - -// OnMutationOperation evaluates the given rule only on a given mutation operation. -func OnMutationOperation(rule MutationRule, op ent.Op) MutationRule { - return MutationRuleFunc(func(ctx context.Context, m ent.Mutation) error { - if m.Op().Is(op) { - return rule.EvalMutation(ctx, m) - } - return Skip - }) -} - -// DenyMutationOperationRule returns a rule denying specified mutation operation. -func DenyMutationOperationRule(op ent.Op) MutationRule { - rule := MutationRuleFunc(func(_ context.Context, m ent.Mutation) error { - return Denyf("ent/privacy: operation %s is not allowed", m.Op()) - }) - return OnMutationOperation(rule, op) -} - -// The ApplicationQueryRuleFunc type is an adapter to allow the use of ordinary -// functions as a query rule. -type ApplicationQueryRuleFunc func(context.Context, *ent.ApplicationQuery) error - -// EvalQuery return f(ctx, q). -func (f ApplicationQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { - if q, ok := q.(*ent.ApplicationQuery); ok { - return f(ctx, q) - } - return Denyf("ent/privacy: unexpected query type %T, expect *ent.ApplicationQuery", q) -} - -// The ApplicationMutationRuleFunc type is an adapter to allow the use of ordinary -// functions as a mutation rule. -type ApplicationMutationRuleFunc func(context.Context, *ent.ApplicationMutation) error - -// EvalMutation calls f(ctx, m). -func (f ApplicationMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { - if m, ok := m.(*ent.ApplicationMutation); ok { - return f(ctx, m) - } - return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.ApplicationMutation", m) -} - -// The CounterQueryRuleFunc type is an adapter to allow the use of ordinary -// functions as a query rule. -type CounterQueryRuleFunc func(context.Context, *ent.CounterQuery) error - -// EvalQuery return f(ctx, q). -func (f CounterQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { - if q, ok := q.(*ent.CounterQuery); ok { - return f(ctx, q) - } - return Denyf("ent/privacy: unexpected query type %T, expect *ent.CounterQuery", q) -} - -// The CounterMutationRuleFunc type is an adapter to allow the use of ordinary -// functions as a mutation rule. -type CounterMutationRuleFunc func(context.Context, *ent.CounterMutation) error - -// EvalMutation calls f(ctx, m). -func (f CounterMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { - if m, ok := m.(*ent.CounterMutation); ok { - return f(ctx, m) - } - return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.CounterMutation", m) -} - -// The GaugeQueryRuleFunc type is an adapter to allow the use of ordinary -// functions as a query rule. -type GaugeQueryRuleFunc func(context.Context, *ent.GaugeQuery) error - -// EvalQuery return f(ctx, q). -func (f GaugeQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { - if q, ok := q.(*ent.GaugeQuery); ok { - return f(ctx, q) - } - return Denyf("ent/privacy: unexpected query type %T, expect *ent.GaugeQuery", q) -} - -// The GaugeMutationRuleFunc type is an adapter to allow the use of ordinary -// functions as a mutation rule. -type GaugeMutationRuleFunc func(context.Context, *ent.GaugeMutation) error - -// EvalMutation calls f(ctx, m). -func (f GaugeMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { - if m, ok := m.(*ent.GaugeMutation); ok { - return f(ctx, m) - } - return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.GaugeMutation", m) -} - -// The GraphQueryRuleFunc type is an adapter to allow the use of ordinary -// functions as a query rule. -type GraphQueryRuleFunc func(context.Context, *ent.GraphQuery) error - -// EvalQuery return f(ctx, q). -func (f GraphQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { - if q, ok := q.(*ent.GraphQuery); ok { - return f(ctx, q) - } - return Denyf("ent/privacy: unexpected query type %T, expect *ent.GraphQuery", q) -} - -// The GraphMutationRuleFunc type is an adapter to allow the use of ordinary -// functions as a mutation rule. -type GraphMutationRuleFunc func(context.Context, *ent.GraphMutation) error - -// EvalMutation calls f(ctx, m). -func (f GraphMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { - if m, ok := m.(*ent.GraphMutation); ok { - return f(ctx, m) - } - return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.GraphMutation", m) -} - -// The GroupQueryRuleFunc type is an adapter to allow the use of ordinary -// functions as a query rule. -type GroupQueryRuleFunc func(context.Context, *ent.GroupQuery) error - -// EvalQuery return f(ctx, q). -func (f GroupQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { - if q, ok := q.(*ent.GroupQuery); ok { - return f(ctx, q) - } - return Denyf("ent/privacy: unexpected query type %T, expect *ent.GroupQuery", q) -} - -// The GroupMutationRuleFunc type is an adapter to allow the use of ordinary -// functions as a mutation rule. -type GroupMutationRuleFunc func(context.Context, *ent.GroupMutation) error - -// EvalMutation calls f(ctx, m). -func (f GroupMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { - if m, ok := m.(*ent.GroupMutation); ok { - return f(ctx, m) - } - return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.GroupMutation", m) -} - -// The HistogramQueryRuleFunc type is an adapter to allow the use of ordinary -// functions as a query rule. -type HistogramQueryRuleFunc func(context.Context, *ent.HistogramQuery) error - -// EvalQuery return f(ctx, q). -func (f HistogramQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { - if q, ok := q.(*ent.HistogramQuery); ok { - return f(ctx, q) - } - return Denyf("ent/privacy: unexpected query type %T, expect *ent.HistogramQuery", q) -} - -// The HistogramMutationRuleFunc type is an adapter to allow the use of ordinary -// functions as a mutation rule. -type HistogramMutationRuleFunc func(context.Context, *ent.HistogramMutation) error - -// EvalMutation calls f(ctx, m). -func (f HistogramMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { - if m, ok := m.(*ent.HistogramMutation); ok { - return f(ctx, m) - } - return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.HistogramMutation", m) -} - -// The MetricQueryRuleFunc type is an adapter to allow the use of ordinary -// functions as a query rule. -type MetricQueryRuleFunc func(context.Context, *ent.MetricQuery) error - -// EvalQuery return f(ctx, q). -func (f MetricQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { - if q, ok := q.(*ent.MetricQuery); ok { - return f(ctx, q) - } - return Denyf("ent/privacy: unexpected query type %T, expect *ent.MetricQuery", q) -} - -// The MetricMutationRuleFunc type is an adapter to allow the use of ordinary -// functions as a mutation rule. -type MetricMutationRuleFunc func(context.Context, *ent.MetricMutation) error - -// EvalMutation calls f(ctx, m). -func (f MetricMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { - if m, ok := m.(*ent.MetricMutation); ok { - return f(ctx, m) - } - return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.MetricMutation", m) -} - -// The TagQueryRuleFunc type is an adapter to allow the use of ordinary -// functions as a query rule. -type TagQueryRuleFunc func(context.Context, *ent.TagQuery) error - -// EvalQuery return f(ctx, q). -func (f TagQueryRuleFunc) EvalQuery(ctx context.Context, q ent.Query) error { - if q, ok := q.(*ent.TagQuery); ok { - return f(ctx, q) - } - return Denyf("ent/privacy: unexpected query type %T, expect *ent.TagQuery", q) -} - -// The TagMutationRuleFunc type is an adapter to allow the use of ordinary -// functions as a mutation rule. -type TagMutationRuleFunc func(context.Context, *ent.TagMutation) error - -// EvalMutation calls f(ctx, m). -func (f TagMutationRuleFunc) EvalMutation(ctx context.Context, m ent.Mutation) error { - if m, ok := m.(*ent.TagMutation); ok { - return f(ctx, m) - } - return Denyf("ent/privacy: unexpected mutation type %T, expect *ent.TagMutation", m) -} diff --git a/ent/runtime.go b/ent/runtime.go index 9eddd741..bfd2449d 100644 --- a/ent/runtime.go +++ b/ent/runtime.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -10,8 +10,8 @@ import ( "github.com/gobench-io/gobench/v2/ent/tag" ) -// The init function reads all schema descriptors with runtime -// code (default values, validators or hooks) and stitches it +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { applicationFields := schema.Application{}.Fields() @@ -34,6 +34,12 @@ func init() { applicationDescGosum := applicationFields[7].Descriptor() // application.DefaultGosum holds the default value on creation for the gosum field. application.DefaultGosum = applicationDescGosum.Default.(string) + // applicationDescVu is the schema descriptor for vu field. + applicationDescVu := applicationFields[8].Descriptor() + // application.DefaultVu holds the default value on creation for the vu field. + application.DefaultVu = applicationDescVu.Default.(int) + // application.VuValidator is a validator for the "vu" field. It is called by the builders before save. + application.VuValidator = applicationDescVu.Validators[0].(func(int) error) tagFields := schema.Tag{}.Fields() _ = tagFields // tagDescName is the schema descriptor for name field. diff --git a/ent/runtime/runtime.go b/ent/runtime/runtime.go index 69c645fc..c89c9fcc 100644 --- a/ent/runtime/runtime.go +++ b/ent/runtime/runtime.go @@ -1,10 +1,10 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package runtime // The schema-stitching logic is generated in github.com/gobench-io/gobench/v2/ent/runtime.go const ( - Version = "v0.4.3" // Version of ent codegen. - Sum = "h1:ds9HENceKzpGBgCRlkZNq6TqBIegwKcF3e5reuV9Z0M=" // Sum of ent codegen. + Version = "v0.12.3" // Version of ent codegen. + Sum = "h1:N5lO2EOrHpCH5HYfiMOCHYbo+oh5M8GjT0/cx5x6xkk=" // Sum of ent codegen. ) diff --git a/ent/schema/application.go b/ent/schema/application.go index 8625e30a..827545ff 100644 --- a/ent/schema/application.go +++ b/ent/schema/application.go @@ -3,9 +3,9 @@ package schema import ( "time" - "github.com/facebook/ent" - "github.com/facebook/ent/schema/edge" - "github.com/facebook/ent/schema/field" + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" ) // Application holds the schema definition for the Application entity. @@ -30,6 +30,9 @@ func (Application) Fields() []ent.Field { Default(""), field.Text("gosum"). Default(""), + field.Int("vu"). + Positive(). + Default(0), } } diff --git a/ent/schema/counter.go b/ent/schema/counter.go index e5d09751..a5371718 100644 --- a/ent/schema/counter.go +++ b/ent/schema/counter.go @@ -1,9 +1,9 @@ package schema import ( - "github.com/facebook/ent" - "github.com/facebook/ent/schema/edge" - "github.com/facebook/ent/schema/field" + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" ) // Counter holds the schema definition for the Counter entity. diff --git a/ent/schema/gauge.go b/ent/schema/gauge.go index 4def0220..071bc72f 100644 --- a/ent/schema/gauge.go +++ b/ent/schema/gauge.go @@ -1,9 +1,9 @@ package schema import ( - "github.com/facebook/ent" - "github.com/facebook/ent/schema/edge" - "github.com/facebook/ent/schema/field" + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" ) // Gauge holds the schema definition for the Gauge entity. diff --git a/ent/schema/graph.go b/ent/schema/graph.go index 30179f34..427ee81e 100644 --- a/ent/schema/graph.go +++ b/ent/schema/graph.go @@ -1,9 +1,9 @@ package schema import ( - "github.com/facebook/ent" - "github.com/facebook/ent/schema/edge" - "github.com/facebook/ent/schema/field" + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" ) // Graph holds the schema definition for the Graph entity. diff --git a/ent/schema/group.go b/ent/schema/group.go index 480cc843..78faec1b 100644 --- a/ent/schema/group.go +++ b/ent/schema/group.go @@ -1,9 +1,9 @@ package schema import ( - "github.com/facebook/ent" - "github.com/facebook/ent/schema/edge" - "github.com/facebook/ent/schema/field" + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" ) // Group holds the schema definition for the Group entity. diff --git a/ent/schema/histogram.go b/ent/schema/histogram.go index 3d2f7145..927414d0 100644 --- a/ent/schema/histogram.go +++ b/ent/schema/histogram.go @@ -1,9 +1,9 @@ package schema import ( - "github.com/facebook/ent" - "github.com/facebook/ent/schema/edge" - "github.com/facebook/ent/schema/field" + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" ) // Histogram holds the schema definition for the Histogram entity. diff --git a/ent/schema/metric.go b/ent/schema/metric.go index 8e381a16..29ee586a 100644 --- a/ent/schema/metric.go +++ b/ent/schema/metric.go @@ -1,9 +1,9 @@ package schema import ( - "github.com/facebook/ent" - "github.com/facebook/ent/schema/edge" - "github.com/facebook/ent/schema/field" + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" ) // Metric holds the schema definition for the Metric entity. diff --git a/ent/schema/tag.go b/ent/schema/tag.go index 22744d81..303532a0 100644 --- a/ent/schema/tag.go +++ b/ent/schema/tag.go @@ -1,10 +1,10 @@ package schema import ( - "github.com/facebook/ent" - "github.com/facebook/ent/schema/edge" - "github.com/facebook/ent/schema/field" - "github.com/facebook/ent/schema/index" + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" ) // Tag holds the schema definition for the Tag entity. diff --git a/ent/tag.go b/ent/tag.go index 5e471326..4006d744 100644 --- a/ent/tag.go +++ b/ent/tag.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -6,7 +6,8 @@ import ( "fmt" "strings" - "github.com/facebook/ent/dialect/sql" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/tag" ) @@ -17,17 +18,18 @@ type Tag struct { // ID of the ent. ID int `json:"id,omitempty"` // Name holds the value of the "name" field. - Name string `json:"name,omitempty"` + Name string `json:"name"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the TagQuery when eager-loading is set. Edges TagEdges `json:"edges"` application_tags *int + selectValues sql.SelectValues } // TagEdges holds the relations/edges for other nodes in the graph. type TagEdges struct { // Application holds the value of the application edge. - Application *Application + Application *Application `json:"application,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [1]bool @@ -38,8 +40,7 @@ type TagEdges struct { func (e TagEdges) ApplicationOrErr() (*Application, error) { if e.loadedTypes[0] { if e.Application == nil { - // The edge application was loaded in eager-loading, - // but was not found. + // Edge was loaded but was not found. return nil, &NotFoundError{label: application.Label} } return e.Application, nil @@ -48,69 +49,83 @@ func (e TagEdges) ApplicationOrErr() (*Application, error) { } // scanValues returns the types for scanning values from sql.Rows. -func (*Tag) scanValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // id - &sql.NullString{}, // name - } -} - -// fkValues returns the types for scanning foreign-keys values from sql.Rows. -func (*Tag) fkValues() []interface{} { - return []interface{}{ - &sql.NullInt64{}, // application_tags +func (*Tag) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case tag.FieldID: + values[i] = new(sql.NullInt64) + case tag.FieldName: + values[i] = new(sql.NullString) + case tag.ForeignKeys[0]: // application_tags + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } } + return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Tag fields. -func (t *Tag) assignValues(values ...interface{}) error { - if m, n := len(values), len(tag.Columns); m < n { +func (t *Tag) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } - value, ok := values[0].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - t.ID = int(value.Int64) - values = values[1:] - if value, ok := values[0].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field name", values[0]) - } else if value.Valid { - t.Name = value.String - } - values = values[1:] - if len(values) == len(tag.ForeignKeys) { - if value, ok := values[0].(*sql.NullInt64); !ok { - return fmt.Errorf("unexpected type %T for edge-field application_tags", value) - } else if value.Valid { - t.application_tags = new(int) - *t.application_tags = int(value.Int64) + for i := range columns { + switch columns[i] { + case tag.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + t.ID = int(value.Int64) + case tag.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + t.Name = value.String + } + case tag.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field application_tags", value) + } else if value.Valid { + t.application_tags = new(int) + *t.application_tags = int(value.Int64) + } + default: + t.selectValues.Set(columns[i], values[i]) } } return nil } -// QueryApplication queries the application edge of the Tag. +// Value returns the ent.Value that was dynamically selected and assigned to the Tag. +// This includes values selected through modifiers, order, etc. +func (t *Tag) Value(name string) (ent.Value, error) { + return t.selectValues.Get(name) +} + +// QueryApplication queries the "application" edge of the Tag entity. func (t *Tag) QueryApplication() *ApplicationQuery { - return (&TagClient{config: t.config}).QueryApplication(t) + return NewTagClient(t.config).QueryApplication(t) } // Update returns a builder for updating this Tag. -// Note that, you need to call Tag.Unwrap() before calling this method, if this Tag +// Note that you need to call Tag.Unwrap() before calling this method if this Tag // was returned from a transaction, and the transaction was committed or rolled back. func (t *Tag) Update() *TagUpdateOne { - return (&TagClient{config: t.config}).UpdateOne(t) + return NewTagClient(t.config).UpdateOne(t) } -// Unwrap unwraps the entity that was returned from a transaction after it was closed, -// so that all next queries will be executed through the driver which created the transaction. +// Unwrap unwraps the Tag entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. func (t *Tag) Unwrap() *Tag { - tx, ok := t.config.driver.(*txDriver) + _tx, ok := t.config.driver.(*txDriver) if !ok { panic("ent: Tag is not a transactional entity") } - t.config.driver = tx.drv + t.config.driver = _tx.drv return t } @@ -118,8 +133,8 @@ func (t *Tag) Unwrap() *Tag { func (t *Tag) String() string { var builder strings.Builder builder.WriteString("Tag(") - builder.WriteString(fmt.Sprintf("id=%v", t.ID)) - builder.WriteString(", name=") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("name=") builder.WriteString(t.Name) builder.WriteByte(')') return builder.String() @@ -127,9 +142,3 @@ func (t *Tag) String() string { // Tags is a parsable slice of Tag. type Tags []*Tag - -func (t Tags) config(cfg config) { - for _i := range t { - t[_i].config = cfg - } -} diff --git a/ent/tag/tag.go b/ent/tag/tag.go index 3b773cda..9254bcd0 100644 --- a/ent/tag/tag.go +++ b/ent/tag/tag.go @@ -1,7 +1,12 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package tag +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + const ( // Label holds the string label denoting the tag type in the database. Label = "tag" @@ -9,13 +14,11 @@ const ( FieldID = "id" // FieldName holds the string denoting the name field in the database. FieldName = "name" - // EdgeApplication holds the string denoting the application edge name in mutations. EdgeApplication = "application" - // Table holds the table name of the tag in the database. Table = "tags" - // ApplicationTable is the table the holds the application relation/edge. + // ApplicationTable is the table that holds the application relation/edge. ApplicationTable = "tags" // ApplicationInverseTable is the table name for the Application entity. // It exists in this package in order to avoid circular dependency with the "application" package. @@ -30,7 +33,8 @@ var Columns = []string{ FieldName, } -// ForeignKeys holds the SQL foreign-keys that are owned by the Tag type. +// ForeignKeys holds the SQL foreign-keys that are owned by the "tags" +// table and are not defined as standalone fields in the schema. var ForeignKeys = []string{ "application_tags", } @@ -54,3 +58,30 @@ var ( // NameValidator is a validator for the "name" field. It is called by the builders before save. NameValidator func(string) error ) + +// OrderOption defines the ordering options for the Tag queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByApplicationField orders the results by application field. +func ByApplicationField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newApplicationStep(), sql.OrderByField(field, opts...)) + } +} +func newApplicationStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ApplicationInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ApplicationTable, ApplicationColumn), + ) +} diff --git a/ent/tag/where.go b/ent/tag/where.go index cfcf3f87..3c03d9fc 100644 --- a/ent/tag/where.go +++ b/ent/tag/where.go @@ -1,212 +1,126 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package tag import ( - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" "github.com/gobench-io/gobench/v2/ent/predicate" ) -// ID filters vertices based on their identifier. +// ID filters vertices based on their ID field. func ID(id int) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Tag(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldID), id)) - }) + return predicate.Tag(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldID), id)) - }) + return predicate.Tag(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.In(s.C(FieldID), v...)) - }) + return predicate.Tag(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(ids) == 0 { - s.Where(sql.False()) - return - } - v := make([]interface{}, len(ids)) - for i := range v { - v[i] = ids[i] - } - s.Where(sql.NotIn(s.C(FieldID), v...)) - }) + return predicate.Tag(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldID), id)) - }) + return predicate.Tag(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldID), id)) - }) + return predicate.Tag(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldID), id)) - }) + return predicate.Tag(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldID), id)) - }) + return predicate.Tag(sql.FieldLTE(FieldID, id)) } // Name applies equality check predicate on the "name" field. It's identical to NameEQ. func Name(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldEQ(FieldName, v)) } // NameEQ applies the EQ predicate on the "name" field. func NameEQ(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldEQ(FieldName, v)) } // NameNEQ applies the NEQ predicate on the "name" field. func NameNEQ(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.NEQ(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldNEQ(FieldName, v)) } // NameIn applies the In predicate on the "name" field. func NameIn(vs ...string) predicate.Tag { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Tag(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.In(s.C(FieldName), v...)) - }) + return predicate.Tag(sql.FieldIn(FieldName, vs...)) } // NameNotIn applies the NotIn predicate on the "name" field. func NameNotIn(vs ...string) predicate.Tag { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Tag(func(s *sql.Selector) { - // if not arguments were provided, append the FALSE constants, - // since we can't apply "IN ()". This will make this predicate falsy. - if len(v) == 0 { - s.Where(sql.False()) - return - } - s.Where(sql.NotIn(s.C(FieldName), v...)) - }) + return predicate.Tag(sql.FieldNotIn(FieldName, vs...)) } // NameGT applies the GT predicate on the "name" field. func NameGT(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.GT(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldGT(FieldName, v)) } // NameGTE applies the GTE predicate on the "name" field. func NameGTE(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.GTE(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldGTE(FieldName, v)) } // NameLT applies the LT predicate on the "name" field. func NameLT(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.LT(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldLT(FieldName, v)) } // NameLTE applies the LTE predicate on the "name" field. func NameLTE(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.LTE(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldLTE(FieldName, v)) } // NameContains applies the Contains predicate on the "name" field. func NameContains(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.Contains(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldContains(FieldName, v)) } // NameHasPrefix applies the HasPrefix predicate on the "name" field. func NameHasPrefix(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.HasPrefix(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldHasPrefix(FieldName, v)) } // NameHasSuffix applies the HasSuffix predicate on the "name" field. func NameHasSuffix(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.HasSuffix(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldHasSuffix(FieldName, v)) } // NameEqualFold applies the EqualFold predicate on the "name" field. func NameEqualFold(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.EqualFold(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldEqualFold(FieldName, v)) } // NameContainsFold applies the ContainsFold predicate on the "name" field. func NameContainsFold(v string) predicate.Tag { - return predicate.Tag(func(s *sql.Selector) { - s.Where(sql.ContainsFold(s.C(FieldName), v)) - }) + return predicate.Tag(sql.FieldContainsFold(FieldName, v)) } // HasApplication applies the HasEdge predicate on the "application" edge. @@ -214,7 +128,6 @@ func HasApplication() predicate.Tag { return predicate.Tag(func(s *sql.Selector) { step := sqlgraph.NewStep( sqlgraph.From(Table, FieldID), - sqlgraph.To(ApplicationTable, FieldID), sqlgraph.Edge(sqlgraph.M2O, true, ApplicationTable, ApplicationColumn), ) sqlgraph.HasNeighbors(s, step) @@ -224,11 +137,7 @@ func HasApplication() predicate.Tag { // HasApplicationWith applies the HasEdge predicate on the "application" edge with a given conditions (other predicates). func HasApplicationWith(preds ...predicate.Application) predicate.Tag { return predicate.Tag(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(ApplicationInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, ApplicationTable, ApplicationColumn), - ) + step := newApplicationStep() sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { for _, p := range preds { p(s) @@ -237,7 +146,7 @@ func HasApplicationWith(preds ...predicate.Application) predicate.Tag { }) } -// And groups list of predicates with the AND operator between them. +// And groups predicates with the AND operator between them. func And(predicates ...predicate.Tag) predicate.Tag { return predicate.Tag(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) @@ -248,7 +157,7 @@ func And(predicates ...predicate.Tag) predicate.Tag { }) } -// Or groups list of predicates with the OR operator between them. +// Or groups predicates with the OR operator between them. func Or(predicates ...predicate.Tag) predicate.Tag { return predicate.Tag(func(s *sql.Selector) { s1 := s.Clone().SetP(nil) diff --git a/ent/tag_create.go b/ent/tag_create.go index 782d4d54..deeea784 100644 --- a/ent/tag_create.go +++ b/ent/tag_create.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -7,8 +7,8 @@ import ( "errors" "fmt" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/tag" ) @@ -20,19 +20,19 @@ type TagCreate struct { hooks []Hook } -// SetName sets the name field. +// SetName sets the "name" field. func (tc *TagCreate) SetName(s string) *TagCreate { tc.mutation.SetName(s) return tc } -// SetApplicationID sets the application edge to Application by id. +// SetApplicationID sets the "application" edge to the Application entity by ID. func (tc *TagCreate) SetApplicationID(id int) *TagCreate { tc.mutation.SetApplicationID(id) return tc } -// SetNillableApplicationID sets the application edge to Application by id if the given value is not nil. +// SetNillableApplicationID sets the "application" edge to the Application entity by ID if the given value is not nil. func (tc *TagCreate) SetNillableApplicationID(id *int) *TagCreate { if id != nil { tc = tc.SetApplicationID(*id) @@ -40,7 +40,7 @@ func (tc *TagCreate) SetNillableApplicationID(id *int) *TagCreate { return tc } -// SetApplication sets the application edge to Application. +// SetApplication sets the "application" edge to the Application entity. func (tc *TagCreate) SetApplication(a *Application) *TagCreate { return tc.SetApplicationID(a.ID) } @@ -52,37 +52,7 @@ func (tc *TagCreate) Mutation() *TagMutation { // Save creates the Tag in the database. func (tc *TagCreate) Save(ctx context.Context) (*Tag, error) { - var ( - err error - node *Tag - ) - if len(tc.hooks) == 0 { - if err = tc.check(); err != nil { - return nil, err - } - node, err = tc.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*TagMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = tc.check(); err != nil { - return nil, err - } - tc.mutation = mutation - node, err = tc.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(tc.hooks) - 1; i >= 0; i-- { - mut = tc.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, tc.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, tc.sqlSave, tc.mutation, tc.hooks) } // SaveX calls Save and panics if Save returns an error. @@ -94,49 +64,57 @@ func (tc *TagCreate) SaveX(ctx context.Context) *Tag { return v } +// Exec executes the query. +func (tc *TagCreate) Exec(ctx context.Context) error { + _, err := tc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tc *TagCreate) ExecX(ctx context.Context) { + if err := tc.Exec(ctx); err != nil { + panic(err) + } +} + // check runs all checks and user-defined validators on the builder. func (tc *TagCreate) check() error { if _, ok := tc.mutation.Name(); !ok { - return &ValidationError{Name: "name", err: errors.New("ent: missing required field \"name\"")} + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Tag.name"`)} } if v, ok := tc.mutation.Name(); ok { if err := tag.NameValidator(v); err != nil { - return &ValidationError{Name: "name", err: fmt.Errorf("ent: validator failed for field \"name\": %w", err)} + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Tag.name": %w`, err)} } } return nil } func (tc *TagCreate) sqlSave(ctx context.Context) (*Tag, error) { + if err := tc.check(); err != nil { + return nil, err + } _node, _spec := tc.createSpec() if err := sqlgraph.CreateNode(ctx, tc.driver, _spec); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } id := _spec.ID.Value.(int64) _node.ID = int(id) + tc.mutation.id = &_node.ID + tc.mutation.done = true return _node, nil } func (tc *TagCreate) createSpec() (*Tag, *sqlgraph.CreateSpec) { var ( _node = &Tag{config: tc.config} - _spec = &sqlgraph.CreateSpec{ - Table: tag.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, - } + _spec = sqlgraph.NewCreateSpec(tag.Table, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) ) if value, ok := tc.mutation.Name(); ok { - _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: tag.FieldName, - }) + _spec.SetField(tag.FieldName, field.TypeString, value) _node.Name = value } if nodes := tc.mutation.ApplicationIDs(); len(nodes) > 0 { @@ -147,21 +125,19 @@ func (tc *TagCreate) createSpec() (*Tag, *sqlgraph.CreateSpec) { Columns: []string{tag.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } + _node.application_tags = &nodes[0] _spec.Edges = append(_spec.Edges, edge) } return _node, _spec } -// TagCreateBulk is the builder for creating a bulk of Tag entities. +// TagCreateBulk is the builder for creating many Tag entities in bulk. type TagCreateBulk struct { config builders []*TagCreate @@ -184,24 +160,28 @@ func (tcb *TagCreateBulk) Save(ctx context.Context) ([]*Tag, error) { return nil, err } builder.mutation = mutation - nodes[i], specs[i] = builder.createSpec() var err error + nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, tcb.builders[i+1].mutation) } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, tcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil { - if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + if err = sqlgraph.BatchCreate(ctx, tcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } } } - mutation.done = true if err != nil { return nil, err } - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) + mutation.id = &nodes[i].ID + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { @@ -218,7 +198,7 @@ func (tcb *TagCreateBulk) Save(ctx context.Context) ([]*Tag, error) { return nodes, nil } -// SaveX calls Save and panics if Save returns an error. +// SaveX is like Save, but panics if an error occurs. func (tcb *TagCreateBulk) SaveX(ctx context.Context) []*Tag { v, err := tcb.Save(ctx) if err != nil { @@ -226,3 +206,16 @@ func (tcb *TagCreateBulk) SaveX(ctx context.Context) []*Tag { } return v } + +// Exec executes the query. +func (tcb *TagCreateBulk) Exec(ctx context.Context) error { + _, err := tcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tcb *TagCreateBulk) ExecX(ctx context.Context) { + if err := tcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/tag_delete.go b/ent/tag_delete.go index eec782aa..dd8ff977 100644 --- a/ent/tag_delete.go +++ b/ent/tag_delete.go @@ -1,14 +1,13 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/predicate" "github.com/gobench-io/gobench/v2/ent/tag" ) @@ -16,44 +15,19 @@ import ( // TagDelete is the builder for deleting a Tag entity. type TagDelete struct { config - hooks []Hook - mutation *TagMutation - predicates []predicate.Tag + hooks []Hook + mutation *TagMutation } -// Where adds a new predicate to the delete builder. +// Where appends a list predicates to the TagDelete builder. func (td *TagDelete) Where(ps ...predicate.Tag) *TagDelete { - td.predicates = append(td.predicates, ps...) + td.mutation.Where(ps...) return td } // Exec executes the deletion query and returns how many vertices were deleted. func (td *TagDelete) Exec(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(td.hooks) == 0 { - affected, err = td.sqlExec(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*TagMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - td.mutation = mutation - affected, err = td.sqlExec(ctx) - mutation.done = true - return affected, err - }) - for i := len(td.hooks) - 1; i >= 0; i-- { - mut = td.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, td.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, td.sqlExec, td.mutation, td.hooks) } // ExecX is like Exec, but panics if an error occurs. @@ -66,23 +40,20 @@ func (td *TagDelete) ExecX(ctx context.Context) int { } func (td *TagDelete) sqlExec(ctx context.Context) (int, error) { - _spec := &sqlgraph.DeleteSpec{ - Node: &sqlgraph.NodeSpec{ - Table: tag.Table, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, - }, - } - if ps := td.predicates; len(ps) > 0 { + _spec := sqlgraph.NewDeleteSpec(tag.Table, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) + if ps := td.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - return sqlgraph.DeleteNodes(ctx, td.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, td.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + td.mutation.done = true + return affected, err } // TagDeleteOne is the builder for deleting a single Tag entity. @@ -90,6 +61,12 @@ type TagDeleteOne struct { td *TagDelete } +// Where appends a list predicates to the TagDelete builder. +func (tdo *TagDeleteOne) Where(ps ...predicate.Tag) *TagDeleteOne { + tdo.td.mutation.Where(ps...) + return tdo +} + // Exec executes the deletion query. func (tdo *TagDeleteOne) Exec(ctx context.Context) error { n, err := tdo.td.Exec(ctx) @@ -105,5 +82,7 @@ func (tdo *TagDeleteOne) Exec(ctx context.Context) error { // ExecX is like Exec, but panics if an error occurs. func (tdo *TagDeleteOne) ExecX(ctx context.Context) { - tdo.td.ExecX(ctx) + if err := tdo.Exec(ctx); err != nil { + panic(err) + } } diff --git a/ent/tag_query.go b/ent/tag_query.go index 2f3d864a..4b014c08 100644 --- a/ent/tag_query.go +++ b/ent/tag_query.go @@ -1,16 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" - "errors" "fmt" "math" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/predicate" "github.com/gobench-io/gobench/v2/ent/tag" @@ -19,12 +18,10 @@ import ( // TagQuery is the builder for querying Tag entities. type TagQuery struct { config - limit *int - offset *int - order []OrderFunc - unique []string - predicates []predicate.Tag - // eager-loading edges. + ctx *QueryContext + order []tag.OrderOption + inters []Interceptor + predicates []predicate.Tag withApplication *ApplicationQuery withFKs bool // intermediate query (i.e. traversal path). @@ -32,38 +29,45 @@ type TagQuery struct { path func(context.Context) (*sql.Selector, error) } -// Where adds a new predicate for the builder. +// Where adds a new predicate for the TagQuery builder. func (tq *TagQuery) Where(ps ...predicate.Tag) *TagQuery { tq.predicates = append(tq.predicates, ps...) return tq } -// Limit adds a limit step to the query. +// Limit the number of records to be returned by this query. func (tq *TagQuery) Limit(limit int) *TagQuery { - tq.limit = &limit + tq.ctx.Limit = &limit return tq } -// Offset adds an offset step to the query. +// Offset to start from. func (tq *TagQuery) Offset(offset int) *TagQuery { - tq.offset = &offset + tq.ctx.Offset = &offset return tq } -// Order adds an order step to the query. -func (tq *TagQuery) Order(o ...OrderFunc) *TagQuery { +// 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 (tq *TagQuery) Unique(unique bool) *TagQuery { + tq.ctx.Unique = &unique + return tq +} + +// Order specifies how the records should be ordered. +func (tq *TagQuery) Order(o ...tag.OrderOption) *TagQuery { tq.order = append(tq.order, o...) return tq } -// QueryApplication chains the current query on the application edge. +// QueryApplication chains the current query on the "application" edge. func (tq *TagQuery) QueryApplication() *ApplicationQuery { - query := &ApplicationQuery{config: tq.config} + query := (&ApplicationClient{config: tq.config}).Query() query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { if err := tq.prepareQuery(ctx); err != nil { return nil, err } - selector := tq.sqlQuery() + selector := tq.sqlQuery(ctx) if err := selector.Err(); err != nil { return nil, err } @@ -78,9 +82,10 @@ func (tq *TagQuery) QueryApplication() *ApplicationQuery { return query } -// First returns the first Tag entity in the query. Returns *NotFoundError when no tag was found. +// First returns the first Tag entity from the query. +// Returns a *NotFoundError when no Tag was found. func (tq *TagQuery) First(ctx context.Context) (*Tag, error) { - nodes, err := tq.Limit(1).All(ctx) + nodes, err := tq.Limit(1).All(setContextOp(ctx, tq.ctx, "First")) if err != nil { return nil, err } @@ -99,10 +104,11 @@ func (tq *TagQuery) FirstX(ctx context.Context) *Tag { return node } -// FirstID returns the first Tag id in the query. Returns *NotFoundError when no id was found. +// FirstID returns the first Tag ID from the query. +// Returns a *NotFoundError when no Tag ID was found. func (tq *TagQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = tq.Limit(1).IDs(ctx); err != nil { + if ids, err = tq.Limit(1).IDs(setContextOp(ctx, tq.ctx, "FirstID")); err != nil { return } if len(ids) == 0 { @@ -112,8 +118,8 @@ func (tq *TagQuery) FirstID(ctx context.Context) (id int, err error) { return ids[0], nil } -// FirstXID is like FirstID, but panics if an error occurs. -func (tq *TagQuery) FirstXID(ctx context.Context) int { +// FirstIDX is like FirstID, but panics if an error occurs. +func (tq *TagQuery) FirstIDX(ctx context.Context) int { id, err := tq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) @@ -121,9 +127,11 @@ func (tq *TagQuery) FirstXID(ctx context.Context) int { return id } -// Only returns the only Tag entity in the query, returns an error if not exactly one entity was returned. +// Only returns a single Tag entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Tag entity is found. +// Returns a *NotFoundError when no Tag entities are found. func (tq *TagQuery) Only(ctx context.Context) (*Tag, error) { - nodes, err := tq.Limit(2).All(ctx) + nodes, err := tq.Limit(2).All(setContextOp(ctx, tq.ctx, "Only")) if err != nil { return nil, err } @@ -146,10 +154,12 @@ func (tq *TagQuery) OnlyX(ctx context.Context) *Tag { return node } -// OnlyID returns the only Tag id in the query, returns an error if not exactly one id was returned. +// OnlyID is like Only, but returns the only Tag ID in the query. +// Returns a *NotSingularError when more than one Tag ID is found. +// Returns a *NotFoundError when no entities are found. func (tq *TagQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = tq.Limit(2).IDs(ctx); err != nil { + if ids, err = tq.Limit(2).IDs(setContextOp(ctx, tq.ctx, "OnlyID")); err != nil { return } switch len(ids) { @@ -174,10 +184,12 @@ func (tq *TagQuery) OnlyIDX(ctx context.Context) int { // All executes the query and returns a list of Tags. func (tq *TagQuery) All(ctx context.Context) ([]*Tag, error) { + ctx = setContextOp(ctx, tq.ctx, "All") if err := tq.prepareQuery(ctx); err != nil { return nil, err } - return tq.sqlAll(ctx) + qr := querierAll[[]*Tag, *TagQuery]() + return withInterceptors[[]*Tag](ctx, tq, qr, tq.inters) } // AllX is like All, but panics if an error occurs. @@ -189,10 +201,13 @@ func (tq *TagQuery) AllX(ctx context.Context) []*Tag { return nodes } -// IDs executes the query and returns a list of Tag ids. -func (tq *TagQuery) IDs(ctx context.Context) ([]int, error) { - var ids []int - if err := tq.Select(tag.FieldID).Scan(ctx, &ids); err != nil { +// IDs executes the query and returns a list of Tag IDs. +func (tq *TagQuery) IDs(ctx context.Context) (ids []int, err error) { + if tq.ctx.Unique == nil && tq.path != nil { + tq.Unique(true) + } + ctx = setContextOp(ctx, tq.ctx, "IDs") + if err = tq.Select(tag.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil @@ -209,10 +224,11 @@ func (tq *TagQuery) IDsX(ctx context.Context) []int { // Count returns the count of the given query. func (tq *TagQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, tq.ctx, "Count") if err := tq.prepareQuery(ctx); err != nil { return 0, err } - return tq.sqlCount(ctx) + return withInterceptors[int](ctx, tq, querierCount[*TagQuery](), tq.inters) } // CountX is like Count, but panics if an error occurs. @@ -226,10 +242,15 @@ func (tq *TagQuery) CountX(ctx context.Context) int { // Exist returns true if the query has elements in the graph. func (tq *TagQuery) Exist(ctx context.Context) (bool, error) { - if err := tq.prepareQuery(ctx); err != nil { - return false, err + ctx = setContextOp(ctx, tq.ctx, "Exist") + switch _, err := tq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil } - return tq.sqlExist(ctx) } // ExistX is like Exist, but panics if an error occurs. @@ -241,26 +262,29 @@ func (tq *TagQuery) ExistX(ctx context.Context) bool { return exist } -// Clone returns a duplicate of the query builder, including all associated steps. It can be +// Clone returns a duplicate of the TagQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. func (tq *TagQuery) Clone() *TagQuery { + if tq == nil { + return nil + } return &TagQuery{ - config: tq.config, - limit: tq.limit, - offset: tq.offset, - order: append([]OrderFunc{}, tq.order...), - unique: append([]string{}, tq.unique...), - predicates: append([]predicate.Tag{}, tq.predicates...), + config: tq.config, + ctx: tq.ctx.Clone(), + order: append([]tag.OrderOption{}, tq.order...), + inters: append([]Interceptor{}, tq.inters...), + predicates: append([]predicate.Tag{}, tq.predicates...), + withApplication: tq.withApplication.Clone(), // clone intermediate query. sql: tq.sql.Clone(), path: tq.path, } } -// WithApplication tells the query-builder to eager-loads the nodes that are connected to -// the "application" edge. The optional arguments used to configure the query builder of the edge. +// WithApplication tells the query-builder to eager-load the nodes that are connected to +// the "application" edge. The optional arguments are used to configure the query builder of the edge. func (tq *TagQuery) WithApplication(opts ...func(*ApplicationQuery)) *TagQuery { - query := &ApplicationQuery{config: tq.config} + query := (&ApplicationClient{config: tq.config}).Query() for _, opt := range opts { opt(query) } @@ -268,13 +292,13 @@ func (tq *TagQuery) WithApplication(opts ...func(*ApplicationQuery)) *TagQuery { return tq } -// GroupBy used to group vertices by one or more fields/columns. +// 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"` +// Name string `json:"name"` // Count int `json:"count,omitempty"` // } // @@ -282,44 +306,56 @@ func (tq *TagQuery) WithApplication(opts ...func(*ApplicationQuery)) *TagQuery { // GroupBy(tag.FieldName). // Aggregate(ent.Count()). // Scan(ctx, &v) -// func (tq *TagQuery) GroupBy(field string, fields ...string) *TagGroupBy { - group := &TagGroupBy{config: tq.config} - group.fields = append([]string{field}, fields...) - group.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := tq.prepareQuery(ctx); err != nil { - return nil, err - } - return tq.sqlQuery(), nil - } - return group + tq.ctx.Fields = append([]string{field}, fields...) + grbuild := &TagGroupBy{build: tq} + grbuild.flds = &tq.ctx.Fields + grbuild.label = tag.Label + grbuild.scan = grbuild.Scan + return grbuild } -// Select one or more fields from the given query. +// 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"` +// Name string `json:"name"` // } // // client.Tag.Query(). // Select(tag.FieldName). // Scan(ctx, &v) -// -func (tq *TagQuery) Select(field string, fields ...string) *TagSelect { - selector := &TagSelect{config: tq.config} - selector.fields = append([]string{field}, fields...) - selector.path = func(ctx context.Context) (prev *sql.Selector, err error) { - if err := tq.prepareQuery(ctx); err != nil { - return nil, err - } - return tq.sqlQuery(), nil - } - return selector +func (tq *TagQuery) Select(fields ...string) *TagSelect { + tq.ctx.Fields = append(tq.ctx.Fields, fields...) + sbuild := &TagSelect{TagQuery: tq} + sbuild.label = tag.Label + sbuild.flds, sbuild.scan = &tq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a TagSelect configured with the given aggregations. +func (tq *TagQuery) Aggregate(fns ...AggregateFunc) *TagSelect { + return tq.Select().Aggregate(fns...) } func (tq *TagQuery) prepareQuery(ctx context.Context) error { + for _, inter := range tq.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, tq); err != nil { + return err + } + } + } + for _, f := range tq.ctx.Fields { + if !tag.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } if tq.path != nil { prev, err := tq.path(ctx) if err != nil { @@ -330,7 +366,7 @@ func (tq *TagQuery) prepareQuery(ctx context.Context) error { return nil } -func (tq *TagQuery) sqlAll(ctx context.Context) ([]*Tag, error) { +func (tq *TagQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Tag, error) { var ( nodes = []*Tag{} withFKs = tq.withFKs @@ -345,22 +381,17 @@ func (tq *TagQuery) sqlAll(ctx context.Context) ([]*Tag, error) { if withFKs { _spec.Node.Columns = append(_spec.Node.Columns, tag.ForeignKeys...) } - _spec.ScanValues = func() []interface{} { + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Tag).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { node := &Tag{config: tq.config} nodes = append(nodes, node) - values := node.scanValues() - if withFKs { - values = append(values, node.fkValues()...) - } - return values - } - _spec.Assign = func(values ...interface{}) error { - if len(nodes) == 0 { - return fmt.Errorf("ent: Assign called without calling ScanValues") - } - node := nodes[len(nodes)-1] node.Edges.loadedTypes = loadedTypes - return node.assignValues(values...) + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) } if err := sqlgraph.QueryNodes(ctx, tq.driver, _spec); err != nil { return nil, err @@ -368,60 +399,73 @@ func (tq *TagQuery) sqlAll(ctx context.Context) ([]*Tag, error) { if len(nodes) == 0 { return nodes, nil } - if query := tq.withApplication; query != nil { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*Tag) - for i := range nodes { - if fk := nodes[i].application_tags; fk != nil { - ids = append(ids, *fk) - nodeids[*fk] = append(nodeids[*fk], nodes[i]) - } - } - query.Where(application.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { + if err := tq.loadApplication(ctx, query, nodes, nil, + func(n *Tag, e *Application) { n.Edges.Application = e }); err != nil { return nil, err } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return nil, fmt.Errorf(`unexpected foreign-key "application_tags" returned %v`, n.ID) - } - for i := range nodes { - nodes[i].Edges.Application = n - } - } } - return nodes, nil } -func (tq *TagQuery) sqlCount(ctx context.Context) (int, error) { - _spec := tq.querySpec() - return sqlgraph.CountNodes(ctx, tq.driver, _spec) +func (tq *TagQuery) loadApplication(ctx context.Context, query *ApplicationQuery, nodes []*Tag, init func(*Tag), assign func(*Tag, *Application)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Tag) + for i := range nodes { + if nodes[i].application_tags == nil { + continue + } + fk := *nodes[i].application_tags + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(application.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 "application_tags" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil } -func (tq *TagQuery) sqlExist(ctx context.Context) (bool, error) { - n, err := tq.sqlCount(ctx) - if err != nil { - return false, fmt.Errorf("ent: check existence: %v", err) +func (tq *TagQuery) sqlCount(ctx context.Context) (int, error) { + _spec := tq.querySpec() + _spec.Node.Columns = tq.ctx.Fields + if len(tq.ctx.Fields) > 0 { + _spec.Unique = tq.ctx.Unique != nil && *tq.ctx.Unique } - return n > 0, nil + return sqlgraph.CountNodes(ctx, tq.driver, _spec) } func (tq *TagQuery) querySpec() *sqlgraph.QuerySpec { - _spec := &sqlgraph.QuerySpec{ - Node: &sqlgraph.NodeSpec{ - Table: tag.Table, - Columns: tag.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, - }, - From: tq.sql, - Unique: true, + _spec := sqlgraph.NewQuerySpec(tag.Table, tag.Columns, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) + _spec.From = tq.sql + if unique := tq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if tq.path != nil { + _spec.Unique = true + } + if fields := tq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tag.FieldID) + for i := range fields { + if fields[i] != tag.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } } if ps := tq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { @@ -430,55 +474,58 @@ func (tq *TagQuery) querySpec() *sqlgraph.QuerySpec { } } } - if limit := tq.limit; limit != nil { + if limit := tq.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := tq.offset; offset != nil { + if offset := tq.ctx.Offset; offset != nil { _spec.Offset = *offset } if ps := tq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { - ps[i](selector, tag.ValidColumn) + ps[i](selector) } } } return _spec } -func (tq *TagQuery) sqlQuery() *sql.Selector { +func (tq *TagQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(tq.driver.Dialect()) t1 := builder.Table(tag.Table) - selector := builder.Select(t1.Columns(tag.Columns...)...).From(t1) + columns := tq.ctx.Fields + if len(columns) == 0 { + columns = tag.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) if tq.sql != nil { selector = tq.sql - selector.Select(selector.Columns(tag.Columns...)...) + selector.Select(selector.Columns(columns...)...) + } + if tq.ctx.Unique != nil && *tq.ctx.Unique { + selector.Distinct() } for _, p := range tq.predicates { p(selector) } for _, p := range tq.order { - p(selector, tag.ValidColumn) + p(selector) } - if offset := tq.offset; offset != nil { + if offset := tq.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 := tq.limit; limit != nil { + if limit := tq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector } -// TagGroupBy is the builder for group-by Tag entities. +// TagGroupBy is the group-by builder for Tag entities. type TagGroupBy struct { - config - fields []string - fns []AggregateFunc - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) + selector + build *TagQuery } // Aggregate adds the given aggregation functions to the group-by query. @@ -487,471 +534,80 @@ func (tgb *TagGroupBy) Aggregate(fns ...AggregateFunc) *TagGroupBy { return tgb } -// Scan applies the group-by query and scan the result into the given value. -func (tgb *TagGroupBy) Scan(ctx context.Context, v interface{}) error { - query, err := tgb.path(ctx) - if err != nil { +// Scan applies the selector query and scans the result into the given value. +func (tgb *TagGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, tgb.build.ctx, "GroupBy") + if err := tgb.build.prepareQuery(ctx); err != nil { return err } - tgb.sql = query - return tgb.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (tgb *TagGroupBy) ScanX(ctx context.Context, v interface{}) { - if err := tgb.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field. -func (tgb *TagGroupBy) Strings(ctx context.Context) ([]string, error) { - if len(tgb.fields) > 1 { - return nil, errors.New("ent: TagGroupBy.Strings is not achievable when grouping more than 1 field") - } - var v []string - if err := tgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (tgb *TagGroupBy) StringsX(ctx context.Context) []string { - v, err := tgb.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from group-by. It is only allowed when querying group-by with one field. -func (tgb *TagGroupBy) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = tgb.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{tag.Label} - default: - err = fmt.Errorf("ent: TagGroupBy.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (tgb *TagGroupBy) StringX(ctx context.Context) string { - v, err := tgb.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field. -func (tgb *TagGroupBy) Ints(ctx context.Context) ([]int, error) { - if len(tgb.fields) > 1 { - return nil, errors.New("ent: TagGroupBy.Ints is not achievable when grouping more than 1 field") - } - var v []int - if err := tgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (tgb *TagGroupBy) IntsX(ctx context.Context) []int { - v, err := tgb.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from group-by. It is only allowed when querying group-by with one field. -func (tgb *TagGroupBy) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = tgb.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{tag.Label} - default: - err = fmt.Errorf("ent: TagGroupBy.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (tgb *TagGroupBy) IntX(ctx context.Context) int { - v, err := tgb.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field. -func (tgb *TagGroupBy) Float64s(ctx context.Context) ([]float64, error) { - if len(tgb.fields) > 1 { - return nil, errors.New("ent: TagGroupBy.Float64s is not achievable when grouping more than 1 field") - } - var v []float64 - if err := tgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (tgb *TagGroupBy) Float64sX(ctx context.Context) []float64 { - v, err := tgb.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from group-by. It is only allowed when querying group-by with one field. -func (tgb *TagGroupBy) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = tgb.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{tag.Label} - default: - err = fmt.Errorf("ent: TagGroupBy.Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (tgb *TagGroupBy) Float64X(ctx context.Context) float64 { - v, err := tgb.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field. -func (tgb *TagGroupBy) Bools(ctx context.Context) ([]bool, error) { - if len(tgb.fields) > 1 { - return nil, errors.New("ent: TagGroupBy.Bools is not achievable when grouping more than 1 field") - } - var v []bool - if err := tgb.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil + return scanWithInterceptors[*TagQuery, *TagGroupBy](ctx, tgb.build, tgb, tgb.build.inters, v) } -// BoolsX is like Bools, but panics if an error occurs. -func (tgb *TagGroupBy) BoolsX(ctx context.Context) []bool { - v, err := tgb.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from group-by. It is only allowed when querying group-by with one field. -func (tgb *TagGroupBy) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = tgb.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{tag.Label} - default: - err = fmt.Errorf("ent: TagGroupBy.Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (tgb *TagGroupBy) BoolX(ctx context.Context) bool { - v, err := tgb.Bool(ctx) - if err != nil { - panic(err) +func (tgb *TagGroupBy) sqlScan(ctx context.Context, root *TagQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(tgb.fns)) + for _, fn := range tgb.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (tgb *TagGroupBy) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range tgb.fields { - if !tag.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*tgb.flds)+len(tgb.fns)) + for _, f := range *tgb.flds { + columns = append(columns, selector.C(f)) } + columns = append(columns, aggregation...) + selector.Select(columns...) } - selector := tgb.sqlQuery() + selector.GroupBy(selector.Columns(*tgb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := tgb.driver.Query(ctx, query, args, rows); err != nil { + if err := tgb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } -func (tgb *TagGroupBy) sqlQuery() *sql.Selector { - selector := tgb.sql - columns := make([]string, 0, len(tgb.fields)+len(tgb.fns)) - columns = append(columns, tgb.fields...) - for _, fn := range tgb.fns { - columns = append(columns, fn(selector, tag.ValidColumn)) - } - return selector.Select(columns...).GroupBy(tgb.fields...) -} - -// TagSelect is the builder for select fields of Tag entities. +// TagSelect is the builder for selecting fields of Tag entities. type TagSelect struct { - config - fields []string - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Scan applies the selector query and scan the result into the given value. -func (ts *TagSelect) Scan(ctx context.Context, v interface{}) error { - query, err := ts.path(ctx) - if err != nil { - return err - } - ts.sql = query - return ts.sqlScan(ctx, v) -} - -// ScanX is like Scan, but panics if an error occurs. -func (ts *TagSelect) ScanX(ctx context.Context, v interface{}) { - if err := ts.Scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from selector. It is only allowed when selecting one field. -func (ts *TagSelect) Strings(ctx context.Context) ([]string, error) { - if len(ts.fields) > 1 { - return nil, errors.New("ent: TagSelect.Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := ts.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (ts *TagSelect) StringsX(ctx context.Context) []string { - v, err := ts.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from selector. It is only allowed when selecting one field. -func (ts *TagSelect) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = ts.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{tag.Label} - default: - err = fmt.Errorf("ent: TagSelect.Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (ts *TagSelect) StringX(ctx context.Context) string { - v, err := ts.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from selector. It is only allowed when selecting one field. -func (ts *TagSelect) Ints(ctx context.Context) ([]int, error) { - if len(ts.fields) > 1 { - return nil, errors.New("ent: TagSelect.Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := ts.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (ts *TagSelect) IntsX(ctx context.Context) []int { - v, err := ts.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from selector. It is only allowed when selecting one field. -func (ts *TagSelect) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = ts.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{tag.Label} - default: - err = fmt.Errorf("ent: TagSelect.Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (ts *TagSelect) IntX(ctx context.Context) int { - v, err := ts.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from selector. It is only allowed when selecting one field. -func (ts *TagSelect) Float64s(ctx context.Context) ([]float64, error) { - if len(ts.fields) > 1 { - return nil, errors.New("ent: TagSelect.Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := ts.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (ts *TagSelect) Float64sX(ctx context.Context) []float64 { - v, err := ts.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from selector. It is only allowed when selecting one field. -func (ts *TagSelect) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = ts.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{tag.Label} - default: - err = fmt.Errorf("ent: TagSelect.Float64s returned %d results when one was expected", len(v)) - } - return + *TagQuery + selector } -// Float64X is like Float64, but panics if an error occurs. -func (ts *TagSelect) Float64X(ctx context.Context) float64 { - v, err := ts.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from selector. It is only allowed when selecting one field. -func (ts *TagSelect) Bools(ctx context.Context) ([]bool, error) { - if len(ts.fields) > 1 { - return nil, errors.New("ent: TagSelect.Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := ts.Scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (ts *TagSelect) BoolsX(ctx context.Context) []bool { - v, err := ts.Bools(ctx) - if err != nil { - panic(err) - } - return v +// Aggregate adds the given aggregation functions to the selector query. +func (ts *TagSelect) Aggregate(fns ...AggregateFunc) *TagSelect { + ts.fns = append(ts.fns, fns...) + return ts } -// Bool returns a single bool from selector. It is only allowed when selecting one field. -func (ts *TagSelect) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = ts.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{tag.Label} - default: - err = fmt.Errorf("ent: TagSelect.Bools returned %d results when one was expected", len(v)) +// Scan applies the selector query and scans the result into the given value. +func (ts *TagSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ts.ctx, "Select") + if err := ts.prepareQuery(ctx); err != nil { + return err } - return + return scanWithInterceptors[*TagQuery, *TagSelect](ctx, ts.TagQuery, ts, ts.inters, v) } -// BoolX is like Bool, but panics if an error occurs. -func (ts *TagSelect) BoolX(ctx context.Context) bool { - v, err := ts.Bool(ctx) - if err != nil { - panic(err) +func (ts *TagSelect) sqlScan(ctx context.Context, root *TagQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ts.fns)) + for _, fn := range ts.fns { + aggregation = append(aggregation, fn(selector)) } - return v -} - -func (ts *TagSelect) sqlScan(ctx context.Context, v interface{}) error { - for _, f := range ts.fields { - if !tag.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)} - } + switch n := len(*ts.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 := ts.sqlQuery().Query() + query, args := selector.Query() if err := ts.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } - -func (ts *TagSelect) sqlQuery() sql.Querier { - selector := ts.sql - selector.Select(selector.Columns(ts.fields...)...) - return selector -} diff --git a/ent/tag_update.go b/ent/tag_update.go index 92d072b8..ae032e17 100644 --- a/ent/tag_update.go +++ b/ent/tag_update.go @@ -1,14 +1,15 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent import ( "context" + "errors" "fmt" - "github.com/facebook/ent/dialect/sql" - "github.com/facebook/ent/dialect/sql/sqlgraph" - "github.com/facebook/ent/schema/field" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" "github.com/gobench-io/gobench/v2/ent/application" "github.com/gobench-io/gobench/v2/ent/predicate" "github.com/gobench-io/gobench/v2/ent/tag" @@ -17,30 +18,29 @@ import ( // TagUpdate is the builder for updating Tag entities. type TagUpdate struct { config - hooks []Hook - mutation *TagMutation - predicates []predicate.Tag + hooks []Hook + mutation *TagMutation } -// Where adds a new predicate for the builder. +// Where appends a list predicates to the TagUpdate builder. func (tu *TagUpdate) Where(ps ...predicate.Tag) *TagUpdate { - tu.predicates = append(tu.predicates, ps...) + tu.mutation.Where(ps...) return tu } -// SetName sets the name field. +// SetName sets the "name" field. func (tu *TagUpdate) SetName(s string) *TagUpdate { tu.mutation.SetName(s) return tu } -// SetApplicationID sets the application edge to Application by id. +// SetApplicationID sets the "application" edge to the Application entity by ID. func (tu *TagUpdate) SetApplicationID(id int) *TagUpdate { tu.mutation.SetApplicationID(id) return tu } -// SetNillableApplicationID sets the application edge to Application by id if the given value is not nil. +// SetNillableApplicationID sets the "application" edge to the Application entity by ID if the given value is not nil. func (tu *TagUpdate) SetNillableApplicationID(id *int) *TagUpdate { if id != nil { tu = tu.SetApplicationID(*id) @@ -48,7 +48,7 @@ func (tu *TagUpdate) SetNillableApplicationID(id *int) *TagUpdate { return tu } -// SetApplication sets the application edge to Application. +// SetApplication sets the "application" edge to the Application entity. func (tu *TagUpdate) SetApplication(a *Application) *TagUpdate { return tu.SetApplicationID(a.ID) } @@ -58,45 +58,15 @@ func (tu *TagUpdate) Mutation() *TagMutation { return tu.mutation } -// ClearApplication clears the "application" edge to type Application. +// ClearApplication clears the "application" edge to the Application entity. func (tu *TagUpdate) ClearApplication() *TagUpdate { tu.mutation.ClearApplication() return tu } -// Save executes the query and returns the number of rows/vertices matched by this operation. +// Save executes the query and returns the number of nodes affected by the update operation. func (tu *TagUpdate) Save(ctx context.Context) (int, error) { - var ( - err error - affected int - ) - if len(tu.hooks) == 0 { - if err = tu.check(); err != nil { - return 0, err - } - affected, err = tu.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*TagMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = tu.check(); err != nil { - return 0, err - } - tu.mutation = mutation - affected, err = tu.sqlSave(ctx) - mutation.done = true - return affected, err - }) - for i := len(tu.hooks) - 1; i >= 0; i-- { - mut = tu.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, tu.mutation); err != nil { - return 0, err - } - } - return affected, err + return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -125,24 +95,18 @@ func (tu *TagUpdate) ExecX(ctx context.Context) { func (tu *TagUpdate) check() error { if v, ok := tu.mutation.Name(); ok { if err := tag.NameValidator(v); err != nil { - return &ValidationError{Name: "name", err: fmt.Errorf("ent: validator failed for field \"name\": %w", err)} + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Tag.name": %w`, err)} } } return nil } func (tu *TagUpdate) sqlSave(ctx context.Context) (n int, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: tag.Table, - Columns: tag.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, - }, + if err := tu.check(); err != nil { + return n, err } - if ps := tu.predicates; len(ps) > 0 { + _spec := sqlgraph.NewUpdateSpec(tag.Table, tag.Columns, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) + if ps := tu.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -150,11 +114,7 @@ func (tu *TagUpdate) sqlSave(ctx context.Context) (n int, err error) { } } if value, ok := tu.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: tag.FieldName, - }) + _spec.SetField(tag.FieldName, field.TypeString, value) } if tu.mutation.ApplicationCleared() { edge := &sqlgraph.EdgeSpec{ @@ -164,10 +124,7 @@ func (tu *TagUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{tag.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -180,10 +137,7 @@ func (tu *TagUpdate) sqlSave(ctx context.Context) (n int, err error) { Columns: []string{tag.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -194,34 +148,36 @@ func (tu *TagUpdate) sqlSave(ctx context.Context) (n int, err error) { if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{tag.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } + tu.mutation.done = true return n, nil } // TagUpdateOne is the builder for updating a single Tag entity. type TagUpdateOne struct { config + fields []string hooks []Hook mutation *TagMutation } -// SetName sets the name field. +// SetName sets the "name" field. func (tuo *TagUpdateOne) SetName(s string) *TagUpdateOne { tuo.mutation.SetName(s) return tuo } -// SetApplicationID sets the application edge to Application by id. +// SetApplicationID sets the "application" edge to the Application entity by ID. func (tuo *TagUpdateOne) SetApplicationID(id int) *TagUpdateOne { tuo.mutation.SetApplicationID(id) return tuo } -// SetNillableApplicationID sets the application edge to Application by id if the given value is not nil. +// SetNillableApplicationID sets the "application" edge to the Application entity by ID if the given value is not nil. func (tuo *TagUpdateOne) SetNillableApplicationID(id *int) *TagUpdateOne { if id != nil { tuo = tuo.SetApplicationID(*id) @@ -229,7 +185,7 @@ func (tuo *TagUpdateOne) SetNillableApplicationID(id *int) *TagUpdateOne { return tuo } -// SetApplication sets the application edge to Application. +// SetApplication sets the "application" edge to the Application entity. func (tuo *TagUpdateOne) SetApplication(a *Application) *TagUpdateOne { return tuo.SetApplicationID(a.ID) } @@ -239,45 +195,28 @@ func (tuo *TagUpdateOne) Mutation() *TagMutation { return tuo.mutation } -// ClearApplication clears the "application" edge to type Application. +// ClearApplication clears the "application" edge to the Application entity. func (tuo *TagUpdateOne) ClearApplication() *TagUpdateOne { tuo.mutation.ClearApplication() return tuo } -// Save executes the query and returns the updated entity. +// Where appends a list predicates to the TagUpdate builder. +func (tuo *TagUpdateOne) Where(ps ...predicate.Tag) *TagUpdateOne { + tuo.mutation.Where(ps...) + return tuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (tuo *TagUpdateOne) Select(field string, fields ...string) *TagUpdateOne { + tuo.fields = append([]string{field}, fields...) + return tuo +} + +// Save executes the query and returns the updated Tag entity. func (tuo *TagUpdateOne) Save(ctx context.Context) (*Tag, error) { - var ( - err error - node *Tag - ) - if len(tuo.hooks) == 0 { - if err = tuo.check(); err != nil { - return nil, err - } - node, err = tuo.sqlSave(ctx) - } else { - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*TagMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err = tuo.check(); err != nil { - return nil, err - } - tuo.mutation = mutation - node, err = tuo.sqlSave(ctx) - mutation.done = true - return node, err - }) - for i := len(tuo.hooks) - 1; i >= 0; i-- { - mut = tuo.hooks[i](mut) - } - if _, err := mut.Mutate(ctx, tuo.mutation); err != nil { - return nil, err - } - } - return node, err + return withHooks(ctx, tuo.sqlSave, tuo.mutation, tuo.hooks) } // SaveX is like Save, but panics if an error occurs. @@ -306,34 +245,43 @@ func (tuo *TagUpdateOne) ExecX(ctx context.Context) { func (tuo *TagUpdateOne) check() error { if v, ok := tuo.mutation.Name(); ok { if err := tag.NameValidator(v); err != nil { - return &ValidationError{Name: "name", err: fmt.Errorf("ent: validator failed for field \"name\": %w", err)} + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Tag.name": %w`, err)} } } return nil } func (tuo *TagUpdateOne) sqlSave(ctx context.Context) (_node *Tag, err error) { - _spec := &sqlgraph.UpdateSpec{ - Node: &sqlgraph.NodeSpec{ - Table: tag.Table, - Columns: tag.Columns, - ID: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: tag.FieldID, - }, - }, + if err := tuo.check(); err != nil { + return _node, err } + _spec := sqlgraph.NewUpdateSpec(tag.Table, tag.Columns, sqlgraph.NewFieldSpec(tag.FieldID, field.TypeInt)) id, ok := tuo.mutation.ID() if !ok { - return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Tag.ID for update")} + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Tag.id" for update`)} } _spec.Node.ID.Value = id + if fields := tuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, tag.FieldID) + for _, f := range fields { + if !tag.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != tag.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := tuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } if value, ok := tuo.mutation.Name(); ok { - _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ - Type: field.TypeString, - Value: value, - Column: tag.FieldName, - }) + _spec.SetField(tag.FieldName, field.TypeString, value) } if tuo.mutation.ApplicationCleared() { edge := &sqlgraph.EdgeSpec{ @@ -343,10 +291,7 @@ func (tuo *TagUpdateOne) sqlSave(ctx context.Context) (_node *Tag, err error) { Columns: []string{tag.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) @@ -359,10 +304,7 @@ func (tuo *TagUpdateOne) sqlSave(ctx context.Context) (_node *Tag, err error) { Columns: []string{tag.ApplicationColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: application.FieldID, - }, + IDSpec: sqlgraph.NewFieldSpec(application.FieldID, field.TypeInt), }, } for _, k := range nodes { @@ -372,14 +314,15 @@ func (tuo *TagUpdateOne) sqlSave(ctx context.Context) (_node *Tag, err error) { } _node = &Tag{config: tuo.config} _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues() + _spec.ScanValues = _node.scanValues if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{tag.Label} - } else if cerr, ok := isSQLConstraintError(err); ok { - err = cerr + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } + tuo.mutation.done = true return _node, nil } diff --git a/ent/tx.go b/ent/tx.go index 003a634a..4be7ccd3 100644 --- a/ent/tx.go +++ b/ent/tx.go @@ -1,4 +1,4 @@ -// Code generated by entc, DO NOT EDIT. +// Code generated by ent, DO NOT EDIT. package ent @@ -6,7 +6,7 @@ import ( "context" "sync" - "github.com/facebook/ent/dialect" + "entgo.io/ent/dialect" ) // Tx is a transactional client that is created by calling Client.Tx(). @@ -32,19 +32,13 @@ type Tx struct { // lazily loaded. client *Client clientOnce sync.Once - - // completion callbacks. - mu sync.Mutex - onCommit []CommitHook - onRollback []RollbackHook - // ctx lives for the life of the transaction. It is // the same context used by the underlying connection. ctx context.Context } type ( - // Committer is the interface that wraps the Committer method. + // Committer is the interface that wraps the Commit method. Committer interface { Commit(context.Context, *Tx) error } @@ -58,7 +52,7 @@ type ( // and returns a Committer. For example: // // hook := func(next ent.Committer) ent.Committer { - // return ent.CommitFunc(func(context.Context, tx *ent.Tx) error { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { // // Do some stuff before. // if err := next.Commit(ctx, tx); err != nil { // return err @@ -82,9 +76,9 @@ func (tx *Tx) Commit() error { var fn Committer = CommitFunc(func(context.Context, *Tx) error { return txDriver.tx.Commit() }) - tx.mu.Lock() - hooks := append([]CommitHook(nil), tx.onCommit...) - tx.mu.Unlock() + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() for i := len(hooks) - 1; i >= 0; i-- { fn = hooks[i](fn) } @@ -93,13 +87,14 @@ func (tx *Tx) Commit() error { // OnCommit adds a hook to call on commit. func (tx *Tx) OnCommit(f CommitHook) { - tx.mu.Lock() - defer tx.mu.Unlock() - tx.onCommit = append(tx.onCommit, f) + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() } type ( - // Rollbacker is the interface that wraps the Rollbacker method. + // Rollbacker is the interface that wraps the Rollback method. Rollbacker interface { Rollback(context.Context, *Tx) error } @@ -113,7 +108,7 @@ type ( // and returns a Rollbacker. For example: // // hook := func(next ent.Rollbacker) ent.Rollbacker { - // return ent.RollbackFunc(func(context.Context, tx *ent.Tx) error { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { // // Do some stuff before. // if err := next.Rollback(ctx, tx); err != nil { // return err @@ -137,9 +132,9 @@ func (tx *Tx) Rollback() error { var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { return txDriver.tx.Rollback() }) - tx.mu.Lock() - hooks := append([]RollbackHook(nil), tx.onRollback...) - tx.mu.Unlock() + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() for i := len(hooks) - 1; i >= 0; i-- { fn = hooks[i](fn) } @@ -148,9 +143,10 @@ func (tx *Tx) Rollback() error { // OnRollback adds a hook to call on rollback. func (tx *Tx) OnRollback(f RollbackHook) { - tx.mu.Lock() - defer tx.mu.Unlock() - tx.onRollback = append(tx.onRollback, f) + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() } // Client returns a Client that binds to current transaction. @@ -189,6 +185,10 @@ type txDriver struct { drv dialect.Driver // tx is the underlying transaction. tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook } // newTx creates a new transactional driver. @@ -219,12 +219,12 @@ func (*txDriver) Commit() error { return nil } func (*txDriver) Rollback() error { return nil } // Exec calls tx.Exec. -func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error { +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { return tx.tx.Exec(ctx, query, args, v) } // Query calls tx.Query. -func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error { +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { return tx.tx.Query(ctx, query, args, v) } diff --git a/go.mod b/go.mod index 35f9eb19..3c191921 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/gobench-io/gobench/v2 go 1.20 require ( + entgo.io/ent v0.12.3 github.com/eclipse/paho.mqtt.golang v1.2.1-0.20190829142118-2e9e43b5d02b github.com/facebook/ent v0.4.3 github.com/go-chi/chi v4.1.0+incompatible @@ -10,13 +11,12 @@ require ( github.com/go-chi/jwtauth v4.0.4+incompatible github.com/go-chi/render v1.0.1 github.com/golang-jwt/jwt v3.2.2+incompatible - github.com/golang/protobuf v1.4.3 - github.com/google/uuid v1.1.2 + github.com/google/uuid v1.3.0 github.com/mackerelio/go-osstat v0.1.0 - github.com/mattn/go-sqlite3 v1.14.3 + github.com/mattn/go-sqlite3 v1.14.16 github.com/nats-io/nats.go v1.11.1-0.20210623165838-4b75fc59ae30 github.com/rcrowley/go-metrics v0.0.0-20190826022208-cac0b30c2563 - github.com/stretchr/testify v1.6.1 + github.com/stretchr/testify v1.8.2 go.uber.org/zap v1.15.0 google.golang.org/grpc v1.36.0 google.golang.org/grpc/examples v0.0.0-20210702232146-dd589923e1a1 @@ -24,20 +24,30 @@ require ( ) require ( + ariga.io/atlas v0.10.2-0.20230427182402-87a07dfb83bf // indirect + github.com/agext/levenshtein v1.2.1 // indirect + github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect - github.com/gorilla/websocket v1.4.2 // indirect + github.com/go-openapi/inflect v0.19.0 // indirect + github.com/golang/protobuf v1.4.3 // indirect + github.com/google/go-cmp v0.5.6 // indirect + github.com/gorilla/websocket v1.5.0 // indirect + github.com/hashicorp/hcl/v2 v2.13.0 // indirect + github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect github.com/nats-io/nats-server/v2 v2.3.4 // indirect github.com/nats-io/nkeys v0.3.0 // indirect github.com/nats-io/nuid v1.0.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/stretchr/objx v0.2.0 // indirect + github.com/stretchr/objx v0.5.0 // indirect + github.com/zclconf/go-cty v1.8.0 // indirect go.uber.org/atomic v1.6.0 // indirect go.uber.org/multierr v1.5.0 // indirect - golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect - golang.org/x/net v0.0.0-20220722155237-a158d28d115b // indirect - golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect - golang.org/x/text v0.3.8 // indirect + golang.org/x/crypto v0.0.0-20220517005047-85d78b3ac167 // indirect + golang.org/x/mod v0.10.0 // indirect + golang.org/x/net v0.9.0 // indirect + golang.org/x/sys v0.7.0 // indirect + golang.org/x/text v0.9.0 // indirect google.golang.org/genproto v0.0.0-20210121164019-fc48d45331c7 // indirect - gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index c1dee19a..71114470 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,20 @@ +ariga.io/atlas v0.10.2-0.20230427182402-87a07dfb83bf h1:Tq2DRB39ZHScIwWACjPKLv5oEErv7zv6PBb5RTz5CKA= +ariga.io/atlas v0.10.2-0.20230427182402-87a07dfb83bf/go.mod h1:+TR129FJZ5Lvzms6dvCeGWh1yR6hMvmXBhug4hrNIGk= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +entgo.io/ent v0.12.3 h1:N5lO2EOrHpCH5HYfiMOCHYbo+oh5M8GjT0/cx5x6xkk= +entgo.io/ent v0.12.3/go.mod h1:AigGGx+tbrBBYHAzGOg8ND661E5cxx1Uiu5o/otJ6Yg= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60= github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= +github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= +github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= @@ -48,9 +56,11 @@ github.com/go-chi/render v1.0.1/go.mod h1:pq4Rr7HbnsdaeHagklXub+p6Wd16Af5l9koip1 github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4= github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4= github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= @@ -63,6 +73,7 @@ github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfb github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= @@ -77,19 +88,24 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc= +github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= @@ -105,20 +121,24 @@ github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFB github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4= github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mackerelio/go-osstat v0.1.0 h1:e57QHeHob8kKJ5FhcXGdzx5O6Ktuc5RHMDIkeqhgkFA= github.com/mackerelio/go-osstat v0.1.0/go.mod h1:1K3NeYLhMHPvzUu+ePYXtoB58wkaRpxZsGClZBJyIFw= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-sqlite3 v1.14.3 h1:j7a/xn1U6TKA/PHHxqZuzh64CdtRc7rU9M+AvkOl5bA= github.com/mattn/go-sqlite3 v1.14.3/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI= +github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= +github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/minio/highwayhash v1.0.1 h1:dZ6IIu8Z14VlC0VpfKofAhCy74wu/Qb5gcn52yWoz/0= github.com/minio/highwayhash v1.0.1/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -163,6 +183,7 @@ github.com/rcrowley/go-metrics v0.0.0-20190826022208-cac0b30c2563/go.mod h1:bCqn github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= @@ -176,19 +197,28 @@ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/vmihailenco/msgpack/v4 v4.3.12/go.mod h1:gborTTJjAo/GWTqqRjrLCn9pgNN+NXzzngzBKDPIqw4= +github.com/vmihailenco/tagparser v0.1.1/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/zclconf/go-cty v1.8.0 h1:s4AvqaeQzJIu3ndv4gVIhplVD0krU+bgrcLSVUnaWuA= +github.com/zclconf/go-cty v1.8.0/go.mod h1:vVKLxnk3puL4qRAv72AO+W99LUD4da90g3uUAzyuvAk= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= @@ -210,8 +240,8 @@ golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220517005047-85d78b3ac167 h1:O8uGbHCqlTp2P6QJSLmCojM4mN6UemYv8K+dCnmHmu0= +golang.org/x/crypto v0.0.0-20220517005047-85d78b3ac167/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= @@ -221,7 +251,8 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= +golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk= +golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -231,11 +262,13 @@ golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b h1:PxfKdU9lEEDYjdIzOtC4qFWgkU2rGHdKlKowJSMN9h0= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -256,14 +289,15 @@ golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1 h1:NusfzzA6yGQ+ua51ck7E3omNUX/JuqbFSaRGqU8CcLI= golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -279,7 +313,7 @@ golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= +golang.org/x/tools v0.8.1-0.20230428195545-5283a0178901 h1:0wxTF6pSjIIhNt7mo9GvjDfzyCOiWhmICgtO/Ah948s= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -287,6 +321,7 @@ golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1N golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= @@ -324,8 +359,9 @@ gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= diff --git a/master/master.go b/master/master.go index 6c1fe16f..59f76e58 100644 --- a/master/master.go +++ b/master/master.go @@ -15,6 +15,7 @@ import ( "sync" "time" + "entgo.io/ent/dialect" "github.com/gobench-io/gobench/v2/agent" "github.com/gobench-io/gobench/v2/ent" "github.com/gobench-io/gobench/v2/ent/application" @@ -363,7 +364,11 @@ func (m *Master) setupDb() error { if err != nil { return fmt.Errorf("failed opening sqlite3 connection: %v", err) } - client := ent.NewClient(ent.Driver(drv)) + + client, err := ent.Open(dialect.SQLite, m.dbFilename+"?mode=rwc&cache=shared&&_busy_timeout=9999999&_fk=1") + if err != nil { + return fmt.Errorf("failed creating ent client: %v", err) + } if err = client.Schema.Create(context.Background()); err != nil { return fmt.Errorf("failed creating schema resources: %v", err) diff --git a/web/render.go b/web/render.go index f1442c51..bd5c2c52 100644 --- a/web/render.go +++ b/web/render.go @@ -99,7 +99,6 @@ func (a *applicationRequest) Bind(r *http.Request) (err error) { type applicationResponse struct { *ent.Application - Edges *struct{} `json:"edges,omitempty"` } type countApplicationResponse struct { @@ -123,7 +122,6 @@ func newCountApplicationResponse(count int) *countApplicationResponse { func newApplicationResponse(a *ent.Application) *applicationResponse { return &applicationResponse{ a, - nil, } }