diff --git a/ent/client.go b/ent/client.go index ad4a6c81..297142df 100644 --- a/ent/client.go +++ b/ent/client.go @@ -12,6 +12,7 @@ import ( "github.com/gitploy-io/gitploy/ent/approval" "github.com/gitploy-io/gitploy/ent/callback" "github.com/gitploy-io/gitploy/ent/chatuser" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/deploymentstatistics" "github.com/gitploy-io/gitploy/ent/deploymentstatus" @@ -38,6 +39,8 @@ type Client struct { Callback *CallbackClient // ChatUser is the client for interacting with the ChatUser builders. ChatUser *ChatUserClient + // Comment is the client for interacting with the Comment builders. + Comment *CommentClient // Deployment is the client for interacting with the Deployment builders. Deployment *DeploymentClient // DeploymentStatistics is the client for interacting with the DeploymentStatistics builders. @@ -72,6 +75,7 @@ func (c *Client) init() { c.Approval = NewApprovalClient(c.config) c.Callback = NewCallbackClient(c.config) c.ChatUser = NewChatUserClient(c.config) + c.Comment = NewCommentClient(c.config) c.Deployment = NewDeploymentClient(c.config) c.DeploymentStatistics = NewDeploymentStatisticsClient(c.config) c.DeploymentStatus = NewDeploymentStatusClient(c.config) @@ -117,6 +121,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Approval: NewApprovalClient(cfg), Callback: NewCallbackClient(cfg), ChatUser: NewChatUserClient(cfg), + Comment: NewCommentClient(cfg), Deployment: NewDeploymentClient(cfg), DeploymentStatistics: NewDeploymentStatisticsClient(cfg), DeploymentStatus: NewDeploymentStatusClient(cfg), @@ -147,6 +152,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Approval: NewApprovalClient(cfg), Callback: NewCallbackClient(cfg), ChatUser: NewChatUserClient(cfg), + Comment: NewCommentClient(cfg), Deployment: NewDeploymentClient(cfg), DeploymentStatistics: NewDeploymentStatisticsClient(cfg), DeploymentStatus: NewDeploymentStatusClient(cfg), @@ -188,6 +194,7 @@ func (c *Client) Use(hooks ...Hook) { c.Approval.Use(hooks...) c.Callback.Use(hooks...) c.ChatUser.Use(hooks...) + c.Comment.Use(hooks...) c.Deployment.Use(hooks...) c.DeploymentStatistics.Use(hooks...) c.DeploymentStatus.Use(hooks...) @@ -549,6 +556,128 @@ func (c *ChatUserClient) Hooks() []Hook { return c.hooks.ChatUser } +// CommentClient is a client for the Comment schema. +type CommentClient struct { + config +} + +// NewCommentClient returns a client for the Comment from the given config. +func NewCommentClient(c config) *CommentClient { + return &CommentClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `comment.Hooks(f(g(h())))`. +func (c *CommentClient) Use(hooks ...Hook) { + c.hooks.Comment = append(c.hooks.Comment, hooks...) +} + +// Create returns a create builder for Comment. +func (c *CommentClient) Create() *CommentCreate { + mutation := newCommentMutation(c.config, OpCreate) + return &CommentCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Comment entities. +func (c *CommentClient) CreateBulk(builders ...*CommentCreate) *CommentCreateBulk { + return &CommentCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Comment. +func (c *CommentClient) Update() *CommentUpdate { + mutation := newCommentMutation(c.config, OpUpdate) + return &CommentUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CommentClient) UpdateOne(co *Comment) *CommentUpdateOne { + mutation := newCommentMutation(c.config, OpUpdateOne, withComment(co)) + return &CommentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CommentClient) UpdateOneID(id int) *CommentUpdateOne { + mutation := newCommentMutation(c.config, OpUpdateOne, withCommentID(id)) + return &CommentUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Comment. +func (c *CommentClient) Delete() *CommentDelete { + mutation := newCommentMutation(c.config, OpDelete) + return &CommentDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a delete builder for the given entity. +func (c *CommentClient) DeleteOne(co *Comment) *CommentDeleteOne { + return c.DeleteOneID(co.ID) +} + +// DeleteOneID returns a delete builder for the given id. +func (c *CommentClient) DeleteOneID(id int) *CommentDeleteOne { + builder := c.Delete().Where(comment.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CommentDeleteOne{builder} +} + +// Query returns a query builder for Comment. +func (c *CommentClient) Query() *CommentQuery { + return &CommentQuery{ + config: c.config, + } +} + +// Get returns a Comment entity by its id. +func (c *CommentClient) Get(ctx context.Context, id int) (*Comment, error) { + return c.Query().Where(comment.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CommentClient) GetX(ctx context.Context, id int) *Comment { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a Comment. +func (c *CommentClient) QueryUser(co *Comment) *UserQuery { + query := &UserQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := co.ID + step := sqlgraph.NewStep( + sqlgraph.From(comment.Table, comment.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, comment.UserTable, comment.UserColumn), + ) + fromV = sqlgraph.Neighbors(co.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryDeployment queries the deployment edge of a Comment. +func (c *CommentClient) QueryDeployment(co *Comment) *DeploymentQuery { + query := &DeploymentQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := co.ID + step := sqlgraph.NewStep( + sqlgraph.From(comment.Table, comment.FieldID, id), + sqlgraph.To(deployment.Table, deployment.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, comment.DeploymentTable, comment.DeploymentColumn), + ) + fromV = sqlgraph.Neighbors(co.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CommentClient) Hooks() []Hook { + return c.hooks.Comment +} + // DeploymentClient is a client for the Deployment schema. type DeploymentClient struct { config @@ -682,6 +811,22 @@ func (c *DeploymentClient) QueryApprovals(d *Deployment) *ApprovalQuery { return query } +// QueryComments queries the comments edge of a Deployment. +func (c *DeploymentClient) QueryComments(d *Deployment) *CommentQuery { + query := &CommentQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := d.ID + step := sqlgraph.NewStep( + sqlgraph.From(deployment.Table, deployment.FieldID, id), + sqlgraph.To(comment.Table, comment.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, deployment.CommentsTable, deployment.CommentsColumn), + ) + fromV = sqlgraph.Neighbors(d.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryDeploymentStatuses queries the deployment_statuses edge of a Deployment. func (c *DeploymentClient) QueryDeploymentStatuses(d *Deployment) *DeploymentStatusQuery { query := &DeploymentStatusQuery{config: c.config} @@ -1738,6 +1883,22 @@ func (c *UserClient) QueryApprovals(u *User) *ApprovalQuery { return query } +// QueryComments queries the comments edge of a User. +func (c *UserClient) QueryComments(u *User) *CommentQuery { + query := &CommentQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(comment.Table, comment.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.CommentsTable, user.CommentsColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryLocks queries the locks edge of a User. func (c *UserClient) QueryLocks(u *User) *LockQuery { query := &LockQuery{config: c.config} diff --git a/ent/comment.go b/ent/comment.go new file mode 100644 index 00000000..ab88a9f1 --- /dev/null +++ b/ent/comment.go @@ -0,0 +1,206 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/gitploy-io/gitploy/ent/comment" + "github.com/gitploy-io/gitploy/ent/deployment" + "github.com/gitploy-io/gitploy/ent/user" +) + +// Comment is the model entity for the Comment schema. +type Comment struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Status holds the value of the "status" field. + Status comment.Status `json:"status"` + // Comment holds the value of the "comment" field. + Comment string `json:"comment"` + // 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"` + // UserID holds the value of the "user_id" field. + UserID int64 `json:"user_id"` + // DeploymentID holds the value of the "deployment_id" field. + DeploymentID int `json:"deployment_id"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the CommentQuery when eager-loading is set. + Edges CommentEdges `json:"edges"` +} + +// CommentEdges holds the relations/edges for other nodes in the graph. +type CommentEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // Deployment holds the value of the deployment edge. + Deployment *Deployment `json:"deployment,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e CommentEdges) UserOrErr() (*User, error) { + if e.loadedTypes[0] { + if e.User == nil { + // The edge user was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: user.Label} + } + return e.User, nil + } + return nil, &NotLoadedError{edge: "user"} +} + +// DeploymentOrErr returns the Deployment value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e CommentEdges) DeploymentOrErr() (*Deployment, error) { + if e.loadedTypes[1] { + if e.Deployment == nil { + // The edge deployment was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: deployment.Label} + } + return e.Deployment, nil + } + return nil, &NotLoadedError{edge: "deployment"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Comment) scanValues(columns []string) ([]interface{}, error) { + values := make([]interface{}, len(columns)) + for i := range columns { + switch columns[i] { + case comment.FieldID, comment.FieldUserID, comment.FieldDeploymentID: + values[i] = new(sql.NullInt64) + case comment.FieldStatus, comment.FieldComment: + values[i] = new(sql.NullString) + case comment.FieldCreatedAt, comment.FieldUpdatedAt: + values[i] = new(sql.NullTime) + default: + return nil, fmt.Errorf("unexpected column %q for type Comment", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Comment fields. +func (c *Comment) 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 comment.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + c.ID = int(value.Int64) + case comment.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + c.Status = comment.Status(value.String) + } + case comment.FieldComment: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field comment", values[i]) + } else if value.Valid { + c.Comment = value.String + } + case comment.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 { + c.CreatedAt = value.Time + } + case comment.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 { + c.UpdatedAt = value.Time + } + case comment.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + c.UserID = value.Int64 + } + case comment.FieldDeploymentID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field deployment_id", values[i]) + } else if value.Valid { + c.DeploymentID = int(value.Int64) + } + } + } + return nil +} + +// QueryUser queries the "user" edge of the Comment entity. +func (c *Comment) QueryUser() *UserQuery { + return (&CommentClient{config: c.config}).QueryUser(c) +} + +// QueryDeployment queries the "deployment" edge of the Comment entity. +func (c *Comment) QueryDeployment() *DeploymentQuery { + return (&CommentClient{config: c.config}).QueryDeployment(c) +} + +// Update returns a builder for updating this Comment. +// Note that you need to call Comment.Unwrap() before calling this method if this Comment +// was returned from a transaction, and the transaction was committed or rolled back. +func (c *Comment) Update() *CommentUpdateOne { + return (&CommentClient{config: c.config}).UpdateOne(c) +} + +// Unwrap unwraps the Comment entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (c *Comment) Unwrap() *Comment { + tx, ok := c.config.driver.(*txDriver) + if !ok { + panic("ent: Comment is not a transactional entity") + } + c.config.driver = tx.drv + return c +} + +// String implements the fmt.Stringer. +func (c *Comment) String() string { + var builder strings.Builder + builder.WriteString("Comment(") + builder.WriteString(fmt.Sprintf("id=%v", c.ID)) + builder.WriteString(", status=") + builder.WriteString(fmt.Sprintf("%v", c.Status)) + builder.WriteString(", comment=") + builder.WriteString(c.Comment) + builder.WriteString(", created_at=") + builder.WriteString(c.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", updated_at=") + builder.WriteString(c.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", user_id=") + builder.WriteString(fmt.Sprintf("%v", c.UserID)) + builder.WriteString(", deployment_id=") + builder.WriteString(fmt.Sprintf("%v", c.DeploymentID)) + builder.WriteByte(')') + return builder.String() +} + +// Comments is a parsable slice of Comment. +type Comments []*Comment + +func (c Comments) config(cfg config) { + for _i := range c { + c[_i].config = cfg + } +} diff --git a/ent/comment/comment.go b/ent/comment/comment.go new file mode 100644 index 00000000..2b8b0645 --- /dev/null +++ b/ent/comment/comment.go @@ -0,0 +1,100 @@ +// Code generated by entc, DO NOT EDIT. + +package comment + +import ( + "fmt" + "time" +) + +const ( + // Label holds the string label denoting the comment type in the database. + Label = "comment" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldComment holds the string denoting the comment field in the database. + FieldComment = "comment" + // 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" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldDeploymentID holds the string denoting the deployment_id field in the database. + FieldDeploymentID = "deployment_id" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // EdgeDeployment holds the string denoting the deployment edge name in mutations. + EdgeDeployment = "deployment" + // Table holds the table name of the comment in the database. + Table = "comments" + // UserTable is the table that holds the user relation/edge. + UserTable = "comments" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" + // DeploymentTable is the table that holds the deployment relation/edge. + DeploymentTable = "comments" + // DeploymentInverseTable is the table name for the Deployment entity. + // It exists in this package in order to avoid circular dependency with the "deployment" package. + DeploymentInverseTable = "deployments" + // DeploymentColumn is the table column denoting the deployment relation/edge. + DeploymentColumn = "deployment_id" +) + +// Columns holds all SQL columns for comment fields. +var Columns = []string{ + FieldID, + FieldStatus, + FieldComment, + FieldCreatedAt, + FieldUpdatedAt, + FieldUserID, + FieldDeploymentID, +} + +// 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 ( + // 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 +) + +// Status defines the type for the "status" enum field. +type Status string + +// Status values. +const ( + StatusApproved Status = "approved" + StatusRejected Status = "rejected" +) + +func (s Status) String() string { + return string(s) +} + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s Status) error { + switch s { + case StatusApproved, StatusRejected: + return nil + default: + return fmt.Errorf("comment: invalid enum value for status field: %q", s) + } +} diff --git a/ent/comment/where.go b/ent/comment/where.go new file mode 100644 index 00000000..7a0dc980 --- /dev/null +++ b/ent/comment/where.go @@ -0,0 +1,624 @@ +// Code generated by entc, DO NOT EDIT. + +package comment + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/gitploy-io/gitploy/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// Comment applies equality check predicate on the "comment" field. It's identical to CommentEQ. +func Comment(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldComment), v)) + }) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdatedAt), v)) + }) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int64) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// DeploymentID applies equality check predicate on the "deployment_id" field. It's identical to DeploymentIDEQ. +func DeploymentID(v int) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeploymentID), v)) + }) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v Status) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldStatus), v)) + }) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v Status) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldStatus), v)) + }) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...Status) predicate.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.In(s.C(FieldStatus), v...)) + }) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...Status) predicate.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(func(s *sql.Selector) { + // if not arguments were provided, append the FALSE constants, + // since we can't apply "IN ()". This will make this predicate falsy. + if len(v) == 0 { + s.Where(sql.False()) + return + } + s.Where(sql.NotIn(s.C(FieldStatus), v...)) + }) +} + +// CommentEQ applies the EQ predicate on the "comment" field. +func CommentEQ(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldComment), v)) + }) +} + +// CommentNEQ applies the NEQ predicate on the "comment" field. +func CommentNEQ(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldComment), v)) + }) +} + +// CommentIn applies the In predicate on the "comment" field. +func CommentIn(vs ...string) predicate.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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(FieldComment), v...)) + }) +} + +// CommentNotIn applies the NotIn predicate on the "comment" field. +func CommentNotIn(vs ...string) predicate.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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(FieldComment), v...)) + }) +} + +// CommentGT applies the GT predicate on the "comment" field. +func CommentGT(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldComment), v)) + }) +} + +// CommentGTE applies the GTE predicate on the "comment" field. +func CommentGTE(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldComment), v)) + }) +} + +// CommentLT applies the LT predicate on the "comment" field. +func CommentLT(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldComment), v)) + }) +} + +// CommentLTE applies the LTE predicate on the "comment" field. +func CommentLTE(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldComment), v)) + }) +} + +// CommentContains applies the Contains predicate on the "comment" field. +func CommentContains(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldComment), v)) + }) +} + +// CommentHasPrefix applies the HasPrefix predicate on the "comment" field. +func CommentHasPrefix(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldComment), v)) + }) +} + +// CommentHasSuffix applies the HasSuffix predicate on the "comment" field. +func CommentHasSuffix(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldComment), v)) + }) +} + +// CommentEqualFold applies the EqualFold predicate on the "comment" field. +func CommentEqualFold(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldComment), v)) + }) +} + +// CommentContainsFold applies the ContainsFold predicate on the "comment" field. +func CommentContainsFold(v string) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldComment), v)) + }) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(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.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdatedAt), v)) + }) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int64) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUserID), v)) + }) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int64) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUserID), v)) + }) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int64) predicate.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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(FieldUserID), v...)) + }) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int64) predicate.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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(FieldUserID), v...)) + }) +} + +// DeploymentIDEQ applies the EQ predicate on the "deployment_id" field. +func DeploymentIDEQ(v int) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeploymentID), v)) + }) +} + +// DeploymentIDNEQ applies the NEQ predicate on the "deployment_id" field. +func DeploymentIDNEQ(v int) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeploymentID), v)) + }) +} + +// DeploymentIDIn applies the In predicate on the "deployment_id" field. +func DeploymentIDIn(vs ...int) predicate.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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(FieldDeploymentID), v...)) + }) +} + +// DeploymentIDNotIn applies the NotIn predicate on the "deployment_id" field. +func DeploymentIDNotIn(vs ...int) predicate.Comment { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Comment(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(FieldDeploymentID), v...)) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasDeployment applies the HasEdge predicate on the "deployment" edge. +func HasDeployment() predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DeploymentTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, DeploymentTable, DeploymentColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasDeploymentWith applies the HasEdge predicate on the "deployment" edge with a given conditions (other predicates). +func HasDeploymentWith(preds ...predicate.Deployment) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DeploymentInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, DeploymentTable, DeploymentColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Comment) predicate.Comment { + return predicate.Comment(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.Comment) predicate.Comment { + return predicate.Comment(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.Comment) predicate.Comment { + return predicate.Comment(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/ent/comment_create.go b/ent/comment_create.go new file mode 100644 index 00000000..3c3fc8ad --- /dev/null +++ b/ent/comment_create.go @@ -0,0 +1,383 @@ +// 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/comment" + "github.com/gitploy-io/gitploy/ent/deployment" + "github.com/gitploy-io/gitploy/ent/user" +) + +// CommentCreate is the builder for creating a Comment entity. +type CommentCreate struct { + config + mutation *CommentMutation + hooks []Hook +} + +// SetStatus sets the "status" field. +func (cc *CommentCreate) SetStatus(c comment.Status) *CommentCreate { + cc.mutation.SetStatus(c) + return cc +} + +// SetComment sets the "comment" field. +func (cc *CommentCreate) SetComment(s string) *CommentCreate { + cc.mutation.SetComment(s) + return cc +} + +// SetCreatedAt sets the "created_at" field. +func (cc *CommentCreate) SetCreatedAt(t time.Time) *CommentCreate { + cc.mutation.SetCreatedAt(t) + return cc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (cc *CommentCreate) SetNillableCreatedAt(t *time.Time) *CommentCreate { + if t != nil { + cc.SetCreatedAt(*t) + } + return cc +} + +// SetUpdatedAt sets the "updated_at" field. +func (cc *CommentCreate) SetUpdatedAt(t time.Time) *CommentCreate { + cc.mutation.SetUpdatedAt(t) + return cc +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (cc *CommentCreate) SetNillableUpdatedAt(t *time.Time) *CommentCreate { + if t != nil { + cc.SetUpdatedAt(*t) + } + return cc +} + +// SetUserID sets the "user_id" field. +func (cc *CommentCreate) SetUserID(i int64) *CommentCreate { + cc.mutation.SetUserID(i) + return cc +} + +// SetDeploymentID sets the "deployment_id" field. +func (cc *CommentCreate) SetDeploymentID(i int) *CommentCreate { + cc.mutation.SetDeploymentID(i) + return cc +} + +// SetUser sets the "user" edge to the User entity. +func (cc *CommentCreate) SetUser(u *User) *CommentCreate { + return cc.SetUserID(u.ID) +} + +// SetDeployment sets the "deployment" edge to the Deployment entity. +func (cc *CommentCreate) SetDeployment(d *Deployment) *CommentCreate { + return cc.SetDeploymentID(d.ID) +} + +// Mutation returns the CommentMutation object of the builder. +func (cc *CommentCreate) Mutation() *CommentMutation { + return cc.mutation +} + +// Save creates the Comment in the database. +func (cc *CommentCreate) Save(ctx context.Context) (*Comment, error) { + var ( + err error + node *Comment + ) + cc.defaults() + if len(cc.hooks) == 0 { + if err = cc.check(); err != nil { + return nil, err + } + node, err = cc.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CommentMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = cc.check(); err != nil { + return nil, err + } + cc.mutation = mutation + if node, err = cc.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(cc.hooks) - 1; i >= 0; i-- { + if cc.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = cc.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, cc.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (cc *CommentCreate) SaveX(ctx context.Context) *Comment { + v, err := cc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (cc *CommentCreate) Exec(ctx context.Context) error { + _, err := cc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cc *CommentCreate) ExecX(ctx context.Context) { + if err := cc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (cc *CommentCreate) defaults() { + if _, ok := cc.mutation.CreatedAt(); !ok { + v := comment.DefaultCreatedAt() + cc.mutation.SetCreatedAt(v) + } + if _, ok := cc.mutation.UpdatedAt(); !ok { + v := comment.DefaultUpdatedAt() + cc.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (cc *CommentCreate) check() error { + if _, ok := cc.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "status"`)} + } + if v, ok := cc.mutation.Status(); ok { + if err := comment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "status": %w`, err)} + } + } + if _, ok := cc.mutation.Comment(); !ok { + return &ValidationError{Name: "comment", err: errors.New(`ent: missing required field "comment"`)} + } + if _, ok := cc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "created_at"`)} + } + if _, ok := cc.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "updated_at"`)} + } + if _, ok := cc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "user_id"`)} + } + if _, ok := cc.mutation.DeploymentID(); !ok { + return &ValidationError{Name: "deployment_id", err: errors.New(`ent: missing required field "deployment_id"`)} + } + if _, ok := cc.mutation.UserID(); !ok { + return &ValidationError{Name: "user", err: errors.New("ent: missing required edge \"user\"")} + } + if _, ok := cc.mutation.DeploymentID(); !ok { + return &ValidationError{Name: "deployment", err: errors.New("ent: missing required edge \"deployment\"")} + } + return nil +} + +func (cc *CommentCreate) sqlSave(ctx context.Context) (*Comment, error) { + _node, _spec := cc.createSpec() + if err := sqlgraph.CreateNode(ctx, cc.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 (cc *CommentCreate) createSpec() (*Comment, *sqlgraph.CreateSpec) { + var ( + _node = &Comment{config: cc.config} + _spec = &sqlgraph.CreateSpec{ + Table: comment.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + } + ) + if value, ok := cc.mutation.Status(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Value: value, + Column: comment.FieldStatus, + }) + _node.Status = value + } + if value, ok := cc.mutation.Comment(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: comment.FieldComment, + }) + _node.Comment = value + } + if value, ok := cc.mutation.CreatedAt(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: comment.FieldCreatedAt, + }) + _node.CreatedAt = value + } + if value, ok := cc.mutation.UpdatedAt(); ok { + _spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: comment.FieldUpdatedAt, + }) + _node.UpdatedAt = value + } + if nodes := cc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.UserTable, + Columns: []string{comment.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := cc.mutation.DeploymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.DeploymentTable, + Columns: []string{comment.DeploymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deployment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.DeploymentID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// CommentCreateBulk is the builder for creating many Comment entities in bulk. +type CommentCreateBulk struct { + config + builders []*CommentCreate +} + +// Save creates the Comment entities in the database. +func (ccb *CommentCreateBulk) Save(ctx context.Context) ([]*Comment, error) { + specs := make([]*sqlgraph.CreateSpec, len(ccb.builders)) + nodes := make([]*Comment, len(ccb.builders)) + mutators := make([]Mutator, len(ccb.builders)) + for i := range ccb.builders { + func(i int, root context.Context) { + builder := ccb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CommentMutation) + 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, ccb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, ccb.driver, 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, ccb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ccb *CommentCreateBulk) SaveX(ctx context.Context) []*Comment { + v, err := ccb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ccb *CommentCreateBulk) Exec(ctx context.Context) error { + _, err := ccb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ccb *CommentCreateBulk) ExecX(ctx context.Context) { + if err := ccb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/comment_delete.go b/ent/comment_delete.go new file mode 100644 index 00000000..a48ad36e --- /dev/null +++ b/ent/comment_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/comment" + "github.com/gitploy-io/gitploy/ent/predicate" +) + +// CommentDelete is the builder for deleting a Comment entity. +type CommentDelete struct { + config + hooks []Hook + mutation *CommentMutation +} + +// Where appends a list predicates to the CommentDelete builder. +func (cd *CommentDelete) Where(ps ...predicate.Comment) *CommentDelete { + cd.mutation.Where(ps...) + return cd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (cd *CommentDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(cd.hooks) == 0 { + affected, err = cd.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CommentMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + cd.mutation = mutation + affected, err = cd.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(cd.hooks) - 1; i >= 0; i-- { + if cd.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = cd.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, cd.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cd *CommentDelete) ExecX(ctx context.Context) int { + n, err := cd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (cd *CommentDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: comment.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + if ps := cd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return sqlgraph.DeleteNodes(ctx, cd.driver, _spec) +} + +// CommentDeleteOne is the builder for deleting a single Comment entity. +type CommentDeleteOne struct { + cd *CommentDelete +} + +// Exec executes the deletion query. +func (cdo *CommentDeleteOne) Exec(ctx context.Context) error { + n, err := cdo.cd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{comment.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (cdo *CommentDeleteOne) ExecX(ctx context.Context) { + cdo.cd.ExecX(ctx) +} diff --git a/ent/comment_query.go b/ent/comment_query.go new file mode 100644 index 00000000..6ab3f8bc --- /dev/null +++ b/ent/comment_query.go @@ -0,0 +1,1083 @@ +// 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/comment" + "github.com/gitploy-io/gitploy/ent/deployment" + "github.com/gitploy-io/gitploy/ent/predicate" + "github.com/gitploy-io/gitploy/ent/user" +) + +// CommentQuery is the builder for querying Comment entities. +type CommentQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Comment + // eager-loading edges. + withUser *UserQuery + withDeployment *DeploymentQuery + 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 CommentQuery builder. +func (cq *CommentQuery) Where(ps ...predicate.Comment) *CommentQuery { + cq.predicates = append(cq.predicates, ps...) + return cq +} + +// Limit adds a limit step to the query. +func (cq *CommentQuery) Limit(limit int) *CommentQuery { + cq.limit = &limit + return cq +} + +// Offset adds an offset step to the query. +func (cq *CommentQuery) Offset(offset int) *CommentQuery { + cq.offset = &offset + return cq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (cq *CommentQuery) Unique(unique bool) *CommentQuery { + cq.unique = &unique + return cq +} + +// Order adds an order step to the query. +func (cq *CommentQuery) Order(o ...OrderFunc) *CommentQuery { + cq.order = append(cq.order, o...) + return cq +} + +// QueryUser chains the current query on the "user" edge. +func (cq *CommentQuery) QueryUser() *UserQuery { + query := &UserQuery{config: cq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := cq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(comment.Table, comment.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, comment.UserTable, comment.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(cq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryDeployment chains the current query on the "deployment" edge. +func (cq *CommentQuery) QueryDeployment() *DeploymentQuery { + query := &DeploymentQuery{config: cq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := cq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(comment.Table, comment.FieldID, selector), + sqlgraph.To(deployment.Table, deployment.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, comment.DeploymentTable, comment.DeploymentColumn), + ) + fromU = sqlgraph.SetNeighbors(cq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Comment entity from the query. +// Returns a *NotFoundError when no Comment was found. +func (cq *CommentQuery) First(ctx context.Context) (*Comment, error) { + nodes, err := cq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{comment.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (cq *CommentQuery) FirstX(ctx context.Context) *Comment { + node, err := cq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Comment ID from the query. +// Returns a *NotFoundError when no Comment ID was found. +func (cq *CommentQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = cq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{comment.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (cq *CommentQuery) FirstIDX(ctx context.Context) int { + id, err := cq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Comment entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when exactly one Comment entity is not found. +// Returns a *NotFoundError when no Comment entities are found. +func (cq *CommentQuery) Only(ctx context.Context) (*Comment, error) { + nodes, err := cq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{comment.Label} + default: + return nil, &NotSingularError{comment.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (cq *CommentQuery) OnlyX(ctx context.Context) *Comment { + node, err := cq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Comment ID in the query. +// Returns a *NotSingularError when exactly one Comment ID is not found. +// Returns a *NotFoundError when no entities are found. +func (cq *CommentQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = cq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{comment.Label} + default: + err = &NotSingularError{comment.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (cq *CommentQuery) OnlyIDX(ctx context.Context) int { + id, err := cq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Comments. +func (cq *CommentQuery) All(ctx context.Context) ([]*Comment, error) { + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + return cq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (cq *CommentQuery) AllX(ctx context.Context) []*Comment { + nodes, err := cq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Comment IDs. +func (cq *CommentQuery) IDs(ctx context.Context) ([]int, error) { + var ids []int + if err := cq.Select(comment.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (cq *CommentQuery) IDsX(ctx context.Context) []int { + ids, err := cq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (cq *CommentQuery) Count(ctx context.Context) (int, error) { + if err := cq.prepareQuery(ctx); err != nil { + return 0, err + } + return cq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (cq *CommentQuery) CountX(ctx context.Context) int { + count, err := cq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (cq *CommentQuery) Exist(ctx context.Context) (bool, error) { + if err := cq.prepareQuery(ctx); err != nil { + return false, err + } + return cq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (cq *CommentQuery) ExistX(ctx context.Context) bool { + exist, err := cq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CommentQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (cq *CommentQuery) Clone() *CommentQuery { + if cq == nil { + return nil + } + return &CommentQuery{ + config: cq.config, + limit: cq.limit, + offset: cq.offset, + order: append([]OrderFunc{}, cq.order...), + predicates: append([]predicate.Comment{}, cq.predicates...), + withUser: cq.withUser.Clone(), + withDeployment: cq.withDeployment.Clone(), + // clone intermediate query. + sql: cq.sql.Clone(), + path: cq.path, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (cq *CommentQuery) WithUser(opts ...func(*UserQuery)) *CommentQuery { + query := &UserQuery{config: cq.config} + for _, opt := range opts { + opt(query) + } + cq.withUser = query + return cq +} + +// WithDeployment tells the query-builder to eager-load the nodes that are connected to +// the "deployment" edge. The optional arguments are used to configure the query builder of the edge. +func (cq *CommentQuery) WithDeployment(opts ...func(*DeploymentQuery)) *CommentQuery { + query := &DeploymentQuery{config: cq.config} + for _, opt := range opts { + opt(query) + } + cq.withDeployment = query + return cq +} + +// 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 { +// Status comment.Status `json:"status"` +// Count int `json:"count,omitempty"` +// } +// +// client.Comment.Query(). +// GroupBy(comment.FieldStatus). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +// +func (cq *CommentQuery) GroupBy(field string, fields ...string) *CommentGroupBy { + group := &CommentGroupBy{config: cq.config} + group.fields = append([]string{field}, fields...) + group.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + return cq.sqlQuery(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 { +// Status comment.Status `json:"status"` +// } +// +// client.Comment.Query(). +// Select(comment.FieldStatus). +// Scan(ctx, &v) +// +func (cq *CommentQuery) Select(fields ...string) *CommentSelect { + cq.fields = append(cq.fields, fields...) + return &CommentSelect{CommentQuery: cq} +} + +func (cq *CommentQuery) prepareQuery(ctx context.Context) error { + for _, f := range cq.fields { + if !comment.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if cq.path != nil { + prev, err := cq.path(ctx) + if err != nil { + return err + } + cq.sql = prev + } + return nil +} + +func (cq *CommentQuery) sqlAll(ctx context.Context) ([]*Comment, error) { + var ( + nodes = []*Comment{} + _spec = cq.querySpec() + loadedTypes = [2]bool{ + cq.withUser != nil, + cq.withDeployment != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]interface{}, error) { + node := &Comment{config: cq.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] + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(cq.modifiers) > 0 { + _spec.Modifiers = cq.modifiers + } + if err := sqlgraph.QueryNodes(ctx, cq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + + if query := cq.withUser; query != nil { + ids := make([]int64, 0, len(nodes)) + nodeids := make(map[int64][]*Comment) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.User = n + } + } + } + + if query := cq.withDeployment; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Comment) + for i := range nodes { + fk := nodes[i].DeploymentID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(deployment.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "deployment_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Deployment = n + } + } + } + + return nodes, nil +} + +func (cq *CommentQuery) sqlCount(ctx context.Context) (int, error) { + _spec := cq.querySpec() + if len(cq.modifiers) > 0 { + _spec.Modifiers = cq.modifiers + } + return sqlgraph.CountNodes(ctx, cq.driver, _spec) +} + +func (cq *CommentQuery) sqlExist(ctx context.Context) (bool, error) { + n, err := cq.sqlCount(ctx) + if err != nil { + return false, fmt.Errorf("ent: check existence: %w", err) + } + return n > 0, nil +} + +func (cq *CommentQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: comment.Table, + Columns: comment.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + From: cq.sql, + Unique: true, + } + if unique := cq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := cq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, comment.FieldID) + for i := range fields { + if fields[i] != comment.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := cq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := cq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := cq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := cq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (cq *CommentQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(cq.driver.Dialect()) + t1 := builder.Table(comment.Table) + columns := cq.fields + if len(columns) == 0 { + columns = comment.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if cq.sql != nil { + selector = cq.sql + selector.Select(selector.Columns(columns...)...) + } + for _, m := range cq.modifiers { + m(selector) + } + for _, p := range cq.predicates { + p(selector) + } + for _, p := range cq.order { + p(selector) + } + if offset := cq.offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := cq.limit; limit != nil { + 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 (cq *CommentQuery) ForUpdate(opts ...sql.LockOption) *CommentQuery { + if cq.driver.Dialect() == dialect.Postgres { + cq.Unique(false) + } + cq.modifiers = append(cq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return cq +} + +// 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 (cq *CommentQuery) ForShare(opts ...sql.LockOption) *CommentQuery { + if cq.driver.Dialect() == dialect.Postgres { + cq.Unique(false) + } + cq.modifiers = append(cq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return cq +} + +// CommentGroupBy is the group-by builder for Comment entities. +type CommentGroupBy 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 (cgb *CommentGroupBy) Aggregate(fns ...AggregateFunc) *CommentGroupBy { + cgb.fns = append(cgb.fns, fns...) + return cgb +} + +// Scan applies the group-by query and scans the result into the given value. +func (cgb *CommentGroupBy) Scan(ctx context.Context, v interface{}) error { + query, err := cgb.path(ctx) + if err != nil { + return err + } + cgb.sql = query + return cgb.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (cgb *CommentGroupBy) ScanX(ctx context.Context, v interface{}) { + if err := cgb.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from group-by. +// It is only allowed when executing a group-by query with one field. +func (cgb *CommentGroupBy) Strings(ctx context.Context) ([]string, error) { + if len(cgb.fields) > 1 { + return nil, errors.New("ent: CommentGroupBy.Strings is not achievable when grouping more than 1 field") + } + var v []string + if err := cgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (cgb *CommentGroupBy) StringsX(ctx context.Context) []string { + v, err := cgb.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 (cgb *CommentGroupBy) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = cgb.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{comment.Label} + default: + err = fmt.Errorf("ent: CommentGroupBy.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (cgb *CommentGroupBy) StringX(ctx context.Context) string { + v, err := cgb.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from group-by. +// It is only allowed when executing a group-by query with one field. +func (cgb *CommentGroupBy) Ints(ctx context.Context) ([]int, error) { + if len(cgb.fields) > 1 { + return nil, errors.New("ent: CommentGroupBy.Ints is not achievable when grouping more than 1 field") + } + var v []int + if err := cgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (cgb *CommentGroupBy) IntsX(ctx context.Context) []int { + v, err := cgb.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 (cgb *CommentGroupBy) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = cgb.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{comment.Label} + default: + err = fmt.Errorf("ent: CommentGroupBy.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (cgb *CommentGroupBy) IntX(ctx context.Context) int { + v, err := cgb.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from group-by. +// It is only allowed when executing a group-by query with one field. +func (cgb *CommentGroupBy) Float64s(ctx context.Context) ([]float64, error) { + if len(cgb.fields) > 1 { + return nil, errors.New("ent: CommentGroupBy.Float64s is not achievable when grouping more than 1 field") + } + var v []float64 + if err := cgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (cgb *CommentGroupBy) Float64sX(ctx context.Context) []float64 { + v, err := cgb.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 (cgb *CommentGroupBy) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = cgb.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{comment.Label} + default: + err = fmt.Errorf("ent: CommentGroupBy.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (cgb *CommentGroupBy) Float64X(ctx context.Context) float64 { + v, err := cgb.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from group-by. +// It is only allowed when executing a group-by query with one field. +func (cgb *CommentGroupBy) Bools(ctx context.Context) ([]bool, error) { + if len(cgb.fields) > 1 { + return nil, errors.New("ent: CommentGroupBy.Bools is not achievable when grouping more than 1 field") + } + var v []bool + if err := cgb.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (cgb *CommentGroupBy) BoolsX(ctx context.Context) []bool { + v, err := cgb.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 (cgb *CommentGroupBy) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = cgb.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{comment.Label} + default: + err = fmt.Errorf("ent: CommentGroupBy.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (cgb *CommentGroupBy) BoolX(ctx context.Context) bool { + v, err := cgb.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (cgb *CommentGroupBy) sqlScan(ctx context.Context, v interface{}) error { + for _, f := range cgb.fields { + if !comment.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := cgb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := cgb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (cgb *CommentGroupBy) sqlQuery() *sql.Selector { + selector := cgb.sql.Select() + aggregation := make([]string, 0, len(cgb.fns)) + for _, fn := range cgb.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(cgb.fields)+len(cgb.fns)) + for _, f := range cgb.fields { + columns = append(columns, selector.C(f)) + } + for _, c := range aggregation { + columns = append(columns, c) + } + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(cgb.fields...)...) +} + +// CommentSelect is the builder for selecting fields of Comment entities. +type CommentSelect struct { + *CommentQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Scan applies the selector query and scans the result into the given value. +func (cs *CommentSelect) Scan(ctx context.Context, v interface{}) error { + if err := cs.prepareQuery(ctx); err != nil { + return err + } + cs.sql = cs.CommentQuery.sqlQuery(ctx) + return cs.sqlScan(ctx, v) +} + +// ScanX is like Scan, but panics if an error occurs. +func (cs *CommentSelect) ScanX(ctx context.Context, v interface{}) { + if err := cs.Scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (cs *CommentSelect) Strings(ctx context.Context) ([]string, error) { + if len(cs.fields) > 1 { + return nil, errors.New("ent: CommentSelect.Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := cs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (cs *CommentSelect) StringsX(ctx context.Context) []string { + v, err := cs.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 (cs *CommentSelect) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = cs.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{comment.Label} + default: + err = fmt.Errorf("ent: CommentSelect.Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (cs *CommentSelect) StringX(ctx context.Context) string { + v, err := cs.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 (cs *CommentSelect) Ints(ctx context.Context) ([]int, error) { + if len(cs.fields) > 1 { + return nil, errors.New("ent: CommentSelect.Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := cs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (cs *CommentSelect) IntsX(ctx context.Context) []int { + v, err := cs.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 (cs *CommentSelect) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = cs.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{comment.Label} + default: + err = fmt.Errorf("ent: CommentSelect.Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (cs *CommentSelect) IntX(ctx context.Context) int { + v, err := cs.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 (cs *CommentSelect) Float64s(ctx context.Context) ([]float64, error) { + if len(cs.fields) > 1 { + return nil, errors.New("ent: CommentSelect.Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := cs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (cs *CommentSelect) Float64sX(ctx context.Context) []float64 { + v, err := cs.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 (cs *CommentSelect) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = cs.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{comment.Label} + default: + err = fmt.Errorf("ent: CommentSelect.Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (cs *CommentSelect) Float64X(ctx context.Context) float64 { + v, err := cs.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 (cs *CommentSelect) Bools(ctx context.Context) ([]bool, error) { + if len(cs.fields) > 1 { + return nil, errors.New("ent: CommentSelect.Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := cs.Scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (cs *CommentSelect) BoolsX(ctx context.Context) []bool { + v, err := cs.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 (cs *CommentSelect) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = cs.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{comment.Label} + default: + err = fmt.Errorf("ent: CommentSelect.Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (cs *CommentSelect) BoolX(ctx context.Context) bool { + v, err := cs.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +func (cs *CommentSelect) sqlScan(ctx context.Context, v interface{}) error { + rows := &sql.Rows{} + query, args := cs.sql.Query() + if err := cs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/comment_update.go b/ent/comment_update.go new file mode 100644 index 00000000..e7d3cf5d --- /dev/null +++ b/ent/comment_update.go @@ -0,0 +1,632 @@ +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/gitploy-io/gitploy/ent/comment" + "github.com/gitploy-io/gitploy/ent/deployment" + "github.com/gitploy-io/gitploy/ent/predicate" + "github.com/gitploy-io/gitploy/ent/user" +) + +// CommentUpdate is the builder for updating Comment entities. +type CommentUpdate struct { + config + hooks []Hook + mutation *CommentMutation +} + +// Where appends a list predicates to the CommentUpdate builder. +func (cu *CommentUpdate) Where(ps ...predicate.Comment) *CommentUpdate { + cu.mutation.Where(ps...) + return cu +} + +// SetStatus sets the "status" field. +func (cu *CommentUpdate) SetStatus(c comment.Status) *CommentUpdate { + cu.mutation.SetStatus(c) + return cu +} + +// SetComment sets the "comment" field. +func (cu *CommentUpdate) SetComment(s string) *CommentUpdate { + cu.mutation.SetComment(s) + return cu +} + +// SetCreatedAt sets the "created_at" field. +func (cu *CommentUpdate) SetCreatedAt(t time.Time) *CommentUpdate { + cu.mutation.SetCreatedAt(t) + return cu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (cu *CommentUpdate) SetNillableCreatedAt(t *time.Time) *CommentUpdate { + if t != nil { + cu.SetCreatedAt(*t) + } + return cu +} + +// SetUpdatedAt sets the "updated_at" field. +func (cu *CommentUpdate) SetUpdatedAt(t time.Time) *CommentUpdate { + cu.mutation.SetUpdatedAt(t) + return cu +} + +// SetUserID sets the "user_id" field. +func (cu *CommentUpdate) SetUserID(i int64) *CommentUpdate { + cu.mutation.SetUserID(i) + return cu +} + +// SetDeploymentID sets the "deployment_id" field. +func (cu *CommentUpdate) SetDeploymentID(i int) *CommentUpdate { + cu.mutation.SetDeploymentID(i) + return cu +} + +// SetUser sets the "user" edge to the User entity. +func (cu *CommentUpdate) SetUser(u *User) *CommentUpdate { + return cu.SetUserID(u.ID) +} + +// SetDeployment sets the "deployment" edge to the Deployment entity. +func (cu *CommentUpdate) SetDeployment(d *Deployment) *CommentUpdate { + return cu.SetDeploymentID(d.ID) +} + +// Mutation returns the CommentMutation object of the builder. +func (cu *CommentUpdate) Mutation() *CommentMutation { + return cu.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (cu *CommentUpdate) ClearUser() *CommentUpdate { + cu.mutation.ClearUser() + return cu +} + +// ClearDeployment clears the "deployment" edge to the Deployment entity. +func (cu *CommentUpdate) ClearDeployment() *CommentUpdate { + cu.mutation.ClearDeployment() + return cu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (cu *CommentUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + cu.defaults() + if len(cu.hooks) == 0 { + if err = cu.check(); err != nil { + return 0, err + } + affected, err = cu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CommentMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = cu.check(); err != nil { + return 0, err + } + cu.mutation = mutation + affected, err = cu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(cu.hooks) - 1; i >= 0; i-- { + if cu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = cu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, cu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (cu *CommentUpdate) SaveX(ctx context.Context) int { + affected, err := cu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (cu *CommentUpdate) Exec(ctx context.Context) error { + _, err := cu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cu *CommentUpdate) ExecX(ctx context.Context) { + if err := cu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (cu *CommentUpdate) defaults() { + if _, ok := cu.mutation.UpdatedAt(); !ok { + v := comment.UpdateDefaultUpdatedAt() + cu.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (cu *CommentUpdate) check() error { + if v, ok := cu.mutation.Status(); ok { + if err := comment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf("ent: validator failed for field \"status\": %w", err)} + } + } + if _, ok := cu.mutation.UserID(); cu.mutation.UserCleared() && !ok { + return errors.New("ent: clearing a required unique edge \"user\"") + } + if _, ok := cu.mutation.DeploymentID(); cu.mutation.DeploymentCleared() && !ok { + return errors.New("ent: clearing a required unique edge \"deployment\"") + } + return nil +} + +func (cu *CommentUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: comment.Table, + Columns: comment.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + if ps := cu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := cu.mutation.Status(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Value: value, + Column: comment.FieldStatus, + }) + } + if value, ok := cu.mutation.Comment(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: comment.FieldComment, + }) + } + if value, ok := cu.mutation.CreatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: comment.FieldCreatedAt, + }) + } + if value, ok := cu.mutation.UpdatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: comment.FieldUpdatedAt, + }) + } + if cu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.UserTable, + Columns: []string{comment.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.UserTable, + Columns: []string{comment.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if cu.mutation.DeploymentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.DeploymentTable, + Columns: []string{comment.DeploymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deployment.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cu.mutation.DeploymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.DeploymentTable, + Columns: []string{comment.DeploymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deployment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, cu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{comment.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return 0, err + } + return n, nil +} + +// CommentUpdateOne is the builder for updating a single Comment entity. +type CommentUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CommentMutation +} + +// SetStatus sets the "status" field. +func (cuo *CommentUpdateOne) SetStatus(c comment.Status) *CommentUpdateOne { + cuo.mutation.SetStatus(c) + return cuo +} + +// SetComment sets the "comment" field. +func (cuo *CommentUpdateOne) SetComment(s string) *CommentUpdateOne { + cuo.mutation.SetComment(s) + return cuo +} + +// SetCreatedAt sets the "created_at" field. +func (cuo *CommentUpdateOne) SetCreatedAt(t time.Time) *CommentUpdateOne { + cuo.mutation.SetCreatedAt(t) + return cuo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (cuo *CommentUpdateOne) SetNillableCreatedAt(t *time.Time) *CommentUpdateOne { + if t != nil { + cuo.SetCreatedAt(*t) + } + return cuo +} + +// SetUpdatedAt sets the "updated_at" field. +func (cuo *CommentUpdateOne) SetUpdatedAt(t time.Time) *CommentUpdateOne { + cuo.mutation.SetUpdatedAt(t) + return cuo +} + +// SetUserID sets the "user_id" field. +func (cuo *CommentUpdateOne) SetUserID(i int64) *CommentUpdateOne { + cuo.mutation.SetUserID(i) + return cuo +} + +// SetDeploymentID sets the "deployment_id" field. +func (cuo *CommentUpdateOne) SetDeploymentID(i int) *CommentUpdateOne { + cuo.mutation.SetDeploymentID(i) + return cuo +} + +// SetUser sets the "user" edge to the User entity. +func (cuo *CommentUpdateOne) SetUser(u *User) *CommentUpdateOne { + return cuo.SetUserID(u.ID) +} + +// SetDeployment sets the "deployment" edge to the Deployment entity. +func (cuo *CommentUpdateOne) SetDeployment(d *Deployment) *CommentUpdateOne { + return cuo.SetDeploymentID(d.ID) +} + +// Mutation returns the CommentMutation object of the builder. +func (cuo *CommentUpdateOne) Mutation() *CommentMutation { + return cuo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (cuo *CommentUpdateOne) ClearUser() *CommentUpdateOne { + cuo.mutation.ClearUser() + return cuo +} + +// ClearDeployment clears the "deployment" edge to the Deployment entity. +func (cuo *CommentUpdateOne) ClearDeployment() *CommentUpdateOne { + cuo.mutation.ClearDeployment() + return cuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (cuo *CommentUpdateOne) Select(field string, fields ...string) *CommentUpdateOne { + cuo.fields = append([]string{field}, fields...) + return cuo +} + +// Save executes the query and returns the updated Comment entity. +func (cuo *CommentUpdateOne) Save(ctx context.Context) (*Comment, error) { + var ( + err error + node *Comment + ) + cuo.defaults() + if len(cuo.hooks) == 0 { + if err = cuo.check(); err != nil { + return nil, err + } + node, err = cuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CommentMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = cuo.check(); err != nil { + return nil, err + } + cuo.mutation = mutation + node, err = cuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(cuo.hooks) - 1; i >= 0; i-- { + if cuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = cuo.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, cuo.mutation); err != nil { + return nil, err + } + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (cuo *CommentUpdateOne) SaveX(ctx context.Context) *Comment { + node, err := cuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (cuo *CommentUpdateOne) Exec(ctx context.Context) error { + _, err := cuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cuo *CommentUpdateOne) ExecX(ctx context.Context) { + if err := cuo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (cuo *CommentUpdateOne) defaults() { + if _, ok := cuo.mutation.UpdatedAt(); !ok { + v := comment.UpdateDefaultUpdatedAt() + cuo.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (cuo *CommentUpdateOne) check() error { + if v, ok := cuo.mutation.Status(); ok { + if err := comment.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf("ent: validator failed for field \"status\": %w", err)} + } + } + if _, ok := cuo.mutation.UserID(); cuo.mutation.UserCleared() && !ok { + return errors.New("ent: clearing a required unique edge \"user\"") + } + if _, ok := cuo.mutation.DeploymentID(); cuo.mutation.DeploymentCleared() && !ok { + return errors.New("ent: clearing a required unique edge \"deployment\"") + } + return nil +} + +func (cuo *CommentUpdateOne) sqlSave(ctx context.Context) (_node *Comment, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: comment.Table, + Columns: comment.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + id, ok := cuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Comment.ID for update")} + } + _spec.Node.ID.Value = id + if fields := cuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, comment.FieldID) + for _, f := range fields { + if !comment.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != comment.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := cuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := cuo.mutation.Status(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeEnum, + Value: value, + Column: comment.FieldStatus, + }) + } + if value, ok := cuo.mutation.Comment(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeString, + Value: value, + Column: comment.FieldComment, + }) + } + if value, ok := cuo.mutation.CreatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: comment.FieldCreatedAt, + }) + } + if value, ok := cuo.mutation.UpdatedAt(); ok { + _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ + Type: field.TypeTime, + Value: value, + Column: comment.FieldUpdatedAt, + }) + } + if cuo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.UserTable, + Columns: []string{comment.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: user.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.UserTable, + Columns: []string{comment.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: user.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if cuo.mutation.DeploymentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.DeploymentTable, + Columns: []string{comment.DeploymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deployment.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cuo.mutation.DeploymentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: comment.DeploymentTable, + Columns: []string{comment.DeploymentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deployment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &Comment{config: cuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{comment.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{err.Error(), err} + } + return nil, err + } + return _node, nil +} diff --git a/ent/config.go b/ent/config.go index c37af045..feda581c 100644 --- a/ent/config.go +++ b/ent/config.go @@ -27,6 +27,7 @@ type hooks struct { Approval []ent.Hook Callback []ent.Hook ChatUser []ent.Hook + Comment []ent.Hook Deployment []ent.Hook DeploymentStatistics []ent.Hook DeploymentStatus []ent.Hook diff --git a/ent/deployment.go b/ent/deployment.go index c736f41c..3c3b3b5c 100644 --- a/ent/deployment.go +++ b/ent/deployment.go @@ -63,13 +63,15 @@ type DeploymentEdges struct { Repo *Repo `json:"repo,omitempty"` // Approvals holds the value of the approvals edge. Approvals []*Approval `json:"approvals,omitempty"` + // Comments holds the value of the comments edge. + Comments []*Comment `json:"comments,omitempty"` // DeploymentStatuses holds the value of the deployment_statuses edge. DeploymentStatuses []*DeploymentStatus `json:"deployment_statuses,omitempty"` // Event holds the value of the event edge. Event []*Event `json:"event,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [5]bool + loadedTypes [6]bool } // UserOrErr returns the User value or an error if the edge @@ -109,10 +111,19 @@ func (e DeploymentEdges) ApprovalsOrErr() ([]*Approval, error) { return nil, &NotLoadedError{edge: "approvals"} } +// CommentsOrErr returns the Comments value or an error if the edge +// was not loaded in eager-loading. +func (e DeploymentEdges) CommentsOrErr() ([]*Comment, error) { + if e.loadedTypes[3] { + return e.Comments, nil + } + return nil, &NotLoadedError{edge: "comments"} +} + // DeploymentStatusesOrErr returns the DeploymentStatuses value or an error if the edge // was not loaded in eager-loading. func (e DeploymentEdges) DeploymentStatusesOrErr() ([]*DeploymentStatus, error) { - if e.loadedTypes[3] { + if e.loadedTypes[4] { return e.DeploymentStatuses, nil } return nil, &NotLoadedError{edge: "deployment_statuses"} @@ -121,7 +132,7 @@ func (e DeploymentEdges) DeploymentStatusesOrErr() ([]*DeploymentStatus, error) // EventOrErr returns the Event value or an error if the edge // was not loaded in eager-loading. func (e DeploymentEdges) EventOrErr() ([]*Event, error) { - if e.loadedTypes[4] { + if e.loadedTypes[5] { return e.Event, nil } return nil, &NotLoadedError{edge: "event"} @@ -277,6 +288,11 @@ func (d *Deployment) QueryApprovals() *ApprovalQuery { return (&DeploymentClient{config: d.config}).QueryApprovals(d) } +// QueryComments queries the "comments" edge of the Deployment entity. +func (d *Deployment) QueryComments() *CommentQuery { + return (&DeploymentClient{config: d.config}).QueryComments(d) +} + // QueryDeploymentStatuses queries the "deployment_statuses" edge of the Deployment entity. func (d *Deployment) QueryDeploymentStatuses() *DeploymentStatusQuery { return (&DeploymentClient{config: d.config}).QueryDeploymentStatuses(d) diff --git a/ent/deployment/deployment.go b/ent/deployment/deployment.go index 1a694c35..415727aa 100644 --- a/ent/deployment/deployment.go +++ b/ent/deployment/deployment.go @@ -50,6 +50,8 @@ const ( EdgeRepo = "repo" // EdgeApprovals holds the string denoting the approvals edge name in mutations. EdgeApprovals = "approvals" + // EdgeComments holds the string denoting the comments edge name in mutations. + EdgeComments = "comments" // EdgeDeploymentStatuses holds the string denoting the deployment_statuses edge name in mutations. EdgeDeploymentStatuses = "deployment_statuses" // EdgeEvent holds the string denoting the event edge name in mutations. @@ -77,6 +79,13 @@ const ( ApprovalsInverseTable = "approvals" // ApprovalsColumn is the table column denoting the approvals relation/edge. ApprovalsColumn = "deployment_id" + // CommentsTable is the table that holds the comments relation/edge. + CommentsTable = "comments" + // CommentsInverseTable is the table name for the Comment entity. + // It exists in this package in order to avoid circular dependency with the "comment" package. + CommentsInverseTable = "comments" + // CommentsColumn is the table column denoting the comments relation/edge. + CommentsColumn = "deployment_id" // DeploymentStatusesTable is the table that holds the deployment_statuses relation/edge. DeploymentStatusesTable = "deployment_status" // DeploymentStatusesInverseTable is the table name for the DeploymentStatus entity. diff --git a/ent/deployment/where.go b/ent/deployment/where.go index 46554dd1..9391888c 100644 --- a/ent/deployment/where.go +++ b/ent/deployment/where.go @@ -1375,6 +1375,34 @@ func HasApprovalsWith(preds ...predicate.Approval) predicate.Deployment { }) } +// HasComments applies the HasEdge predicate on the "comments" edge. +func HasComments() predicate.Deployment { + return predicate.Deployment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CommentsTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CommentsTable, CommentsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCommentsWith applies the HasEdge predicate on the "comments" edge with a given conditions (other predicates). +func HasCommentsWith(preds ...predicate.Comment) predicate.Deployment { + return predicate.Deployment(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CommentsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CommentsTable, CommentsColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasDeploymentStatuses applies the HasEdge predicate on the "deployment_statuses" edge. func HasDeploymentStatuses() predicate.Deployment { return predicate.Deployment(func(s *sql.Selector) { diff --git a/ent/deployment_create.go b/ent/deployment_create.go index 2ea27bfe..263ba317 100644 --- a/ent/deployment_create.go +++ b/ent/deployment_create.go @@ -11,6 +11,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/ent/approval" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/deploymentstatus" "github.com/gitploy-io/gitploy/ent/event" @@ -234,6 +235,21 @@ func (dc *DeploymentCreate) AddApprovals(a ...*Approval) *DeploymentCreate { return dc.AddApprovalIDs(ids...) } +// AddCommentIDs adds the "comments" edge to the Comment entity by IDs. +func (dc *DeploymentCreate) AddCommentIDs(ids ...int) *DeploymentCreate { + dc.mutation.AddCommentIDs(ids...) + return dc +} + +// AddComments adds the "comments" edges to the Comment entity. +func (dc *DeploymentCreate) AddComments(c ...*Comment) *DeploymentCreate { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return dc.AddCommentIDs(ids...) +} + // AddDeploymentStatusIDs adds the "deployment_statuses" edge to the DeploymentStatus entity by IDs. func (dc *DeploymentCreate) AddDeploymentStatusIDs(ids ...int) *DeploymentCreate { dc.mutation.AddDeploymentStatusIDs(ids...) @@ -629,6 +645,25 @@ func (dc *DeploymentCreate) createSpec() (*Deployment, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := dc.mutation.CommentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deployment.CommentsTable, + Columns: []string{deployment.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } if nodes := dc.mutation.DeploymentStatusesIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/ent/deployment_query.go b/ent/deployment_query.go index 1665e162..723d8ed3 100644 --- a/ent/deployment_query.go +++ b/ent/deployment_query.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/ent/approval" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/deploymentstatus" "github.com/gitploy-io/gitploy/ent/event" @@ -35,6 +36,7 @@ type DeploymentQuery struct { withUser *UserQuery withRepo *RepoQuery withApprovals *ApprovalQuery + withComments *CommentQuery withDeploymentStatuses *DeploymentStatusQuery withEvent *EventQuery modifiers []func(s *sql.Selector) @@ -140,6 +142,28 @@ func (dq *DeploymentQuery) QueryApprovals() *ApprovalQuery { return query } +// QueryComments chains the current query on the "comments" edge. +func (dq *DeploymentQuery) QueryComments() *CommentQuery { + query := &CommentQuery{config: dq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := dq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := dq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(deployment.Table, deployment.FieldID, selector), + sqlgraph.To(comment.Table, comment.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, deployment.CommentsTable, deployment.CommentsColumn), + ) + fromU = sqlgraph.SetNeighbors(dq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryDeploymentStatuses chains the current query on the "deployment_statuses" edge. func (dq *DeploymentQuery) QueryDeploymentStatuses() *DeploymentStatusQuery { query := &DeploymentStatusQuery{config: dq.config} @@ -368,6 +392,7 @@ func (dq *DeploymentQuery) Clone() *DeploymentQuery { withUser: dq.withUser.Clone(), withRepo: dq.withRepo.Clone(), withApprovals: dq.withApprovals.Clone(), + withComments: dq.withComments.Clone(), withDeploymentStatuses: dq.withDeploymentStatuses.Clone(), withEvent: dq.withEvent.Clone(), // clone intermediate query. @@ -409,6 +434,17 @@ func (dq *DeploymentQuery) WithApprovals(opts ...func(*ApprovalQuery)) *Deployme return dq } +// WithComments tells the query-builder to eager-load the nodes that are connected to +// the "comments" edge. The optional arguments are used to configure the query builder of the edge. +func (dq *DeploymentQuery) WithComments(opts ...func(*CommentQuery)) *DeploymentQuery { + query := &CommentQuery{config: dq.config} + for _, opt := range opts { + opt(query) + } + dq.withComments = query + return dq +} + // WithDeploymentStatuses tells the query-builder to eager-load the nodes that are connected to // the "deployment_statuses" edge. The optional arguments are used to configure the query builder of the edge. func (dq *DeploymentQuery) WithDeploymentStatuses(opts ...func(*DeploymentStatusQuery)) *DeploymentQuery { @@ -496,10 +532,11 @@ func (dq *DeploymentQuery) sqlAll(ctx context.Context) ([]*Deployment, error) { var ( nodes = []*Deployment{} _spec = dq.querySpec() - loadedTypes = [5]bool{ + loadedTypes = [6]bool{ dq.withUser != nil, dq.withRepo != nil, dq.withApprovals != nil, + dq.withComments != nil, dq.withDeploymentStatuses != nil, dq.withEvent != nil, } @@ -604,6 +641,31 @@ func (dq *DeploymentQuery) sqlAll(ctx context.Context) ([]*Deployment, error) { } } + if query := dq.withComments; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Deployment) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Comments = []*Comment{} + } + query.Where(predicate.Comment(func(s *sql.Selector) { + s.Where(sql.InValues(deployment.CommentsColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.DeploymentID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "deployment_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.Comments = append(node.Edges.Comments, n) + } + } + if query := dq.withDeploymentStatuses; query != nil { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[int]*Deployment) diff --git a/ent/deployment_update.go b/ent/deployment_update.go index 756e0621..2f88c12b 100644 --- a/ent/deployment_update.go +++ b/ent/deployment_update.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/ent/approval" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/deploymentstatus" "github.com/gitploy-io/gitploy/ent/event" @@ -273,6 +274,21 @@ func (du *DeploymentUpdate) AddApprovals(a ...*Approval) *DeploymentUpdate { return du.AddApprovalIDs(ids...) } +// AddCommentIDs adds the "comments" edge to the Comment entity by IDs. +func (du *DeploymentUpdate) AddCommentIDs(ids ...int) *DeploymentUpdate { + du.mutation.AddCommentIDs(ids...) + return du +} + +// AddComments adds the "comments" edges to the Comment entity. +func (du *DeploymentUpdate) AddComments(c ...*Comment) *DeploymentUpdate { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return du.AddCommentIDs(ids...) +} + // AddDeploymentStatusIDs adds the "deployment_statuses" edge to the DeploymentStatus entity by IDs. func (du *DeploymentUpdate) AddDeploymentStatusIDs(ids ...int) *DeploymentUpdate { du.mutation.AddDeploymentStatusIDs(ids...) @@ -341,6 +357,27 @@ func (du *DeploymentUpdate) RemoveApprovals(a ...*Approval) *DeploymentUpdate { return du.RemoveApprovalIDs(ids...) } +// ClearComments clears all "comments" edges to the Comment entity. +func (du *DeploymentUpdate) ClearComments() *DeploymentUpdate { + du.mutation.ClearComments() + return du +} + +// RemoveCommentIDs removes the "comments" edge to Comment entities by IDs. +func (du *DeploymentUpdate) RemoveCommentIDs(ids ...int) *DeploymentUpdate { + du.mutation.RemoveCommentIDs(ids...) + return du +} + +// RemoveComments removes "comments" edges to Comment entities. +func (du *DeploymentUpdate) RemoveComments(c ...*Comment) *DeploymentUpdate { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return du.RemoveCommentIDs(ids...) +} + // ClearDeploymentStatuses clears all "deployment_statuses" edges to the DeploymentStatus entity. func (du *DeploymentUpdate) ClearDeploymentStatuses() *DeploymentUpdate { du.mutation.ClearDeploymentStatuses() @@ -757,6 +794,60 @@ func (du *DeploymentUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if du.mutation.CommentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deployment.CommentsTable, + Columns: []string{deployment.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := du.mutation.RemovedCommentsIDs(); len(nodes) > 0 && !du.mutation.CommentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deployment.CommentsTable, + Columns: []string{deployment.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := du.mutation.CommentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deployment.CommentsTable, + Columns: []string{deployment.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if du.mutation.DeploymentStatusesCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -1124,6 +1215,21 @@ func (duo *DeploymentUpdateOne) AddApprovals(a ...*Approval) *DeploymentUpdateOn return duo.AddApprovalIDs(ids...) } +// AddCommentIDs adds the "comments" edge to the Comment entity by IDs. +func (duo *DeploymentUpdateOne) AddCommentIDs(ids ...int) *DeploymentUpdateOne { + duo.mutation.AddCommentIDs(ids...) + return duo +} + +// AddComments adds the "comments" edges to the Comment entity. +func (duo *DeploymentUpdateOne) AddComments(c ...*Comment) *DeploymentUpdateOne { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return duo.AddCommentIDs(ids...) +} + // AddDeploymentStatusIDs adds the "deployment_statuses" edge to the DeploymentStatus entity by IDs. func (duo *DeploymentUpdateOne) AddDeploymentStatusIDs(ids ...int) *DeploymentUpdateOne { duo.mutation.AddDeploymentStatusIDs(ids...) @@ -1192,6 +1298,27 @@ func (duo *DeploymentUpdateOne) RemoveApprovals(a ...*Approval) *DeploymentUpdat return duo.RemoveApprovalIDs(ids...) } +// ClearComments clears all "comments" edges to the Comment entity. +func (duo *DeploymentUpdateOne) ClearComments() *DeploymentUpdateOne { + duo.mutation.ClearComments() + return duo +} + +// RemoveCommentIDs removes the "comments" edge to Comment entities by IDs. +func (duo *DeploymentUpdateOne) RemoveCommentIDs(ids ...int) *DeploymentUpdateOne { + duo.mutation.RemoveCommentIDs(ids...) + return duo +} + +// RemoveComments removes "comments" edges to Comment entities. +func (duo *DeploymentUpdateOne) RemoveComments(c ...*Comment) *DeploymentUpdateOne { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return duo.RemoveCommentIDs(ids...) +} + // ClearDeploymentStatuses clears all "deployment_statuses" edges to the DeploymentStatus entity. func (duo *DeploymentUpdateOne) ClearDeploymentStatuses() *DeploymentUpdateOne { duo.mutation.ClearDeploymentStatuses() @@ -1632,6 +1759,60 @@ func (duo *DeploymentUpdateOne) sqlSave(ctx context.Context) (_node *Deployment, } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if duo.mutation.CommentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deployment.CommentsTable, + Columns: []string{deployment.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := duo.mutation.RemovedCommentsIDs(); len(nodes) > 0 && !duo.mutation.CommentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deployment.CommentsTable, + Columns: []string{deployment.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := duo.mutation.CommentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deployment.CommentsTable, + Columns: []string{deployment.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if duo.mutation.DeploymentStatusesCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/ent/ent.go b/ent/ent.go index 6f6e854d..44a6183d 100644 --- a/ent/ent.go +++ b/ent/ent.go @@ -11,6 +11,7 @@ import ( "github.com/gitploy-io/gitploy/ent/approval" "github.com/gitploy-io/gitploy/ent/callback" "github.com/gitploy-io/gitploy/ent/chatuser" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/deploymentstatistics" "github.com/gitploy-io/gitploy/ent/deploymentstatus" @@ -43,6 +44,7 @@ func columnChecker(table string) func(string) error { approval.Table: approval.ValidColumn, callback.Table: callback.ValidColumn, chatuser.Table: chatuser.ValidColumn, + comment.Table: comment.ValidColumn, deployment.Table: deployment.ValidColumn, deploymentstatistics.Table: deploymentstatistics.ValidColumn, deploymentstatus.Table: deploymentstatus.ValidColumn, diff --git a/ent/hook/hook.go b/ent/hook/hook.go index 76577f9f..27cd4706 100644 --- a/ent/hook/hook.go +++ b/ent/hook/hook.go @@ -48,6 +48,19 @@ func (f ChatUserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, er return f(ctx, mv) } +// The CommentFunc type is an adapter to allow the use of ordinary +// function as Comment mutator. +type CommentFunc func(context.Context, *ent.CommentMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f CommentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.CommentMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CommentMutation", m) + } + return f(ctx, mv) +} + // The DeploymentFunc type is an adapter to allow the use of ordinary // function as Deployment mutator. type DeploymentFunc func(context.Context, *ent.DeploymentMutation) (ent.Value, error) diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go index fa9ba499..d6e26fd4 100644 --- a/ent/migrate/schema.go +++ b/ent/migrate/schema.go @@ -85,6 +85,36 @@ var ( }, }, } + // CommentsColumns holds the columns for the "comments" table. + CommentsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"approved", "rejected"}}, + {Name: "comment", Type: field.TypeString, Size: 2147483647}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "deployment_id", Type: field.TypeInt, Nullable: true}, + {Name: "user_id", Type: field.TypeInt64, Nullable: true}, + } + // CommentsTable holds the schema information for the "comments" table. + CommentsTable = &schema.Table{ + Name: "comments", + Columns: CommentsColumns, + PrimaryKey: []*schema.Column{CommentsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "comments_deployments_comments", + Columns: []*schema.Column{CommentsColumns[5]}, + RefColumns: []*schema.Column{DeploymentsColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "comments_users_comments", + Columns: []*schema.Column{CommentsColumns[6]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } // DeploymentsColumns holds the columns for the "deployments" table. DeploymentsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, @@ -416,6 +446,7 @@ var ( ApprovalsTable, CallbacksTable, ChatUsersTable, + CommentsTable, DeploymentsTable, DeploymentStatisticsTable, DeploymentStatusTable, @@ -433,6 +464,8 @@ func init() { ApprovalsTable.ForeignKeys[1].RefTable = UsersTable CallbacksTable.ForeignKeys[0].RefTable = ReposTable ChatUsersTable.ForeignKeys[0].RefTable = UsersTable + CommentsTable.ForeignKeys[0].RefTable = DeploymentsTable + CommentsTable.ForeignKeys[1].RefTable = UsersTable DeploymentsTable.ForeignKeys[0].RefTable = ReposTable DeploymentsTable.ForeignKeys[1].RefTable = UsersTable DeploymentStatisticsTable.ForeignKeys[0].RefTable = ReposTable diff --git a/ent/mutation.go b/ent/mutation.go index 1bb2c52d..c0f48498 100644 --- a/ent/mutation.go +++ b/ent/mutation.go @@ -11,6 +11,7 @@ import ( "github.com/gitploy-io/gitploy/ent/approval" "github.com/gitploy-io/gitploy/ent/callback" "github.com/gitploy-io/gitploy/ent/chatuser" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/deploymentstatistics" "github.com/gitploy-io/gitploy/ent/deploymentstatus" @@ -37,6 +38,7 @@ const ( TypeApproval = "Approval" TypeCallback = "Callback" TypeChatUser = "ChatUser" + TypeComment = "Comment" TypeDeployment = "Deployment" TypeDeploymentStatistics = "DeploymentStatistics" TypeDeploymentStatus = "DeploymentStatus" @@ -1988,6 +1990,671 @@ func (m *ChatUserMutation) ResetEdge(name string) error { return fmt.Errorf("unknown ChatUser edge %s", name) } +// CommentMutation represents an operation that mutates the Comment nodes in the graph. +type CommentMutation struct { + config + op Op + typ string + id *int + status *comment.Status + comment *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + user *int64 + cleareduser bool + deployment *int + cleareddeployment bool + done bool + oldValue func(context.Context) (*Comment, error) + predicates []predicate.Comment +} + +var _ ent.Mutation = (*CommentMutation)(nil) + +// commentOption allows management of the mutation configuration using functional options. +type commentOption func(*CommentMutation) + +// newCommentMutation creates new mutation for the Comment entity. +func newCommentMutation(c config, op Op, opts ...commentOption) *CommentMutation { + m := &CommentMutation{ + config: c, + op: op, + typ: TypeComment, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCommentID sets the ID field of the mutation. +func withCommentID(id int) commentOption { + return func(m *CommentMutation) { + var ( + err error + once sync.Once + value *Comment + ) + m.oldValue = func(ctx context.Context) (*Comment, error) { + once.Do(func() { + if m.done { + err = fmt.Errorf("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Comment.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withComment sets the old Comment of the mutation. +func withComment(node *Comment) commentOption { + return func(m *CommentMutation) { + m.oldValue = func(context.Context) (*Comment, 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 CommentMutation) 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 CommentMutation) 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 *CommentMutation) ID() (id int, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// SetStatus sets the "status" field. +func (m *CommentMutation) SetStatus(c comment.Status) { + m.status = &c +} + +// Status returns the value of the "status" field in the mutation. +func (m *CommentMutation) Status() (r comment.Status, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the Comment entity. +// If the Comment 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 *CommentMutation) OldStatus(ctx context.Context) (v comment.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *CommentMutation) ResetStatus() { + m.status = nil +} + +// SetComment sets the "comment" field. +func (m *CommentMutation) SetComment(s string) { + m.comment = &s +} + +// Comment returns the value of the "comment" field in the mutation. +func (m *CommentMutation) Comment() (r string, exists bool) { + v := m.comment + if v == nil { + return + } + return *v, true +} + +// OldComment returns the old "comment" field's value of the Comment entity. +// If the Comment 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 *CommentMutation) OldComment(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldComment is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldComment requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldComment: %w", err) + } + return oldValue.Comment, nil +} + +// ResetComment resets all changes to the "comment" field. +func (m *CommentMutation) ResetComment() { + m.comment = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *CommentMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *CommentMutation) 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 Comment entity. +// If the Comment 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 *CommentMutation) 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 *CommentMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *CommentMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *CommentMutation) 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 Comment entity. +// If the Comment 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 *CommentMutation) 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 *CommentMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetUserID sets the "user_id" field. +func (m *CommentMutation) SetUserID(i int64) { + m.user = &i +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *CommentMutation) UserID() (r int64, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the Comment entity. +// If the Comment 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 *CommentMutation) OldUserID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *CommentMutation) ResetUserID() { + m.user = nil +} + +// SetDeploymentID sets the "deployment_id" field. +func (m *CommentMutation) SetDeploymentID(i int) { + m.deployment = &i +} + +// DeploymentID returns the value of the "deployment_id" field in the mutation. +func (m *CommentMutation) DeploymentID() (r int, exists bool) { + v := m.deployment + if v == nil { + return + } + return *v, true +} + +// OldDeploymentID returns the old "deployment_id" field's value of the Comment entity. +// If the Comment 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 *CommentMutation) OldDeploymentID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, fmt.Errorf("OldDeploymentID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, fmt.Errorf("OldDeploymentID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeploymentID: %w", err) + } + return oldValue.DeploymentID, nil +} + +// ResetDeploymentID resets all changes to the "deployment_id" field. +func (m *CommentMutation) ResetDeploymentID() { + m.deployment = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *CommentMutation) ClearUser() { + m.cleareduser = true +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *CommentMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *CommentMutation) UserIDs() (ids []int64) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *CommentMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearDeployment clears the "deployment" edge to the Deployment entity. +func (m *CommentMutation) ClearDeployment() { + m.cleareddeployment = true +} + +// DeploymentCleared reports if the "deployment" edge to the Deployment entity was cleared. +func (m *CommentMutation) DeploymentCleared() bool { + return m.cleareddeployment +} + +// DeploymentIDs returns the "deployment" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// DeploymentID instead. It exists only for internal usage by the builders. +func (m *CommentMutation) DeploymentIDs() (ids []int) { + if id := m.deployment; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetDeployment resets all changes to the "deployment" edge. +func (m *CommentMutation) ResetDeployment() { + m.deployment = nil + m.cleareddeployment = false +} + +// Where appends a list predicates to the CommentMutation builder. +func (m *CommentMutation) Where(ps ...predicate.Comment) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *CommentMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (Comment). +func (m *CommentMutation) 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 *CommentMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.status != nil { + fields = append(fields, comment.FieldStatus) + } + if m.comment != nil { + fields = append(fields, comment.FieldComment) + } + if m.created_at != nil { + fields = append(fields, comment.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, comment.FieldUpdatedAt) + } + if m.user != nil { + fields = append(fields, comment.FieldUserID) + } + if m.deployment != nil { + fields = append(fields, comment.FieldDeploymentID) + } + 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 *CommentMutation) Field(name string) (ent.Value, bool) { + switch name { + case comment.FieldStatus: + return m.Status() + case comment.FieldComment: + return m.Comment() + case comment.FieldCreatedAt: + return m.CreatedAt() + case comment.FieldUpdatedAt: + return m.UpdatedAt() + case comment.FieldUserID: + return m.UserID() + case comment.FieldDeploymentID: + return m.DeploymentID() + } + 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 *CommentMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case comment.FieldStatus: + return m.OldStatus(ctx) + case comment.FieldComment: + return m.OldComment(ctx) + case comment.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case comment.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case comment.FieldUserID: + return m.OldUserID(ctx) + case comment.FieldDeploymentID: + return m.OldDeploymentID(ctx) + } + return nil, fmt.Errorf("unknown Comment 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 *CommentMutation) SetField(name string, value ent.Value) error { + switch name { + case comment.FieldStatus: + v, ok := value.(comment.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case comment.FieldComment: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetComment(v) + return nil + case comment.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 comment.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + case comment.FieldUserID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case comment.FieldDeploymentID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeploymentID(v) + return nil + } + return fmt.Errorf("unknown Comment field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CommentMutation) AddedFields() []string { + var fields []string + 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 *CommentMutation) AddedField(name string) (ent.Value, bool) { + switch name { + } + 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 *CommentMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Comment numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CommentMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CommentMutation) 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 *CommentMutation) ClearField(name string) error { + return fmt.Errorf("unknown Comment 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 *CommentMutation) ResetField(name string) error { + switch name { + case comment.FieldStatus: + m.ResetStatus() + return nil + case comment.FieldComment: + m.ResetComment() + return nil + case comment.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case comment.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case comment.FieldUserID: + m.ResetUserID() + return nil + case comment.FieldDeploymentID: + m.ResetDeploymentID() + return nil + } + return fmt.Errorf("unknown Comment field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CommentMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user != nil { + edges = append(edges, comment.EdgeUser) + } + if m.deployment != nil { + edges = append(edges, comment.EdgeDeployment) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CommentMutation) AddedIDs(name string) []ent.Value { + switch name { + case comment.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case comment.EdgeDeployment: + if id := m.deployment; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CommentMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *CommentMutation) RemovedIDs(name string) []ent.Value { + switch name { + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CommentMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser { + edges = append(edges, comment.EdgeUser) + } + if m.cleareddeployment { + edges = append(edges, comment.EdgeDeployment) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CommentMutation) EdgeCleared(name string) bool { + switch name { + case comment.EdgeUser: + return m.cleareduser + case comment.EdgeDeployment: + return m.cleareddeployment + } + 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 *CommentMutation) ClearEdge(name string) error { + switch name { + case comment.EdgeUser: + m.ClearUser() + return nil + case comment.EdgeDeployment: + m.ClearDeployment() + return nil + } + return fmt.Errorf("unknown Comment 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 *CommentMutation) ResetEdge(name string) error { + switch name { + case comment.EdgeUser: + m.ResetUser() + return nil + case comment.EdgeDeployment: + m.ResetDeployment() + return nil + } + return fmt.Errorf("unknown Comment edge %s", name) +} + // DeploymentMutation represents an operation that mutates the Deployment nodes in the graph. type DeploymentMutation struct { config @@ -2019,6 +2686,9 @@ type DeploymentMutation struct { approvals map[int]struct{} removedapprovals map[int]struct{} clearedapprovals bool + comments map[int]struct{} + removedcomments map[int]struct{} + clearedcomments bool deployment_statuses map[int]struct{} removeddeployment_statuses map[int]struct{} cleareddeployment_statuses bool @@ -2891,6 +3561,60 @@ func (m *DeploymentMutation) ResetApprovals() { m.removedapprovals = nil } +// AddCommentIDs adds the "comments" edge to the Comment entity by ids. +func (m *DeploymentMutation) AddCommentIDs(ids ...int) { + if m.comments == nil { + m.comments = make(map[int]struct{}) + } + for i := range ids { + m.comments[ids[i]] = struct{}{} + } +} + +// ClearComments clears the "comments" edge to the Comment entity. +func (m *DeploymentMutation) ClearComments() { + m.clearedcomments = true +} + +// CommentsCleared reports if the "comments" edge to the Comment entity was cleared. +func (m *DeploymentMutation) CommentsCleared() bool { + return m.clearedcomments +} + +// RemoveCommentIDs removes the "comments" edge to the Comment entity by IDs. +func (m *DeploymentMutation) RemoveCommentIDs(ids ...int) { + if m.removedcomments == nil { + m.removedcomments = make(map[int]struct{}) + } + for i := range ids { + delete(m.comments, ids[i]) + m.removedcomments[ids[i]] = struct{}{} + } +} + +// RemovedComments returns the removed IDs of the "comments" edge to the Comment entity. +func (m *DeploymentMutation) RemovedCommentsIDs() (ids []int) { + for id := range m.removedcomments { + ids = append(ids, id) + } + return +} + +// CommentsIDs returns the "comments" edge IDs in the mutation. +func (m *DeploymentMutation) CommentsIDs() (ids []int) { + for id := range m.comments { + ids = append(ids, id) + } + return +} + +// ResetComments resets all changes to the "comments" edge. +func (m *DeploymentMutation) ResetComments() { + m.comments = nil + m.clearedcomments = false + m.removedcomments = nil +} + // AddDeploymentStatusIDs adds the "deployment_statuses" edge to the DeploymentStatus entity by ids. func (m *DeploymentMutation) AddDeploymentStatusIDs(ids ...int) { if m.deployment_statuses == nil { @@ -3432,7 +4156,7 @@ func (m *DeploymentMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *DeploymentMutation) AddedEdges() []string { - edges := make([]string, 0, 5) + edges := make([]string, 0, 6) if m.user != nil { edges = append(edges, deployment.EdgeUser) } @@ -3442,6 +4166,9 @@ func (m *DeploymentMutation) AddedEdges() []string { if m.approvals != nil { edges = append(edges, deployment.EdgeApprovals) } + if m.comments != nil { + edges = append(edges, deployment.EdgeComments) + } if m.deployment_statuses != nil { edges = append(edges, deployment.EdgeDeploymentStatuses) } @@ -3469,6 +4196,12 @@ func (m *DeploymentMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case deployment.EdgeComments: + ids := make([]ent.Value, 0, len(m.comments)) + for id := range m.comments { + ids = append(ids, id) + } + return ids case deployment.EdgeDeploymentStatuses: ids := make([]ent.Value, 0, len(m.deployment_statuses)) for id := range m.deployment_statuses { @@ -3487,10 +4220,13 @@ func (m *DeploymentMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *DeploymentMutation) RemovedEdges() []string { - edges := make([]string, 0, 5) + edges := make([]string, 0, 6) if m.removedapprovals != nil { edges = append(edges, deployment.EdgeApprovals) } + if m.removedcomments != nil { + edges = append(edges, deployment.EdgeComments) + } if m.removeddeployment_statuses != nil { edges = append(edges, deployment.EdgeDeploymentStatuses) } @@ -3510,6 +4246,12 @@ func (m *DeploymentMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case deployment.EdgeComments: + ids := make([]ent.Value, 0, len(m.removedcomments)) + for id := range m.removedcomments { + ids = append(ids, id) + } + return ids case deployment.EdgeDeploymentStatuses: ids := make([]ent.Value, 0, len(m.removeddeployment_statuses)) for id := range m.removeddeployment_statuses { @@ -3528,7 +4270,7 @@ func (m *DeploymentMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *DeploymentMutation) ClearedEdges() []string { - edges := make([]string, 0, 5) + edges := make([]string, 0, 6) if m.cleareduser { edges = append(edges, deployment.EdgeUser) } @@ -3538,6 +4280,9 @@ func (m *DeploymentMutation) ClearedEdges() []string { if m.clearedapprovals { edges = append(edges, deployment.EdgeApprovals) } + if m.clearedcomments { + edges = append(edges, deployment.EdgeComments) + } if m.cleareddeployment_statuses { edges = append(edges, deployment.EdgeDeploymentStatuses) } @@ -3557,6 +4302,8 @@ func (m *DeploymentMutation) EdgeCleared(name string) bool { return m.clearedrepo case deployment.EdgeApprovals: return m.clearedapprovals + case deployment.EdgeComments: + return m.clearedcomments case deployment.EdgeDeploymentStatuses: return m.cleareddeployment_statuses case deployment.EdgeEvent: @@ -3592,6 +4339,9 @@ func (m *DeploymentMutation) ResetEdge(name string) error { case deployment.EdgeApprovals: m.ResetApprovals() return nil + case deployment.EdgeComments: + m.ResetComments() + return nil case deployment.EdgeDeploymentStatuses: m.ResetDeploymentStatuses() return nil @@ -9132,6 +9882,9 @@ type UserMutation struct { approvals map[int]struct{} removedapprovals map[int]struct{} clearedapprovals bool + comments map[int]struct{} + removedcomments map[int]struct{} + clearedcomments bool locks map[int]struct{} removedlocks map[int]struct{} clearedlocks bool @@ -9750,6 +10503,60 @@ func (m *UserMutation) ResetApprovals() { m.removedapprovals = nil } +// AddCommentIDs adds the "comments" edge to the Comment entity by ids. +func (m *UserMutation) AddCommentIDs(ids ...int) { + if m.comments == nil { + m.comments = make(map[int]struct{}) + } + for i := range ids { + m.comments[ids[i]] = struct{}{} + } +} + +// ClearComments clears the "comments" edge to the Comment entity. +func (m *UserMutation) ClearComments() { + m.clearedcomments = true +} + +// CommentsCleared reports if the "comments" edge to the Comment entity was cleared. +func (m *UserMutation) CommentsCleared() bool { + return m.clearedcomments +} + +// RemoveCommentIDs removes the "comments" edge to the Comment entity by IDs. +func (m *UserMutation) RemoveCommentIDs(ids ...int) { + if m.removedcomments == nil { + m.removedcomments = make(map[int]struct{}) + } + for i := range ids { + delete(m.comments, ids[i]) + m.removedcomments[ids[i]] = struct{}{} + } +} + +// RemovedComments returns the removed IDs of the "comments" edge to the Comment entity. +func (m *UserMutation) RemovedCommentsIDs() (ids []int) { + for id := range m.removedcomments { + ids = append(ids, id) + } + return +} + +// CommentsIDs returns the "comments" edge IDs in the mutation. +func (m *UserMutation) CommentsIDs() (ids []int) { + for id := range m.comments { + ids = append(ids, id) + } + return +} + +// ResetComments resets all changes to the "comments" edge. +func (m *UserMutation) ResetComments() { + m.comments = nil + m.clearedcomments = false + m.removedcomments = nil +} + // AddLockIDs adds the "locks" edge to the Lock entity by ids. func (m *UserMutation) AddLockIDs(ids ...int) { if m.locks == nil { @@ -10058,7 +10865,7 @@ func (m *UserMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 5) + edges := make([]string, 0, 6) if m.chat_user != nil { edges = append(edges, user.EdgeChatUser) } @@ -10071,6 +10878,9 @@ func (m *UserMutation) AddedEdges() []string { if m.approvals != nil { edges = append(edges, user.EdgeApprovals) } + if m.comments != nil { + edges = append(edges, user.EdgeComments) + } if m.locks != nil { edges = append(edges, user.EdgeLocks) } @@ -10103,6 +10913,12 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeComments: + ids := make([]ent.Value, 0, len(m.comments)) + for id := range m.comments { + ids = append(ids, id) + } + return ids case user.EdgeLocks: ids := make([]ent.Value, 0, len(m.locks)) for id := range m.locks { @@ -10115,7 +10931,7 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 5) + edges := make([]string, 0, 6) if m.removedperms != nil { edges = append(edges, user.EdgePerms) } @@ -10125,6 +10941,9 @@ func (m *UserMutation) RemovedEdges() []string { if m.removedapprovals != nil { edges = append(edges, user.EdgeApprovals) } + if m.removedcomments != nil { + edges = append(edges, user.EdgeComments) + } if m.removedlocks != nil { edges = append(edges, user.EdgeLocks) } @@ -10153,6 +10972,12 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeComments: + ids := make([]ent.Value, 0, len(m.removedcomments)) + for id := range m.removedcomments { + ids = append(ids, id) + } + return ids case user.EdgeLocks: ids := make([]ent.Value, 0, len(m.removedlocks)) for id := range m.removedlocks { @@ -10165,7 +10990,7 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 5) + edges := make([]string, 0, 6) if m.clearedchat_user { edges = append(edges, user.EdgeChatUser) } @@ -10178,6 +11003,9 @@ func (m *UserMutation) ClearedEdges() []string { if m.clearedapprovals { edges = append(edges, user.EdgeApprovals) } + if m.clearedcomments { + edges = append(edges, user.EdgeComments) + } if m.clearedlocks { edges = append(edges, user.EdgeLocks) } @@ -10196,6 +11024,8 @@ func (m *UserMutation) EdgeCleared(name string) bool { return m.cleareddeployments case user.EdgeApprovals: return m.clearedapprovals + case user.EdgeComments: + return m.clearedcomments case user.EdgeLocks: return m.clearedlocks } @@ -10229,6 +11059,9 @@ func (m *UserMutation) ResetEdge(name string) error { case user.EdgeApprovals: m.ResetApprovals() return nil + case user.EdgeComments: + m.ResetComments() + return nil case user.EdgeLocks: m.ResetLocks() return nil diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go index 1c6cf729..f8354373 100644 --- a/ent/predicate/predicate.go +++ b/ent/predicate/predicate.go @@ -15,6 +15,9 @@ type Callback func(*sql.Selector) // ChatUser is the predicate function for chatuser builders. type ChatUser func(*sql.Selector) +// Comment is the predicate function for comment builders. +type Comment func(*sql.Selector) + // Deployment is the predicate function for deployment builders. type Deployment func(*sql.Selector) diff --git a/ent/runtime.go b/ent/runtime.go index da22dd25..d8112ed5 100644 --- a/ent/runtime.go +++ b/ent/runtime.go @@ -8,6 +8,7 @@ import ( "github.com/gitploy-io/gitploy/ent/approval" "github.com/gitploy-io/gitploy/ent/callback" "github.com/gitploy-io/gitploy/ent/chatuser" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/deploymentstatistics" "github.com/gitploy-io/gitploy/ent/deploymentstatus" @@ -63,6 +64,18 @@ func init() { chatuser.DefaultUpdatedAt = chatuserDescUpdatedAt.Default.(func() time.Time) // chatuser.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. chatuser.UpdateDefaultUpdatedAt = chatuserDescUpdatedAt.UpdateDefault.(func() time.Time) + commentFields := schema.Comment{}.Fields() + _ = commentFields + // commentDescCreatedAt is the schema descriptor for created_at field. + commentDescCreatedAt := commentFields[2].Descriptor() + // comment.DefaultCreatedAt holds the default value on creation for the created_at field. + comment.DefaultCreatedAt = commentDescCreatedAt.Default.(func() time.Time) + // commentDescUpdatedAt is the schema descriptor for updated_at field. + commentDescUpdatedAt := commentFields[3].Descriptor() + // comment.DefaultUpdatedAt holds the default value on creation for the updated_at field. + comment.DefaultUpdatedAt = commentDescUpdatedAt.Default.(func() time.Time) + // comment.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + comment.UpdateDefaultUpdatedAt = commentDescUpdatedAt.UpdateDefault.(func() time.Time) deploymentFields := schema.Deployment{}.Fields() _ = deploymentFields // deploymentDescHTMLURL is the schema descriptor for html_url field. diff --git a/ent/schema/comment.go b/ent/schema/comment.go new file mode 100644 index 00000000..45bcb92a --- /dev/null +++ b/ent/schema/comment.go @@ -0,0 +1,48 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Comment holds the schema definition for the Comment entity. +type Comment struct { + ent.Schema +} + +// Fields of the Comment. +func (Comment) Fields() []ent.Field { + return []ent.Field{ + field.Enum("status"). + Values( + "approved", + "rejected", + ), + field.Text("comment"), + field.Time("created_at"). + Default(nowUTC), + field.Time("updated_at"). + Default(nowUTC). + UpdateDefault(nowUTC), + // Edges + field.Int64("user_id"), + field.Int("deployment_id"), + } +} + +// Edges of the Comment. +func (Comment) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("user", User.Type). + Ref("comments"). + Field("user_id"). + Unique(). + Required(), + edge.From("deployment", Deployment.Type). + Ref("comments"). + Field("deployment_id"). + Unique(). + Required(), + } +} diff --git a/ent/schema/deployment.go b/ent/schema/deployment.go index 54f4c020..02d7bfa1 100644 --- a/ent/schema/deployment.go +++ b/ent/schema/deployment.go @@ -81,6 +81,10 @@ func (Deployment) Edges() []ent.Edge { Annotations(entsql.Annotation{ OnDelete: entsql.Cascade, }), + edge.To("comments", Comment.Type). + Annotations(entsql.Annotation{ + OnDelete: entsql.Cascade, + }), edge.To("deployment_statuses", DeploymentStatus.Type). Annotations(entsql.Annotation{ OnDelete: entsql.Cascade, diff --git a/ent/schema/user.go b/ent/schema/user.go index 0b15689d..3064d6bc 100644 --- a/ent/schema/user.go +++ b/ent/schema/user.go @@ -53,6 +53,7 @@ func (User) Edges() []ent.Edge { }), edge.To("deployments", Deployment.Type), edge.To("approvals", Approval.Type), + edge.To("comments", Comment.Type), edge.To("locks", Lock.Type), } } diff --git a/ent/tx.go b/ent/tx.go index ee298594..c1cacfc5 100644 --- a/ent/tx.go +++ b/ent/tx.go @@ -18,6 +18,8 @@ type Tx struct { Callback *CallbackClient // ChatUser is the client for interacting with the ChatUser builders. ChatUser *ChatUserClient + // Comment is the client for interacting with the Comment builders. + Comment *CommentClient // Deployment is the client for interacting with the Deployment builders. Deployment *DeploymentClient // DeploymentStatistics is the client for interacting with the DeploymentStatistics builders. @@ -174,6 +176,7 @@ func (tx *Tx) init() { tx.Approval = NewApprovalClient(tx.config) tx.Callback = NewCallbackClient(tx.config) tx.ChatUser = NewChatUserClient(tx.config) + tx.Comment = NewCommentClient(tx.config) tx.Deployment = NewDeploymentClient(tx.config) tx.DeploymentStatistics = NewDeploymentStatisticsClient(tx.config) tx.DeploymentStatus = NewDeploymentStatusClient(tx.config) diff --git a/ent/user.go b/ent/user.go index 64e13632..1585c91c 100644 --- a/ent/user.go +++ b/ent/user.go @@ -50,11 +50,13 @@ type UserEdges struct { Deployments []*Deployment `json:"deployments,omitempty"` // Approvals holds the value of the approvals edge. Approvals []*Approval `json:"approvals,omitempty"` + // Comments holds the value of the comments edge. + Comments []*Comment `json:"comments,omitempty"` // Locks holds the value of the locks edge. Locks []*Lock `json:"locks,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [5]bool + loadedTypes [6]bool } // ChatUserOrErr returns the ChatUser value or an error if the edge @@ -98,10 +100,19 @@ func (e UserEdges) ApprovalsOrErr() ([]*Approval, error) { return nil, &NotLoadedError{edge: "approvals"} } +// CommentsOrErr returns the Comments value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) CommentsOrErr() ([]*Comment, error) { + if e.loadedTypes[4] { + return e.Comments, nil + } + return nil, &NotLoadedError{edge: "comments"} +} + // LocksOrErr returns the Locks value or an error if the edge // was not loaded in eager-loading. func (e UserEdges) LocksOrErr() ([]*Lock, error) { - if e.loadedTypes[4] { + if e.loadedTypes[5] { return e.Locks, nil } return nil, &NotLoadedError{edge: "locks"} @@ -220,6 +231,11 @@ func (u *User) QueryApprovals() *ApprovalQuery { return (&UserClient{config: u.config}).QueryApprovals(u) } +// QueryComments queries the "comments" edge of the User entity. +func (u *User) QueryComments() *CommentQuery { + return (&UserClient{config: u.config}).QueryComments(u) +} + // QueryLocks queries the "locks" edge of the User entity. func (u *User) QueryLocks() *LockQuery { return (&UserClient{config: u.config}).QueryLocks(u) diff --git a/ent/user/user.go b/ent/user/user.go index 4848ee67..8edd93ef 100644 --- a/ent/user/user.go +++ b/ent/user/user.go @@ -37,6 +37,8 @@ const ( EdgeDeployments = "deployments" // EdgeApprovals holds the string denoting the approvals edge name in mutations. EdgeApprovals = "approvals" + // EdgeComments holds the string denoting the comments edge name in mutations. + EdgeComments = "comments" // EdgeLocks holds the string denoting the locks edge name in mutations. EdgeLocks = "locks" // Table holds the table name of the user in the database. @@ -69,6 +71,13 @@ const ( ApprovalsInverseTable = "approvals" // ApprovalsColumn is the table column denoting the approvals relation/edge. ApprovalsColumn = "user_id" + // CommentsTable is the table that holds the comments relation/edge. + CommentsTable = "comments" + // CommentsInverseTable is the table name for the Comment entity. + // It exists in this package in order to avoid circular dependency with the "comment" package. + CommentsInverseTable = "comments" + // CommentsColumn is the table column denoting the comments relation/edge. + CommentsColumn = "user_id" // LocksTable is the table that holds the locks relation/edge. LocksTable = "locks" // LocksInverseTable is the table name for the Lock entity. diff --git a/ent/user/where.go b/ent/user/where.go index 633314ee..51c6a959 100644 --- a/ent/user/where.go +++ b/ent/user/where.go @@ -1065,6 +1065,34 @@ func HasApprovalsWith(preds ...predicate.Approval) predicate.User { }) } +// HasComments applies the HasEdge predicate on the "comments" edge. +func HasComments() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CommentsTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CommentsTable, CommentsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCommentsWith applies the HasEdge predicate on the "comments" edge with a given conditions (other predicates). +func HasCommentsWith(preds ...predicate.Comment) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CommentsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, CommentsTable, CommentsColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasLocks applies the HasEdge predicate on the "locks" edge. func HasLocks() predicate.User { return predicate.User(func(s *sql.Selector) { diff --git a/ent/user_create.go b/ent/user_create.go index d0177f13..836e06e0 100644 --- a/ent/user_create.go +++ b/ent/user_create.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/ent/approval" "github.com/gitploy-io/gitploy/ent/chatuser" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/lock" "github.com/gitploy-io/gitploy/ent/perm" @@ -181,6 +182,21 @@ func (uc *UserCreate) AddApprovals(a ...*Approval) *UserCreate { return uc.AddApprovalIDs(ids...) } +// AddCommentIDs adds the "comments" edge to the Comment entity by IDs. +func (uc *UserCreate) AddCommentIDs(ids ...int) *UserCreate { + uc.mutation.AddCommentIDs(ids...) + return uc +} + +// AddComments adds the "comments" edges to the Comment entity. +func (uc *UserCreate) AddComments(c ...*Comment) *UserCreate { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return uc.AddCommentIDs(ids...) +} + // AddLockIDs adds the "locks" edge to the Lock entity by IDs. func (uc *UserCreate) AddLockIDs(ids ...int) *UserCreate { uc.mutation.AddLockIDs(ids...) @@ -495,6 +511,25 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := uc.mutation.CommentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.CommentsTable, + Columns: []string{user.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } if nodes := uc.mutation.LocksIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/ent/user_query.go b/ent/user_query.go index 55231f89..2622304e 100644 --- a/ent/user_query.go +++ b/ent/user_query.go @@ -15,6 +15,7 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/ent/approval" "github.com/gitploy-io/gitploy/ent/chatuser" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/lock" "github.com/gitploy-io/gitploy/ent/perm" @@ -36,6 +37,7 @@ type UserQuery struct { withPerms *PermQuery withDeployments *DeploymentQuery withApprovals *ApprovalQuery + withComments *CommentQuery withLocks *LockQuery modifiers []func(s *sql.Selector) // intermediate query (i.e. traversal path). @@ -162,6 +164,28 @@ func (uq *UserQuery) QueryApprovals() *ApprovalQuery { return query } +// QueryComments chains the current query on the "comments" edge. +func (uq *UserQuery) QueryComments() *CommentQuery { + query := &CommentQuery{config: uq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(comment.Table, comment.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.CommentsTable, user.CommentsColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryLocks chains the current query on the "locks" edge. func (uq *UserQuery) QueryLocks() *LockQuery { query := &LockQuery{config: uq.config} @@ -369,6 +393,7 @@ func (uq *UserQuery) Clone() *UserQuery { withPerms: uq.withPerms.Clone(), withDeployments: uq.withDeployments.Clone(), withApprovals: uq.withApprovals.Clone(), + withComments: uq.withComments.Clone(), withLocks: uq.withLocks.Clone(), // clone intermediate query. sql: uq.sql.Clone(), @@ -420,6 +445,17 @@ func (uq *UserQuery) WithApprovals(opts ...func(*ApprovalQuery)) *UserQuery { return uq } +// WithComments tells the query-builder to eager-load the nodes that are connected to +// the "comments" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithComments(opts ...func(*CommentQuery)) *UserQuery { + query := &CommentQuery{config: uq.config} + for _, opt := range opts { + opt(query) + } + uq.withComments = query + return uq +} + // WithLocks tells the query-builder to eager-load the nodes that are connected to // the "locks" edge. The optional arguments are used to configure the query builder of the edge. func (uq *UserQuery) WithLocks(opts ...func(*LockQuery)) *UserQuery { @@ -496,11 +532,12 @@ func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) { var ( nodes = []*User{} _spec = uq.querySpec() - loadedTypes = [5]bool{ + loadedTypes = [6]bool{ uq.withChatUser != nil, uq.withPerms != nil, uq.withDeployments != nil, uq.withApprovals != nil, + uq.withComments != nil, uq.withLocks != nil, } ) @@ -626,6 +663,31 @@ func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) { } } + if query := uq.withComments; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int64]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Comments = []*Comment{} + } + query.Where(predicate.Comment(func(s *sql.Selector) { + s.Where(sql.InValues(user.CommentsColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.Comments = append(node.Edges.Comments, n) + } + } + if query := uq.withLocks; query != nil { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[int64]*User) diff --git a/ent/user_update.go b/ent/user_update.go index 351b885c..755007ed 100644 --- a/ent/user_update.go +++ b/ent/user_update.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/ent/approval" "github.com/gitploy-io/gitploy/ent/chatuser" + "github.com/gitploy-io/gitploy/ent/comment" "github.com/gitploy-io/gitploy/ent/deployment" "github.com/gitploy-io/gitploy/ent/lock" "github.com/gitploy-io/gitploy/ent/perm" @@ -160,6 +161,21 @@ func (uu *UserUpdate) AddApprovals(a ...*Approval) *UserUpdate { return uu.AddApprovalIDs(ids...) } +// AddCommentIDs adds the "comments" edge to the Comment entity by IDs. +func (uu *UserUpdate) AddCommentIDs(ids ...int) *UserUpdate { + uu.mutation.AddCommentIDs(ids...) + return uu +} + +// AddComments adds the "comments" edges to the Comment entity. +func (uu *UserUpdate) AddComments(c ...*Comment) *UserUpdate { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return uu.AddCommentIDs(ids...) +} + // AddLockIDs adds the "locks" edge to the Lock entity by IDs. func (uu *UserUpdate) AddLockIDs(ids ...int) *UserUpdate { uu.mutation.AddLockIDs(ids...) @@ -249,6 +265,27 @@ func (uu *UserUpdate) RemoveApprovals(a ...*Approval) *UserUpdate { return uu.RemoveApprovalIDs(ids...) } +// ClearComments clears all "comments" edges to the Comment entity. +func (uu *UserUpdate) ClearComments() *UserUpdate { + uu.mutation.ClearComments() + return uu +} + +// RemoveCommentIDs removes the "comments" edge to Comment entities by IDs. +func (uu *UserUpdate) RemoveCommentIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveCommentIDs(ids...) + return uu +} + +// RemoveComments removes "comments" edges to Comment entities. +func (uu *UserUpdate) RemoveComments(c ...*Comment) *UserUpdate { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return uu.RemoveCommentIDs(ids...) +} + // ClearLocks clears all "locks" edges to the Lock entity. func (uu *UserUpdate) ClearLocks() *UserUpdate { uu.mutation.ClearLocks() @@ -604,6 +641,60 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uu.mutation.CommentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.CommentsTable, + Columns: []string{user.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedCommentsIDs(); len(nodes) > 0 && !uu.mutation.CommentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.CommentsTable, + Columns: []string{user.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.CommentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.CommentsTable, + Columns: []string{user.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if uu.mutation.LocksCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -805,6 +896,21 @@ func (uuo *UserUpdateOne) AddApprovals(a ...*Approval) *UserUpdateOne { return uuo.AddApprovalIDs(ids...) } +// AddCommentIDs adds the "comments" edge to the Comment entity by IDs. +func (uuo *UserUpdateOne) AddCommentIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddCommentIDs(ids...) + return uuo +} + +// AddComments adds the "comments" edges to the Comment entity. +func (uuo *UserUpdateOne) AddComments(c ...*Comment) *UserUpdateOne { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return uuo.AddCommentIDs(ids...) +} + // AddLockIDs adds the "locks" edge to the Lock entity by IDs. func (uuo *UserUpdateOne) AddLockIDs(ids ...int) *UserUpdateOne { uuo.mutation.AddLockIDs(ids...) @@ -894,6 +1000,27 @@ func (uuo *UserUpdateOne) RemoveApprovals(a ...*Approval) *UserUpdateOne { return uuo.RemoveApprovalIDs(ids...) } +// ClearComments clears all "comments" edges to the Comment entity. +func (uuo *UserUpdateOne) ClearComments() *UserUpdateOne { + uuo.mutation.ClearComments() + return uuo +} + +// RemoveCommentIDs removes the "comments" edge to Comment entities by IDs. +func (uuo *UserUpdateOne) RemoveCommentIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveCommentIDs(ids...) + return uuo +} + +// RemoveComments removes "comments" edges to Comment entities. +func (uuo *UserUpdateOne) RemoveComments(c ...*Comment) *UserUpdateOne { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return uuo.RemoveCommentIDs(ids...) +} + // ClearLocks clears all "locks" edges to the Lock entity. func (uuo *UserUpdateOne) ClearLocks() *UserUpdateOne { uuo.mutation.ClearLocks() @@ -1273,6 +1400,60 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uuo.mutation.CommentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.CommentsTable, + Columns: []string{user.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedCommentsIDs(); len(nodes) > 0 && !uuo.mutation.CommentsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.CommentsTable, + Columns: []string{user.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.CommentsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.CommentsTable, + Columns: []string{user.CommentsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: comment.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if uuo.mutation.LocksCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/internal/interactor/interface.go b/internal/interactor/interface.go index 44cb915a..3804c909 100644 --- a/internal/interactor/interface.go +++ b/internal/interactor/interface.go @@ -78,6 +78,10 @@ type ( UpdateApproval(ctx context.Context, a *ent.Approval) (*ent.Approval, error) DeleteApproval(ctx context.Context, a *ent.Approval) error + ListCommentsOfDeployment(ctx context.Context, d *ent.Deployment) ([]*ent.Comment, error) + FindCommentByID(ctx context.Context, id int) (*ent.Comment, error) + CreateComment(ctx context.Context, cmt *ent.Comment) (*ent.Comment, error) + ListExpiredLocksLessThanTime(ctx context.Context, t time.Time) ([]*ent.Lock, error) ListLocksOfRepo(ctx context.Context, r *ent.Repo) ([]*ent.Lock, error) FindLockOfRepoByEnv(ctx context.Context, r *ent.Repo, env string) (*ent.Lock, error) diff --git a/internal/interactor/mock/pkg.go b/internal/interactor/mock/pkg.go index 940bb143..03ca36de 100644 --- a/internal/interactor/mock/pkg.go +++ b/internal/interactor/mock/pkg.go @@ -173,6 +173,21 @@ func (mr *MockStoreMockRecorder) CreateChatUser(ctx, cu interface{}) *gomock.Cal return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateChatUser", reflect.TypeOf((*MockStore)(nil).CreateChatUser), ctx, cu) } +// CreateComment mocks base method. +func (m *MockStore) CreateComment(ctx context.Context, cmt *ent.Comment) (*ent.Comment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateComment", ctx, cmt) + ret0, _ := ret[0].(*ent.Comment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateComment indicates an expected call of CreateComment. +func (mr *MockStoreMockRecorder) CreateComment(ctx, cmt interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateComment", reflect.TypeOf((*MockStore)(nil).CreateComment), ctx, cmt) +} + // CreateDeployment mocks base method. func (m *MockStore) CreateDeployment(ctx context.Context, d *ent.Deployment) (*ent.Deployment, error) { m.ctrl.T.Helper() @@ -424,6 +439,21 @@ func (mr *MockStoreMockRecorder) FindChatUserByID(ctx, id interface{}) *gomock.C return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindChatUserByID", reflect.TypeOf((*MockStore)(nil).FindChatUserByID), ctx, id) } +// FindCommentByID mocks base method. +func (m *MockStore) FindCommentByID(ctx context.Context, id int) (*ent.Comment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindCommentByID", ctx, id) + ret0, _ := ret[0].(*ent.Comment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindCommentByID indicates an expected call of FindCommentByID. +func (mr *MockStoreMockRecorder) FindCommentByID(ctx, id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindCommentByID", reflect.TypeOf((*MockStore)(nil).FindCommentByID), ctx, id) +} + // FindDeploymentByID mocks base method. func (m *MockStore) FindDeploymentByID(ctx context.Context, id int) (*ent.Deployment, error) { m.ctrl.T.Helper() @@ -694,6 +724,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) } +// ListCommentsOfDeployment mocks base method. +func (m *MockStore) ListCommentsOfDeployment(ctx context.Context, d *ent.Deployment) ([]*ent.Comment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListCommentsOfDeployment", ctx, d) + ret0, _ := ret[0].([]*ent.Comment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListCommentsOfDeployment indicates an expected call of ListCommentsOfDeployment. +func (mr *MockStoreMockRecorder) ListCommentsOfDeployment(ctx, d interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListCommentsOfDeployment", reflect.TypeOf((*MockStore)(nil).ListCommentsOfDeployment), ctx, d) +} + // ListDeploymentStatisticsGreaterThanTime mocks base method. func (m *MockStore) ListDeploymentStatisticsGreaterThanTime(ctx context.Context, updated time.Time) ([]*ent.DeploymentStatistics, error) { m.ctrl.T.Helper() diff --git a/internal/pkg/store/comment.go b/internal/pkg/store/comment.go new file mode 100644 index 00000000..c4a1ba50 --- /dev/null +++ b/internal/pkg/store/comment.go @@ -0,0 +1,58 @@ +package store + +import ( + "context" + + "github.com/gitploy-io/gitploy/ent" + "github.com/gitploy-io/gitploy/ent/comment" + "github.com/gitploy-io/gitploy/pkg/e" +) + +func (s *Store) ListCommentsOfDeployment(ctx context.Context, d *ent.Deployment) ([]*ent.Comment, error) { + cmts, err := s.c.Comment. + Query(). + Where( + comment.DeploymentIDEQ(d.ID), + ). + WithDeployment(). + WithUser(). + All(ctx) + if err != nil { + return nil, e.NewError(e.ErrorCodeInternalError, err) + } + + return cmts, nil +} + +func (s *Store) FindCommentByID(ctx context.Context, id int) (*ent.Comment, error) { + cmt, err := s.c.Comment. + Query(). + Where( + comment.IDEQ(id), + ). + WithDeployment(). + WithUser(). + Only(ctx) + if ent.IsNotFound(err) { + return nil, e.NewErrorWithMessage(e.ErrorCodeNotFound, "The comment is not found.", err) + } else if err != nil { + return nil, e.NewError(e.ErrorCodeInternalError, err) + } + + return cmt, nil +} + +func (s *Store) CreateComment(ctx context.Context, cmt *ent.Comment) (*ent.Comment, error) { + cmt, err := s.c.Comment. + Create(). + SetStatus(cmt.Status). + SetComment(cmt.Comment). + SetUserID(cmt.UserID). + SetDeploymentID(cmt.DeploymentID). + Save(ctx) + if err != nil { + return nil, e.NewError(e.ErrorCodeInternalError, err) + } + + return cmt, nil +} diff --git a/internal/pkg/store/deployment.go b/internal/pkg/store/deployment.go index 3e386f02..c0c31eac 100644 --- a/internal/pkg/store/deployment.go +++ b/internal/pkg/store/deployment.go @@ -150,7 +150,7 @@ func (s *Store) FindDeploymentByID(ctx context.Context, id int) (*ent.Deployment } func (s *Store) FindDeploymentOfRepoByNumber(ctx context.Context, r *ent.Repo, number int) (*ent.Deployment, error) { - return s.c.Deployment. + d, err := s.c.Deployment. Query(). Where( deployment.And( @@ -162,6 +162,11 @@ func (s *Store) FindDeploymentOfRepoByNumber(ctx context.Context, r *ent.Repo, n WithUser(). WithDeploymentStatuses(). First(ctx) + if ent.IsNotFound(err) { + return nil, e.NewErrorWithMessage(e.ErrorCodeNotFound, "The deployment is not found.", err) + } + + return d, nil } func (s *Store) FindDeploymentByUID(ctx context.Context, uid int64) (*ent.Deployment, error) { diff --git a/internal/server/api/v1/repos/comment.go b/internal/server/api/v1/repos/comment.go new file mode 100644 index 00000000..7bcb5984 --- /dev/null +++ b/internal/server/api/v1/repos/comment.go @@ -0,0 +1,144 @@ +// Copyright 2021 Gitploy.IO Inc. All rights reserved. +// Use of this source code is governed by the Gitploy Non-Commercial License +// that can be found in the LICENSE file. + +// +build !oss + +package repos + +import ( + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/binding" + "github.com/gitploy-io/gitploy/ent" + "github.com/gitploy-io/gitploy/ent/comment" + gb "github.com/gitploy-io/gitploy/internal/server/global" + "github.com/gitploy-io/gitploy/pkg/e" + "go.uber.org/zap" +) + +type ( + commentPostPayload struct { + Status string `json:"status"` + Comment string `json:"comment"` + } +) + +func (r *Repo) ListComments(c *gin.Context) { + ctx := c.Request.Context() + + var ( + number int + err error + ) + + if number, err = strconv.Atoi(c.Param("number")); err != nil { + gb.ResponseWithError( + c, + e.NewErrorWithMessage(e.ErrorCodeInvalidRequest, "The number must be integer.", nil), + ) + return + } + + vr, _ := c.Get(KeyRepo) + re := vr.(*ent.Repo) + + d, err := r.i.FindDeploymentOfRepoByNumber(ctx, re, number) + if err != nil { + gb.LogWithError(r.log, "Failed to find the deployment.", err) + gb.ResponseWithError(c, err) + return + } + + cmts, err := r.i.ListCommentsOfDeployment(ctx, d) + if err != nil { + gb.LogWithError(r.log, "Failed to list comments.", err) + gb.ResponseWithError(c, err) + return + } + + gb.Response(c, http.StatusOK, cmts) +} + +func (r *Repo) GetComment(c *gin.Context) { + ctx := c.Request.Context() + + var ( + id int + err error + ) + if id, err = strconv.Atoi(c.Param("id")); err != nil { + gb.ResponseWithError( + c, + e.NewErrorWithMessage(e.ErrorCodeInvalidRequest, "The id must be integer.", nil), + ) + return + } + + cmt, err := r.i.FindCommentByID(ctx, id) + if err != nil { + gb.LogWithError(r.log, "Failed to find the comment.", err) + gb.ResponseWithError(c, err) + return + } + + gb.Response(c, http.StatusOK, cmt) +} + +func (r *Repo) CreateComment(c *gin.Context) { + ctx := c.Request.Context() + + var ( + number int + err error + ) + + if number, err = strconv.Atoi(c.Param("number")); err != nil { + r.log.Warn("Failed to parse 'number'.", zap.Error(err)) + gb.ResponseWithError( + c, + e.NewErrorWithMessage(e.ErrorCodeInvalidRequest, "The number must be integer.", err), + ) + return + } + + p := &commentPostPayload{} + if err := c.ShouldBindBodyWith(p, binding.JSON); err != nil { + r.log.Warn("Failed to parse the payload.", zap.Error(err)) + gb.ResponseWithError( + c, + e.NewError(e.ErrorCodeInvalidRequest, err), + ) + return + } + + vu, _ := c.Get(gb.KeyUser) + u := vu.(*ent.User) + + vr, _ := c.Get(KeyRepo) + re := vr.(*ent.Repo) + + d, err := r.i.FindDeploymentOfRepoByNumber(ctx, re, number) + if err != nil { + gb.LogWithError(r.log, "Failed to find the deployment.", err) + gb.ResponseWithError(c, err) + return + } + + cmt, err := r.i.CreateComment(ctx, &ent.Comment{ + Status: comment.Status(p.Status), + Comment: p.Comment, + UserID: u.ID, + DeploymentID: d.ID, + }) + if err != nil { + gb.LogWithError(r.log, "Failed to create a new comment.", err) + gb.ResponseWithError(c, err) + return + } + + cmt, _ = r.i.FindCommentByID(ctx, cmt.ID) + gb.Response(c, http.StatusCreated, cmt) +} diff --git a/internal/server/api/v1/repos/comment_oss.go b/internal/server/api/v1/repos/comment_oss.go new file mode 100644 index 00000000..82955b2f --- /dev/null +++ b/internal/server/api/v1/repos/comment_oss.go @@ -0,0 +1,24 @@ +// +build oss + +package repos + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "github.com/gitploy-io/gitploy/ent" + gb "github.com/gitploy-io/gitploy/internal/server/global" +) + +func (r *Repo) ListComments(c *gin.Context) { + gb.Response(c, http.StatusOK, make([]*ent.Comment, 0)) +} + +func (r *Repo) GetComment(c *gin.Context) { + gb.Response(c, http.StatusNotFound, nil) +} + +func (r *Repo) CreateComment(c *gin.Context) { + gb.ErrorResponse(c, http.StatusPaymentRequired, "It is limited to the community edition.") +} diff --git a/internal/server/api/v1/repos/comment_test.go b/internal/server/api/v1/repos/comment_test.go new file mode 100644 index 00000000..6f5dd9d4 --- /dev/null +++ b/internal/server/api/v1/repos/comment_test.go @@ -0,0 +1,95 @@ +package repos + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/golang/mock/gomock" + + "github.com/gitploy-io/gitploy/ent" + "github.com/gitploy-io/gitploy/ent/comment" + "github.com/gitploy-io/gitploy/internal/server/api/v1/repos/mock" + gb "github.com/gitploy-io/gitploy/internal/server/global" +) + +func init() { + gin.SetMode(gin.ReleaseMode) +} + +func TestRepo_CreateComment(t *testing.T) { + t.Run("Return 400 when the number parameter is invalid", func(t *testing.T) { + ctrl := gomock.NewController(t) + m := mock.NewMockInteractor(ctrl) + + r := NewRepo(RepoConfig{}, m) + router := gin.New() + router.POST("/deployments/:number/comments", r.CreateComment) + + req, _ := http.NewRequest("POST", "/deployments/foo/comments", nil) + + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("Code != %d, wanted %d", w.Code, http.StatusBadRequest) + } + }) + + t.Run("Return 201 when the payload is valid", func(t *testing.T) { + input := struct { + payload *commentPostPayload + }{ + payload: &commentPostPayload{ + Status: "approved", + Comment: "LGTM", + }, + } + + ctrl := gomock.NewController(t) + m := mock.NewMockInteractor(ctrl) + + t.Log("MOCK - Find the deployment.") + m. + EXPECT(). + FindDeploymentOfRepoByNumber(gomock.Any(), gomock.AssignableToTypeOf(&ent.Repo{}), gomock.Any()). + Return(&ent.Deployment{}, nil) + + t.Log("MOCK - Create a new deployment with the payload.") + m. + EXPECT(). + CreateComment(gomock.Any(), gomock.Eq(&ent.Comment{ + Status: comment.StatusApproved, + Comment: "LGTM", + })). + DoAndReturn(func(ctx context.Context, cmt *ent.Comment) (*ent.Comment, error) { + return cmt, nil + }) + + m. + EXPECT(). + FindCommentByID(gomock.Any(), gomock.Any()). + Return(&ent.Comment{}, nil) + + r := NewRepo(RepoConfig{}, m) + router := gin.New() + router.POST("/deployments/:number/comments", func(c *gin.Context) { + c.Set(gb.KeyUser, &ent.User{}) + c.Set(KeyRepo, &ent.Repo{}) + }, r.CreateComment) + + body, _ := json.Marshal(input.payload) + req, _ := http.NewRequest("POST", "/deployments/1/comments", bytes.NewBuffer(body)) + + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + if w.Code != http.StatusCreated { + t.Fatalf("Code = %v, wanted %v", w.Code, http.StatusCreated) + } + }) +} diff --git a/internal/server/api/v1/repos/interface.go b/internal/server/api/v1/repos/interface.go index 22bbe48c..7ca7e640 100644 --- a/internal/server/api/v1/repos/interface.go +++ b/internal/server/api/v1/repos/interface.go @@ -39,6 +39,10 @@ type ( UpdateApproval(ctx context.Context, a *ent.Approval) (*ent.Approval, error) DeleteApproval(ctx context.Context, a *ent.Approval) error + ListCommentsOfDeployment(ctx context.Context, d *ent.Deployment) ([]*ent.Comment, error) + FindCommentByID(ctx context.Context, id int) (*ent.Comment, error) + CreateComment(ctx context.Context, cmt *ent.Comment) (*ent.Comment, error) + ListLocksOfRepo(ctx context.Context, r *ent.Repo) ([]*ent.Lock, error) HasLockOfRepoForEnv(ctx context.Context, r *ent.Repo, env string) (bool, error) FindLockByID(ctx context.Context, id int) (*ent.Lock, error) diff --git a/internal/server/api/v1/repos/mock/interactor.go b/internal/server/api/v1/repos/mock/interactor.go index 3778dd9a..361e3ca1 100644 --- a/internal/server/api/v1/repos/mock/interactor.go +++ b/internal/server/api/v1/repos/mock/interactor.go @@ -82,6 +82,21 @@ func (mr *MockInteractorMockRecorder) CreateApproval(ctx, a interface{}) *gomock return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateApproval", reflect.TypeOf((*MockInteractor)(nil).CreateApproval), ctx, a) } +// CreateComment mocks base method. +func (m *MockInteractor) CreateComment(ctx context.Context, cmt *ent.Comment) (*ent.Comment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateComment", ctx, cmt) + ret0, _ := ret[0].(*ent.Comment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateComment indicates an expected call of CreateComment. +func (mr *MockInteractorMockRecorder) CreateComment(ctx, cmt interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateComment", reflect.TypeOf((*MockInteractor)(nil).CreateComment), ctx, cmt) +} + // CreateEvent mocks base method. func (m *MockInteractor) CreateEvent(ctx context.Context, e *ent.Event) (*ent.Event, error) { m.ctrl.T.Helper() @@ -215,6 +230,21 @@ func (mr *MockInteractorMockRecorder) FindApprovalOfUser(ctx, d, u interface{}) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindApprovalOfUser", reflect.TypeOf((*MockInteractor)(nil).FindApprovalOfUser), ctx, d, u) } +// FindCommentByID mocks base method. +func (m *MockInteractor) FindCommentByID(ctx context.Context, id int) (*ent.Comment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindCommentByID", ctx, id) + ret0, _ := ret[0].(*ent.Comment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindCommentByID indicates an expected call of FindCommentByID. +func (mr *MockInteractorMockRecorder) FindCommentByID(ctx, id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindCommentByID", reflect.TypeOf((*MockInteractor)(nil).FindCommentByID), ctx, id) +} + // FindDeploymentByID mocks base method. func (m *MockInteractor) FindDeploymentByID(ctx context.Context, id int) (*ent.Deployment, error) { m.ctrl.T.Helper() @@ -454,6 +484,21 @@ func (mr *MockInteractorMockRecorder) ListBranches(ctx, u, r, page, perPage inte return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListBranches", reflect.TypeOf((*MockInteractor)(nil).ListBranches), ctx, u, r, page, perPage) } +// ListCommentsOfDeployment mocks base method. +func (m *MockInteractor) ListCommentsOfDeployment(ctx context.Context, d *ent.Deployment) ([]*ent.Comment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListCommentsOfDeployment", ctx, d) + ret0, _ := ret[0].([]*ent.Comment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListCommentsOfDeployment indicates an expected call of ListCommentsOfDeployment. +func (mr *MockInteractorMockRecorder) ListCommentsOfDeployment(ctx, d interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListCommentsOfDeployment", reflect.TypeOf((*MockInteractor)(nil).ListCommentsOfDeployment), ctx, d) +} + // ListCommitStatuses mocks base method. func (m *MockInteractor) ListCommitStatuses(ctx context.Context, u *ent.User, r *ent.Repo, sha string) ([]*vo.Status, error) { m.ctrl.T.Helper() diff --git a/internal/server/router.go b/internal/server/router.go index 1c86321a..fa7576f7 100644 --- a/internal/server/router.go +++ b/internal/server/router.go @@ -151,6 +151,9 @@ func NewRouter(c *RouterConfig) *gin.Engine { repov1.POST("/:namespace/:name/deployments/:number/approvals", rm.RepoReadPerm(), r.CreateApproval) repov1.GET("/:namespace/:name/deployments/:number/approval", rm.RepoReadPerm(), r.GetMyApproval) repov1.PATCH("/:namespace/:name/deployments/:number/approval", rm.RepoReadPerm(), r.UpdateMyApproval) + repov1.GET("/:namespace/:name/deployments/:number/comments", rm.RepoReadPerm(), r.ListComments) + repov1.POST("/:namespace/:name/deployments/:number/comments", rm.RepoReadPerm(), r.CreateComment) + repov1.GET("/:namespace/:name/deployments/:number/comments/:id", rm.RepoReadPerm(), r.GetComment) repov1.GET("/:namespace/:name/approvals/:aid", rm.RepoReadPerm(), r.GetApproval) repov1.DELETE("/:namespace/:name/approvals/:aid", rm.RepoReadPerm(), r.DeleteApproval) repov1.GET("/:namespace/:name/locks", rm.RepoReadPerm(), r.ListLocks) diff --git a/openapi/v1.yaml b/openapi/v1.yaml index 88dfc822..488e3668 100644 --- a/openapi/v1.yaml +++ b/openapi/v1.yaml @@ -993,6 +993,144 @@ paths: $ref: '#/components/responses/404NotFound' '500': $ref: '#/components/responses/500InternalError' + /repos/{namespace}/{name}/deployments/{number}/comments: + get: + tags: + - Repo + summary: List comments for the deployment + parameters: + - in: path + name: namespace + required: true + schema: + type: string + - in: path + name: name + required: true + schema: + type: string + - in: path + name: number + required: true + schema: + type: integer + description: The deployment number. + responses: + '200': + description: List of comments. + content: + application/json: + schema: + $ref: '#/components/schemas/Comments' + '401': + $ref: '#/components/responses/401Unauthorized' + '402': + $ref: '#/components/responses/402PaymentRequired' + '403': + $ref: '#/components/responses/403Forbidden' + '500': + $ref: '#/components/responses/500InternalError' + post: + tags: + - Repo + summary: Post a new comment. + parameters: + - in: path + name: namespace + required: true + schema: + type: string + - in: path + name: name + required: true + schema: + type: string + - in: path + name: number + required: true + schema: + type: integer + description: The deployment number. + requestBody: + content: + application/json: + schema: + type: object + properties: + status: + type: string + enum: + - approved + - rejected + comment: + type: string + required: + - status + - comment + responses: + '201': + description: A new comment is created. + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '401': + $ref: '#/components/responses/401Unauthorized' + '402': + $ref: '#/components/responses/402PaymentRequired' + '403': + $ref: '#/components/responses/403Forbidden' + '404': + $ref: '#/components/responses/404NotFound' + '422': + $ref: '#/components/responses/422UnprocessableEntity' + '500': + $ref: '#/components/responses/500InternalError' + /repos/{namespace}/{name}/deployments/{number}/comments/{id}: + get: + tags: + - Repo + summary: Get the comment. + parameters: + - in: path + name: namespace + required: true + schema: + type: string + - in: path + name: name + required: true + schema: + type: string + - in: path + name: number + required: true + schema: + type: integer + description: The deployment number. + - in: path + name: id + required: true + schema: + type: integer + description: The comment ID. + responses: + '200': + description: Return the comment. + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '401': + $ref: '#/components/responses/401Unauthorized' + '402': + $ref: '#/components/responses/402PaymentRequired' + '403': + $ref: '#/components/responses/403Forbidden' + '404': + $ref: '#/components/responses/404NotFound' + '500': + $ref: '#/components/responses/500InternalError' /repos/{namespace}/{name}/locks: get: tags: @@ -1951,6 +2089,40 @@ components: - status - created_at - updated_at + Comments: + type: array + items: + $ref: '#components/schemas/Comment' + Comment: + type: object + properties: + id: + type: integer + status: + type: string + enum: + - declined + - approved + comment: + type: string + created_at: + type: string + updated_at: + type: string + edges: + type: object + properties: + user: + $ref: '#/components/schemas/User' + deployment: + $ref: '#/components/schemas/Deployment' + required: + - id + - status + - comment + - created_at + - updated_at + - edges RateLimit: type: object properties: diff --git a/pkg/e/code.go b/pkg/e/code.go index 72d7690e..d7e5532c 100644 --- a/pkg/e/code.go +++ b/pkg/e/code.go @@ -7,6 +7,7 @@ import ( const ( // ErrorCodeConfigNotFound is that the configuration file is not found. + // TODO: migrate into ErrorCodeNotFound ErrorCodeConfigNotFound ErrorCode = "config_not_found" // ErrorCodeConfigParseError is that an error occurs when it parse the file. ErrorCodeConfigParseError ErrorCode = "config_parse_error" @@ -26,9 +27,13 @@ const ( ErrorCodeLicenseDecode ErrorCode = "license_decode" // ErrorCodeRefNotFound is that the ref is not found. + // TODO: migrate into ErrorCodeNotFound ErrorCodeRefNotFound ErrorCode = "ref_not_found" - ErrorCodeInternalError ErrorCode = "internal_error" + // General purpose error codes. + ErrorCodeInvalidRequest ErrorCode = "invalid_request" + ErrorCodeNotFound ErrorCode = "not_found" + ErrorCodeInternalError ErrorCode = "internal_error" ) type ( @@ -50,6 +55,14 @@ func NewError(code ErrorCode, wrap error) *Error { } } +func NewErrorWithMessage(code ErrorCode, message string, wrap error) *Error { + return &Error{ + Code: code, + Message: message, + Wrap: wrap, + } +} + func (e *Error) Error() string { return fmt.Sprintf("code: %s, message: %s, wrap: %s", e.Code, GetMessage(e.Code), e.Wrap) } diff --git a/pkg/e/trans.go b/pkg/e/trans.go index bd07f954..cbd87564 100644 --- a/pkg/e/trans.go +++ b/pkg/e/trans.go @@ -12,6 +12,8 @@ var messages = map[ErrorCode]string{ ErrorCodeDeploymentUndeployable: "There is merge conflict or a commit status check failed.", ErrorCodeLicenseDecode: "Decoding the license is failed.", ErrorCodeRefNotFound: "The reference is not found.", + ErrorCodeInvalidRequest: "Invalid request parameter.", + ErrorCodeNotFound: "It is not found.", ErrorCodeInternalError: "Server internal error.", } @@ -34,6 +36,8 @@ var httpCodes = map[ErrorCode]int{ ErrorCodeDeploymentUndeployable: http.StatusUnprocessableEntity, ErrorCodeLicenseDecode: http.StatusUnprocessableEntity, ErrorCodeRefNotFound: http.StatusNotFound, + ErrorCodeInvalidRequest: http.StatusBadRequest, + ErrorCodeNotFound: http.StatusNotFound, ErrorCodeInternalError: http.StatusInternalServerError, }