diff --git a/ent/client.go b/ent/client.go index 1fc6979b..717c689f 100644 --- a/ent/client.go +++ b/ent/client.go @@ -13,6 +13,7 @@ import ( "github.com/gitploy-io/gitploy/ent/callback" "github.com/gitploy-io/gitploy/ent/chatuser" "github.com/gitploy-io/gitploy/ent/deployment" + "github.com/gitploy-io/gitploy/ent/deploymentcount" "github.com/gitploy-io/gitploy/ent/deploymentstatus" "github.com/gitploy-io/gitploy/ent/event" "github.com/gitploy-io/gitploy/ent/lock" @@ -39,6 +40,8 @@ type Client struct { ChatUser *ChatUserClient // Deployment is the client for interacting with the Deployment builders. Deployment *DeploymentClient + // DeploymentCount is the client for interacting with the DeploymentCount builders. + DeploymentCount *DeploymentCountClient // DeploymentStatus is the client for interacting with the DeploymentStatus builders. DeploymentStatus *DeploymentStatusClient // Event is the client for interacting with the Event builders. @@ -70,6 +73,7 @@ func (c *Client) init() { c.Callback = NewCallbackClient(c.config) c.ChatUser = NewChatUserClient(c.config) c.Deployment = NewDeploymentClient(c.config) + c.DeploymentCount = NewDeploymentCountClient(c.config) c.DeploymentStatus = NewDeploymentStatusClient(c.config) c.Event = NewEventClient(c.config) c.Lock = NewLockClient(c.config) @@ -114,6 +118,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Callback: NewCallbackClient(cfg), ChatUser: NewChatUserClient(cfg), Deployment: NewDeploymentClient(cfg), + DeploymentCount: NewDeploymentCountClient(cfg), DeploymentStatus: NewDeploymentStatusClient(cfg), Event: NewEventClient(cfg), Lock: NewLockClient(cfg), @@ -143,6 +148,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Callback: NewCallbackClient(cfg), ChatUser: NewChatUserClient(cfg), Deployment: NewDeploymentClient(cfg), + DeploymentCount: NewDeploymentCountClient(cfg), DeploymentStatus: NewDeploymentStatusClient(cfg), Event: NewEventClient(cfg), Lock: NewLockClient(cfg), @@ -183,6 +189,7 @@ func (c *Client) Use(hooks ...Hook) { c.Callback.Use(hooks...) c.ChatUser.Use(hooks...) c.Deployment.Use(hooks...) + c.DeploymentCount.Use(hooks...) c.DeploymentStatus.Use(hooks...) c.Event.Use(hooks...) c.Lock.Use(hooks...) @@ -712,6 +719,96 @@ func (c *DeploymentClient) Hooks() []Hook { return c.hooks.Deployment } +// DeploymentCountClient is a client for the DeploymentCount schema. +type DeploymentCountClient struct { + config +} + +// NewDeploymentCountClient returns a client for the DeploymentCount from the given config. +func NewDeploymentCountClient(c config) *DeploymentCountClient { + return &DeploymentCountClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `deploymentcount.Hooks(f(g(h())))`. +func (c *DeploymentCountClient) Use(hooks ...Hook) { + c.hooks.DeploymentCount = append(c.hooks.DeploymentCount, hooks...) +} + +// Create returns a create builder for DeploymentCount. +func (c *DeploymentCountClient) Create() *DeploymentCountCreate { + mutation := newDeploymentCountMutation(c.config, OpCreate) + return &DeploymentCountCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of DeploymentCount entities. +func (c *DeploymentCountClient) CreateBulk(builders ...*DeploymentCountCreate) *DeploymentCountCreateBulk { + return &DeploymentCountCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for DeploymentCount. +func (c *DeploymentCountClient) Update() *DeploymentCountUpdate { + mutation := newDeploymentCountMutation(c.config, OpUpdate) + return &DeploymentCountUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *DeploymentCountClient) UpdateOne(dc *DeploymentCount) *DeploymentCountUpdateOne { + mutation := newDeploymentCountMutation(c.config, OpUpdateOne, withDeploymentCount(dc)) + return &DeploymentCountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *DeploymentCountClient) UpdateOneID(id int) *DeploymentCountUpdateOne { + mutation := newDeploymentCountMutation(c.config, OpUpdateOne, withDeploymentCountID(id)) + return &DeploymentCountUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for DeploymentCount. +func (c *DeploymentCountClient) Delete() *DeploymentCountDelete { + mutation := newDeploymentCountMutation(c.config, OpDelete) + return &DeploymentCountDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *DeploymentCountClient) DeleteOne(dc *DeploymentCount) *DeploymentCountDeleteOne { + return c.DeleteOneID(dc.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *DeploymentCountClient) DeleteOneID(id int) *DeploymentCountDeleteOne { + builder := c.Delete().Where(deploymentcount.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &DeploymentCountDeleteOne{builder} +} + +// Query returns a query builder for DeploymentCount. +func (c *DeploymentCountClient) Query() *DeploymentCountQuery { + return &DeploymentCountQuery{ + config: c.config, + } +} + +// Get returns a DeploymentCount entity by its id. +func (c *DeploymentCountClient) Get(ctx context.Context, id int) (*DeploymentCount, error) { + return c.Query().Where(deploymentcount.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *DeploymentCountClient) GetX(ctx context.Context, id int) *DeploymentCount { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *DeploymentCountClient) Hooks() []Hook { + return c.hooks.DeploymentCount +} + // DeploymentStatusClient is a client for the DeploymentStatus schema. type DeploymentStatusClient struct { config diff --git a/ent/config.go b/ent/config.go index 2d771d19..a278c67d 100644 --- a/ent/config.go +++ b/ent/config.go @@ -28,6 +28,7 @@ type hooks struct { Callback []ent.Hook ChatUser []ent.Hook Deployment []ent.Hook + DeploymentCount []ent.Hook DeploymentStatus []ent.Hook Event []ent.Hook Lock []ent.Hook diff --git a/ent/deploymentcount.go b/ent/deploymentcount.go new file mode 100644 index 00000000..f053798e --- /dev/null +++ b/ent/deploymentcount.go @@ -0,0 +1,152 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/gitploy-io/gitploy/ent/deploymentcount" +) + +// DeploymentCount is the model entity for the DeploymentCount schema. +type DeploymentCount struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Namespace holds the value of the "namespace" field. + Namespace string `json:"namespace"` + // Name holds the value of the "name" field. + Name string `json:"name"` + // Env holds the value of the "env" field. + Env string `json:"env"` + // Count holds the value of the "count" field. + Count int `json:"count"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at"` + // UpdatedAt holds the value of the "updated_at" field. + UpdatedAt time.Time `json:"updated_at"` +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*DeploymentCount) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case deploymentcount.FieldID, deploymentcount.FieldCount: + values[i] = new(sql.NullInt64) + case deploymentcount.FieldNamespace, deploymentcount.FieldName, deploymentcount.FieldEnv: + values[i] = new(sql.NullString) + case deploymentcount.FieldCreatedAt, deploymentcount.FieldUpdatedAt: + values[i] = new(sql.NullTime) + default: + return nil, fmt.Errorf("unexpected column %q for type DeploymentCount", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the DeploymentCount fields. +func (dc *DeploymentCount) assignValues(columns []string, values []interface{}) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case deploymentcount.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + dc.ID = int(value.Int64) + case deploymentcount.FieldNamespace: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field namespace", values[i]) + } else if value.Valid { + dc.Namespace = value.String + } + case deploymentcount.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + dc.Name = value.String + } + case deploymentcount.FieldEnv: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field env", values[i]) + } else if value.Valid { + dc.Env = value.String + } + case deploymentcount.FieldCount: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field count", values[i]) + } else if value.Valid { + dc.Count = int(value.Int64) + } + case deploymentcount.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 { + dc.CreatedAt = value.Time + } + case deploymentcount.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 { + dc.UpdatedAt = value.Time + } + } + } + return nil +} + +// Update returns a builder for updating this DeploymentCount. +// Note that you need to call DeploymentCount.Unwrap() before calling this method if this DeploymentCount +// was returned from a transaction, and the transaction was committed or rolled back. +func (dc *DeploymentCount) Update() *DeploymentCountUpdateOne { + return (&DeploymentCountClient{config: dc.config}).UpdateOne(dc) +} + +// Unwrap unwraps the DeploymentCount 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 (dc *DeploymentCount) Unwrap() *DeploymentCount { + tx, ok := dc.config.driver.(*txDriver) + if !ok { + panic("ent: DeploymentCount is not a transactional entity") + } + dc.config.driver = tx.drv + return dc +} + +// String implements the fmt.Stringer. +func (dc *DeploymentCount) String() string { + var builder strings.Builder + builder.WriteString("DeploymentCount(") + builder.WriteString(fmt.Sprintf("id=%v", dc.ID)) + builder.WriteString(", namespace=") + builder.WriteString(dc.Namespace) + builder.WriteString(", name=") + builder.WriteString(dc.Name) + builder.WriteString(", env=") + builder.WriteString(dc.Env) + builder.WriteString(", count=") + builder.WriteString(fmt.Sprintf("%v", dc.Count)) + builder.WriteString(", created_at=") + builder.WriteString(dc.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", updated_at=") + builder.WriteString(dc.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// DeploymentCounts is a parsable slice of DeploymentCount. +type DeploymentCounts []*DeploymentCount + +func (dc DeploymentCounts) config(cfg config) { + for _i := range dc { + dc[_i].config = cfg + } +} diff --git a/ent/deploymentcount/deploymentcount.go b/ent/deploymentcount/deploymentcount.go new file mode 100644 index 00000000..80182f64 --- /dev/null +++ b/ent/deploymentcount/deploymentcount.go @@ -0,0 +1,60 @@ +// Code generated by entc, DO NOT EDIT. + +package deploymentcount + +import ( + "time" +) + +const ( + // Label holds the string label denoting the deploymentcount type in the database. + Label = "deployment_count" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldNamespace holds the string denoting the namespace field in the database. + FieldNamespace = "namespace" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldEnv holds the string denoting the env field in the database. + FieldEnv = "env" + // FieldCount holds the string denoting the count field in the database. + FieldCount = "count" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUpdatedAt holds the string denoting the updated_at field in the database. + FieldUpdatedAt = "updated_at" + // Table holds the table name of the deploymentcount in the database. + Table = "deployment_counts" +) + +// Columns holds all SQL columns for deploymentcount fields. +var Columns = []string{ + FieldID, + FieldNamespace, + FieldName, + FieldEnv, + FieldCount, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCount holds the default value on creation for the "count" field. + DefaultCount int + // 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 func() time.Time + // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. + UpdateDefaultUpdatedAt func() time.Time +) diff --git a/ent/deploymentcount/where.go b/ent/deploymentcount/where.go new file mode 100644 index 00000000..31b3a34a --- /dev/null +++ b/ent/deploymentcount/where.go @@ -0,0 +1,728 @@ +// Code generated by entc, DO NOT EDIT. + +package deploymentcount + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "github.com/gitploy-io/gitploy/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.DeploymentCount { + return predicate.DeploymentCount(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...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.DeploymentCount { + return predicate.DeploymentCount(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...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Namespace applies equality check predicate on the "namespace" field. It's identical to NamespaceEQ. +func Namespace(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldNamespace), v)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Env applies equality check predicate on the "env" field. It's identical to EnvEQ. +func Env(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEnv), v)) + }) +} + +// Count applies equality check predicate on the "count" field. It's identical to CountEQ. +func Count(v int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCount), v)) + }) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreatedAt), v)) + }) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdatedAt), v)) + }) +} + +// NamespaceEQ applies the EQ predicate on the "namespace" field. +func NamespaceEQ(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldNamespace), v)) + }) +} + +// NamespaceNEQ applies the NEQ predicate on the "namespace" field. +func NamespaceNEQ(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldNamespace), v)) + }) +} + +// NamespaceIn applies the In predicate on the "namespace" field. +func NamespaceIn(vs ...string) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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(FieldNamespace), v...)) + }) +} + +// NamespaceNotIn applies the NotIn predicate on the "namespace" field. +func NamespaceNotIn(vs ...string) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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(FieldNamespace), v...)) + }) +} + +// NamespaceGT applies the GT predicate on the "namespace" field. +func NamespaceGT(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldNamespace), v)) + }) +} + +// NamespaceGTE applies the GTE predicate on the "namespace" field. +func NamespaceGTE(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldNamespace), v)) + }) +} + +// NamespaceLT applies the LT predicate on the "namespace" field. +func NamespaceLT(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldNamespace), v)) + }) +} + +// NamespaceLTE applies the LTE predicate on the "namespace" field. +func NamespaceLTE(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldNamespace), v)) + }) +} + +// NamespaceContains applies the Contains predicate on the "namespace" field. +func NamespaceContains(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldNamespace), v)) + }) +} + +// NamespaceHasPrefix applies the HasPrefix predicate on the "namespace" field. +func NamespaceHasPrefix(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldNamespace), v)) + }) +} + +// NamespaceHasSuffix applies the HasSuffix predicate on the "namespace" field. +func NamespaceHasSuffix(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldNamespace), v)) + }) +} + +// NamespaceEqualFold applies the EqualFold predicate on the "namespace" field. +func NamespaceEqualFold(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldNamespace), v)) + }) +} + +// NamespaceContainsFold applies the ContainsFold predicate on the "namespace" field. +func NamespaceContainsFold(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldNamespace), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// EnvEQ applies the EQ predicate on the "env" field. +func EnvEQ(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldEnv), v)) + }) +} + +// EnvNEQ applies the NEQ predicate on the "env" field. +func EnvNEQ(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldEnv), v)) + }) +} + +// EnvIn applies the In predicate on the "env" field. +func EnvIn(vs ...string) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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(FieldEnv), v...)) + }) +} + +// EnvNotIn applies the NotIn predicate on the "env" field. +func EnvNotIn(vs ...string) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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(FieldEnv), v...)) + }) +} + +// EnvGT applies the GT predicate on the "env" field. +func EnvGT(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldEnv), v)) + }) +} + +// EnvGTE applies the GTE predicate on the "env" field. +func EnvGTE(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldEnv), v)) + }) +} + +// EnvLT applies the LT predicate on the "env" field. +func EnvLT(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldEnv), v)) + }) +} + +// EnvLTE applies the LTE predicate on the "env" field. +func EnvLTE(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldEnv), v)) + }) +} + +// EnvContains applies the Contains predicate on the "env" field. +func EnvContains(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldEnv), v)) + }) +} + +// EnvHasPrefix applies the HasPrefix predicate on the "env" field. +func EnvHasPrefix(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldEnv), v)) + }) +} + +// EnvHasSuffix applies the HasSuffix predicate on the "env" field. +func EnvHasSuffix(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldEnv), v)) + }) +} + +// EnvEqualFold applies the EqualFold predicate on the "env" field. +func EnvEqualFold(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldEnv), v)) + }) +} + +// EnvContainsFold applies the ContainsFold predicate on the "env" field. +func EnvContainsFold(v string) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldEnv), v)) + }) +} + +// CountEQ applies the EQ predicate on the "count" field. +func CountEQ(v int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCount), v)) + }) +} + +// CountNEQ applies the NEQ predicate on the "count" field. +func CountNEQ(v int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCount), v)) + }) +} + +// CountIn applies the In predicate on the "count" field. +func CountIn(vs ...int) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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...)) + }) +} + +// CountNotIn applies the NotIn predicate on the "count" field. +func CountNotIn(vs ...int) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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...)) + }) +} + +// CountGT applies the GT predicate on the "count" field. +func CountGT(v int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCount), v)) + }) +} + +// CountGTE applies the GTE predicate on the "count" field. +func CountGTE(v int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCount), v)) + }) +} + +// CountLT applies the LT predicate on the "count" field. +func CountLT(v int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCount), v)) + }) +} + +// CountLTE applies the LTE predicate on the "count" field. +func CountLTE(v int) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCount), v)) + }) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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...)) + }) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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...)) + }) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreatedAt), v)) + }) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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...)) + }) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.DeploymentCount { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentCount(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...)) + }) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdatedAt), v)) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.DeploymentCount) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.DeploymentCount) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.DeploymentCount) predicate.DeploymentCount { + return predicate.DeploymentCount(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/ent/deploymentcount_create.go b/ent/deploymentcount_create.go new file mode 100644 index 00000000..f5df47f0 --- /dev/null +++ b/ent/deploymentcount_create.go @@ -0,0 +1,348 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/gitploy-io/gitploy/ent/deploymentcount" +) + +// DeploymentCountCreate is the builder for creating a DeploymentCount entity. +type DeploymentCountCreate struct { + config + mutation *DeploymentCountMutation + hooks []Hook +} + +// SetNamespace sets the "namespace" field. +func (dcc *DeploymentCountCreate) SetNamespace(s string) *DeploymentCountCreate { + dcc.mutation.SetNamespace(s) + return dcc +} + +// SetName sets the "name" field. +func (dcc *DeploymentCountCreate) SetName(s string) *DeploymentCountCreate { + dcc.mutation.SetName(s) + return dcc +} + +// SetEnv sets the "env" field. +func (dcc *DeploymentCountCreate) SetEnv(s string) *DeploymentCountCreate { + dcc.mutation.SetEnv(s) + return dcc +} + +// SetCount sets the "count" field. +func (dcc *DeploymentCountCreate) SetCount(i int) *DeploymentCountCreate { + dcc.mutation.SetCount(i) + return dcc +} + +// SetNillableCount sets the "count" field if the given value is not nil. +func (dcc *DeploymentCountCreate) SetNillableCount(i *int) *DeploymentCountCreate { + if i != nil { + dcc.SetCount(*i) + } + return dcc +} + +// SetCreatedAt sets the "created_at" field. +func (dcc *DeploymentCountCreate) SetCreatedAt(t time.Time) *DeploymentCountCreate { + dcc.mutation.SetCreatedAt(t) + return dcc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (dcc *DeploymentCountCreate) SetNillableCreatedAt(t *time.Time) *DeploymentCountCreate { + if t != nil { + dcc.SetCreatedAt(*t) + } + return dcc +} + +// SetUpdatedAt sets the "updated_at" field. +func (dcc *DeploymentCountCreate) SetUpdatedAt(t time.Time) *DeploymentCountCreate { + dcc.mutation.SetUpdatedAt(t) + return dcc +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (dcc *DeploymentCountCreate) SetNillableUpdatedAt(t *time.Time) *DeploymentCountCreate { + if t != nil { + dcc.SetUpdatedAt(*t) + } + return dcc +} + +// Mutation returns the DeploymentCountMutation object of the builder. +func (dcc *DeploymentCountCreate) Mutation() *DeploymentCountMutation { + return dcc.mutation +} + +// Save creates the DeploymentCount in the database. +func (dcc *DeploymentCountCreate) Save(ctx context.Context) (*DeploymentCount, error) { + var ( + err error + node *DeploymentCount + ) + dcc.defaults() + if len(dcc.hooks) == 0 { + if err = dcc.check(); err != nil { + return nil, err + } + node, err = dcc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*DeploymentCountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = dcc.check(); err != nil { + return nil, err + } + dcc.mutation = mutation + if node, err = dcc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(dcc.hooks) - 1; i >= 0; i-- { + if dcc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = dcc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, dcc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (dcc *DeploymentCountCreate) SaveX(ctx context.Context) *DeploymentCount { + v, err := dcc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (dcc *DeploymentCountCreate) Exec(ctx context.Context) error { + _, err := dcc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (dcc *DeploymentCountCreate) ExecX(ctx context.Context) { + if err := dcc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (dcc *DeploymentCountCreate) defaults() { + if _, ok := dcc.mutation.Count(); !ok { + v := deploymentcount.DefaultCount + dcc.mutation.SetCount(v) + } + if _, ok := dcc.mutation.CreatedAt(); !ok { + v := deploymentcount.DefaultCreatedAt() + dcc.mutation.SetCreatedAt(v) + } + if _, ok := dcc.mutation.UpdatedAt(); !ok { + v := deploymentcount.DefaultUpdatedAt() + dcc.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (dcc *DeploymentCountCreate) check() error { + if _, ok := dcc.mutation.Namespace(); !ok { + return &ValidationError{Name: "namespace", err: errors.New(`ent: missing required field "namespace"`)} + } + if _, ok := dcc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "name"`)} + } + if _, ok := dcc.mutation.Env(); !ok { + return &ValidationError{Name: "env", err: errors.New(`ent: missing required field "env"`)} + } + if _, ok := dcc.mutation.Count(); !ok { + return &ValidationError{Name: "count", err: errors.New(`ent: missing required field "count"`)} + } + if _, ok := dcc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "created_at"`)} + } + if _, ok := dcc.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "updated_at"`)} + } + return nil +} + +func (dcc *DeploymentCountCreate) sqlSave(ctx context.Context) (*DeploymentCount, error) { + _node, _spec := dcc.createSpec() + if err := sqlgraph.CreateNode(ctx, dcc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + return _node, nil +} + +func (dcc *DeploymentCountCreate) createSpec() (*DeploymentCount, *sqlgraph.CreateSpec) { + var ( + _node = &DeploymentCount{config: dcc.config} + _spec = &sqlgraph.CreateSpec{ + Table: deploymentcount.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentcount.FieldID, + }, + } + ) + if value, ok := dcc.mutation.Namespace(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: deploymentcount.FieldNamespace, + }) + _node.Namespace = value + } + if value, ok := dcc.mutation.Name(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: deploymentcount.FieldName, + }) + _node.Name = value + } + if value, ok := dcc.mutation.Env(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: deploymentcount.FieldEnv, + }) + _node.Env = value + } + if value, ok := dcc.mutation.Count(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: deploymentcount.FieldCount, + }) + _node.Count = value + } + if value, ok := dcc.mutation.CreatedAt(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: deploymentcount.FieldCreatedAt, + }) + _node.CreatedAt = value + } + if value, ok := dcc.mutation.UpdatedAt(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: deploymentcount.FieldUpdatedAt, + }) + _node.UpdatedAt = value + } + return _node, _spec +} + +// DeploymentCountCreateBulk is the builder for creating many DeploymentCount entities in bulk. +type DeploymentCountCreateBulk struct { + config + builders []*DeploymentCountCreate +} + +// Save creates the DeploymentCount entities in the database. +func (dccb *DeploymentCountCreateBulk) Save(ctx context.Context) ([]*DeploymentCount, error) { + specs := make([]*sqlgraph.CreateSpec, len(dccb.builders)) + nodes := make([]*DeploymentCount, len(dccb.builders)) + mutators := make([]Mutator, len(dccb.builders)) + for i := range dccb.builders { + func(i int, root context.Context) { + builder := dccb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*DeploymentCountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, dccb.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, dccb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(id) + } + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, dccb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (dccb *DeploymentCountCreateBulk) SaveX(ctx context.Context) []*DeploymentCount { + v, err := dccb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (dccb *DeploymentCountCreateBulk) Exec(ctx context.Context) error { + _, err := dccb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (dccb *DeploymentCountCreateBulk) ExecX(ctx context.Context) { + if err := dccb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/deploymentcount_delete.go b/ent/deploymentcount_delete.go new file mode 100644 index 00000000..8b3e1c7b --- /dev/null +++ b/ent/deploymentcount_delete.go @@ -0,0 +1,111 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/gitploy-io/gitploy/ent/deploymentcount" + "github.com/gitploy-io/gitploy/ent/predicate" +) + +// DeploymentCountDelete is the builder for deleting a DeploymentCount entity. +type DeploymentCountDelete struct { + config + hooks []Hook + mutation *DeploymentCountMutation +} + +// Where appends a list predicates to the DeploymentCountDelete builder. +func (dcd *DeploymentCountDelete) Where(ps ...predicate.DeploymentCount) *DeploymentCountDelete { + dcd.mutation.Where(ps...) + return dcd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (dcd *DeploymentCountDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(dcd.hooks) == 0 { + affected, err = dcd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*DeploymentCountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + dcd.mutation = mutation + affected, err = dcd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(dcd.hooks) - 1; i >= 0; i-- { + if dcd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = dcd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, dcd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (dcd *DeploymentCountDelete) ExecX(ctx context.Context) int { + n, err := dcd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (dcd *DeploymentCountDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: deploymentcount.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentcount.FieldID, + }, + }, + } + if ps := dcd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, dcd.driver, _spec) +} + +// DeploymentCountDeleteOne is the builder for deleting a single DeploymentCount entity. +type DeploymentCountDeleteOne struct { + dcd *DeploymentCountDelete +} + +// Exec executes the deletion query. +func (dcdo *DeploymentCountDeleteOne) Exec(ctx context.Context) error { + n, err := dcdo.dcd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{deploymentcount.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (dcdo *DeploymentCountDeleteOne) ExecX(ctx context.Context) { + dcdo.dcd.ExecX(ctx) +} diff --git a/ent/deploymentcount_query.go b/ent/deploymentcount_query.go new file mode 100644 index 00000000..bb345017 --- /dev/null +++ b/ent/deploymentcount_query.go @@ -0,0 +1,952 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "math" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/gitploy-io/gitploy/ent/deploymentcount" + "github.com/gitploy-io/gitploy/ent/predicate" +) + +// DeploymentCountQuery is the builder for querying DeploymentCount entities. +type DeploymentCountQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.DeploymentCount + modifiers []func(s *sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the DeploymentCountQuery builder. +func (dcq *DeploymentCountQuery) Where(ps ...predicate.DeploymentCount) *DeploymentCountQuery { + dcq.predicates = append(dcq.predicates, ps...) + return dcq +} + +// Limit adds a limit step to the query. +func (dcq *DeploymentCountQuery) Limit(limit int) *DeploymentCountQuery { + dcq.limit = &limit + return dcq +} + +// Offset adds an offset step to the query. +func (dcq *DeploymentCountQuery) Offset(offset int) *DeploymentCountQuery { + dcq.offset = &offset + return dcq +} + +// 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 (dcq *DeploymentCountQuery) Unique(unique bool) *DeploymentCountQuery { + dcq.unique = &unique + return dcq +} + +// Order adds an order step to the query. +func (dcq *DeploymentCountQuery) Order(o ...OrderFunc) *DeploymentCountQuery { + dcq.order = append(dcq.order, o...) + return dcq +} + +// First returns the first DeploymentCount entity from the query. +// Returns a *NotFoundError when no DeploymentCount was found. +func (dcq *DeploymentCountQuery) First(ctx context.Context) (*DeploymentCount, error) { + nodes, err := dcq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{deploymentcount.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (dcq *DeploymentCountQuery) FirstX(ctx context.Context) *DeploymentCount { + node, err := dcq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first DeploymentCount ID from the query. +// Returns a *NotFoundError when no DeploymentCount ID was found. +func (dcq *DeploymentCountQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = dcq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{deploymentcount.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (dcq *DeploymentCountQuery) FirstIDX(ctx context.Context) int { + id, err := dcq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single DeploymentCount entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one DeploymentCount entity is not found. +// Returns a *NotFoundError when no DeploymentCount entities are found. +func (dcq *DeploymentCountQuery) Only(ctx context.Context) (*DeploymentCount, error) { + nodes, err := dcq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{deploymentcount.Label} + default: + return nil, &NotSingularError{deploymentcount.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (dcq *DeploymentCountQuery) OnlyX(ctx context.Context) *DeploymentCount { + node, err := dcq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only DeploymentCount ID in the query. +// Returns a *NotSingularError when exactly one DeploymentCount ID is not found. +// Returns a *NotFoundError when no entities are found. +func (dcq *DeploymentCountQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = dcq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{deploymentcount.Label} + default: + err = &NotSingularError{deploymentcount.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (dcq *DeploymentCountQuery) OnlyIDX(ctx context.Context) int { + id, err := dcq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of DeploymentCounts. +func (dcq *DeploymentCountQuery) All(ctx context.Context) ([]*DeploymentCount, error) { + if err := dcq.prepareQuery(ctx); err != nil { + return nil, err + } + return dcq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (dcq *DeploymentCountQuery) AllX(ctx context.Context) []*DeploymentCount { + nodes, err := dcq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of DeploymentCount IDs. +func (dcq *DeploymentCountQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := dcq.Select(deploymentcount.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (dcq *DeploymentCountQuery) IDsX(ctx context.Context) []int { + ids, err := dcq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (dcq *DeploymentCountQuery) Count(ctx context.Context) (int, error) { + if err := dcq.prepareQuery(ctx); err != nil { + return 0, err + } + return dcq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (dcq *DeploymentCountQuery) CountX(ctx context.Context) int { + count, err := dcq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (dcq *DeploymentCountQuery) Exist(ctx context.Context) (bool, error) { + if err := dcq.prepareQuery(ctx); err != nil { + return false, err + } + return dcq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (dcq *DeploymentCountQuery) ExistX(ctx context.Context) bool { + exist, err := dcq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the DeploymentCountQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (dcq *DeploymentCountQuery) Clone() *DeploymentCountQuery { + if dcq == nil { + return nil + } + return &DeploymentCountQuery{ + config: dcq.config, + limit: dcq.limit, + offset: dcq.offset, + order: append([]OrderFunc{}, dcq.order...), + predicates: append([]predicate.DeploymentCount{}, dcq.predicates...), + // clone intermediate query. + sql: dcq.sql.Clone(), + path: dcq.path, + } +} + +// 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 { +// Namespace string `json:"namespace"` +// Count int `json:"count,omitempty"` +// } +// +// client.DeploymentCount.Query(). +// GroupBy(deploymentcount.FieldNamespace). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (dcq *DeploymentCountQuery) GroupBy(field string, fields ...string) *DeploymentCountGroupBy { + group := &DeploymentCountGroupBy{config: dcq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := dcq.prepareQuery(ctx); err != nil { + return nil, err + } + return dcq.sqlQuery(ctx), nil + } + return group +} + +// 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 { +// Namespace string `json:"namespace"` +// } +// +// client.DeploymentCount.Query(). +// Select(deploymentcount.FieldNamespace). +// Scan(ctx, &v) +// +func (dcq *DeploymentCountQuery) Select(fields ...string) *DeploymentCountSelect { + dcq.fields = append(dcq.fields, fields...) + return &DeploymentCountSelect{DeploymentCountQuery: dcq} +} + +func (dcq *DeploymentCountQuery) prepareQuery(ctx context.Context) error { + for _, f := range dcq.fields { + if !deploymentcount.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if dcq.path != nil { + prev, err := dcq.path(ctx) + if err != nil { + return err + } + dcq.sql = prev + } + return nil +} + +func (dcq *DeploymentCountQuery) sqlAll(ctx context.Context) ([]*DeploymentCount, error) { + var ( + nodes = []*DeploymentCount{} + _spec = dcq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &DeploymentCount{config: dcq.config} + nodes = append(nodes, node) + return node.scanValues(columns) + } + _spec.Assign = func(columns []string, values []interface{}) error { + if len(nodes) == 0 { + return fmt.Errorf("ent: Assign called without calling ScanValues") + } + node := nodes[len(nodes)-1] + return node.assignValues(columns, values) + } + if len(dcq.modifiers) > 0 { + _spec.Modifiers = dcq.modifiers + } + if err := sqlgraph.QueryNodes(ctx, dcq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + return nodes, nil +} + +func (dcq *DeploymentCountQuery) sqlCount(ctx context.Context) (int, error) { + _spec := dcq.querySpec() + if len(dcq.modifiers) > 0 { + _spec.Modifiers = dcq.modifiers + } + return sqlgraph.CountNodes(ctx, dcq.driver, _spec) +} + +func (dcq *DeploymentCountQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := dcq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (dcq *DeploymentCountQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: deploymentcount.Table, + Columns: deploymentcount.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentcount.FieldID, + }, + }, + From: dcq.sql, + Unique: true, + } + if unique := dcq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := dcq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, deploymentcount.FieldID) + for i := range fields { + if fields[i] != deploymentcount.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := dcq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := dcq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := dcq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := dcq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (dcq *DeploymentCountQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(dcq.driver.Dialect()) + t1 := builder.Table(deploymentcount.Table) + columns := dcq.fields + if len(columns) == 0 { + columns = deploymentcount.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if dcq.sql != nil { + selector = dcq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, m := range dcq.modifiers { + m(selector) + } + for _, p := range dcq.predicates { + p(selector) + } + for _, p := range dcq.order { + p(selector) + } + if offset := dcq.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 := dcq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (dcq *DeploymentCountQuery) ForUpdate(opts ...sql.LockOption) *DeploymentCountQuery { + if dcq.driver.Dialect() == dialect.Postgres { + dcq.Unique(false) + } + dcq.modifiers = append(dcq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return dcq +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (dcq *DeploymentCountQuery) ForShare(opts ...sql.LockOption) *DeploymentCountQuery { + if dcq.driver.Dialect() == dialect.Postgres { + dcq.Unique(false) + } + dcq.modifiers = append(dcq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return dcq +} + +// DeploymentCountGroupBy is the group-by builder for DeploymentCount entities. +type DeploymentCountGroupBy struct { + config + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (dcgb *DeploymentCountGroupBy) Aggregate(fns ...AggregateFunc) *DeploymentCountGroupBy { + dcgb.fns = append(dcgb.fns, fns...) + return dcgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (dcgb *DeploymentCountGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := dcgb.path(ctx) + if err != nil { + return err + } + dcgb.sql = query + return dcgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (dcgb *DeploymentCountGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := dcgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (dcgb *DeploymentCountGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(dcgb.fields) > 1 { + return nil, errors.New("ent: DeploymentCountGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := dcgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (dcgb *DeploymentCountGroupBy) StringsX(ctx context.Context) []string { + v, err := dcgb.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (dcgb *DeploymentCountGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = dcgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{deploymentcount.Label} + default: + err = fmt.Errorf("ent: DeploymentCountGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (dcgb *DeploymentCountGroupBy) StringX(ctx context.Context) string { + v, err := dcgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (dcgb *DeploymentCountGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(dcgb.fields) > 1 { + return nil, errors.New("ent: DeploymentCountGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := dcgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (dcgb *DeploymentCountGroupBy) IntsX(ctx context.Context) []int { + v, err := dcgb.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (dcgb *DeploymentCountGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = dcgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{deploymentcount.Label} + default: + err = fmt.Errorf("ent: DeploymentCountGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (dcgb *DeploymentCountGroupBy) IntX(ctx context.Context) int { + v, err := dcgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (dcgb *DeploymentCountGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(dcgb.fields) > 1 { + return nil, errors.New("ent: DeploymentCountGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := dcgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (dcgb *DeploymentCountGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := dcgb.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (dcgb *DeploymentCountGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = dcgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{deploymentcount.Label} + default: + err = fmt.Errorf("ent: DeploymentCountGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (dcgb *DeploymentCountGroupBy) Float64X(ctx context.Context) float64 { + v, err := dcgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (dcgb *DeploymentCountGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(dcgb.fields) > 1 { + return nil, errors.New("ent: DeploymentCountGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := dcgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (dcgb *DeploymentCountGroupBy) BoolsX(ctx context.Context) []bool { + v, err := dcgb.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a group-by query. +// It is only allowed when executing a group-by query with one field. +func (dcgb *DeploymentCountGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = dcgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{deploymentcount.Label} + default: + err = fmt.Errorf("ent: DeploymentCountGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (dcgb *DeploymentCountGroupBy) BoolX(ctx context.Context) bool { + v, err := dcgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (dcgb *DeploymentCountGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range dcgb.fields { + if !deploymentcount.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := dcgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := dcgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (dcgb *DeploymentCountGroupBy) sqlQuery() *sql.Selector { + selector := dcgb.sql.Select() + aggregation := make([]string, 0, len(dcgb.fns)) + for _, fn := range dcgb.fns { + aggregation = append(aggregation, fn(selector)) + } + // If no columns were selected in a custom aggregation function, the default + // selection is the fields used for "group-by", and the aggregation functions. + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(dcgb.fields)+len(dcgb.fns)) + for _, f := range dcgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(dcgb.fields...)...) +} + +// DeploymentCountSelect is the builder for selecting fields of DeploymentCount entities. +type DeploymentCountSelect struct { + *DeploymentCountQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (dcs *DeploymentCountSelect) Scan(ctx context.Context, v interface{}) error { + if err := dcs.prepareQuery(ctx); err != nil { + return err + } + dcs.sql = dcs.DeploymentCountQuery.sqlQuery(ctx) + return dcs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (dcs *DeploymentCountSelect) ScanX(ctx context.Context, v interface{}) { + if err := dcs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (dcs *DeploymentCountSelect) Strings(ctx context.Context) ([]string, error) { + if len(dcs.fields) > 1 { + return nil, errors.New("ent: DeploymentCountSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := dcs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (dcs *DeploymentCountSelect) StringsX(ctx context.Context) []string { + v, err := dcs.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 (dcs *DeploymentCountSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = dcs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{deploymentcount.Label} + default: + err = fmt.Errorf("ent: DeploymentCountSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (dcs *DeploymentCountSelect) StringX(ctx context.Context) string { + v, err := dcs.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 (dcs *DeploymentCountSelect) Ints(ctx context.Context) ([]int, error) { + if len(dcs.fields) > 1 { + return nil, errors.New("ent: DeploymentCountSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := dcs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (dcs *DeploymentCountSelect) IntsX(ctx context.Context) []int { + v, err := dcs.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 (dcs *DeploymentCountSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = dcs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{deploymentcount.Label} + default: + err = fmt.Errorf("ent: DeploymentCountSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (dcs *DeploymentCountSelect) IntX(ctx context.Context) int { + v, err := dcs.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 (dcs *DeploymentCountSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(dcs.fields) > 1 { + return nil, errors.New("ent: DeploymentCountSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := dcs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (dcs *DeploymentCountSelect) Float64sX(ctx context.Context) []float64 { + v, err := dcs.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 (dcs *DeploymentCountSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = dcs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{deploymentcount.Label} + default: + err = fmt.Errorf("ent: DeploymentCountSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (dcs *DeploymentCountSelect) Float64X(ctx context.Context) float64 { + v, err := dcs.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 (dcs *DeploymentCountSelect) Bools(ctx context.Context) ([]bool, error) { + if len(dcs.fields) > 1 { + return nil, errors.New("ent: DeploymentCountSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := dcs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (dcs *DeploymentCountSelect) BoolsX(ctx context.Context) []bool { + v, err := dcs.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 (dcs *DeploymentCountSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = dcs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{deploymentcount.Label} + default: + err = fmt.Errorf("ent: DeploymentCountSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (dcs *DeploymentCountSelect) BoolX(ctx context.Context) bool { + v, err := dcs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (dcs *DeploymentCountSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := dcs.sql.Query() + if err := dcs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/deploymentcount_update.go b/ent/deploymentcount_update.go new file mode 100644 index 00000000..2cfe21bd --- /dev/null +++ b/ent/deploymentcount_update.go @@ -0,0 +1,473 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/gitploy-io/gitploy/ent/deploymentcount" + "github.com/gitploy-io/gitploy/ent/predicate" +) + +// DeploymentCountUpdate is the builder for updating DeploymentCount entities. +type DeploymentCountUpdate struct { + config + hooks []Hook + mutation *DeploymentCountMutation +} + +// Where appends a list predicates to the DeploymentCountUpdate builder. +func (dcu *DeploymentCountUpdate) Where(ps ...predicate.DeploymentCount) *DeploymentCountUpdate { + dcu.mutation.Where(ps...) + return dcu +} + +// SetNamespace sets the "namespace" field. +func (dcu *DeploymentCountUpdate) SetNamespace(s string) *DeploymentCountUpdate { + dcu.mutation.SetNamespace(s) + return dcu +} + +// SetName sets the "name" field. +func (dcu *DeploymentCountUpdate) SetName(s string) *DeploymentCountUpdate { + dcu.mutation.SetName(s) + return dcu +} + +// SetEnv sets the "env" field. +func (dcu *DeploymentCountUpdate) SetEnv(s string) *DeploymentCountUpdate { + dcu.mutation.SetEnv(s) + return dcu +} + +// SetCount sets the "count" field. +func (dcu *DeploymentCountUpdate) SetCount(i int) *DeploymentCountUpdate { + dcu.mutation.ResetCount() + dcu.mutation.SetCount(i) + return dcu +} + +// SetNillableCount sets the "count" field if the given value is not nil. +func (dcu *DeploymentCountUpdate) SetNillableCount(i *int) *DeploymentCountUpdate { + if i != nil { + dcu.SetCount(*i) + } + return dcu +} + +// AddCount adds i to the "count" field. +func (dcu *DeploymentCountUpdate) AddCount(i int) *DeploymentCountUpdate { + dcu.mutation.AddCount(i) + return dcu +} + +// SetCreatedAt sets the "created_at" field. +func (dcu *DeploymentCountUpdate) SetCreatedAt(t time.Time) *DeploymentCountUpdate { + dcu.mutation.SetCreatedAt(t) + return dcu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (dcu *DeploymentCountUpdate) SetNillableCreatedAt(t *time.Time) *DeploymentCountUpdate { + if t != nil { + dcu.SetCreatedAt(*t) + } + return dcu +} + +// SetUpdatedAt sets the "updated_at" field. +func (dcu *DeploymentCountUpdate) SetUpdatedAt(t time.Time) *DeploymentCountUpdate { + dcu.mutation.SetUpdatedAt(t) + return dcu +} + +// Mutation returns the DeploymentCountMutation object of the builder. +func (dcu *DeploymentCountUpdate) Mutation() *DeploymentCountMutation { + return dcu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (dcu *DeploymentCountUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + dcu.defaults() + if len(dcu.hooks) == 0 { + affected, err = dcu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*DeploymentCountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + dcu.mutation = mutation + affected, err = dcu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(dcu.hooks) - 1; i >= 0; i-- { + if dcu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = dcu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, dcu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (dcu *DeploymentCountUpdate) SaveX(ctx context.Context) int { + affected, err := dcu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (dcu *DeploymentCountUpdate) Exec(ctx context.Context) error { + _, err := dcu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (dcu *DeploymentCountUpdate) ExecX(ctx context.Context) { + if err := dcu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (dcu *DeploymentCountUpdate) defaults() { + if _, ok := dcu.mutation.UpdatedAt(); !ok { + v := deploymentcount.UpdateDefaultUpdatedAt() + dcu.mutation.SetUpdatedAt(v) + } +} + +func (dcu *DeploymentCountUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: deploymentcount.Table, + Columns: deploymentcount.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentcount.FieldID, + }, + }, + } + if ps := dcu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := dcu.mutation.Namespace(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: deploymentcount.FieldNamespace, + }) + } + if value, ok := dcu.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: deploymentcount.FieldName, + }) + } + if value, ok := dcu.mutation.Env(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: deploymentcount.FieldEnv, + }) + } + if value, ok := dcu.mutation.Count(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: deploymentcount.FieldCount, + }) + } + if value, ok := dcu.mutation.AddedCount(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: deploymentcount.FieldCount, + }) + } + if value, ok := dcu.mutation.CreatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: deploymentcount.FieldCreatedAt, + }) + } + if value, ok := dcu.mutation.UpdatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: deploymentcount.FieldUpdatedAt, + }) + } + if n, err = sqlgraph.UpdateNodes(ctx, dcu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{deploymentcount.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// DeploymentCountUpdateOne is the builder for updating a single DeploymentCount entity. +type DeploymentCountUpdateOne struct { + config + fields []string + hooks []Hook + mutation *DeploymentCountMutation +} + +// SetNamespace sets the "namespace" field. +func (dcuo *DeploymentCountUpdateOne) SetNamespace(s string) *DeploymentCountUpdateOne { + dcuo.mutation.SetNamespace(s) + return dcuo +} + +// SetName sets the "name" field. +func (dcuo *DeploymentCountUpdateOne) SetName(s string) *DeploymentCountUpdateOne { + dcuo.mutation.SetName(s) + return dcuo +} + +// SetEnv sets the "env" field. +func (dcuo *DeploymentCountUpdateOne) SetEnv(s string) *DeploymentCountUpdateOne { + dcuo.mutation.SetEnv(s) + return dcuo +} + +// SetCount sets the "count" field. +func (dcuo *DeploymentCountUpdateOne) SetCount(i int) *DeploymentCountUpdateOne { + dcuo.mutation.ResetCount() + dcuo.mutation.SetCount(i) + return dcuo +} + +// SetNillableCount sets the "count" field if the given value is not nil. +func (dcuo *DeploymentCountUpdateOne) SetNillableCount(i *int) *DeploymentCountUpdateOne { + if i != nil { + dcuo.SetCount(*i) + } + return dcuo +} + +// AddCount adds i to the "count" field. +func (dcuo *DeploymentCountUpdateOne) AddCount(i int) *DeploymentCountUpdateOne { + dcuo.mutation.AddCount(i) + return dcuo +} + +// SetCreatedAt sets the "created_at" field. +func (dcuo *DeploymentCountUpdateOne) SetCreatedAt(t time.Time) *DeploymentCountUpdateOne { + dcuo.mutation.SetCreatedAt(t) + return dcuo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (dcuo *DeploymentCountUpdateOne) SetNillableCreatedAt(t *time.Time) *DeploymentCountUpdateOne { + if t != nil { + dcuo.SetCreatedAt(*t) + } + return dcuo +} + +// SetUpdatedAt sets the "updated_at" field. +func (dcuo *DeploymentCountUpdateOne) SetUpdatedAt(t time.Time) *DeploymentCountUpdateOne { + dcuo.mutation.SetUpdatedAt(t) + return dcuo +} + +// Mutation returns the DeploymentCountMutation object of the builder. +func (dcuo *DeploymentCountUpdateOne) Mutation() *DeploymentCountMutation { + return dcuo.mutation +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (dcuo *DeploymentCountUpdateOne) Select(field string, fields ...string) *DeploymentCountUpdateOne { + dcuo.fields = append([]string{field}, fields...) + return dcuo +} + +// Save executes the query and returns the updated DeploymentCount entity. +func (dcuo *DeploymentCountUpdateOne) Save(ctx context.Context) (*DeploymentCount, error) { + var ( + err error + node *DeploymentCount + ) + dcuo.defaults() + if len(dcuo.hooks) == 0 { + node, err = dcuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*DeploymentCountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + dcuo.mutation = mutation + node, err = dcuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(dcuo.hooks) - 1; i >= 0; i-- { + if dcuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = dcuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, dcuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (dcuo *DeploymentCountUpdateOne) SaveX(ctx context.Context) *DeploymentCount { + node, err := dcuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (dcuo *DeploymentCountUpdateOne) Exec(ctx context.Context) error { + _, err := dcuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (dcuo *DeploymentCountUpdateOne) ExecX(ctx context.Context) { + if err := dcuo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (dcuo *DeploymentCountUpdateOne) defaults() { + if _, ok := dcuo.mutation.UpdatedAt(); !ok { + v := deploymentcount.UpdateDefaultUpdatedAt() + dcuo.mutation.SetUpdatedAt(v) + } +} + +func (dcuo *DeploymentCountUpdateOne) sqlSave(ctx context.Context) (_node *DeploymentCount, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: deploymentcount.Table, + Columns: deploymentcount.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentcount.FieldID, + }, + }, + } + id, ok := dcuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing DeploymentCount.ID for update")} + } + _spec.Node.ID.Value = id + if fields := dcuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, deploymentcount.FieldID) + for _, f := range fields { + if !deploymentcount.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != deploymentcount.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := dcuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := dcuo.mutation.Namespace(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: deploymentcount.FieldNamespace, + }) + } + if value, ok := dcuo.mutation.Name(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: deploymentcount.FieldName, + }) + } + if value, ok := dcuo.mutation.Env(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: deploymentcount.FieldEnv, + }) + } + if value, ok := dcuo.mutation.Count(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: deploymentcount.FieldCount, + }) + } + if value, ok := dcuo.mutation.AddedCount(); ok { + _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Value: value, + Column: deploymentcount.FieldCount, + }) + } + if value, ok := dcuo.mutation.CreatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: deploymentcount.FieldCreatedAt, + }) + } + if value, ok := dcuo.mutation.UpdatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: deploymentcount.FieldUpdatedAt, + }) + } + _node = &DeploymentCount{config: dcuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, dcuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{deploymentcount.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/ent/ent.go b/ent/ent.go index ab32e7e7..44e50d1a 100644 --- a/ent/ent.go +++ b/ent/ent.go @@ -12,6 +12,7 @@ import ( "github.com/gitploy-io/gitploy/ent/callback" "github.com/gitploy-io/gitploy/ent/chatuser" "github.com/gitploy-io/gitploy/ent/deployment" + "github.com/gitploy-io/gitploy/ent/deploymentcount" "github.com/gitploy-io/gitploy/ent/deploymentstatus" "github.com/gitploy-io/gitploy/ent/event" "github.com/gitploy-io/gitploy/ent/lock" @@ -43,6 +44,7 @@ func columnChecker(table string) func(string) error { callback.Table: callback.ValidColumn, chatuser.Table: chatuser.ValidColumn, deployment.Table: deployment.ValidColumn, + deploymentcount.Table: deploymentcount.ValidColumn, deploymentstatus.Table: deploymentstatus.ValidColumn, event.Table: event.ValidColumn, lock.Table: lock.ValidColumn, diff --git a/ent/hook/hook.go b/ent/hook/hook.go index edd85988..d07a7171 100644 --- a/ent/hook/hook.go +++ b/ent/hook/hook.go @@ -61,6 +61,19 @@ func (f DeploymentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, return f(ctx, mv) } +// The DeploymentCountFunc type is an adapter to allow the use of ordinary +// function as DeploymentCount mutator. +type DeploymentCountFunc func(context.Context, *ent.DeploymentCountMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f DeploymentCountFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.DeploymentCountMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.DeploymentCountMutation", m) + } + return f(ctx, mv) +} + // The DeploymentStatusFunc type is an adapter to allow the use of ordinary // function as DeploymentStatus mutator. type DeploymentStatusFunc func(context.Context, *ent.DeploymentStatusMutation) (ent.Value, error) diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go index fa4f35c2..f8f15e4e 100644 --- a/ent/migrate/schema.go +++ b/ent/migrate/schema.go @@ -156,6 +156,29 @@ var ( }, }, } + // DeploymentCountsColumns holds the columns for the "deployment_counts" table. + DeploymentCountsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "namespace", Type: field.TypeString}, + {Name: "name", Type: field.TypeString}, + {Name: "env", Type: field.TypeString}, + {Name: "count", Type: field.TypeInt, Default: 1}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + } + // DeploymentCountsTable holds the schema information for the "deployment_counts" table. + DeploymentCountsTable = &schema.Table{ + Name: "deployment_counts", + Columns: DeploymentCountsColumns, + PrimaryKey: []*schema.Column{DeploymentCountsColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "deploymentcount_namespace_name_env", + Unique: true, + Columns: []*schema.Column{DeploymentCountsColumns[1], DeploymentCountsColumns[2], DeploymentCountsColumns[3]}, + }, + }, + } // DeploymentStatusColumns holds the columns for the "deployment_status" table. DeploymentStatusColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -369,6 +392,7 @@ var ( CallbacksTable, ChatUsersTable, DeploymentsTable, + DeploymentCountsTable, DeploymentStatusTable, EventsTable, LocksTable, diff --git a/ent/mutation.go b/ent/mutation.go index f5d06da3..42a361c3 100644 --- a/ent/mutation.go +++ b/ent/mutation.go @@ -12,6 +12,7 @@ import ( "github.com/gitploy-io/gitploy/ent/callback" "github.com/gitploy-io/gitploy/ent/chatuser" "github.com/gitploy-io/gitploy/ent/deployment" + "github.com/gitploy-io/gitploy/ent/deploymentcount" "github.com/gitploy-io/gitploy/ent/deploymentstatus" "github.com/gitploy-io/gitploy/ent/event" "github.com/gitploy-io/gitploy/ent/lock" @@ -37,6 +38,7 @@ const ( TypeCallback = "Callback" TypeChatUser = "ChatUser" TypeDeployment = "Deployment" + TypeDeploymentCount = "DeploymentCount" TypeDeploymentStatus = "DeploymentStatus" TypeEvent = "Event" TypeLock = "Lock" @@ -3546,6 +3548,604 @@ func (m *DeploymentMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Deployment edge %s", name) } +// DeploymentCountMutation represents an operation that mutates the DeploymentCount nodes in the graph. +type DeploymentCountMutation struct { + config + op Op + typ string + id *int + namespace *string + name *string + env *string + count *int + addcount *int + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*DeploymentCount, error) + predicates []predicate.DeploymentCount +} + +var _ ent.Mutation = (*DeploymentCountMutation)(nil) + +// deploymentcountOption allows management of the mutation configuration using functional options. +type deploymentcountOption func(*DeploymentCountMutation) + +// newDeploymentCountMutation creates new mutation for the DeploymentCount entity. +func newDeploymentCountMutation(c config, op Op, opts ...deploymentcountOption) *DeploymentCountMutation { + m := &DeploymentCountMutation{ + config: c, + op: op, + typ: TypeDeploymentCount, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withDeploymentCountID sets the ID field of the mutation. +func withDeploymentCountID(id int) deploymentcountOption { + return func(m *DeploymentCountMutation) { + var ( + err error + once sync.Once + value *DeploymentCount + ) + m.oldValue = func(ctx context.Context) (*DeploymentCount, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().DeploymentCount.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withDeploymentCount sets the old DeploymentCount of the mutation. +func withDeploymentCount(node *DeploymentCount) deploymentcountOption { + return func(m *DeploymentCountMutation) { + m.oldValue = func(context.Context) (*DeploymentCount, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m DeploymentCountMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m DeploymentCountMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, fmt.Errorf("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 only available +// if it was provided to the builder or after it was returned from the database. +func (m *DeploymentCountMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetNamespace sets the "namespace" field. +func (m *DeploymentCountMutation) SetNamespace(s string) { + m.namespace = &s +} + +// Namespace returns the value of the "namespace" field in the mutation. +func (m *DeploymentCountMutation) Namespace() (r string, exists bool) { + v := m.namespace + if v == nil { + return + } + return *v, true +} + +// OldNamespace returns the old "namespace" field's value of the DeploymentCount entity. +// If the DeploymentCount 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 *DeploymentCountMutation) OldNamespace(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldNamespace is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldNamespace requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNamespace: %w", err) + } + return oldValue.Namespace, nil +} + +// ResetNamespace resets all changes to the "namespace" field. +func (m *DeploymentCountMutation) ResetNamespace() { + m.namespace = nil +} + +// SetName sets the "name" field. +func (m *DeploymentCountMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *DeploymentCountMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the DeploymentCount entity. +// If the DeploymentCount 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 *DeploymentCountMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("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") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *DeploymentCountMutation) ResetName() { + m.name = nil +} + +// SetEnv sets the "env" field. +func (m *DeploymentCountMutation) SetEnv(s string) { + m.env = &s +} + +// Env returns the value of the "env" field in the mutation. +func (m *DeploymentCountMutation) Env() (r string, exists bool) { + v := m.env + if v == nil { + return + } + return *v, true +} + +// OldEnv returns the old "env" field's value of the DeploymentCount entity. +// If the DeploymentCount 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 *DeploymentCountMutation) OldEnv(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldEnv is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldEnv requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEnv: %w", err) + } + return oldValue.Env, nil +} + +// ResetEnv resets all changes to the "env" field. +func (m *DeploymentCountMutation) ResetEnv() { + m.env = nil +} + +// SetCount sets the "count" field. +func (m *DeploymentCountMutation) SetCount(i int) { + m.count = &i + m.addcount = nil +} + +// Count returns the value of the "count" field in the mutation. +func (m *DeploymentCountMutation) Count() (r int, exists bool) { + v := m.count + if v == nil { + return + } + return *v, true +} + +// OldCount returns the old "count" field's value of the DeploymentCount entity. +// If the DeploymentCount 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 *DeploymentCountMutation) OldCount(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("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") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCount: %w", err) + } + return oldValue.Count, nil +} + +// AddCount adds i to the "count" field. +func (m *DeploymentCountMutation) AddCount(i int) { + if m.addcount != nil { + *m.addcount += i + } else { + m.addcount = &i + } +} + +// AddedCount returns the value that was added to the "count" field in this mutation. +func (m *DeploymentCountMutation) AddedCount() (r int, exists bool) { + v := m.addcount + if v == nil { + return + } + return *v, true +} + +// ResetCount resets all changes to the "count" field. +func (m *DeploymentCountMutation) ResetCount() { + m.count = nil + m.addcount = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *DeploymentCountMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *DeploymentCountMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the DeploymentCount entity. +// If the DeploymentCount 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 *DeploymentCountMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("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") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *DeploymentCountMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *DeploymentCountMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *DeploymentCountMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return + } + return *v, true +} + +// OldUpdatedAt returns the old "updated_at" field's value of the DeploymentCount entity. +// If the DeploymentCount 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 *DeploymentCountMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("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") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + } + return oldValue.UpdatedAt, nil +} + +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *DeploymentCountMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// Where appends a list predicates to the DeploymentCountMutation builder. +func (m *DeploymentCountMutation) Where(ps ...predicate.DeploymentCount) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *DeploymentCountMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (DeploymentCount). +func (m *DeploymentCountMutation) 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 incremented/decremented, call +// AddedFields(). +func (m *DeploymentCountMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.namespace != nil { + fields = append(fields, deploymentcount.FieldNamespace) + } + if m.name != nil { + fields = append(fields, deploymentcount.FieldName) + } + if m.env != nil { + fields = append(fields, deploymentcount.FieldEnv) + } + if m.count != nil { + fields = append(fields, deploymentcount.FieldCount) + } + if m.created_at != nil { + fields = append(fields, deploymentcount.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, deploymentcount.FieldUpdatedAt) + } + return fields +} + +// 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 *DeploymentCountMutation) Field(name string) (ent.Value, bool) { + switch name { + case deploymentcount.FieldNamespace: + return m.Namespace() + case deploymentcount.FieldName: + return m.Name() + case deploymentcount.FieldEnv: + return m.Env() + case deploymentcount.FieldCount: + return m.Count() + case deploymentcount.FieldCreatedAt: + return m.CreatedAt() + case deploymentcount.FieldUpdatedAt: + return m.UpdatedAt() + } + 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 failed. +func (m *DeploymentCountMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case deploymentcount.FieldNamespace: + return m.OldNamespace(ctx) + case deploymentcount.FieldName: + return m.OldName(ctx) + case deploymentcount.FieldEnv: + return m.OldEnv(ctx) + case deploymentcount.FieldCount: + return m.OldCount(ctx) + case deploymentcount.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case deploymentcount.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown DeploymentCount field %s", name) +} + +// 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 *DeploymentCountMutation) SetField(name string, value ent.Value) error { + switch name { + case deploymentcount.FieldNamespace: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetNamespace(v) + return nil + case deploymentcount.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case deploymentcount.FieldEnv: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEnv(v) + return nil + case deploymentcount.FieldCount: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCount(v) + return nil + case deploymentcount.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case deploymentcount.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown DeploymentCount field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *DeploymentCountMutation) AddedFields() []string { + var fields []string + if m.addcount != nil { + fields = append(fields, deploymentcount.FieldCount) + } + return fields +} + +// 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 *DeploymentCountMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case deploymentcount.FieldCount: + return m.AddedCount() + } + return nil, false +} + +// 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 *DeploymentCountMutation) AddField(name string, value ent.Value) error { + switch name { + case deploymentcount.FieldCount: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCount(v) + return nil + } + return fmt.Errorf("unknown DeploymentCount numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *DeploymentCountMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *DeploymentCountMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// 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 *DeploymentCountMutation) ClearField(name string) error { + return fmt.Errorf("unknown DeploymentCount nullable field %s", name) +} + +// 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 *DeploymentCountMutation) ResetField(name string) error { + switch name { + case deploymentcount.FieldNamespace: + m.ResetNamespace() + return nil + case deploymentcount.FieldName: + m.ResetName() + return nil + case deploymentcount.FieldEnv: + m.ResetEnv() + return nil + case deploymentcount.FieldCount: + m.ResetCount() + return nil + case deploymentcount.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case deploymentcount.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown DeploymentCount field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *DeploymentCountMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *DeploymentCountMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *DeploymentCountMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *DeploymentCountMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *DeploymentCountMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *DeploymentCountMutation) EdgeCleared(name string) bool { + return false +} + +// 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 *DeploymentCountMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown DeploymentCount unique edge %s", name) +} + +// 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 *DeploymentCountMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown DeploymentCount edge %s", name) +} + // DeploymentStatusMutation represents an operation that mutates the DeploymentStatus nodes in the graph. type DeploymentStatusMutation struct { config diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go index fb53aeb4..6d4f5001 100644 --- a/ent/predicate/predicate.go +++ b/ent/predicate/predicate.go @@ -18,6 +18,9 @@ type ChatUser func(*sql.Selector) // Deployment is the predicate function for deployment builders. type Deployment func(*sql.Selector) +// DeploymentCount is the predicate function for deploymentcount builders. +type DeploymentCount func(*sql.Selector) + // DeploymentStatus is the predicate function for deploymentstatus builders. type DeploymentStatus func(*sql.Selector) diff --git a/ent/runtime.go b/ent/runtime.go index 134170d5..a5d379a7 100644 --- a/ent/runtime.go +++ b/ent/runtime.go @@ -9,6 +9,7 @@ import ( "github.com/gitploy-io/gitploy/ent/callback" "github.com/gitploy-io/gitploy/ent/chatuser" "github.com/gitploy-io/gitploy/ent/deployment" + "github.com/gitploy-io/gitploy/ent/deploymentcount" "github.com/gitploy-io/gitploy/ent/deploymentstatus" "github.com/gitploy-io/gitploy/ent/event" "github.com/gitploy-io/gitploy/ent/lock" @@ -90,6 +91,22 @@ func init() { deployment.DefaultUpdatedAt = deploymentDescUpdatedAt.Default.(func() time.Time) // deployment.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. deployment.UpdateDefaultUpdatedAt = deploymentDescUpdatedAt.UpdateDefault.(func() time.Time) + deploymentcountFields := schema.DeploymentCount{}.Fields() + _ = deploymentcountFields + // deploymentcountDescCount is the schema descriptor for count field. + deploymentcountDescCount := deploymentcountFields[3].Descriptor() + // deploymentcount.DefaultCount holds the default value on creation for the count field. + deploymentcount.DefaultCount = deploymentcountDescCount.Default.(int) + // deploymentcountDescCreatedAt is the schema descriptor for created_at field. + deploymentcountDescCreatedAt := deploymentcountFields[4].Descriptor() + // deploymentcount.DefaultCreatedAt holds the default value on creation for the created_at field. + deploymentcount.DefaultCreatedAt = deploymentcountDescCreatedAt.Default.(func() time.Time) + // deploymentcountDescUpdatedAt is the schema descriptor for updated_at field. + deploymentcountDescUpdatedAt := deploymentcountFields[5].Descriptor() + // deploymentcount.DefaultUpdatedAt holds the default value on creation for the updated_at field. + deploymentcount.DefaultUpdatedAt = deploymentcountDescUpdatedAt.Default.(func() time.Time) + // deploymentcount.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + deploymentcount.UpdateDefaultUpdatedAt = deploymentcountDescUpdatedAt.UpdateDefault.(func() time.Time) deploymentstatusFields := schema.DeploymentStatus{}.Fields() _ = deploymentstatusFields // deploymentstatusDescCreatedAt is the schema descriptor for created_at field. diff --git a/ent/schema/deploymentcount.go b/ent/schema/deploymentcount.go new file mode 100644 index 00000000..515a0446 --- /dev/null +++ b/ent/schema/deploymentcount.go @@ -0,0 +1,45 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// DeploymentCount holds the schema definition for the DeploymentCount entity. +// It is the kind of statistics table to count deployments. +type DeploymentCount struct { + ent.Schema +} + +// Fields of the DeploymentCount. +func (DeploymentCount) Fields() []ent.Field { + return []ent.Field{ + field.String("namespace"), + field.String("name"), + field.String("env"), + field.Int("count"). + Default(1), + field.Time("created_at"). + Default(time.Now), + field.Time("updated_at"). + Default(time.Now). + UpdateDefault(time.Now), + } +} + +// Edges of the DeploymentCount. +func (DeploymentCount) Edges() []ent.Edge { + return nil +} + +func (DeploymentCount) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("namespace", "name", "env"). + Unique(), + // The collector searches updated records only. + index.Fields("updated_at"), + } +} diff --git a/ent/tx.go b/ent/tx.go index 358158af..b767dcfd 100644 --- a/ent/tx.go +++ b/ent/tx.go @@ -20,6 +20,8 @@ type Tx struct { ChatUser *ChatUserClient // Deployment is the client for interacting with the Deployment builders. Deployment *DeploymentClient + // DeploymentCount is the client for interacting with the DeploymentCount builders. + DeploymentCount *DeploymentCountClient // DeploymentStatus is the client for interacting with the DeploymentStatus builders. DeploymentStatus *DeploymentStatusClient // Event is the client for interacting with the Event builders. @@ -173,6 +175,7 @@ func (tx *Tx) init() { tx.Callback = NewCallbackClient(tx.config) tx.ChatUser = NewChatUserClient(tx.config) tx.Deployment = NewDeploymentClient(tx.config) + tx.DeploymentCount = NewDeploymentCountClient(tx.config) tx.DeploymentStatus = NewDeploymentStatusClient(tx.config) tx.Event = NewEventClient(tx.config) tx.Lock = NewLockClient(tx.config) diff --git a/go.mod b/go.mod index 09b26f81..7644dc6c 100644 --- a/go.mod +++ b/go.mod @@ -19,12 +19,12 @@ require ( github.com/google/go-github/v32 v32.1.0 github.com/jackc/pgx/v4 v4.13.0 github.com/joho/godotenv v1.3.0 - github.com/json-iterator/go v1.1.11 // indirect github.com/kelseyhightower/envconfig v1.4.0 github.com/leodido/go-urn v1.2.1 // indirect github.com/mattn/go-sqlite3 v1.14.8 github.com/nleeper/goment v1.4.2 github.com/pkg/errors v0.9.1 + github.com/prometheus/client_golang v1.11.0 github.com/shurcooL/githubv4 v0.0.0-20201206200315-234843c633fa github.com/shurcooL/graphql v0.0.0-20200928012149-18c5c3165e3a // indirect github.com/slack-go/slack v0.9.1 diff --git a/go.sum b/go.sum index c1dd3122..aca58a90 100644 --- a/go.sum +++ b/go.sum @@ -45,7 +45,10 @@ github.com/Masterminds/semver/v3 v3.1.1 h1:hLg3sBzpNErnxhQtUy/mmLR2I9foDujNK030I github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= @@ -53,10 +56,15 @@ github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef h1:2JGTg6JapxP github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef/go.mod h1:JS7hed4L1fj0hXcyEejnW57/7LCetXggd+vwrRnYeII= 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= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= @@ -100,6 +108,7 @@ github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9 github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= 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= @@ -167,6 +176,7 @@ github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-github/v32 v32.1.0 h1:GWkQOdXqviCPx7Q7Fj+KyPoGm4SwHRh8rheoPhd27II= @@ -268,6 +278,7 @@ github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -278,6 +289,7 @@ github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1 github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8= github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= @@ -285,6 +297,7 @@ github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQL github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -314,6 +327,7 @@ github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Ky github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-sqlite3 v1.14.8 h1:gDp86IdQsN/xWjIEmr9MF6o9mpksUgh0fu+9ByFxzIU= github.com/mattn/go-sqlite3 v1.14.8/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= @@ -332,6 +346,7 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/nleeper/goment v1.4.2 h1:r4c8KkCrsBJUnVi/IJ5HEqev5QY8aCWOXQtu+eYXtnI= github.com/nleeper/goment v1.4.2/go.mod h1:zDl5bAyDhqxwQKAvkSXMRLOdCowrdZz53ofRJc4VhTo= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= @@ -347,13 +362,27 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_golang v1.11.0 h1:HNkLOAEQMIDv/K+04rukrLx6ch7msSRwf3/SASFAGtQ= +github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/common v0.26.0 h1:iMAkS2TDoNWnKM+Kopnx/8tnEStIfpYA0ur0xQzzhMQ= +github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= +github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= 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= @@ -375,6 +404,7 @@ github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeV github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/slack-go/slack v0.9.1 h1:pekQBs0RmrdAgoqzcMCzUCWSyIkhzUU3F83ExAdZrKo= github.com/slack-go/slack v0.9.1/go.mod h1:wWL//kk0ho+FcQXcBTmEafUI5dz4qz5f4mMk8oIkioQ= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= @@ -495,6 +525,7 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -533,6 +564,7 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -556,6 +588,7 @@ golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -569,13 +602,17 @@ golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= @@ -730,8 +767,9 @@ google.golang.org/protobuf v1.26.0 h1:bxAC2xTBsZGibn2RTntX0oH50xLsqy1OxA9tTL3p/l google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/go-playground/validator.v9 v9.29.1/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ= @@ -742,7 +780,9 @@ gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bl 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.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= diff --git a/internal/interactor/interface.go b/internal/interactor/interface.go index f61bf8c0..be69794d 100644 --- a/internal/interactor/interface.go +++ b/internal/interactor/interface.go @@ -56,6 +56,9 @@ type ( CreateDeploymentStatus(ctx context.Context, s *ent.DeploymentStatus) (*ent.DeploymentStatus, error) + ListAllDeploymentCounts(ctx context.Context) ([]*ent.DeploymentCount, error) + ListDeploymentCountsGreaterThanTime(ctx context.Context, updated time.Time) ([]*ent.DeploymentCount, error) + CreateCallback(ctx context.Context, cb *ent.Callback) (*ent.Callback, error) FindCallbackByHash(ctx context.Context, hash string) (*ent.Callback, error) diff --git a/internal/interactor/mock/pkg.go b/internal/interactor/mock/pkg.go index c8ab40b0..4c5927ac 100644 --- a/internal/interactor/mock/pkg.go +++ b/internal/interactor/mock/pkg.go @@ -589,6 +589,21 @@ func (mr *MockStoreMockRecorder) HasLockOfRepoForEnv(ctx, r, env interface{}) *g return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasLockOfRepoForEnv", reflect.TypeOf((*MockStore)(nil).HasLockOfRepoForEnv), ctx, r, env) } +// ListAllDeploymentCounts mocks base method. +func (m *MockStore) ListAllDeploymentCounts(ctx context.Context) ([]*ent.DeploymentCount, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListAllDeploymentCounts", ctx) + ret0, _ := ret[0].([]*ent.DeploymentCount) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListAllDeploymentCounts indicates an expected call of ListAllDeploymentCounts. +func (mr *MockStoreMockRecorder) ListAllDeploymentCounts(ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListAllDeploymentCounts", reflect.TypeOf((*MockStore)(nil).ListAllDeploymentCounts), ctx) +} + // ListApprovals mocks base method. func (m *MockStore) ListApprovals(ctx context.Context, d *ent.Deployment) ([]*ent.Approval, error) { m.ctrl.T.Helper() @@ -604,6 +619,21 @@ func (mr *MockStoreMockRecorder) ListApprovals(ctx, d interface{}) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListApprovals", reflect.TypeOf((*MockStore)(nil).ListApprovals), ctx, d) } +// ListDeploymentCountsGreaterThanTime mocks base method. +func (m *MockStore) ListDeploymentCountsGreaterThanTime(ctx context.Context, updated time.Time) ([]*ent.DeploymentCount, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListDeploymentCountsGreaterThanTime", ctx, updated) + ret0, _ := ret[0].([]*ent.DeploymentCount) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListDeploymentCountsGreaterThanTime indicates an expected call of ListDeploymentCountsGreaterThanTime. +func (mr *MockStoreMockRecorder) ListDeploymentCountsGreaterThanTime(ctx, updated interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDeploymentCountsGreaterThanTime", reflect.TypeOf((*MockStore)(nil).ListDeploymentCountsGreaterThanTime), ctx, updated) +} + // ListDeploymentsOfRepo mocks base method. func (m *MockStore) ListDeploymentsOfRepo(ctx context.Context, r *ent.Repo, env, status string, page, perPage int) ([]*ent.Deployment, error) { m.ctrl.T.Helper() diff --git a/internal/pkg/store/deployment.go b/internal/pkg/store/deployment.go index 7dc243db..1bfea4de 100644 --- a/internal/pkg/store/deployment.go +++ b/internal/pkg/store/deployment.go @@ -7,8 +7,10 @@ import ( "entgo.io/ent/dialect/sql" "github.com/gitploy-io/gitploy/ent" "github.com/gitploy-io/gitploy/ent/deployment" + "github.com/gitploy-io/gitploy/ent/deploymentcount" "github.com/gitploy-io/gitploy/ent/perm" "github.com/gitploy-io/gitploy/ent/predicate" + "go.uber.org/zap" ) func (s *Store) SearchDeployments(ctx context.Context, u *ent.User, ss []deployment.Status, owned bool, from time.Time, to time.Time, page, perPage int) ([]*ent.Deployment, error) { @@ -189,8 +191,8 @@ func (s *Store) FindPrevSuccessDeployment(ctx context.Context, d *ent.Deployment First(ctx) } -// CreateDeployment always set the next number of deployment -// when it creates. +// CreateDeployment create a new deployment, and +// it updates the 'latest_deployed_at' field of the repository. func (s *Store) CreateDeployment(ctx context.Context, d *ent.Deployment) (*ent.Deployment, error) { d, err := s.c.Deployment.Create(). SetNumber(d.Number). @@ -215,11 +217,13 @@ func (s *Store) CreateDeployment(ctx context.Context, d *ent.Deployment) (*ent.D UpdateOneID(d.RepoID). SetLatestDeployedAt(d.CreatedAt). Save(ctx) + return d, nil } func (s *Store) UpdateDeployment(ctx context.Context, d *ent.Deployment) (*ent.Deployment, error) { - return s.c.Deployment.UpdateOne(d). + d, err := s.c.Deployment. + UpdateOne(d). SetType(d.Type). SetRef(d.Ref). SetEnv(d.Env). @@ -231,4 +235,51 @@ func (s *Store) UpdateDeployment(ctx context.Context, d *ent.Deployment) (*ent.D SetRequiredApprovalCount(d.RequiredApprovalCount). SetStatus(d.Status). Save(ctx) + if err != nil { + return nil, err + } + + if d.Status != deployment.StatusSuccess { + return d, nil + } + + // Update the statistics of deployment by + // increasing the count. + err = s.WithTx(ctx, func(tx *ent.Tx) error { + r, err := tx.Repo.Get(ctx, d.RepoID) + if err != nil { + return err + } + + dc, err := s.c.DeploymentCount. + Query(). + Where( + deploymentcount.NamespaceEQ(r.Namespace), + deploymentcount.NameEQ(r.Name), + deploymentcount.EnvEQ(d.Env), + ). + Only(ctx) + if ent.IsNotFound(err) { + s.c.DeploymentCount. + Create(). + SetNamespace(r.Namespace). + SetName(r.Name). + SetEnv(d.Env). + Save(ctx) + return nil + } else if err != nil { + return err + } + + s.c.DeploymentCount. + UpdateOne(dc). + SetCount(dc.Count + 1). + Save(ctx) + return nil + }) + if err != nil { + zap.L().Error("It has failed to increase the deployment count.", zap.Error(err)) + } + + return d, nil } diff --git a/internal/pkg/store/deployment_test.go b/internal/pkg/store/deployment_test.go index 51826341..65957646 100644 --- a/internal/pkg/store/deployment_test.go +++ b/internal/pkg/store/deployment_test.go @@ -391,3 +391,134 @@ func TestStore_FindPrevSuccessDeployment(t *testing.T) { } }) } + +func TestStore_UpdateDeployment(t *testing.T) { + t.Run("Update the status of deployment.", func(t *testing.T) { + ctx := context.Background() + + client := enttest.Open(t, "sqlite3", "file:ent?mode=memory&cache=shared&_fk=1", + enttest.WithMigrateOptions(migrate.WithForeignKeys(false)), + ) + defer client.Close() + + d := client.Deployment.Create(). + SetType(deployment.TypeBranch). + SetNumber(1). + SetType("branch"). + SetRef("main"). + SetEnv("prod"). + SetStatus(deployment.StatusCreated). + SetUserID(1). + SetRepoID(1). + SaveX(ctx) + + s := NewStore(client) + + d.Status = deployment.StatusRunning + + d, err := s.UpdateDeployment(ctx, d) + if err != nil { + t.Fatalf("UpdateDeployment returns an error: %s", err) + } + + expected := deployment.StatusRunning + if d.Status != expected { + t.Fatalf("UpdateDeployment = %v, wanted %v", d.Status, expected) + } + }) + + t.Run("Add a new statistics when the status of deployment is updated.", func(t *testing.T) { + ctx := context.Background() + + client := enttest.Open(t, "sqlite3", "file:ent?mode=memory&cache=shared&_fk=1", + enttest.WithMigrateOptions(migrate.WithForeignKeys(false)), + ) + defer client.Close() + + client.Repo. + Create(). + SetID(1). + SetNamespace("octocat"). + SetName("Hello"). + SetDescription(""). + SaveX(ctx) + + d := client.Deployment.Create(). + SetType(deployment.TypeBranch). + SetNumber(1). + SetType("branch"). + SetRef("main"). + SetEnv("prod"). + SetStatus(deployment.StatusCreated). + SetUserID(1). + SetRepoID(1). + SaveX(ctx) + + s := NewStore(client) + + d.Status = deployment.StatusSuccess + + _, err := s.UpdateDeployment(ctx, d) + if err != nil { + t.Fatalf("UpdateDeployment returns an error: %s", err) + } + + expected := 1 + dc := client.DeploymentCount.GetX(ctx, 1) + + if dc.Count != expected { + t.Fatalf("The statistics was not created.") + } + }) + + t.Run("Update the statistics is updated when the status of deployment is updated.", func(t *testing.T) { + ctx := context.Background() + + client := enttest.Open(t, "sqlite3", "file:ent?mode=memory&cache=shared&_fk=1", + enttest.WithMigrateOptions(migrate.WithForeignKeys(false)), + ) + defer client.Close() + + client.Repo. + Create(). + SetID(1). + SetNamespace("octocat"). + SetName("Hello"). + SetDescription(""). + SaveX(ctx) + + d := client.Deployment.Create(). + SetType(deployment.TypeBranch). + SetNumber(1). + SetType("branch"). + SetRef("main"). + SetEnv("prod"). + SetStatus(deployment.StatusCreated). + SetUserID(1). + SetRepoID(1). + SaveX(ctx) + + t.Log("Add the deployment count.") + client.DeploymentCount.Create(). + SetNamespace("octocat"). + SetName("Hello"). + SetEnv("prod"). + SaveX(ctx) + + s := NewStore(client) + + d.Status = deployment.StatusSuccess + + _, err := s.UpdateDeployment(ctx, d) + if err != nil { + t.Fatalf("UpdateDeployment returns an error: %s", err) + } + + expected := 2 + dc := client.DeploymentCount.GetX(ctx, 1) + + if dc.Count != expected { + t.Fatalf("The statistics was not created.") + } + }) +} diff --git a/internal/pkg/store/deploymentcount.go b/internal/pkg/store/deploymentcount.go new file mode 100644 index 00000000..ca5d666b --- /dev/null +++ b/internal/pkg/store/deploymentcount.go @@ -0,0 +1,24 @@ +package store + +import ( + "context" + "time" + + "github.com/gitploy-io/gitploy/ent" + "github.com/gitploy-io/gitploy/ent/deploymentcount" +) + +func (s *Store) ListAllDeploymentCounts(ctx context.Context) ([]*ent.DeploymentCount, error) { + return s.c.DeploymentCount. + Query(). + All(ctx) +} + +func (s *Store) ListDeploymentCountsGreaterThanTime(ctx context.Context, updated time.Time) ([]*ent.DeploymentCount, error) { + return s.c.DeploymentCount. + Query(). + Where( + deploymentcount.UpdatedAtGT(updated), + ). + All(ctx) +} diff --git a/internal/pkg/store/deploymentcount_test.go b/internal/pkg/store/deploymentcount_test.go new file mode 100644 index 00000000..cbce4ec9 --- /dev/null +++ b/internal/pkg/store/deploymentcount_test.go @@ -0,0 +1,49 @@ +package store + +import ( + "context" + "testing" + "time" + + "github.com/gitploy-io/gitploy/ent/enttest" + "github.com/gitploy-io/gitploy/ent/migrate" +) + +func TestStore_ListDeploymentCountsGreaterThanTime(t *testing.T) { + ctx := context.Background() + + client := enttest.Open(t, "sqlite3", "file:ent?mode=memory&cache=shared&_fk=1", + enttest.WithMigrateOptions(migrate.WithForeignKeys(false)), + ) + defer client.Close() + + tm := time.Now() + + client.DeploymentCount. + Create(). + SetNamespace("octocat"). + SetName("Hello"). + SetEnv("dev"). + SetUpdatedAt(tm.Add(-time.Hour)). + SaveX(ctx) + + client.DeploymentCount. + Create(). + SetNamespace("octocat"). + SetName("Hello"). + SetEnv("prod"). + SetUpdatedAt(tm.Add(time.Hour)). + SaveX(ctx) + + s := NewStore(client) + + dcs, err := s.ListDeploymentCountsGreaterThanTime(ctx, tm) + if err != nil { + t.Fatalf("ListDeploymentCountsGreaterThanTime returns an error: %s", err) + } + + expected := 1 + if len(dcs) != expected { + t.Fatalf("ListDeploymentCountsGreaterThanTime = %v, wanted %v", len(dcs), expected) + } +} diff --git a/internal/server/metrics/interface.go b/internal/server/metrics/interface.go new file mode 100644 index 00000000..fa055324 --- /dev/null +++ b/internal/server/metrics/interface.go @@ -0,0 +1,17 @@ +package metrics + +import ( + "context" + "time" + + "github.com/gitploy-io/gitploy/ent" + "github.com/gitploy-io/gitploy/vo" +) + +type ( + Interactor interface { + ListAllDeploymentCounts(ctx context.Context) ([]*ent.DeploymentCount, error) + ListDeploymentCountsGreaterThanTime(ctx context.Context, updated time.Time) ([]*ent.DeploymentCount, error) + GetLicense(ctx context.Context) (*vo.License, error) + } +) diff --git a/internal/server/metrics/metrics.go b/internal/server/metrics/metrics.go new file mode 100644 index 00000000..3a5cc0c1 --- /dev/null +++ b/internal/server/metrics/metrics.go @@ -0,0 +1,149 @@ +package metrics + +import ( + "context" + "time" + + "github.com/gin-gonic/gin" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "go.uber.org/zap" + + "github.com/gitploy-io/gitploy/ent" +) + +type ( + Metric struct{} + + MetricConfig struct { + Interactor + } + + collector struct { + i Interactor + + cache map[int]*ent.DeploymentCount + lastTime time.Time + + log *zap.Logger + } +) + +func NewMetric(c *MetricConfig) *Metric { + prometheus.MustRegister( + newCollector(c.Interactor), + ) + + return &Metric{} +} + +func (m *Metric) CollectMetrics(c *gin.Context) { + h := promhttp.Handler() + h.ServeHTTP(c.Writer, c.Request) +} + +func newCollector(i Interactor) *collector { + return &collector{ + i: i, + cache: map[int]*ent.DeploymentCount{}, + log: zap.L().Named("collector"), + } +} + +func (c *collector) Describe(ch chan<- *prometheus.Desc) { + prometheus.DescribeByCollect(c, ch) +} + +func (c *collector) Collect(ch chan<- prometheus.Metric) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + + { + var ( + dcs []*ent.DeploymentCount + err error + ) + + start := time.Now() + defer func() { + c.lastTime = start + }() + + if len(c.cache) == 0 { + c.log.Debug("List all deployment_count.") + if dcs, err = c.i.ListAllDeploymentCounts(ctx); err != nil { + c.log.Error("It has failed to list all deployment_counts.", zap.Error(err)) + return + } + } else { + c.log.Debug("List deployment_count from the last time.", zap.Time("last", c.lastTime)) + if dcs, err = c.i.ListDeploymentCountsGreaterThanTime(ctx, c.lastTime); err != nil { + c.log.Error("It has failed to list deployment_counts.", zap.Error(err)) + return + } + } + + for _, dc := range dcs { + c.cache[dc.ID] = dc + } + + for _, dc := range c.cache { + ch <- prometheus.MustNewConstMetric( + prometheus.NewDesc( + prometheus.BuildFQName( + namespace, + "", + "deployment_count", + ), + "The count of success deployment for each environment, respectively.", + []string{"namespace", "name", "env"}, + nil, + ), + prometheus.CounterValue, + float64(dc.Count), + dc.Namespace, dc.Name, dc.Env, + ) + } + + c.log.Debug("Collect deployment_count metrics successfully.") + } + + { + lic, err := c.i.GetLicense(ctx) + if err != nil { + c.log.Error("It has failed to get the license.", zap.Error(err)) + return + } + + ch <- prometheus.MustNewConstMetric( + prometheus.NewDesc( + prometheus.BuildFQName( + namespace, + "", + "member_count", + ), + "The total count of member.", + nil, + nil, + ), + prometheus.CounterValue, + float64(lic.MemberCount), + ) + + ch <- prometheus.MustNewConstMetric( + prometheus.NewDesc( + prometheus.BuildFQName( + namespace, + "", + "member_limit", + ), + "The limit of count of member.", + []string{"kind"}, + nil, + ), + prometheus.CounterValue, + float64(lic.MemberLimit), + string(lic.Kind), + ) + } +} diff --git a/internal/server/metrics/middleware.go b/internal/server/metrics/middleware.go new file mode 100644 index 00000000..751393d5 --- /dev/null +++ b/internal/server/metrics/middleware.go @@ -0,0 +1,53 @@ +package metrics + +import ( + "strconv" + "time" + + "github.com/gin-gonic/gin" + "github.com/prometheus/client_golang/prometheus" +) + +const ( + namespace = "gitploy" +) + +var ( + RequestCount = prometheus.NewCounterVec(prometheus.CounterOpts{ + Namespace: namespace, + Subsystem: "", + Name: "requests_total", + Help: "How many HTTP requests processed, partitioned by status code and HTTP method.", + }, []string{"code", "method", "path"}) + + RequestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Namespace: namespace, + Subsystem: "", + Name: "request_duration_seconds", + Help: "The HTTP request latencies in seconds.", + }, []string{"code", "method", "path"}) +) + +func init() { + prometheus.MustRegister(RequestCount) + prometheus.MustRegister(RequestDuration) +} + +// ReponseMetrics is the middleware to collect metrics about the response. +func ReponseMetrics() gin.HandlerFunc { + return func(c *gin.Context) { + start := time.Now() + + c.Next() + + status := strconv.Itoa(c.Writer.Status()) + + { + RequestCount.WithLabelValues(status, c.Request.Method, c.Request.URL.Path).Inc() + } + { + elapsed := float64(time.Since(start)) / float64(time.Second) + RequestDuration.WithLabelValues(status, c.Request.Method, c.Request.URL.Path).Observe(elapsed) + } + } +} diff --git a/internal/server/router.go b/internal/server/router.go index 0b1aab37..d50eccb7 100644 --- a/internal/server/router.go +++ b/internal/server/router.go @@ -16,6 +16,7 @@ import ( "github.com/gitploy-io/gitploy/internal/server/api/v1/sync" "github.com/gitploy-io/gitploy/internal/server/api/v1/users" "github.com/gitploy-io/gitploy/internal/server/hooks" + "github.com/gitploy-io/gitploy/internal/server/metrics" mw "github.com/gitploy-io/gitploy/internal/server/middlewares" s "github.com/gitploy-io/gitploy/internal/server/slack" "github.com/gitploy-io/gitploy/internal/server/web" @@ -74,6 +75,7 @@ type ( hooks.Interactor search.Interactor license.Interactor + metrics.Interactor } ) @@ -95,7 +97,7 @@ func NewRouter(c *RouterConfig) *gin.Engine { sm := mw.NewSessMiddleware(c.Interactor) lm := mw.NewLicenseMiddleware(c.Interactor) - r.Use(sm.User()) + r.Use(sm.User(), metrics.ReponseMetrics()) v1 := r.Group("/api/v1") { @@ -169,17 +171,17 @@ func NewRouter(c *RouterConfig) *gin.Engine { streamv1.GET("/events", s.GetEvents) } - searchapi := v1.Group("/search") + searchv1 := v1.Group("/search") { s := search.NewSearch(c.Interactor) - searchapi.GET("/deployments", s.SearchDeployments) - searchapi.GET("/approvals", s.SearchApprovals) + searchv1.GET("/deployments", s.SearchDeployments) + searchv1.GET("/approvals", s.SearchApprovals) } - licenseapi := v1.Group("/license") + licensev1 := v1.Group("/license") { l := license.NewLicenser(c.Interactor) - licenseapi.GET("", l.GetLicense) + licensev1.GET("", l.GetLicense) } hooksapi := r.Group("/hooks") @@ -191,6 +193,14 @@ func NewRouter(c *RouterConfig) *gin.Engine { hooksapi.POST("", h.HandleHook) } + metricsapi := r.Group("/metrics") + { + m := metrics.NewMetric(&metrics.MetricConfig{ + Interactor: c.Interactor, + }) + metricsapi.GET("", mw.OnlyAuthorized(), m.CollectMetrics) + } + r.HEAD("/slack", func(gc *gin.Context) { if isSlackEnabled(c) { gc.Status(http.StatusOK) @@ -237,8 +247,7 @@ func NewRouter(c *RouterConfig) *gin.Engine { root.GET("/signin", w.Signin) - // Static files - // Files in ui/public + // Static files located at the 'ui/public' directory. r.StaticFile("/favicon.ico", "./favicon.ico") r.StaticFile("/manifest.json", "./manifest.json") r.StaticFile("/robots.txt", "./robots.txt") diff --git a/openapi.yml b/openapi.yml index 2eec120a..d054cfd0 100644 --- a/openapi.yml +++ b/openapi.yml @@ -122,11 +122,15 @@ paths: type: boolean parameters: - in: path - name: id + name: namespace required: true schema: - type: integer - description: The repository id + type: string + - in: path + name: name + required: true + schema: + type: string responses: '200': description: Ok @@ -497,11 +501,15 @@ paths: summary: Create a new deployment. parameters: - in: path - name: id + name: namespace required: true schema: - type: integer - description: The repository id + type: string + - in: path + name: name + required: true + schema: + type: string requestBody: content: application/json: @@ -586,11 +594,15 @@ paths: summary: Deploy to SCM if a status of the deployment is waiting. parameters: - in: path - name: id + name: namespace required: true schema: - type: integer - description: The repository id + type: string + - in: path + name: name + required: true + schema: + type: string - in: path name: number required: true @@ -767,11 +779,15 @@ paths: summary: Create a new approval. parameters: - in: path - name: id + name: namespace required: true schema: - type: integer - description: The repository id + type: string + - in: path + name: name + required: true + schema: + type: string - in: path name: number required: true @@ -852,11 +868,15 @@ paths: summary: Approve (or Decline) for the approval. parameters: - in: path - name: id + name: namespace required: true schema: - type: integer - description: The repository id + type: string + - in: path + name: name + required: true + schema: + type: string - in: path name: number required: true @@ -939,11 +959,15 @@ paths: summary: Delete the approval. parameters: - in: path - name: id + name: namespace required: true schema: - type: integer - description: The repository id. + type: string + - in: path + name: name + required: true + schema: + type: string - in: path name: number required: true @@ -1006,11 +1030,15 @@ paths: summary: Lock the environment. parameters: - in: path - name: id + name: namespace required: true schema: - type: integer - description: The repository id. + type: string + - in: path + name: name + required: true + schema: + type: string requestBody: content: application/json: