From 27cc83223d5f1ba9f25671e4d1b891bab1205add Mon Sep 17 00:00:00 2001 From: noah Date: Sun, 17 Apr 2022 13:50:56 +0900 Subject: [PATCH 1/9] Add the `deployment_status_id` field to event schema --- model/ent/client.go | 32 +++ model/ent/deploymentstatus.go | 18 +- .../ent/deploymentstatus/deploymentstatus.go | 9 + model/ent/deploymentstatus/where.go | 28 +++ model/ent/deploymentstatus_create.go | 35 +++ model/ent/deploymentstatus_query.go | 65 +++++- model/ent/deploymentstatus_update.go | 181 +++++++++++++++ model/ent/event.go | 40 +++- model/ent/event/event.go | 20 +- model/ent/event/where.go | 97 ++++++++ model/ent/event_create.go | 40 ++++ model/ent/event_query.go | 65 +++++- model/ent/event_update.go | 133 +++++++++++ model/ent/migrate/schema.go | 14 +- model/ent/mutation.go | 215 +++++++++++++++++- model/ent/schema/deploymentstatus.go | 5 + model/ent/schema/event.go | 9 +- 17 files changed, 983 insertions(+), 23 deletions(-) diff --git a/model/ent/client.go b/model/ent/client.go index 07dd5c34..c3931438 100644 --- a/model/ent/client.go +++ b/model/ent/client.go @@ -676,6 +676,22 @@ func (c *DeploymentStatusClient) QueryDeployment(ds *DeploymentStatus) *Deployme return query } +// QueryEvent queries the event edge of a DeploymentStatus. +func (c *DeploymentStatusClient) QueryEvent(ds *DeploymentStatus) *EventQuery { + query := &EventQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := ds.ID + step := sqlgraph.NewStep( + sqlgraph.From(deploymentstatus.Table, deploymentstatus.FieldID, id), + sqlgraph.To(event.Table, event.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, deploymentstatus.EventTable, deploymentstatus.EventColumn), + ) + fromV = sqlgraph.Neighbors(ds.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *DeploymentStatusClient) Hooks() []Hook { return c.hooks.DeploymentStatus @@ -782,6 +798,22 @@ func (c *EventClient) QueryDeployment(e *Event) *DeploymentQuery { return query } +// QueryDeploymentStatus queries the deployment_status edge of a Event. +func (c *EventClient) QueryDeploymentStatus(e *Event) *DeploymentStatusQuery { + query := &DeploymentStatusQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := e.ID + step := sqlgraph.NewStep( + sqlgraph.From(event.Table, event.FieldID, id), + sqlgraph.To(deploymentstatus.Table, deploymentstatus.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, event.DeploymentStatusTable, event.DeploymentStatusColumn), + ) + fromV = sqlgraph.Neighbors(e.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryReview queries the review edge of a Event. func (c *EventClient) QueryReview(e *Event) *ReviewQuery { query := &ReviewQuery{config: c.config} diff --git a/model/ent/deploymentstatus.go b/model/ent/deploymentstatus.go index 8880b11c..d71144dd 100644 --- a/model/ent/deploymentstatus.go +++ b/model/ent/deploymentstatus.go @@ -38,9 +38,11 @@ type DeploymentStatus struct { type DeploymentStatusEdges struct { // Deployment holds the value of the deployment edge. Deployment *Deployment `json:"deployment,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 [1]bool + loadedTypes [2]bool } // DeploymentOrErr returns the Deployment value or an error if the edge @@ -57,6 +59,15 @@ func (e DeploymentStatusEdges) DeploymentOrErr() (*Deployment, error) { return nil, &NotLoadedError{edge: "deployment"} } +// EventOrErr returns the Event value or an error if the edge +// was not loaded in eager-loading. +func (e DeploymentStatusEdges) EventOrErr() ([]*Event, error) { + if e.loadedTypes[1] { + return e.Event, nil + } + return nil, &NotLoadedError{edge: "event"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*DeploymentStatus) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) @@ -135,6 +146,11 @@ func (ds *DeploymentStatus) QueryDeployment() *DeploymentQuery { return (&DeploymentStatusClient{config: ds.config}).QueryDeployment(ds) } +// QueryEvent queries the "event" edge of the DeploymentStatus entity. +func (ds *DeploymentStatus) QueryEvent() *EventQuery { + return (&DeploymentStatusClient{config: ds.config}).QueryEvent(ds) +} + // Update returns a builder for updating this DeploymentStatus. // Note that you need to call DeploymentStatus.Unwrap() before calling this method if this DeploymentStatus // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/model/ent/deploymentstatus/deploymentstatus.go b/model/ent/deploymentstatus/deploymentstatus.go index d6e7eab6..7a98cb88 100644 --- a/model/ent/deploymentstatus/deploymentstatus.go +++ b/model/ent/deploymentstatus/deploymentstatus.go @@ -25,6 +25,8 @@ const ( FieldDeploymentID = "deployment_id" // EdgeDeployment holds the string denoting the deployment edge name in mutations. EdgeDeployment = "deployment" + // EdgeEvent holds the string denoting the event edge name in mutations. + EdgeEvent = "event" // Table holds the table name of the deploymentstatus in the database. Table = "deployment_status" // DeploymentTable is the table that holds the deployment relation/edge. @@ -34,6 +36,13 @@ const ( DeploymentInverseTable = "deployments" // DeploymentColumn is the table column denoting the deployment relation/edge. DeploymentColumn = "deployment_id" + // EventTable is the table that holds the event relation/edge. + EventTable = "events" + // EventInverseTable is the table name for the Event entity. + // It exists in this package in order to avoid circular dependency with the "event" package. + EventInverseTable = "events" + // EventColumn is the table column denoting the event relation/edge. + EventColumn = "deployment_status_id" ) // Columns holds all SQL columns for deploymentstatus fields. diff --git a/model/ent/deploymentstatus/where.go b/model/ent/deploymentstatus/where.go index 8c5ee253..23c608e1 100644 --- a/model/ent/deploymentstatus/where.go +++ b/model/ent/deploymentstatus/where.go @@ -724,6 +724,34 @@ func HasDeploymentWith(preds ...predicate.Deployment) predicate.DeploymentStatus }) } +// HasEvent applies the HasEdge predicate on the "event" edge. +func HasEvent() predicate.DeploymentStatus { + return predicate.DeploymentStatus(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EventTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EventTable, EventColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEventWith applies the HasEdge predicate on the "event" edge with a given conditions (other predicates). +func HasEventWith(preds ...predicate.Event) predicate.DeploymentStatus { + return predicate.DeploymentStatus(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EventInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EventTable, EventColumn), + ) + 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.DeploymentStatus) predicate.DeploymentStatus { return predicate.DeploymentStatus(func(s *sql.Selector) { diff --git a/model/ent/deploymentstatus_create.go b/model/ent/deploymentstatus_create.go index e80f74c1..d03af385 100644 --- a/model/ent/deploymentstatus_create.go +++ b/model/ent/deploymentstatus_create.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" + "github.com/gitploy-io/gitploy/model/ent/event" ) // DeploymentStatusCreate is the builder for creating a DeploymentStatus entity. @@ -94,6 +95,21 @@ func (dsc *DeploymentStatusCreate) SetDeployment(d *Deployment) *DeploymentStatu return dsc.SetDeploymentID(d.ID) } +// AddEventIDs adds the "event" edge to the Event entity by IDs. +func (dsc *DeploymentStatusCreate) AddEventIDs(ids ...int) *DeploymentStatusCreate { + dsc.mutation.AddEventIDs(ids...) + return dsc +} + +// AddEvent adds the "event" edges to the Event entity. +func (dsc *DeploymentStatusCreate) AddEvent(e ...*Event) *DeploymentStatusCreate { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return dsc.AddEventIDs(ids...) +} + // Mutation returns the DeploymentStatusMutation object of the builder. func (dsc *DeploymentStatusCreate) Mutation() *DeploymentStatusMutation { return dsc.mutation @@ -279,6 +295,25 @@ func (dsc *DeploymentStatusCreate) createSpec() (*DeploymentStatus, *sqlgraph.Cr _node.DeploymentID = nodes[0] _spec.Edges = append(_spec.Edges, edge) } + if nodes := dsc.mutation.EventIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deploymentstatus.EventTable, + Columns: []string{deploymentstatus.EventColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: event.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/model/ent/deploymentstatus_query.go b/model/ent/deploymentstatus_query.go index 0eab01d9..a3b05b46 100644 --- a/model/ent/deploymentstatus_query.go +++ b/model/ent/deploymentstatus_query.go @@ -4,6 +4,7 @@ package ent import ( "context" + "database/sql/driver" "errors" "fmt" "math" @@ -14,6 +15,7 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" + "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/predicate" ) @@ -28,6 +30,7 @@ type DeploymentStatusQuery struct { predicates []predicate.DeploymentStatus // eager-loading edges. withDeployment *DeploymentQuery + withEvent *EventQuery modifiers []func(s *sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -87,6 +90,28 @@ func (dsq *DeploymentStatusQuery) QueryDeployment() *DeploymentQuery { return query } +// QueryEvent chains the current query on the "event" edge. +func (dsq *DeploymentStatusQuery) QueryEvent() *EventQuery { + query := &EventQuery{config: dsq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := dsq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := dsq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(deploymentstatus.Table, deploymentstatus.FieldID, selector), + sqlgraph.To(event.Table, event.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, deploymentstatus.EventTable, deploymentstatus.EventColumn), + ) + fromU = sqlgraph.SetNeighbors(dsq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first DeploymentStatus entity from the query. // Returns a *NotFoundError when no DeploymentStatus was found. func (dsq *DeploymentStatusQuery) First(ctx context.Context) (*DeploymentStatus, error) { @@ -269,6 +294,7 @@ func (dsq *DeploymentStatusQuery) Clone() *DeploymentStatusQuery { order: append([]OrderFunc{}, dsq.order...), predicates: append([]predicate.DeploymentStatus{}, dsq.predicates...), withDeployment: dsq.withDeployment.Clone(), + withEvent: dsq.withEvent.Clone(), // clone intermediate query. sql: dsq.sql.Clone(), path: dsq.path, @@ -287,6 +313,17 @@ func (dsq *DeploymentStatusQuery) WithDeployment(opts ...func(*DeploymentQuery)) return dsq } +// WithEvent tells the query-builder to eager-load the nodes that are connected to +// the "event" edge. The optional arguments are used to configure the query builder of the edge. +func (dsq *DeploymentStatusQuery) WithEvent(opts ...func(*EventQuery)) *DeploymentStatusQuery { + query := &EventQuery{config: dsq.config} + for _, opt := range opts { + opt(query) + } + dsq.withEvent = query + return dsq +} + // 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. // @@ -352,8 +389,9 @@ func (dsq *DeploymentStatusQuery) sqlAll(ctx context.Context) ([]*DeploymentStat var ( nodes = []*DeploymentStatus{} _spec = dsq.querySpec() - loadedTypes = [1]bool{ + loadedTypes = [2]bool{ dsq.withDeployment != nil, + dsq.withEvent != nil, } ) _spec.ScanValues = func(columns []string) ([]interface{}, error) { @@ -405,6 +443,31 @@ func (dsq *DeploymentStatusQuery) sqlAll(ctx context.Context) ([]*DeploymentStat } } + if query := dsq.withEvent; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*DeploymentStatus) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.Event = []*Event{} + } + query.Where(predicate.Event(func(s *sql.Selector) { + s.Where(sql.InValues(deploymentstatus.EventColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.DeploymentStatusID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "deployment_status_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.Event = append(node.Edges.Event, n) + } + } + return nodes, nil } diff --git a/model/ent/deploymentstatus_update.go b/model/ent/deploymentstatus_update.go index 7c5fba3a..cd696d55 100644 --- a/model/ent/deploymentstatus_update.go +++ b/model/ent/deploymentstatus_update.go @@ -13,6 +13,7 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" + "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/predicate" ) @@ -106,6 +107,21 @@ func (dsu *DeploymentStatusUpdate) SetDeployment(d *Deployment) *DeploymentStatu return dsu.SetDeploymentID(d.ID) } +// AddEventIDs adds the "event" edge to the Event entity by IDs. +func (dsu *DeploymentStatusUpdate) AddEventIDs(ids ...int) *DeploymentStatusUpdate { + dsu.mutation.AddEventIDs(ids...) + return dsu +} + +// AddEvent adds the "event" edges to the Event entity. +func (dsu *DeploymentStatusUpdate) AddEvent(e ...*Event) *DeploymentStatusUpdate { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return dsu.AddEventIDs(ids...) +} + // Mutation returns the DeploymentStatusMutation object of the builder. func (dsu *DeploymentStatusUpdate) Mutation() *DeploymentStatusMutation { return dsu.mutation @@ -117,6 +133,27 @@ func (dsu *DeploymentStatusUpdate) ClearDeployment() *DeploymentStatusUpdate { return dsu } +// ClearEvent clears all "event" edges to the Event entity. +func (dsu *DeploymentStatusUpdate) ClearEvent() *DeploymentStatusUpdate { + dsu.mutation.ClearEvent() + return dsu +} + +// RemoveEventIDs removes the "event" edge to Event entities by IDs. +func (dsu *DeploymentStatusUpdate) RemoveEventIDs(ids ...int) *DeploymentStatusUpdate { + dsu.mutation.RemoveEventIDs(ids...) + return dsu +} + +// RemoveEvent removes "event" edges to Event entities. +func (dsu *DeploymentStatusUpdate) RemoveEvent(e ...*Event) *DeploymentStatusUpdate { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return dsu.RemoveEventIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (dsu *DeploymentStatusUpdate) Save(ctx context.Context) (int, error) { var ( @@ -294,6 +331,60 @@ func (dsu *DeploymentStatusUpdate) sqlSave(ctx context.Context) (n int, err erro } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if dsu.mutation.EventCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deploymentstatus.EventTable, + Columns: []string{deploymentstatus.EventColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: event.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := dsu.mutation.RemovedEventIDs(); len(nodes) > 0 && !dsu.mutation.EventCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deploymentstatus.EventTable, + Columns: []string{deploymentstatus.EventColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: event.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := dsu.mutation.EventIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deploymentstatus.EventTable, + Columns: []string{deploymentstatus.EventColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: event.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, dsu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{deploymentstatus.Label} @@ -390,6 +481,21 @@ func (dsuo *DeploymentStatusUpdateOne) SetDeployment(d *Deployment) *DeploymentS return dsuo.SetDeploymentID(d.ID) } +// AddEventIDs adds the "event" edge to the Event entity by IDs. +func (dsuo *DeploymentStatusUpdateOne) AddEventIDs(ids ...int) *DeploymentStatusUpdateOne { + dsuo.mutation.AddEventIDs(ids...) + return dsuo +} + +// AddEvent adds the "event" edges to the Event entity. +func (dsuo *DeploymentStatusUpdateOne) AddEvent(e ...*Event) *DeploymentStatusUpdateOne { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return dsuo.AddEventIDs(ids...) +} + // Mutation returns the DeploymentStatusMutation object of the builder. func (dsuo *DeploymentStatusUpdateOne) Mutation() *DeploymentStatusMutation { return dsuo.mutation @@ -401,6 +507,27 @@ func (dsuo *DeploymentStatusUpdateOne) ClearDeployment() *DeploymentStatusUpdate return dsuo } +// ClearEvent clears all "event" edges to the Event entity. +func (dsuo *DeploymentStatusUpdateOne) ClearEvent() *DeploymentStatusUpdateOne { + dsuo.mutation.ClearEvent() + return dsuo +} + +// RemoveEventIDs removes the "event" edge to Event entities by IDs. +func (dsuo *DeploymentStatusUpdateOne) RemoveEventIDs(ids ...int) *DeploymentStatusUpdateOne { + dsuo.mutation.RemoveEventIDs(ids...) + return dsuo +} + +// RemoveEvent removes "event" edges to Event entities. +func (dsuo *DeploymentStatusUpdateOne) RemoveEvent(e ...*Event) *DeploymentStatusUpdateOne { + ids := make([]int, len(e)) + for i := range e { + ids[i] = e[i].ID + } + return dsuo.RemoveEventIDs(ids...) +} + // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. func (dsuo *DeploymentStatusUpdateOne) Select(field string, fields ...string) *DeploymentStatusUpdateOne { @@ -602,6 +729,60 @@ func (dsuo *DeploymentStatusUpdateOne) sqlSave(ctx context.Context) (_node *Depl } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if dsuo.mutation.EventCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deploymentstatus.EventTable, + Columns: []string{deploymentstatus.EventColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: event.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := dsuo.mutation.RemovedEventIDs(); len(nodes) > 0 && !dsuo.mutation.EventCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deploymentstatus.EventTable, + Columns: []string{deploymentstatus.EventColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: event.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := dsuo.mutation.EventIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: deploymentstatus.EventTable, + Columns: []string{deploymentstatus.EventColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: event.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &DeploymentStatus{config: dsuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/model/ent/event.go b/model/ent/event.go index 9502b5cc..2810aa81 100644 --- a/model/ent/event.go +++ b/model/ent/event.go @@ -9,6 +9,7 @@ import ( "entgo.io/ent/dialect/sql" "github.com/gitploy-io/gitploy/model/ent/deployment" + "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/notificationrecord" "github.com/gitploy-io/gitploy/model/ent/review" @@ -27,6 +28,8 @@ type Event struct { CreatedAt time.Time `json:"created_at"` // DeploymentID holds the value of the "deployment_id" field. DeploymentID int `json:"deployment_id,omitemtpy"` + // DeploymentStatusID holds the value of the "deployment_status_id" field. + DeploymentStatusID int `json:"deployment_status_id,omitemtpy"` // ReviewID holds the value of the "review_id" field. ReviewID int `json:"review_id,omitemtpy"` // DeletedID holds the value of the "deleted_id" field. @@ -40,13 +43,15 @@ type Event struct { type EventEdges struct { // Deployment holds the value of the deployment edge. Deployment *Deployment `json:"deployment,omitempty"` + // DeploymentStatus holds the value of the deployment_status edge. + DeploymentStatus *DeploymentStatus `json:"deployment_status,omitempty"` // Review holds the value of the review edge. Review *Review `json:"review,omitempty"` // NotificationRecord holds the value of the notification_record edge. NotificationRecord *NotificationRecord `json:"notification_record,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [3]bool + loadedTypes [4]bool } // DeploymentOrErr returns the Deployment value or an error if the edge @@ -63,10 +68,24 @@ func (e EventEdges) DeploymentOrErr() (*Deployment, error) { return nil, &NotLoadedError{edge: "deployment"} } +// DeploymentStatusOrErr returns the DeploymentStatus value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e EventEdges) DeploymentStatusOrErr() (*DeploymentStatus, error) { + if e.loadedTypes[1] { + if e.DeploymentStatus == nil { + // The edge deployment_status was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: deploymentstatus.Label} + } + return e.DeploymentStatus, nil + } + return nil, &NotLoadedError{edge: "deployment_status"} +} + // ReviewOrErr returns the Review value or an error if the edge // was not loaded in eager-loading, or loaded but was not found. func (e EventEdges) ReviewOrErr() (*Review, error) { - if e.loadedTypes[1] { + if e.loadedTypes[2] { if e.Review == nil { // The edge review was loaded in eager-loading, // but was not found. @@ -80,7 +99,7 @@ func (e EventEdges) ReviewOrErr() (*Review, error) { // NotificationRecordOrErr returns the NotificationRecord value or an error if the edge // was not loaded in eager-loading, or loaded but was not found. func (e EventEdges) NotificationRecordOrErr() (*NotificationRecord, error) { - if e.loadedTypes[2] { + if e.loadedTypes[3] { if e.NotificationRecord == nil { // The edge notification_record was loaded in eager-loading, // but was not found. @@ -96,7 +115,7 @@ func (*Event) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) for i := range columns { switch columns[i] { - case event.FieldID, event.FieldDeploymentID, event.FieldReviewID, event.FieldDeletedID: + case event.FieldID, event.FieldDeploymentID, event.FieldDeploymentStatusID, event.FieldReviewID, event.FieldDeletedID: values[i] = new(sql.NullInt64) case event.FieldKind, event.FieldType: values[i] = new(sql.NullString) @@ -147,6 +166,12 @@ func (e *Event) assignValues(columns []string, values []interface{}) error { } else if value.Valid { e.DeploymentID = int(value.Int64) } + case event.FieldDeploymentStatusID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field deployment_status_id", values[i]) + } else if value.Valid { + e.DeploymentStatusID = int(value.Int64) + } case event.FieldReviewID: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field review_id", values[i]) @@ -169,6 +194,11 @@ func (e *Event) QueryDeployment() *DeploymentQuery { return (&EventClient{config: e.config}).QueryDeployment(e) } +// QueryDeploymentStatus queries the "deployment_status" edge of the Event entity. +func (e *Event) QueryDeploymentStatus() *DeploymentStatusQuery { + return (&EventClient{config: e.config}).QueryDeploymentStatus(e) +} + // QueryReview queries the "review" edge of the Event entity. func (e *Event) QueryReview() *ReviewQuery { return (&EventClient{config: e.config}).QueryReview(e) @@ -210,6 +240,8 @@ func (e *Event) String() string { builder.WriteString(e.CreatedAt.Format(time.ANSIC)) builder.WriteString(", deployment_id=") builder.WriteString(fmt.Sprintf("%v", e.DeploymentID)) + builder.WriteString(", deployment_status_id=") + builder.WriteString(fmt.Sprintf("%v", e.DeploymentStatusID)) builder.WriteString(", review_id=") builder.WriteString(fmt.Sprintf("%v", e.ReviewID)) builder.WriteString(", deleted_id=") diff --git a/model/ent/event/event.go b/model/ent/event/event.go index 2f376908..c71c7fb8 100644 --- a/model/ent/event/event.go +++ b/model/ent/event/event.go @@ -20,12 +20,16 @@ const ( FieldCreatedAt = "created_at" // FieldDeploymentID holds the string denoting the deployment_id field in the database. FieldDeploymentID = "deployment_id" + // FieldDeploymentStatusID holds the string denoting the deployment_status_id field in the database. + FieldDeploymentStatusID = "deployment_status_id" // FieldReviewID holds the string denoting the review_id field in the database. FieldReviewID = "review_id" // FieldDeletedID holds the string denoting the deleted_id field in the database. FieldDeletedID = "deleted_id" // EdgeDeployment holds the string denoting the deployment edge name in mutations. EdgeDeployment = "deployment" + // EdgeDeploymentStatus holds the string denoting the deployment_status edge name in mutations. + EdgeDeploymentStatus = "deployment_status" // EdgeReview holds the string denoting the review edge name in mutations. EdgeReview = "review" // EdgeNotificationRecord holds the string denoting the notification_record edge name in mutations. @@ -39,6 +43,13 @@ const ( DeploymentInverseTable = "deployments" // DeploymentColumn is the table column denoting the deployment relation/edge. DeploymentColumn = "deployment_id" + // DeploymentStatusTable is the table that holds the deployment_status relation/edge. + DeploymentStatusTable = "events" + // DeploymentStatusInverseTable is the table name for the DeploymentStatus entity. + // It exists in this package in order to avoid circular dependency with the "deploymentstatus" package. + DeploymentStatusInverseTable = "deployment_status" + // DeploymentStatusColumn is the table column denoting the deployment_status relation/edge. + DeploymentStatusColumn = "deployment_status_id" // ReviewTable is the table that holds the review relation/edge. ReviewTable = "events" // ReviewInverseTable is the table name for the Review entity. @@ -62,6 +73,7 @@ var Columns = []string{ FieldType, FieldCreatedAt, FieldDeploymentID, + FieldDeploymentStatusID, FieldReviewID, FieldDeletedID, } @@ -86,9 +98,9 @@ type Kind string // Kind values. const ( - KindDeployment Kind = "deployment" - KindReview Kind = "review" - KindApproval Kind = "approval" + KindDeployment Kind = "deployment" + KindDeploymentStatus Kind = "deployment_status" + KindReview Kind = "review" ) func (k Kind) String() string { @@ -98,7 +110,7 @@ func (k Kind) String() string { // KindValidator is a validator for the "kind" field enum values. It is called by the builders before save. func KindValidator(k Kind) error { switch k { - case KindDeployment, KindReview, KindApproval: + case KindDeployment, KindDeploymentStatus, KindReview: return nil default: return fmt.Errorf("event: invalid enum value for kind field: %q", k) diff --git a/model/ent/event/where.go b/model/ent/event/where.go index b8645559..c27012ac 100644 --- a/model/ent/event/where.go +++ b/model/ent/event/where.go @@ -107,6 +107,13 @@ func DeploymentID(v int) predicate.Event { }) } +// DeploymentStatusID applies equality check predicate on the "deployment_status_id" field. It's identical to DeploymentStatusIDEQ. +func DeploymentStatusID(v int) predicate.Event { + return predicate.Event(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeploymentStatusID), v)) + }) +} + // ReviewID applies equality check predicate on the "review_id" field. It's identical to ReviewIDEQ. func ReviewID(v int) predicate.Event { return predicate.Event(func(s *sql.Selector) { @@ -355,6 +362,68 @@ func DeploymentIDNotNil() predicate.Event { }) } +// DeploymentStatusIDEQ applies the EQ predicate on the "deployment_status_id" field. +func DeploymentStatusIDEQ(v int) predicate.Event { + return predicate.Event(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDeploymentStatusID), v)) + }) +} + +// DeploymentStatusIDNEQ applies the NEQ predicate on the "deployment_status_id" field. +func DeploymentStatusIDNEQ(v int) predicate.Event { + return predicate.Event(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDeploymentStatusID), v)) + }) +} + +// DeploymentStatusIDIn applies the In predicate on the "deployment_status_id" field. +func DeploymentStatusIDIn(vs ...int) predicate.Event { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Event(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(FieldDeploymentStatusID), v...)) + }) +} + +// DeploymentStatusIDNotIn applies the NotIn predicate on the "deployment_status_id" field. +func DeploymentStatusIDNotIn(vs ...int) predicate.Event { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.Event(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(FieldDeploymentStatusID), v...)) + }) +} + +// DeploymentStatusIDIsNil applies the IsNil predicate on the "deployment_status_id" field. +func DeploymentStatusIDIsNil() predicate.Event { + return predicate.Event(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldDeploymentStatusID))) + }) +} + +// DeploymentStatusIDNotNil applies the NotNil predicate on the "deployment_status_id" field. +func DeploymentStatusIDNotNil() predicate.Event { + return predicate.Event(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldDeploymentStatusID))) + }) +} + // ReviewIDEQ applies the EQ predicate on the "review_id" field. func ReviewIDEQ(v int) predicate.Event { return predicate.Event(func(s *sql.Selector) { @@ -535,6 +604,34 @@ func HasDeploymentWith(preds ...predicate.Deployment) predicate.Event { }) } +// HasDeploymentStatus applies the HasEdge predicate on the "deployment_status" edge. +func HasDeploymentStatus() predicate.Event { + return predicate.Event(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DeploymentStatusTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, DeploymentStatusTable, DeploymentStatusColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasDeploymentStatusWith applies the HasEdge predicate on the "deployment_status" edge with a given conditions (other predicates). +func HasDeploymentStatusWith(preds ...predicate.DeploymentStatus) predicate.Event { + return predicate.Event(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DeploymentStatusInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, DeploymentStatusTable, DeploymentStatusColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasReview applies the HasEdge predicate on the "review" edge. func HasReview() predicate.Event { return predicate.Event(func(s *sql.Selector) { diff --git a/model/ent/event_create.go b/model/ent/event_create.go index 7067e73a..55ae8cdd 100644 --- a/model/ent/event_create.go +++ b/model/ent/event_create.go @@ -11,6 +11,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" + "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/notificationrecord" "github.com/gitploy-io/gitploy/model/ent/review" @@ -63,6 +64,20 @@ func (ec *EventCreate) SetNillableDeploymentID(i *int) *EventCreate { return ec } +// SetDeploymentStatusID sets the "deployment_status_id" field. +func (ec *EventCreate) SetDeploymentStatusID(i int) *EventCreate { + ec.mutation.SetDeploymentStatusID(i) + return ec +} + +// SetNillableDeploymentStatusID sets the "deployment_status_id" field if the given value is not nil. +func (ec *EventCreate) SetNillableDeploymentStatusID(i *int) *EventCreate { + if i != nil { + ec.SetDeploymentStatusID(*i) + } + return ec +} + // SetReviewID sets the "review_id" field. func (ec *EventCreate) SetReviewID(i int) *EventCreate { ec.mutation.SetReviewID(i) @@ -96,6 +111,11 @@ func (ec *EventCreate) SetDeployment(d *Deployment) *EventCreate { return ec.SetDeploymentID(d.ID) } +// SetDeploymentStatus sets the "deployment_status" edge to the DeploymentStatus entity. +func (ec *EventCreate) SetDeploymentStatus(d *DeploymentStatus) *EventCreate { + return ec.SetDeploymentStatusID(d.ID) +} + // SetReview sets the "review" edge to the Review entity. func (ec *EventCreate) SetReview(r *Review) *EventCreate { return ec.SetReviewID(r.ID) @@ -297,6 +317,26 @@ func (ec *EventCreate) createSpec() (*Event, *sqlgraph.CreateSpec) { _node.DeploymentID = nodes[0] _spec.Edges = append(_spec.Edges, edge) } + if nodes := ec.mutation.DeploymentStatusIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: event.DeploymentStatusTable, + Columns: []string{event.DeploymentStatusColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.DeploymentStatusID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } if nodes := ec.mutation.ReviewIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, diff --git a/model/ent/event_query.go b/model/ent/event_query.go index 563d35dc..d9e257fc 100644 --- a/model/ent/event_query.go +++ b/model/ent/event_query.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" + "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/notificationrecord" "github.com/gitploy-io/gitploy/model/ent/predicate" @@ -31,6 +32,7 @@ type EventQuery struct { predicates []predicate.Event // eager-loading edges. withDeployment *DeploymentQuery + withDeploymentStatus *DeploymentStatusQuery withReview *ReviewQuery withNotificationRecord *NotificationRecordQuery modifiers []func(s *sql.Selector) @@ -92,6 +94,28 @@ func (eq *EventQuery) QueryDeployment() *DeploymentQuery { return query } +// QueryDeploymentStatus chains the current query on the "deployment_status" edge. +func (eq *EventQuery) QueryDeploymentStatus() *DeploymentStatusQuery { + query := &DeploymentStatusQuery{config: eq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := eq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := eq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(event.Table, event.FieldID, selector), + sqlgraph.To(deploymentstatus.Table, deploymentstatus.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, event.DeploymentStatusTable, event.DeploymentStatusColumn), + ) + fromU = sqlgraph.SetNeighbors(eq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryReview chains the current query on the "review" edge. func (eq *EventQuery) QueryReview() *ReviewQuery { query := &ReviewQuery{config: eq.config} @@ -318,6 +342,7 @@ func (eq *EventQuery) Clone() *EventQuery { order: append([]OrderFunc{}, eq.order...), predicates: append([]predicate.Event{}, eq.predicates...), withDeployment: eq.withDeployment.Clone(), + withDeploymentStatus: eq.withDeploymentStatus.Clone(), withReview: eq.withReview.Clone(), withNotificationRecord: eq.withNotificationRecord.Clone(), // clone intermediate query. @@ -338,6 +363,17 @@ func (eq *EventQuery) WithDeployment(opts ...func(*DeploymentQuery)) *EventQuery return eq } +// WithDeploymentStatus tells the query-builder to eager-load the nodes that are connected to +// the "deployment_status" edge. The optional arguments are used to configure the query builder of the edge. +func (eq *EventQuery) WithDeploymentStatus(opts ...func(*DeploymentStatusQuery)) *EventQuery { + query := &DeploymentStatusQuery{config: eq.config} + for _, opt := range opts { + opt(query) + } + eq.withDeploymentStatus = query + return eq +} + // WithReview tells the query-builder to eager-load the nodes that are connected to // the "review" edge. The optional arguments are used to configure the query builder of the edge. func (eq *EventQuery) WithReview(opts ...func(*ReviewQuery)) *EventQuery { @@ -425,8 +461,9 @@ func (eq *EventQuery) sqlAll(ctx context.Context) ([]*Event, error) { var ( nodes = []*Event{} _spec = eq.querySpec() - loadedTypes = [3]bool{ + loadedTypes = [4]bool{ eq.withDeployment != nil, + eq.withDeploymentStatus != nil, eq.withReview != nil, eq.withNotificationRecord != nil, } @@ -480,6 +517,32 @@ func (eq *EventQuery) sqlAll(ctx context.Context) ([]*Event, error) { } } + if query := eq.withDeploymentStatus; query != nil { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Event) + for i := range nodes { + fk := nodes[i].DeploymentStatusID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(deploymentstatus.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_status_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.DeploymentStatus = n + } + } + } + if query := eq.withReview; query != nil { ids := make([]int, 0, len(nodes)) nodeids := make(map[int][]*Event) diff --git a/model/ent/event_update.go b/model/ent/event_update.go index cddcfeba..be3759c2 100644 --- a/model/ent/event_update.go +++ b/model/ent/event_update.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" + "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/notificationrecord" "github.com/gitploy-io/gitploy/model/ent/predicate" @@ -77,6 +78,26 @@ func (eu *EventUpdate) ClearDeploymentID() *EventUpdate { return eu } +// SetDeploymentStatusID sets the "deployment_status_id" field. +func (eu *EventUpdate) SetDeploymentStatusID(i int) *EventUpdate { + eu.mutation.SetDeploymentStatusID(i) + return eu +} + +// SetNillableDeploymentStatusID sets the "deployment_status_id" field if the given value is not nil. +func (eu *EventUpdate) SetNillableDeploymentStatusID(i *int) *EventUpdate { + if i != nil { + eu.SetDeploymentStatusID(*i) + } + return eu +} + +// ClearDeploymentStatusID clears the value of the "deployment_status_id" field. +func (eu *EventUpdate) ClearDeploymentStatusID() *EventUpdate { + eu.mutation.ClearDeploymentStatusID() + return eu +} + // SetReviewID sets the "review_id" field. func (eu *EventUpdate) SetReviewID(i int) *EventUpdate { eu.mutation.SetReviewID(i) @@ -129,6 +150,11 @@ func (eu *EventUpdate) SetDeployment(d *Deployment) *EventUpdate { return eu.SetDeploymentID(d.ID) } +// SetDeploymentStatus sets the "deployment_status" edge to the DeploymentStatus entity. +func (eu *EventUpdate) SetDeploymentStatus(d *DeploymentStatus) *EventUpdate { + return eu.SetDeploymentStatusID(d.ID) +} + // SetReview sets the "review" edge to the Review entity. func (eu *EventUpdate) SetReview(r *Review) *EventUpdate { return eu.SetReviewID(r.ID) @@ -164,6 +190,12 @@ func (eu *EventUpdate) ClearDeployment() *EventUpdate { return eu } +// ClearDeploymentStatus clears the "deployment_status" edge to the DeploymentStatus entity. +func (eu *EventUpdate) ClearDeploymentStatus() *EventUpdate { + eu.mutation.ClearDeploymentStatus() + return eu +} + // ClearReview clears the "review" edge to the Review entity. func (eu *EventUpdate) ClearReview() *EventUpdate { eu.mutation.ClearReview() @@ -345,6 +377,41 @@ func (eu *EventUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if eu.mutation.DeploymentStatusCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: event.DeploymentStatusTable, + Columns: []string{event.DeploymentStatusColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := eu.mutation.DeploymentStatusIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: event.DeploymentStatusTable, + Columns: []string{event.DeploymentStatusColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if eu.mutation.ReviewCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -480,6 +547,26 @@ func (euo *EventUpdateOne) ClearDeploymentID() *EventUpdateOne { return euo } +// SetDeploymentStatusID sets the "deployment_status_id" field. +func (euo *EventUpdateOne) SetDeploymentStatusID(i int) *EventUpdateOne { + euo.mutation.SetDeploymentStatusID(i) + return euo +} + +// SetNillableDeploymentStatusID sets the "deployment_status_id" field if the given value is not nil. +func (euo *EventUpdateOne) SetNillableDeploymentStatusID(i *int) *EventUpdateOne { + if i != nil { + euo.SetDeploymentStatusID(*i) + } + return euo +} + +// ClearDeploymentStatusID clears the value of the "deployment_status_id" field. +func (euo *EventUpdateOne) ClearDeploymentStatusID() *EventUpdateOne { + euo.mutation.ClearDeploymentStatusID() + return euo +} + // SetReviewID sets the "review_id" field. func (euo *EventUpdateOne) SetReviewID(i int) *EventUpdateOne { euo.mutation.SetReviewID(i) @@ -532,6 +619,11 @@ func (euo *EventUpdateOne) SetDeployment(d *Deployment) *EventUpdateOne { return euo.SetDeploymentID(d.ID) } +// SetDeploymentStatus sets the "deployment_status" edge to the DeploymentStatus entity. +func (euo *EventUpdateOne) SetDeploymentStatus(d *DeploymentStatus) *EventUpdateOne { + return euo.SetDeploymentStatusID(d.ID) +} + // SetReview sets the "review" edge to the Review entity. func (euo *EventUpdateOne) SetReview(r *Review) *EventUpdateOne { return euo.SetReviewID(r.ID) @@ -567,6 +659,12 @@ func (euo *EventUpdateOne) ClearDeployment() *EventUpdateOne { return euo } +// ClearDeploymentStatus clears the "deployment_status" edge to the DeploymentStatus entity. +func (euo *EventUpdateOne) ClearDeploymentStatus() *EventUpdateOne { + euo.mutation.ClearDeploymentStatus() + return euo +} + // ClearReview clears the "review" edge to the Review entity. func (euo *EventUpdateOne) ClearReview() *EventUpdateOne { euo.mutation.ClearReview() @@ -772,6 +870,41 @@ func (euo *EventUpdateOne) sqlSave(ctx context.Context) (_node *Event, err error } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if euo.mutation.DeploymentStatusCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: event.DeploymentStatusTable, + Columns: []string{event.DeploymentStatusColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := euo.mutation.DeploymentStatusIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: event.DeploymentStatusTable, + Columns: []string{event.DeploymentStatusColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if euo.mutation.ReviewCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, diff --git a/model/ent/migrate/schema.go b/model/ent/migrate/schema.go index 587d1d18..be677e69 100644 --- a/model/ent/migrate/schema.go +++ b/model/ent/migrate/schema.go @@ -174,11 +174,12 @@ var ( // EventsColumns holds the columns for the "events" table. EventsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "kind", Type: field.TypeEnum, Enums: []string{"deployment", "review", "approval"}}, + {Name: "kind", Type: field.TypeEnum, Enums: []string{"deployment", "deployment_status", "review"}}, {Name: "type", Type: field.TypeEnum, Enums: []string{"created", "updated", "deleted"}}, {Name: "created_at", Type: field.TypeTime}, {Name: "deleted_id", Type: field.TypeInt, Nullable: true}, {Name: "deployment_id", Type: field.TypeInt, Nullable: true}, + {Name: "deployment_status_id", Type: field.TypeInt, Nullable: true}, {Name: "review_id", Type: field.TypeInt, Nullable: true}, } // EventsTable holds the schema information for the "events" table. @@ -194,8 +195,14 @@ var ( OnDelete: schema.Cascade, }, { - Symbol: "events_reviews_event", + Symbol: "events_deployment_status_event", Columns: []*schema.Column{EventsColumns[6]}, + RefColumns: []*schema.Column{DeploymentStatusColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "events_reviews_event", + Columns: []*schema.Column{EventsColumns[7]}, RefColumns: []*schema.Column{ReviewsColumns[0]}, OnDelete: schema.Cascade, }, @@ -422,7 +429,8 @@ func init() { DeploymentStatisticsTable.ForeignKeys[0].RefTable = ReposTable DeploymentStatusTable.ForeignKeys[0].RefTable = DeploymentsTable EventsTable.ForeignKeys[0].RefTable = DeploymentsTable - EventsTable.ForeignKeys[1].RefTable = ReviewsTable + EventsTable.ForeignKeys[1].RefTable = DeploymentStatusTable + EventsTable.ForeignKeys[2].RefTable = ReviewsTable LocksTable.ForeignKeys[0].RefTable = ReposTable LocksTable.ForeignKeys[1].RefTable = UsersTable NotificationRecordsTable.ForeignKeys[0].RefTable = EventsTable diff --git a/model/ent/mutation.go b/model/ent/mutation.go index c14beeed..edf8399e 100644 --- a/model/ent/mutation.go +++ b/model/ent/mutation.go @@ -3645,6 +3645,9 @@ type DeploymentStatusMutation struct { clearedFields map[string]struct{} deployment *int cleareddeployment bool + event map[int]struct{} + removedevent map[int]struct{} + clearedevent bool done bool oldValue func(context.Context) (*DeploymentStatus, error) predicates []predicate.DeploymentStatus @@ -4016,6 +4019,60 @@ func (m *DeploymentStatusMutation) ResetDeployment() { m.cleareddeployment = false } +// AddEventIDs adds the "event" edge to the Event entity by ids. +func (m *DeploymentStatusMutation) AddEventIDs(ids ...int) { + if m.event == nil { + m.event = make(map[int]struct{}) + } + for i := range ids { + m.event[ids[i]] = struct{}{} + } +} + +// ClearEvent clears the "event" edge to the Event entity. +func (m *DeploymentStatusMutation) ClearEvent() { + m.clearedevent = true +} + +// EventCleared reports if the "event" edge to the Event entity was cleared. +func (m *DeploymentStatusMutation) EventCleared() bool { + return m.clearedevent +} + +// RemoveEventIDs removes the "event" edge to the Event entity by IDs. +func (m *DeploymentStatusMutation) RemoveEventIDs(ids ...int) { + if m.removedevent == nil { + m.removedevent = make(map[int]struct{}) + } + for i := range ids { + delete(m.event, ids[i]) + m.removedevent[ids[i]] = struct{}{} + } +} + +// RemovedEvent returns the removed IDs of the "event" edge to the Event entity. +func (m *DeploymentStatusMutation) RemovedEventIDs() (ids []int) { + for id := range m.removedevent { + ids = append(ids, id) + } + return +} + +// EventIDs returns the "event" edge IDs in the mutation. +func (m *DeploymentStatusMutation) EventIDs() (ids []int) { + for id := range m.event { + ids = append(ids, id) + } + return +} + +// ResetEvent resets all changes to the "event" edge. +func (m *DeploymentStatusMutation) ResetEvent() { + m.event = nil + m.clearedevent = false + m.removedevent = nil +} + // Where appends a list predicates to the DeploymentStatusMutation builder. func (m *DeploymentStatusMutation) Where(ps ...predicate.DeploymentStatus) { m.predicates = append(m.predicates, ps...) @@ -4237,10 +4294,13 @@ func (m *DeploymentStatusMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *DeploymentStatusMutation) AddedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 2) if m.deployment != nil { edges = append(edges, deploymentstatus.EdgeDeployment) } + if m.event != nil { + edges = append(edges, deploymentstatus.EdgeEvent) + } return edges } @@ -4252,13 +4312,22 @@ func (m *DeploymentStatusMutation) AddedIDs(name string) []ent.Value { if id := m.deployment; id != nil { return []ent.Value{*id} } + case deploymentstatus.EdgeEvent: + ids := make([]ent.Value, 0, len(m.event)) + for id := range m.event { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *DeploymentStatusMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 2) + if m.removedevent != nil { + edges = append(edges, deploymentstatus.EdgeEvent) + } return edges } @@ -4266,16 +4335,25 @@ func (m *DeploymentStatusMutation) RemovedEdges() []string { // the given name in this mutation. func (m *DeploymentStatusMutation) RemovedIDs(name string) []ent.Value { switch name { + case deploymentstatus.EdgeEvent: + ids := make([]ent.Value, 0, len(m.removedevent)) + for id := range m.removedevent { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *DeploymentStatusMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 2) if m.cleareddeployment { edges = append(edges, deploymentstatus.EdgeDeployment) } + if m.clearedevent { + edges = append(edges, deploymentstatus.EdgeEvent) + } return edges } @@ -4285,6 +4363,8 @@ func (m *DeploymentStatusMutation) EdgeCleared(name string) bool { switch name { case deploymentstatus.EdgeDeployment: return m.cleareddeployment + case deploymentstatus.EdgeEvent: + return m.clearedevent } return false } @@ -4307,6 +4387,9 @@ func (m *DeploymentStatusMutation) ResetEdge(name string) error { case deploymentstatus.EdgeDeployment: m.ResetDeployment() return nil + case deploymentstatus.EdgeEvent: + m.ResetEvent() + return nil } return fmt.Errorf("unknown DeploymentStatus edge %s", name) } @@ -4325,6 +4408,8 @@ type EventMutation struct { clearedFields map[string]struct{} deployment *int cleareddeployment bool + deployment_status *int + cleareddeployment_status bool review *int clearedreview bool notification_record *int @@ -4589,6 +4674,55 @@ func (m *EventMutation) ResetDeploymentID() { delete(m.clearedFields, event.FieldDeploymentID) } +// SetDeploymentStatusID sets the "deployment_status_id" field. +func (m *EventMutation) SetDeploymentStatusID(i int) { + m.deployment_status = &i +} + +// DeploymentStatusID returns the value of the "deployment_status_id" field in the mutation. +func (m *EventMutation) DeploymentStatusID() (r int, exists bool) { + v := m.deployment_status + if v == nil { + return + } + return *v, true +} + +// OldDeploymentStatusID returns the old "deployment_status_id" field's value of the Event entity. +// If the Event 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 *EventMutation) OldDeploymentStatusID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeploymentStatusID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeploymentStatusID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeploymentStatusID: %w", err) + } + return oldValue.DeploymentStatusID, nil +} + +// ClearDeploymentStatusID clears the value of the "deployment_status_id" field. +func (m *EventMutation) ClearDeploymentStatusID() { + m.deployment_status = nil + m.clearedFields[event.FieldDeploymentStatusID] = struct{}{} +} + +// DeploymentStatusIDCleared returns if the "deployment_status_id" field was cleared in this mutation. +func (m *EventMutation) DeploymentStatusIDCleared() bool { + _, ok := m.clearedFields[event.FieldDeploymentStatusID] + return ok +} + +// ResetDeploymentStatusID resets all changes to the "deployment_status_id" field. +func (m *EventMutation) ResetDeploymentStatusID() { + m.deployment_status = nil + delete(m.clearedFields, event.FieldDeploymentStatusID) +} + // SetReviewID sets the "review_id" field. func (m *EventMutation) SetReviewID(i int) { m.review = &i @@ -4734,6 +4868,32 @@ func (m *EventMutation) ResetDeployment() { m.cleareddeployment = false } +// ClearDeploymentStatus clears the "deployment_status" edge to the DeploymentStatus entity. +func (m *EventMutation) ClearDeploymentStatus() { + m.cleareddeployment_status = true +} + +// DeploymentStatusCleared reports if the "deployment_status" edge to the DeploymentStatus entity was cleared. +func (m *EventMutation) DeploymentStatusCleared() bool { + return m.DeploymentStatusIDCleared() || m.cleareddeployment_status +} + +// DeploymentStatusIDs returns the "deployment_status" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// DeploymentStatusID instead. It exists only for internal usage by the builders. +func (m *EventMutation) DeploymentStatusIDs() (ids []int) { + if id := m.deployment_status; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetDeploymentStatus resets all changes to the "deployment_status" edge. +func (m *EventMutation) ResetDeploymentStatus() { + m.deployment_status = nil + m.cleareddeployment_status = false +} + // ClearReview clears the "review" edge to the Review entity. func (m *EventMutation) ClearReview() { m.clearedreview = true @@ -4818,7 +4978,7 @@ func (m *EventMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *EventMutation) Fields() []string { - fields := make([]string, 0, 6) + fields := make([]string, 0, 7) if m.kind != nil { fields = append(fields, event.FieldKind) } @@ -4831,6 +4991,9 @@ func (m *EventMutation) Fields() []string { if m.deployment != nil { fields = append(fields, event.FieldDeploymentID) } + if m.deployment_status != nil { + fields = append(fields, event.FieldDeploymentStatusID) + } if m.review != nil { fields = append(fields, event.FieldReviewID) } @@ -4853,6 +5016,8 @@ func (m *EventMutation) Field(name string) (ent.Value, bool) { return m.CreatedAt() case event.FieldDeploymentID: return m.DeploymentID() + case event.FieldDeploymentStatusID: + return m.DeploymentStatusID() case event.FieldReviewID: return m.ReviewID() case event.FieldDeletedID: @@ -4874,6 +5039,8 @@ func (m *EventMutation) OldField(ctx context.Context, name string) (ent.Value, e return m.OldCreatedAt(ctx) case event.FieldDeploymentID: return m.OldDeploymentID(ctx) + case event.FieldDeploymentStatusID: + return m.OldDeploymentStatusID(ctx) case event.FieldReviewID: return m.OldReviewID(ctx) case event.FieldDeletedID: @@ -4915,6 +5082,13 @@ func (m *EventMutation) SetField(name string, value ent.Value) error { } m.SetDeploymentID(v) return nil + case event.FieldDeploymentStatusID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeploymentStatusID(v) + return nil case event.FieldReviewID: v, ok := value.(int) if !ok { @@ -4977,6 +5151,9 @@ func (m *EventMutation) ClearedFields() []string { if m.FieldCleared(event.FieldDeploymentID) { fields = append(fields, event.FieldDeploymentID) } + if m.FieldCleared(event.FieldDeploymentStatusID) { + fields = append(fields, event.FieldDeploymentStatusID) + } if m.FieldCleared(event.FieldReviewID) { fields = append(fields, event.FieldReviewID) } @@ -5000,6 +5177,9 @@ func (m *EventMutation) ClearField(name string) error { case event.FieldDeploymentID: m.ClearDeploymentID() return nil + case event.FieldDeploymentStatusID: + m.ClearDeploymentStatusID() + return nil case event.FieldReviewID: m.ClearReviewID() return nil @@ -5026,6 +5206,9 @@ func (m *EventMutation) ResetField(name string) error { case event.FieldDeploymentID: m.ResetDeploymentID() return nil + case event.FieldDeploymentStatusID: + m.ResetDeploymentStatusID() + return nil case event.FieldReviewID: m.ResetReviewID() return nil @@ -5038,10 +5221,13 @@ func (m *EventMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *EventMutation) AddedEdges() []string { - edges := make([]string, 0, 3) + edges := make([]string, 0, 4) if m.deployment != nil { edges = append(edges, event.EdgeDeployment) } + if m.deployment_status != nil { + edges = append(edges, event.EdgeDeploymentStatus) + } if m.review != nil { edges = append(edges, event.EdgeReview) } @@ -5059,6 +5245,10 @@ func (m *EventMutation) AddedIDs(name string) []ent.Value { if id := m.deployment; id != nil { return []ent.Value{*id} } + case event.EdgeDeploymentStatus: + if id := m.deployment_status; id != nil { + return []ent.Value{*id} + } case event.EdgeReview: if id := m.review; id != nil { return []ent.Value{*id} @@ -5073,7 +5263,7 @@ func (m *EventMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *EventMutation) RemovedEdges() []string { - edges := make([]string, 0, 3) + edges := make([]string, 0, 4) return edges } @@ -5087,10 +5277,13 @@ func (m *EventMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *EventMutation) ClearedEdges() []string { - edges := make([]string, 0, 3) + edges := make([]string, 0, 4) if m.cleareddeployment { edges = append(edges, event.EdgeDeployment) } + if m.cleareddeployment_status { + edges = append(edges, event.EdgeDeploymentStatus) + } if m.clearedreview { edges = append(edges, event.EdgeReview) } @@ -5106,6 +5299,8 @@ func (m *EventMutation) EdgeCleared(name string) bool { switch name { case event.EdgeDeployment: return m.cleareddeployment + case event.EdgeDeploymentStatus: + return m.cleareddeployment_status case event.EdgeReview: return m.clearedreview case event.EdgeNotificationRecord: @@ -5121,6 +5316,9 @@ func (m *EventMutation) ClearEdge(name string) error { case event.EdgeDeployment: m.ClearDeployment() return nil + case event.EdgeDeploymentStatus: + m.ClearDeploymentStatus() + return nil case event.EdgeReview: m.ClearReview() return nil @@ -5138,6 +5336,9 @@ func (m *EventMutation) ResetEdge(name string) error { case event.EdgeDeployment: m.ResetDeployment() return nil + case event.EdgeDeploymentStatus: + m.ResetDeploymentStatus() + return nil case event.EdgeReview: m.ResetReview() return nil diff --git a/model/ent/schema/deploymentstatus.go b/model/ent/schema/deploymentstatus.go index 13cf7695..b71b0f9b 100644 --- a/model/ent/schema/deploymentstatus.go +++ b/model/ent/schema/deploymentstatus.go @@ -2,6 +2,7 @@ package schema import ( "entgo.io/ent" + "entgo.io/ent/dialect/entsql" "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" ) @@ -38,5 +39,9 @@ func (DeploymentStatus) Edges() []ent.Edge { Field("deployment_id"). Unique(). Required(), + edge.To("event", Event.Type). + Annotations(entsql.Annotation{ + OnDelete: entsql.Cascade, + }), } } diff --git a/model/ent/schema/event.go b/model/ent/schema/event.go index c7f1b4c6..65e5fc29 100644 --- a/model/ent/schema/event.go +++ b/model/ent/schema/event.go @@ -18,9 +18,8 @@ func (Event) Fields() []ent.Field { field.Enum("kind"). Values( "deployment", + "deployment_status", "review", - // Deprecated values: - "approval", ), field.Enum("type"). Values( @@ -32,6 +31,8 @@ func (Event) Fields() []ent.Field { Default(nowUTC), field.Int("deployment_id"). Optional(), + field.Int("deployment_status_id"). + Optional(), field.Int("review_id"). Optional(), // This field is filled when the type is 'deleted'. @@ -47,6 +48,10 @@ func (Event) Edges() []ent.Edge { Ref("event"). Field("deployment_id"). Unique(), + edge.From("deployment_status", DeploymentStatus.Type). + Ref("event"). + Field("deployment_status_id"). + Unique(), edge.From("review", Review.Type). Ref("event"). Field("review_id"). From 5f6f9c8f219228c31050aef16066a4441a735e43 Mon Sep 17 00:00:00 2001 From: noah Date: Sun, 17 Apr 2022 17:46:54 +0900 Subject: [PATCH 2/9] Move `CreateEvent` into `CreateDeploymentStatus` --- internal/interactor/deployment.go | 46 ++++++++++------ internal/interactor/deployment_test.go | 4 +- internal/interactor/interface.go | 5 +- internal/interactor/mock/pkg.go | 54 +++++-------------- internal/pkg/store/deploymentstatus.go | 37 +++++-------- internal/server/api/v1/repos/interface.go | 2 - .../server/api/v1/repos/mock/interactor.go | 15 ------ internal/server/hooks/hook.go | 11 +--- internal/server/hooks/hook_test.go | 7 +-- internal/server/hooks/interface.go | 3 +- internal/server/hooks/mock/interactor.go | 29 +++------- 11 files changed, 68 insertions(+), 145 deletions(-) diff --git a/internal/interactor/deployment.go b/internal/interactor/deployment.go index 52ec514d..7316f319 100644 --- a/internal/interactor/deployment.go +++ b/internal/interactor/deployment.go @@ -121,14 +121,14 @@ func (i *DeploymentInteractor) Deploy(ctx context.Context, u *ent.User, r *ent.R i.log.Error("Failed to request a review.", zap.Errors("errs", errs)) } - i.log.Debug("Dispatch a event.") - if _, err := i.store.CreateEvent(ctx, &ent.Event{ - Kind: event.KindDeployment, - Type: event.TypeCreated, + if _, err := i.CreateDeploymentStatus(ctx, &ent.DeploymentStatus{ + Status: string(deployment.StatusWaiting), + Description: "Gitploy waits the reviews.", DeploymentID: d.ID, }); err != nil { - i.log.Error("Failed to create the event.", zap.Error(err)) + i.log.Error("Failed to create a deployment status.", zap.Error(err)) } + return d, nil } @@ -149,20 +149,14 @@ func (i *DeploymentInteractor) Deploy(ctx context.Context, u *ent.User, r *ent.R return nil, fmt.Errorf("It failed to save a new deployment.: %w", err) } - i.store.CreateDeploymentStatus(ctx, &ent.DeploymentStatus{ + if _, err := i.CreateDeploymentStatus(ctx, &ent.DeploymentStatus{ Status: string(deployment.StatusCreated), Description: "Gitploy starts to deploy.", DeploymentID: d.ID, - }) - - i.log.Debug("Dispatch a event.") - if _, err := i.store.CreateEvent(ctx, &ent.Event{ - Kind: event.KindDeployment, - Type: event.TypeCreated, - DeploymentID: d.ID, }); err != nil { - i.log.Error("Failed to create the event.", zap.Error(err)) + i.log.Error("Failed to create a deployment status.", zap.Error(err)) } + return d, nil } @@ -237,9 +231,9 @@ func (i *DeploymentInteractor) DeployToRemote(ctx context.Context, u *ent.User, return nil, err } - i.store.CreateDeploymentStatus(ctx, &ent.DeploymentStatus{ + i.CreateDeploymentStatus(ctx, &ent.DeploymentStatus{ Status: string(deployment.StatusCreated), - Description: "Gitploy creates a new deployment.", + Description: "Gitploy start to deploy.", DeploymentID: d.ID, }) @@ -258,6 +252,24 @@ func (i *DeploymentInteractor) createRemoteDeployment(ctx context.Context, u *en return i.scm.CreateRemoteDeployment(ctx, u, r, d, env) } +// CreateDeploymentStatus create a DeploymentStatus and dispatch the event. +func (i *DeploymentInteractor) CreateDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { + ds, err := i.store.CreateEntDeploymentStatus(ctx, ds) + if err != nil { + return nil, err + } + + if _, err := i.store.CreateEvent(ctx, &ent.Event{ + Kind: event.KindDeploymentStatus, + Type: event.TypeCreated, + DeploymentStatusID: ds.ID, + }); err != nil { + i.log.Error("Failed to dispatch the event.", zap.Error(err)) + } + + return ds, nil +} + func (i *DeploymentInteractor) runClosingInactiveDeployment(stop <-chan struct{}) { ctx := context.Background() @@ -295,7 +307,7 @@ L: continue } - if _, err := i.store.CreateDeploymentStatus(ctx, s); err != nil { + if _, err := i.CreateDeploymentStatus(ctx, s); err != nil { i.log.Error("It has failed to create a new deployment status.", zap.Error(err)) continue } diff --git a/internal/interactor/deployment_test.go b/internal/interactor/deployment_test.go index cb299d6e..1bd1af32 100644 --- a/internal/interactor/deployment_test.go +++ b/internal/interactor/deployment_test.go @@ -57,7 +57,7 @@ func TestInteractor_Deploy(t *testing.T) { store. EXPECT(). - CreateDeploymentStatus(ctx, gomock.AssignableToTypeOf(&ent.DeploymentStatus{})) + CreateEntDeploymentStatus(ctx, gomock.AssignableToTypeOf(&ent.DeploymentStatus{})) it := i.NewInteractor(&i.InteractorConfig{ Store: store, @@ -160,7 +160,7 @@ func TestInteractor_DeployToRemote(t *testing.T) { store. EXPECT(). - CreateDeploymentStatus(ctx, gomock.AssignableToTypeOf(&ent.DeploymentStatus{})) + CreateEntDeploymentStatus(ctx, gomock.AssignableToTypeOf(&ent.DeploymentStatus{})) it := i.NewInteractor(&i.InteractorConfig{ Store: store, diff --git a/internal/interactor/interface.go b/internal/interactor/interface.go index 12204939..b4d305cd 100644 --- a/internal/interactor/interface.go +++ b/internal/interactor/interface.go @@ -43,8 +43,9 @@ type ( // PermStore defines operations for working with deployment_statuses. DeploymentStatusStore interface { ListDeploymentStatuses(ctx context.Context, d *ent.Deployment) ([]*ent.DeploymentStatus, error) - CreateDeploymentStatus(ctx context.Context, s *ent.DeploymentStatus) (*ent.DeploymentStatus, error) - SyncDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) + // CreateEntDeploymentStatus create a DeploymentStatus entity to the store. + // Ent is appended to distinguish it from the interactor. + CreateEntDeploymentStatus(ctx context.Context, s *ent.DeploymentStatus) (*ent.DeploymentStatus, error) } SCM interface { diff --git a/internal/interactor/mock/pkg.go b/internal/interactor/mock/pkg.go index e9021537..695c2645 100644 --- a/internal/interactor/mock/pkg.go +++ b/internal/interactor/mock/pkg.go @@ -172,19 +172,19 @@ func (mr *MockStoreMockRecorder) CreateDeploymentStatistics(ctx, s interface{}) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateDeploymentStatistics", reflect.TypeOf((*MockStore)(nil).CreateDeploymentStatistics), ctx, s) } -// CreateDeploymentStatus mocks base method. -func (m *MockStore) CreateDeploymentStatus(ctx context.Context, s *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { +// CreateEntDeploymentStatus mocks base method. +func (m *MockStore) CreateEntDeploymentStatus(ctx context.Context, s *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateDeploymentStatus", ctx, s) + ret := m.ctrl.Call(m, "CreateEntDeploymentStatus", ctx, s) ret0, _ := ret[0].(*ent.DeploymentStatus) ret1, _ := ret[1].(error) return ret0, ret1 } -// CreateDeploymentStatus indicates an expected call of CreateDeploymentStatus. -func (mr *MockStoreMockRecorder) CreateDeploymentStatus(ctx, s interface{}) *gomock.Call { +// CreateEntDeploymentStatus indicates an expected call of CreateEntDeploymentStatus. +func (mr *MockStoreMockRecorder) CreateEntDeploymentStatus(ctx, s interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateDeploymentStatus", reflect.TypeOf((*MockStore)(nil).CreateDeploymentStatus), ctx, s) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateEntDeploymentStatus", reflect.TypeOf((*MockStore)(nil).CreateEntDeploymentStatus), ctx, s) } // CreateEvent mocks base method. @@ -844,21 +844,6 @@ func (mr *MockStoreMockRecorder) SearchUsers(ctx, opts interface{}) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SearchUsers", reflect.TypeOf((*MockStore)(nil).SearchUsers), ctx, opts) } -// SyncDeploymentStatus mocks base method. -func (m *MockStore) SyncDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SyncDeploymentStatus", ctx, ds) - ret0, _ := ret[0].(*ent.DeploymentStatus) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// SyncDeploymentStatus indicates an expected call of SyncDeploymentStatus. -func (mr *MockStoreMockRecorder) SyncDeploymentStatus(ctx, ds interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SyncDeploymentStatus", reflect.TypeOf((*MockStore)(nil).SyncDeploymentStatus), ctx, ds) -} - // SyncRepo mocks base method. func (m *MockStore) SyncRepo(ctx context.Context, r *extent.RemoteRepo) (*ent.Repo, error) { m.ctrl.T.Helper() @@ -1115,19 +1100,19 @@ func (m *MockDeploymentStatusStore) EXPECT() *MockDeploymentStatusStoreMockRecor return m.recorder } -// CreateDeploymentStatus mocks base method. -func (m *MockDeploymentStatusStore) CreateDeploymentStatus(ctx context.Context, s *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { +// CreateEntDeploymentStatus mocks base method. +func (m *MockDeploymentStatusStore) CreateEntDeploymentStatus(ctx context.Context, s *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateDeploymentStatus", ctx, s) + ret := m.ctrl.Call(m, "CreateEntDeploymentStatus", ctx, s) ret0, _ := ret[0].(*ent.DeploymentStatus) ret1, _ := ret[1].(error) return ret0, ret1 } -// CreateDeploymentStatus indicates an expected call of CreateDeploymentStatus. -func (mr *MockDeploymentStatusStoreMockRecorder) CreateDeploymentStatus(ctx, s interface{}) *gomock.Call { +// CreateEntDeploymentStatus indicates an expected call of CreateEntDeploymentStatus. +func (mr *MockDeploymentStatusStoreMockRecorder) CreateEntDeploymentStatus(ctx, s interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateDeploymentStatus", reflect.TypeOf((*MockDeploymentStatusStore)(nil).CreateDeploymentStatus), ctx, s) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateEntDeploymentStatus", reflect.TypeOf((*MockDeploymentStatusStore)(nil).CreateEntDeploymentStatus), ctx, s) } // ListDeploymentStatuses mocks base method. @@ -1145,21 +1130,6 @@ func (mr *MockDeploymentStatusStoreMockRecorder) ListDeploymentStatuses(ctx, d i return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListDeploymentStatuses", reflect.TypeOf((*MockDeploymentStatusStore)(nil).ListDeploymentStatuses), ctx, d) } -// SyncDeploymentStatus mocks base method. -func (m *MockDeploymentStatusStore) SyncDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SyncDeploymentStatus", ctx, ds) - ret0, _ := ret[0].(*ent.DeploymentStatus) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// SyncDeploymentStatus indicates an expected call of SyncDeploymentStatus. -func (mr *MockDeploymentStatusStoreMockRecorder) SyncDeploymentStatus(ctx, ds interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SyncDeploymentStatus", reflect.TypeOf((*MockDeploymentStatusStore)(nil).SyncDeploymentStatus), ctx, ds) -} - // MockSCM is a mock of SCM interface. type MockSCM struct { ctrl *gomock.Controller diff --git a/internal/pkg/store/deploymentstatus.go b/internal/pkg/store/deploymentstatus.go index b7098d45..18f9c077 100644 --- a/internal/pkg/store/deploymentstatus.go +++ b/internal/pkg/store/deploymentstatus.go @@ -21,40 +21,27 @@ func (s *Store) ListDeploymentStatuses(ctx context.Context, d *ent.Deployment) ( return dss, nil } -func (s *Store) CreateDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { - ret, err := s.c.DeploymentStatus. - Create(). +func (s *Store) CreateEntDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { + // Build the query creating a deployment status. + qry := s.c.DeploymentStatus.Create(). SetStatus(ds.Status). SetDescription(ds.Description). SetLogURL(ds.LogURL). - SetDeploymentID(ds.DeploymentID). - Save(ctx) - if ent.IsConstraintError(err) { - return nil, e.NewErrorWithMessage( - e.ErrorCodeEntityUnprocessable, - fmt.Sprintf("Failed to create a deployment status. The value of \"%s\" field is invalid.", err.(*ent.ValidationError).Name), - err) - } else if err != nil { - return nil, e.NewError(e.ErrorCodeInternalError, err) + SetDeploymentID(ds.DeploymentID) + + if !ds.CreatedAt.IsZero() { + qry.SetCreatedAt(ds.CreatedAt.UTC()) } - return ret, nil -} + if !ds.UpdatedAt.IsZero() { + qry.SetUpdatedAt(ds.UpdatedAt.UTC()) + } -func (s *Store) SyncDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { - ret, err := s.c.DeploymentStatus. - Create(). - SetStatus(ds.Status). - SetDescription(ds.Description). - SetLogURL(ds.LogURL). - SetDeploymentID(ds.DeploymentID). - SetCreatedAt(ds.CreatedAt). - SetUpdatedAt(ds.UpdatedAt). - Save(ctx) + ret, err := qry.Save(ctx) if ent.IsConstraintError(err) { return nil, e.NewErrorWithMessage( e.ErrorCodeEntityUnprocessable, - fmt.Sprintf("Failed to sync the deployment status. The value of \"%s\" field is invalid.", err.(*ent.ValidationError).Name), + fmt.Sprintf("Failed to create a deployment status. The value of \"%s\" field is invalid.", err.(*ent.ValidationError).Name), err) } else if err != nil { return nil, e.NewError(e.ErrorCodeInternalError, err) diff --git a/internal/server/api/v1/repos/interface.go b/internal/server/api/v1/repos/interface.go index 5c161108..fbf86191 100644 --- a/internal/server/api/v1/repos/interface.go +++ b/internal/server/api/v1/repos/interface.go @@ -48,8 +48,6 @@ type ( UpdateLock(ctx context.Context, l *ent.Lock) (*ent.Lock, error) DeleteLock(ctx context.Context, l *ent.Lock) error - CreateEvent(ctx context.Context, e *ent.Event) (*ent.Event, error) - ListCommits(ctx context.Context, u *ent.User, r *ent.Repo, branch string, opt *i.ListOptions) ([]*extent.Commit, error) CompareCommits(ctx context.Context, u *ent.User, r *ent.Repo, base, head string, opt *i.ListOptions) ([]*extent.Commit, []*extent.CommitFile, error) GetCommit(ctx context.Context, u *ent.User, r *ent.Repo, sha string) (*extent.Commit, error) diff --git a/internal/server/api/v1/repos/mock/interactor.go b/internal/server/api/v1/repos/mock/interactor.go index 696776f8..142e711d 100644 --- a/internal/server/api/v1/repos/mock/interactor.go +++ b/internal/server/api/v1/repos/mock/interactor.go @@ -68,21 +68,6 @@ func (mr *MockInteractorMockRecorder) CompareCommits(ctx, u, r, base, head, opt return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CompareCommits", reflect.TypeOf((*MockInteractor)(nil).CompareCommits), ctx, u, r, base, head, opt) } -// CreateEvent mocks base method. -func (m *MockInteractor) CreateEvent(ctx context.Context, e *ent.Event) (*ent.Event, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateEvent", ctx, e) - ret0, _ := ret[0].(*ent.Event) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateEvent indicates an expected call of CreateEvent. -func (mr *MockInteractorMockRecorder) CreateEvent(ctx, e interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateEvent", reflect.TypeOf((*MockInteractor)(nil).CreateEvent), ctx, e) -} - // CreateLock mocks base method. func (m *MockInteractor) CreateLock(ctx context.Context, l *ent.Lock) (*ent.Lock, error) { m.ctrl.T.Helper() diff --git a/internal/server/hooks/hook.go b/internal/server/hooks/hook.go index 1c020e56..4a3cf7ea 100644 --- a/internal/server/hooks/hook.go +++ b/internal/server/hooks/hook.go @@ -12,7 +12,6 @@ import ( gb "github.com/gitploy-io/gitploy/internal/server/global" "github.com/gitploy-io/gitploy/model/ent" "github.com/gitploy-io/gitploy/model/ent/deployment" - "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/extent" "github.com/gitploy-io/gitploy/pkg/e" ) @@ -118,7 +117,7 @@ func (h *Hooks) handleGithubDeploymentEvent(c *gin.Context) { } ds.DeploymentID = d.ID - if ds, err = h.i.SyncDeploymentStatus(ctx, ds); err != nil { + if ds, err = h.i.CreateDeploymentStatus(ctx, ds); err != nil { h.log.Check(gb.GetZapLogLevel(err), "Failed to create a new the deployment status.").Write(zap.Error(err)) gb.ResponseWithError(c, err) return @@ -131,14 +130,6 @@ func (h *Hooks) handleGithubDeploymentEvent(c *gin.Context) { return } - if _, err := h.i.CreateEvent(ctx, &ent.Event{ - Kind: event.KindDeployment, - Type: event.TypeUpdated, - DeploymentID: d.ID, - }); err != nil { - h.log.Error("It has failed to create the event.", zap.Error(err)) - } - // Produce statistics when the deployment is success, and production environment. if d.Status == deployment.StatusSuccess && d.ProductionEnvironment && diff --git a/internal/server/hooks/hook_test.go b/internal/server/hooks/hook_test.go index a833506d..9656b41f 100644 --- a/internal/server/hooks/hook_test.go +++ b/internal/server/hooks/hook_test.go @@ -46,7 +46,7 @@ func TestHook_HandleHook(t *testing.T) { m. EXPECT(). - SyncDeploymentStatus(gomock.Any(), gomock.Eq(&ent.DeploymentStatus{ + CreateDeploymentStatus(gomock.Any(), gomock.Eq(&ent.DeploymentStatus{ Status: *e.DeploymentStatus.State, Description: *e.DeploymentStatus.Description, CreatedAt: e.DeploymentStatus.CreatedAt.Time.UTC(), @@ -75,11 +75,6 @@ func TestHook_HandleHook(t *testing.T) { Status: deployment.StatusSuccess, }, nil) - m. - EXPECT(). - CreateEvent(gomock.Any(), gomock.Any()). - Return(&ent.Event{}, nil) - h := NewHooks(&ConfigHooks{}, m) r := gin.New() r.POST("/hooks", h.HandleHook) diff --git a/internal/server/hooks/interface.go b/internal/server/hooks/interface.go index 8f286a68..a0a7a9ee 100644 --- a/internal/server/hooks/interface.go +++ b/internal/server/hooks/interface.go @@ -13,11 +13,10 @@ type ( Interactor interface { FindRepoByID(ctx context.Context, id int64) (*ent.Repo, error) FindDeploymentByUID(ctx context.Context, uid int64) (*ent.Deployment, error) - SyncDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) Deploy(ctx context.Context, u *ent.User, r *ent.Repo, d *ent.Deployment, env *extent.Env) (*ent.Deployment, error) UpdateDeployment(ctx context.Context, d *ent.Deployment) (*ent.Deployment, error) + CreateDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) ProduceDeploymentStatisticsOfRepo(ctx context.Context, r *ent.Repo, d *ent.Deployment) (*ent.DeploymentStatistics, error) - CreateEvent(ctx context.Context, e *ent.Event) (*ent.Event, error) GetEvaluatedConfig(ctx context.Context, u *ent.User, r *ent.Repo, v *extent.EvalValues) (*extent.Config, error) } ) diff --git a/internal/server/hooks/mock/interactor.go b/internal/server/hooks/mock/interactor.go index e7274aed..b3abdb60 100644 --- a/internal/server/hooks/mock/interactor.go +++ b/internal/server/hooks/mock/interactor.go @@ -36,19 +36,19 @@ func (m *MockInteractor) EXPECT() *MockInteractorMockRecorder { return m.recorder } -// CreateEvent mocks base method. -func (m *MockInteractor) CreateEvent(ctx context.Context, e *ent.Event) (*ent.Event, error) { +// CreateDeploymentStatus mocks base method. +func (m *MockInteractor) CreateDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateEvent", ctx, e) - ret0, _ := ret[0].(*ent.Event) + ret := m.ctrl.Call(m, "CreateDeploymentStatus", ctx, ds) + ret0, _ := ret[0].(*ent.DeploymentStatus) ret1, _ := ret[1].(error) return ret0, ret1 } -// CreateEvent indicates an expected call of CreateEvent. -func (mr *MockInteractorMockRecorder) CreateEvent(ctx, e interface{}) *gomock.Call { +// CreateDeploymentStatus indicates an expected call of CreateDeploymentStatus. +func (mr *MockInteractorMockRecorder) CreateDeploymentStatus(ctx, ds interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateEvent", reflect.TypeOf((*MockInteractor)(nil).CreateEvent), ctx, e) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateDeploymentStatus", reflect.TypeOf((*MockInteractor)(nil).CreateDeploymentStatus), ctx, ds) } // Deploy mocks base method. @@ -126,21 +126,6 @@ func (mr *MockInteractorMockRecorder) ProduceDeploymentStatisticsOfRepo(ctx, r, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProduceDeploymentStatisticsOfRepo", reflect.TypeOf((*MockInteractor)(nil).ProduceDeploymentStatisticsOfRepo), ctx, r, d) } -// SyncDeploymentStatus mocks base method. -func (m *MockInteractor) SyncDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SyncDeploymentStatus", ctx, ds) - ret0, _ := ret[0].(*ent.DeploymentStatus) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// SyncDeploymentStatus indicates an expected call of SyncDeploymentStatus. -func (mr *MockInteractorMockRecorder) SyncDeploymentStatus(ctx, ds interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SyncDeploymentStatus", reflect.TypeOf((*MockInteractor)(nil).SyncDeploymentStatus), ctx, ds) -} - // UpdateDeployment mocks base method. func (m *MockInteractor) UpdateDeployment(ctx context.Context, d *ent.Deployment) (*ent.Deployment, error) { m.ctrl.T.Helper() From d776bb86644db2659ff7634ee5d34f2338c9f445 Mon Sep 17 00:00:00 2001 From: noah Date: Sun, 17 Apr 2022 21:14:43 +0900 Subject: [PATCH 3/9] Change the slack message format --- internal/interactor/interface.go | 1 + internal/interactor/mock/pkg.go | 30 ++++ internal/pkg/store/deploymentstatus.go | 9 + internal/pkg/store/event.go | 6 +- internal/server/slack/interface.go | 5 + internal/server/slack/mock/interactor.go | 45 +++++ internal/server/slack/notification.go | 215 ++++++++++------------- 7 files changed, 187 insertions(+), 124 deletions(-) diff --git a/internal/interactor/interface.go b/internal/interactor/interface.go index b4d305cd..8c2469c4 100644 --- a/internal/interactor/interface.go +++ b/internal/interactor/interface.go @@ -43,6 +43,7 @@ type ( // PermStore defines operations for working with deployment_statuses. DeploymentStatusStore interface { ListDeploymentStatuses(ctx context.Context, d *ent.Deployment) ([]*ent.DeploymentStatus, error) + FindDeploymentStatusByID(ctx context.Context, id int) (*ent.DeploymentStatus, error) // CreateEntDeploymentStatus create a DeploymentStatus entity to the store. // Ent is appended to distinguish it from the interactor. CreateEntDeploymentStatus(ctx context.Context, s *ent.DeploymentStatus) (*ent.DeploymentStatus, error) diff --git a/internal/interactor/mock/pkg.go b/internal/interactor/mock/pkg.go index 695c2645..2e7ad932 100644 --- a/internal/interactor/mock/pkg.go +++ b/internal/interactor/mock/pkg.go @@ -409,6 +409,21 @@ func (mr *MockStoreMockRecorder) FindDeploymentStatisticsOfRepoByEnv(ctx, r, env return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindDeploymentStatisticsOfRepoByEnv", reflect.TypeOf((*MockStore)(nil).FindDeploymentStatisticsOfRepoByEnv), ctx, r, env) } +// FindDeploymentStatusByID mocks base method. +func (m *MockStore) FindDeploymentStatusByID(ctx context.Context, id int) (*ent.DeploymentStatus, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindDeploymentStatusByID", ctx, id) + ret0, _ := ret[0].(*ent.DeploymentStatus) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindDeploymentStatusByID indicates an expected call of FindDeploymentStatusByID. +func (mr *MockStoreMockRecorder) FindDeploymentStatusByID(ctx, id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindDeploymentStatusByID", reflect.TypeOf((*MockStore)(nil).FindDeploymentStatusByID), ctx, id) +} + // FindLockByID mocks base method. func (m *MockStore) FindLockByID(ctx context.Context, id int) (*ent.Lock, error) { m.ctrl.T.Helper() @@ -1115,6 +1130,21 @@ func (mr *MockDeploymentStatusStoreMockRecorder) CreateEntDeploymentStatus(ctx, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateEntDeploymentStatus", reflect.TypeOf((*MockDeploymentStatusStore)(nil).CreateEntDeploymentStatus), ctx, s) } +// FindDeploymentStatusByID mocks base method. +func (m *MockDeploymentStatusStore) FindDeploymentStatusByID(ctx context.Context, id int) (*ent.DeploymentStatus, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindDeploymentStatusByID", ctx, id) + ret0, _ := ret[0].(*ent.DeploymentStatus) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindDeploymentStatusByID indicates an expected call of FindDeploymentStatusByID. +func (mr *MockDeploymentStatusStoreMockRecorder) FindDeploymentStatusByID(ctx, id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindDeploymentStatusByID", reflect.TypeOf((*MockDeploymentStatusStore)(nil).FindDeploymentStatusByID), ctx, id) +} + // ListDeploymentStatuses mocks base method. func (m *MockDeploymentStatusStore) ListDeploymentStatuses(ctx context.Context, d *ent.Deployment) ([]*ent.DeploymentStatus, error) { m.ctrl.T.Helper() diff --git a/internal/pkg/store/deploymentstatus.go b/internal/pkg/store/deploymentstatus.go index 18f9c077..47290f3e 100644 --- a/internal/pkg/store/deploymentstatus.go +++ b/internal/pkg/store/deploymentstatus.go @@ -49,3 +49,12 @@ func (s *Store) CreateEntDeploymentStatus(ctx context.Context, ds *ent.Deploymen return ret, nil } + +func (s *Store) FindDeploymentStatusByID(ctx context.Context, id int) (*ent.DeploymentStatus, error) { + ds, err := s.c.DeploymentStatus.Get(ctx, id) + if ent.IsNotFound(err) { + return nil, e.NewError(e.ErrorCodeEntityNotFound, err) + } + + return ds, nil +} diff --git a/internal/pkg/store/event.go b/internal/pkg/store/event.go index 8404d826..94c2de4f 100644 --- a/internal/pkg/store/event.go +++ b/internal/pkg/store/event.go @@ -47,10 +47,8 @@ func (s *Store) CreateEvent(ctx context.Context, e *ent.Event) (*ent.Event, erro SetKind(e.Kind). SetType(e.Type) - if e.Type == event.TypeDeleted { - qry = qry.SetDeletedID(e.DeletedID) - } else if e.Kind == event.KindDeployment { - qry = qry.SetDeploymentID(e.DeploymentID) + if e.Kind == event.KindDeploymentStatus { + qry = qry.SetDeploymentStatusID(e.DeploymentStatusID) } else if e.Kind == event.KindReview { qry = qry.SetReviewID(e.ReviewID) } diff --git a/internal/server/slack/interface.go b/internal/server/slack/interface.go index 545a5c95..91ffeba4 100644 --- a/internal/server/slack/interface.go +++ b/internal/server/slack/interface.go @@ -17,6 +17,11 @@ type ( UpdateChatUser(ctx context.Context, cu *ent.ChatUser) (*ent.ChatUser, error) DeleteChatUser(ctx context.Context, cu *ent.ChatUser) error + FindDeploymentByID(ctx context.Context, id int) (*ent.Deployment, error) + FindDeploymentStatusByID(ctx context.Context, id int) (*ent.DeploymentStatus, error) + + FindReviewByID(ctx context.Context, id int) (*ent.Review, error) + SubscribeEvent(fn func(e *ent.Event)) error UnsubscribeEvent(fn func(e *ent.Event)) error } diff --git a/internal/server/slack/mock/interactor.go b/internal/server/slack/mock/interactor.go index ef8a371d..607f46dd 100644 --- a/internal/server/slack/mock/interactor.go +++ b/internal/server/slack/mock/interactor.go @@ -79,6 +79,51 @@ func (mr *MockInteractorMockRecorder) FindChatUserByID(ctx, id interface{}) *gom return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindChatUserByID", reflect.TypeOf((*MockInteractor)(nil).FindChatUserByID), ctx, id) } +// FindDeploymentByID mocks base method. +func (m *MockInteractor) FindDeploymentByID(ctx context.Context, id int) (*ent.Deployment, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindDeploymentByID", ctx, id) + ret0, _ := ret[0].(*ent.Deployment) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindDeploymentByID indicates an expected call of FindDeploymentByID. +func (mr *MockInteractorMockRecorder) FindDeploymentByID(ctx, id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindDeploymentByID", reflect.TypeOf((*MockInteractor)(nil).FindDeploymentByID), ctx, id) +} + +// FindDeploymentStatusByID mocks base method. +func (m *MockInteractor) FindDeploymentStatusByID(ctx context.Context, id int) (*ent.DeploymentStatus, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindDeploymentStatusByID", ctx, id) + ret0, _ := ret[0].(*ent.DeploymentStatus) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindDeploymentStatusByID indicates an expected call of FindDeploymentStatusByID. +func (mr *MockInteractorMockRecorder) FindDeploymentStatusByID(ctx, id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindDeploymentStatusByID", reflect.TypeOf((*MockInteractor)(nil).FindDeploymentStatusByID), ctx, id) +} + +// FindReviewByID mocks base method. +func (m *MockInteractor) FindReviewByID(ctx context.Context, id int) (*ent.Review, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "FindReviewByID", ctx, id) + ret0, _ := ret[0].(*ent.Review) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// FindReviewByID indicates an expected call of FindReviewByID. +func (mr *MockInteractorMockRecorder) FindReviewByID(ctx, id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindReviewByID", reflect.TypeOf((*MockInteractor)(nil).FindReviewByID), ctx, id) +} + // FindUserByID mocks base method. func (m *MockInteractor) FindUserByID(ctx context.Context, id int64) (*ent.User, error) { m.ctrl.T.Helper() diff --git a/internal/server/slack/notification.go b/internal/server/slack/notification.go index 8e9bed99..11129623 100644 --- a/internal/server/slack/notification.go +++ b/internal/server/slack/notification.go @@ -8,141 +8,140 @@ import ( "go.uber.org/zap" "github.com/gitploy-io/gitploy/model/ent" - "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/review" ) -const ( - colorGray = "#bfbfbf" - colorPurple = "#722ed1" - colorGreen = "#52c41a" - colorRed = "#f5222d" -) - func (s *Slack) Notify(ctx context.Context, e *ent.Event) { if e.Type == event.TypeDeleted { s.log.Debug("Skip the deleted type event.") return } - if e.Kind == event.KindDeployment { - s.notifyDeploymentEvent(ctx, e) - } - - if e.Kind == event.KindReview { - s.notifyReviewEvent(ctx, e) - } -} + switch e.Kind { + case event.KindDeploymentStatus: + ds, err := s.i.FindDeploymentStatusByID(ctx, e.DeploymentStatusID) + if err != nil { + s.log.Error("Failed to find the deployment status.", zap.Error(err)) + break + } -func (s *Slack) notifyDeploymentEvent(ctx context.Context, e *ent.Event) { - var d *ent.Deployment + s.notifyDeploymentStatusEvent(ctx, ds) + case event.KindReview: + r, err := s.i.FindReviewByID(ctx, e.ReviewID) + if err != nil { + s.log.Error("Failed to find the review.", zap.Error(err)) + break + } - if d = e.Edges.Deployment; d == nil { - s.log.Error("The eager loading of event has failed.") - return + s.notifyReviewEvent(ctx, r) } +} - if d.Edges.User == nil || d.Edges.Repo == nil { - s.log.Error("The eager loading of deployment has failed.") +func (s *Slack) notifyDeploymentStatusEvent(ctx context.Context, ds *ent.DeploymentStatus) { + d, err := s.i.FindDeploymentByID(ctx, ds.DeploymentID) + if err != nil { + s.log.Error("Failed to find the deployment.", zap.Error(err)) return } - owner, err := s.i.FindUserByID(ctx, d.Edges.User.ID) + owner, err := s.i.FindUserByID(ctx, d.UserID) if err != nil { - s.log.Error("It has failed to find the owner of the deployment.", zap.Error(err)) + s.log.Error("Failed to find the owner of the deployment.", zap.Error(err)) return - } - if owner.Edges.ChatUser == nil { + } else if owner.Edges.ChatUser == nil { s.log.Debug("Skip the notification. The owner is not connected with Slack.") return } // Build the message and post it. - var option slack.MsgOption - - if e.Type == event.TypeCreated { - option = slack.MsgOptionAttachments(slack.Attachment{ - Color: mapDeploymentStatusToColor(d.Status), - Pretext: fmt.Sprintf("*New Deployment #%d*", d.Number), - Text: fmt.Sprintf("*%s* deploys `%s` to the `%s` environment of `%s`. <%s|• View Details> ", owner.Login, d.GetShortRef(), d.Env, d.Edges.Repo.GetFullName(), s.buildDeploymentLink(d.Edges.Repo, d)), - }) - } else if e.Type == event.TypeUpdated { - option = slack.MsgOptionAttachments(slack.Attachment{ - Color: mapDeploymentStatusToColor(d.Status), - Pretext: fmt.Sprintf("*Deployment Updated #%d*", d.Number), - Text: fmt.Sprintf("The deployment <%s|#%d> of `%s` is updated `%s`.", s.buildDeploymentLink(d.Edges.Repo, d), d.Number, d.Edges.Repo.GetFullName(), d.Status), - }) + options := []slack.MsgOption{ + slack.MsgOptionBlocks( + slack.NewSectionBlock( + slack.NewTextBlockObject( + slack.MarkdownType, + fmt.Sprintf("*%s* *#%d* %s", d.Edges.Repo.GetFullName(), d.Number, buildLink(s.buildDeploymentLink(d.Edges.Repo, d), " • View Details")), + false, false, + ), + []*slack.TextBlockObject{ + slack.NewTextBlockObject(slack.MarkdownType, fmt.Sprintf("*Status:*\n`%s`", ds.Status), false, false), + slack.NewTextBlockObject( + slack.MarkdownType, + fmt.Sprintf("*Description:*\n>%s %s", ds.Description, buildLink(ds.LogURL, " • View Log")), + false, false, + ), + }, nil, + ), + ), } - if _, _, err := slack. - New(owner.Edges.ChatUser.BotToken). - PostMessageContext(ctx, owner.Edges.ChatUser.ID, option); err != nil { - s.log.Error("It has failed to post the message.", zap.Error(err)) + if _, _, err := slack.New(owner.Edges.ChatUser.BotToken). + PostMessageContext(ctx, owner.Edges.ChatUser.ID, options...); err != nil { + s.log.Error("Failed to post the message.", zap.Error(err)) } } -func (s *Slack) notifyReviewEvent(ctx context.Context, e *ent.Event) { - var ( - r *ent.Review - d *ent.Deployment - ) - - if r = e.Edges.Review; r == nil { - s.log.Error("The eager loading of review has failed.") +func (s *Slack) notifyReviewEvent(ctx context.Context, r *ent.Review) { + d, err := s.i.FindDeploymentByID(ctx, r.DeploymentID) + if err != nil { + s.log.Error("Failed to find the deployment.", zap.Error(err)) return } - if d = r.Edges.Deployment; d == nil { - s.log.Error("The eager loading of deployment has failed.") - return + deployer := d.Edges.User + if deployer == nil { + s.log.Error("Failed to find the deployer.", zap.Error(err)) } - if e.Type == event.TypeCreated { - option := slack.MsgOptionAttachments(slack.Attachment{ - Color: colorPurple, - Pretext: "*Review Requested*", - Text: fmt.Sprintf("%s requested the review for the deployment <%s|#%d> of `%s`.", d.Edges.User.Login, s.buildDeploymentLink(d.Edges.Repo, d), d.Number, d.Edges.Repo.GetFullName()), - }) + reviewer, err := s.i.FindUserByID(ctx, r.UserID) + if err != nil { + s.log.Error("Failed to find the reviewer.", zap.Error(err)) + return + } - recipient, err := s.i.FindUserByID(ctx, r.Edges.User.ID) - if err != nil { - s.log.Error("It has failed to find the recipient of the review.", zap.Error(err)) - return - } - if recipient.Edges.ChatUser == nil { - s.log.Debug("Skip the notification. The recipient is not connected with Slack.") + switch r.Status { + case review.StatusPending: + option := slack.MsgOptionBlocks( + slack.NewSectionBlock( + slack.NewTextBlockObject( + slack.MarkdownType, + fmt.Sprintf("%s requested a review in `%s` *#%d* %s", deployer.Login, d.Edges.Repo.GetFullName(), d.Number, buildLink(s.buildDeploymentLink(d.Edges.Repo, d), " • View Details")), + false, false, + ), + nil, nil, + ), + ) + + if reviewer.Edges.ChatUser == nil { + s.log.Debug("Skip the notification. The reviewer is not connected with Slack.") return } - if _, _, err := slack. - New(recipient.Edges.ChatUser.BotToken). - PostMessageContext(ctx, recipient.Edges.ChatUser.ID, option); err != nil { - s.log.Error("It has failed to post the message.", zap.Error(err)) + if _, _, err := slack.New(reviewer.Edges.ChatUser.BotToken). + PostMessageContext(ctx, reviewer.Edges.ChatUser.ID, option); err != nil { + s.log.Error("Failed to post the message.", zap.Error(err)) } - } - if e.Type == event.TypeUpdated { - option := slack.MsgOptionAttachments(slack.Attachment{ - Color: mapReviewStatusToColor(r.Status), - Pretext: "*Review Responded*", - Text: fmt.Sprintf("%s *%s* the deployment <%s|#%d> of `%s`.", r.Edges.User.Login, r.Status, s.buildDeploymentLink(d.Edges.Repo, d), d.Number, d.Edges.Repo.GetFullName()), - }) - - requester, err := s.i.FindUserByID(ctx, d.Edges.User.ID) - if err != nil { - s.log.Error("It has failed to find the requester of the review.", zap.Error(err)) - return - } - if requester.Edges.ChatUser == nil { - s.log.Debug("Skip the notification. The requester is not connected with Slack.") + default: + option := slack.MsgOptionBlocks( + slack.NewSectionBlock( + slack.NewTextBlockObject( + slack.MarkdownType, + fmt.Sprintf("%s %s in `%s` *#%d* %s", reviewer.Login, r.Status, d.Edges.Repo.GetFullName(), d.Number, buildLink(s.buildDeploymentLink(d.Edges.Repo, d), " • View Details")), + false, false, + ), + nil, nil, + ), + ) + + if deployer.Edges.ChatUser == nil { + s.log.Debug("Skip the notification. The deployer is not connected with Slack.") return } - if _, _, err := slack. - New(requester.Edges.ChatUser.BotToken). - PostMessageContext(ctx, requester.Edges.ChatUser.ID, option); err != nil { - s.log.Error("It has failed to post the message.", zap.Error(err)) + if _, _, err := slack.New(deployer.Edges.ChatUser.BotToken). + PostMessageContext(ctx, deployer.Edges.ChatUser.ID, option); err != nil { + s.log.Error("Failed to post the message.", zap.Error(err)) } } } @@ -151,34 +150,10 @@ func (s *Slack) buildDeploymentLink(r *ent.Repo, d *ent.Deployment) string { return fmt.Sprintf("%s://%s/%s/deployments/%d", s.proto, s.host, r.GetFullName(), d.Number) } -func mapDeploymentStatusToColor(status deployment.Status) string { - switch status { - case deployment.StatusWaiting: - return colorGray - case deployment.StatusCreated: - return colorPurple - case deployment.StatusQueued: - return colorPurple - case deployment.StatusRunning: - return colorPurple - case deployment.StatusSuccess: - return colorGreen - case deployment.StatusFailure: - return colorRed - default: - return colorGray +func buildLink(link string, msg string) string { + if msg == "" || link == "" { + return "" } -} -func mapReviewStatusToColor(status review.Status) string { - switch status { - case review.StatusPending: - return colorGray - case review.StatusApproved: - return colorGreen - case review.StatusRejected: - return colorRed - default: - return colorGray - } + return fmt.Sprintf("<%s|%s>", link, msg) } From bfc13c74cb966e99a6e9a4fd43049bad7bd5d73c Mon Sep 17 00:00:00 2001 From: noah Date: Sat, 23 Apr 2022 16:13:33 +0900 Subject: [PATCH 4/9] Fix the stream API to support DeploymentStatus --- internal/pkg/store/event.go | 4 ++++ internal/server/api/v1/stream/events.go | 26 +++++++++++++++++++++- internal/server/api/v1/stream/interface.go | 1 + openapi/v1.yaml | 2 ++ 4 files changed, 32 insertions(+), 1 deletion(-) diff --git a/internal/pkg/store/event.go b/internal/pkg/store/event.go index 94c2de4f..c5ab9371 100644 --- a/internal/pkg/store/event.go +++ b/internal/pkg/store/event.go @@ -28,6 +28,10 @@ func (s *Store) ListEventsGreaterThanTime(ctx context.Context, t time.Time) ([]* WithRepo(). WithDeploymentStatuses() }). + WithDeploymentStatus(func(dsq *ent.DeploymentStatusQuery) { + dsq. + WithDeployment() + }). WithReview(func(rq *ent.ReviewQuery) { rq. WithUser(). diff --git a/internal/server/api/v1/stream/events.go b/internal/server/api/v1/stream/events.go index 920f4a38..fc9b0705 100644 --- a/internal/server/api/v1/stream/events.go +++ b/internal/server/api/v1/stream/events.go @@ -39,7 +39,7 @@ func (s *Stream) GetEvents(c *gin.Context) { } if _, err := s.i.FindPermOfRepo(ctx, d.Edges.Repo, u); err != nil { - s.log.Debug("Skip the event. The permission is denied.") + s.log.Debug("Skip the event. The permission is denied.", zap.Error(err)) return } @@ -48,6 +48,30 @@ func (s *Stream) GetEvents(c *gin.Context) { Event: "deployment", Data: d, } + case event.KindDeploymentStatus: + ds, err := s.i.FindDeploymentStatusByID(ctx, e.DeploymentStatusID) + if err != nil { + s.log.Error("Failed to find the deployment status.", zap.Error(err)) + return + } + + // Ensure that a user has access to the repository of the deployment. + d, err := s.i.FindDeploymentByID(ctx, ds.DeploymentID) + if err != nil { + s.log.Error("Failed to find the deployment.", zap.Error(err)) + return + } + + if _, err := s.i.FindPermOfRepo(ctx, d.Edges.Repo, u); err != nil { + s.log.Debug("Skip the event. The permission is denied.", zap.Error(err)) + return + } + + s.log.Debug("Dispatch a deployment_status event.", zap.Int("id", d.ID)) + events <- &sse.Event{ + Event: "deployment_status", + Data: ds, + } case event.KindReview: r, err := s.i.FindReviewByID(ctx, e.ReviewID) diff --git a/internal/server/api/v1/stream/interface.go b/internal/server/api/v1/stream/interface.go index ed4ad007..5a592003 100644 --- a/internal/server/api/v1/stream/interface.go +++ b/internal/server/api/v1/stream/interface.go @@ -11,6 +11,7 @@ type ( SubscribeEvent(fn func(e *ent.Event)) error UnsubscribeEvent(fn func(e *ent.Event)) error FindDeploymentByID(ctx context.Context, id int) (*ent.Deployment, error) + FindDeploymentStatusByID(ctx context.Context, id int) (*ent.DeploymentStatus, error) FindReviewByID(ctx context.Context, id int) (*ent.Review, error) FindPermOfRepo(ctx context.Context, r *ent.Repo, u *ent.User) (*ent.Perm, error) } diff --git a/openapi/v1.yaml b/openapi/v1.yaml index 786ca694..1bb1f696 100644 --- a/openapi/v1.yaml +++ b/openapi/v1.yaml @@ -1438,10 +1438,12 @@ paths: type: string enum: - deployment + - deployment_status - review data: oneOf: - $ref: '#/components/schemas/Deployment' + - $ref: '#/components/schemas/DeploymentStatus' - $ref: '#/components/schemas/Review' /sync: post: From d7a424fd6b7199b69401cb717b9e50cd7f6c2036 Mon Sep 17 00:00:00 2001 From: noah Date: Sat, 23 Apr 2022 17:19:44 +0900 Subject: [PATCH 5/9] Add the RepoID field to DeploymentStatus schema --- go.mod | 2 + go.sum | 1 + model/ent/client.go | 32 +++ model/ent/deploymentstatus.go | 38 +++- .../ent/deploymentstatus/deploymentstatus.go | 12 ++ model/ent/deploymentstatus/where.go | 83 ++++++++ model/ent/deploymentstatus_create.go | 38 ++++ model/ent/deploymentstatus_query.go | 65 +++++- model/ent/deploymentstatus_update.go | 111 ++++++++++ model/ent/migrate/schema.go | 8 + model/ent/mutation.go | 196 +++++++++++++++++- model/ent/repo.go | 24 ++- model/ent/repo/repo.go | 9 + model/ent/repo/where.go | 28 +++ model/ent/repo_create.go | 35 ++++ model/ent/repo_query.go | 64 +++++- model/ent/repo_update.go | 181 ++++++++++++++++ model/ent/schema/deploymentstatus.go | 8 + model/ent/schema/repo.go | 4 + 19 files changed, 923 insertions(+), 16 deletions(-) diff --git a/go.mod b/go.mod index f055d037..920cd259 100644 --- a/go.mod +++ b/go.mod @@ -80,6 +80,8 @@ require ( golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect golang.org/x/text v0.3.7 // indirect + golang.org/x/tools v0.1.9-0.20211216111533-8d383106f7e7 // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/protobuf v1.26.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/go.sum b/go.sum index 3121e5f9..9868e051 100644 --- a/go.sum +++ b/go.sum @@ -882,6 +882,7 @@ golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.9-0.20211216111533-8d383106f7e7 h1:M1gcVrIb2lSn2FIL19DG0+/b8nNVKJ7W7b4WcAGZAYM= golang.org/x/tools v0.1.9-0.20211216111533-8d383106f7e7/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/model/ent/client.go b/model/ent/client.go index c3931438..30a20473 100644 --- a/model/ent/client.go +++ b/model/ent/client.go @@ -676,6 +676,22 @@ func (c *DeploymentStatusClient) QueryDeployment(ds *DeploymentStatus) *Deployme return query } +// QueryRepo queries the repo edge of a DeploymentStatus. +func (c *DeploymentStatusClient) QueryRepo(ds *DeploymentStatus) *RepoQuery { + query := &RepoQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := ds.ID + step := sqlgraph.NewStep( + sqlgraph.From(deploymentstatus.Table, deploymentstatus.FieldID, id), + sqlgraph.To(repo.Table, repo.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, deploymentstatus.RepoTable, deploymentstatus.RepoColumn), + ) + fromV = sqlgraph.Neighbors(ds.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryEvent queries the event edge of a DeploymentStatus. func (c *DeploymentStatusClient) QueryEvent(ds *DeploymentStatus) *EventQuery { query := &EventQuery{config: c.config} @@ -1318,6 +1334,22 @@ func (c *RepoClient) QueryDeployments(r *Repo) *DeploymentQuery { return query } +// QueryDeploymentStatuses queries the deployment_statuses edge of a Repo. +func (c *RepoClient) QueryDeploymentStatuses(r *Repo) *DeploymentStatusQuery { + query := &DeploymentStatusQuery{config: c.config} + query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { + id := r.ID + step := sqlgraph.NewStep( + sqlgraph.From(repo.Table, repo.FieldID, id), + sqlgraph.To(deploymentstatus.Table, deploymentstatus.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, repo.DeploymentStatusesTable, repo.DeploymentStatusesColumn), + ) + fromV = sqlgraph.Neighbors(r.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryLocks queries the locks edge of a Repo. func (c *RepoClient) QueryLocks(r *Repo) *LockQuery { query := &LockQuery{config: c.config} diff --git a/model/ent/deploymentstatus.go b/model/ent/deploymentstatus.go index d71144dd..8061d809 100644 --- a/model/ent/deploymentstatus.go +++ b/model/ent/deploymentstatus.go @@ -10,6 +10,7 @@ import ( "entgo.io/ent/dialect/sql" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" + "github.com/gitploy-io/gitploy/model/ent/repo" ) // DeploymentStatus is the model entity for the DeploymentStatus schema. @@ -29,6 +30,8 @@ type DeploymentStatus struct { UpdatedAt time.Time `json:"updated_at"` // DeploymentID holds the value of the "deployment_id" field. DeploymentID int `json:"deployment_id"` + // RepoID holds the value of the "repo_id" field. + RepoID int64 `json:"repo_id"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the DeploymentStatusQuery when eager-loading is set. Edges DeploymentStatusEdges `json:"edges"` @@ -38,11 +41,13 @@ type DeploymentStatus struct { type DeploymentStatusEdges struct { // Deployment holds the value of the deployment edge. Deployment *Deployment `json:"deployment,omitempty"` + // Repo holds the value of the repo edge. + Repo *Repo `json:"repo,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 [2]bool + loadedTypes [3]bool } // DeploymentOrErr returns the Deployment value or an error if the edge @@ -59,10 +64,24 @@ func (e DeploymentStatusEdges) DeploymentOrErr() (*Deployment, error) { return nil, &NotLoadedError{edge: "deployment"} } +// RepoOrErr returns the Repo value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e DeploymentStatusEdges) RepoOrErr() (*Repo, error) { + if e.loadedTypes[1] { + if e.Repo == nil { + // The edge repo was loaded in eager-loading, + // but was not found. + return nil, &NotFoundError{label: repo.Label} + } + return e.Repo, nil + } + return nil, &NotLoadedError{edge: "repo"} +} + // EventOrErr returns the Event value or an error if the edge // was not loaded in eager-loading. func (e DeploymentStatusEdges) EventOrErr() ([]*Event, error) { - if e.loadedTypes[1] { + if e.loadedTypes[2] { return e.Event, nil } return nil, &NotLoadedError{edge: "event"} @@ -73,7 +92,7 @@ func (*DeploymentStatus) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) for i := range columns { switch columns[i] { - case deploymentstatus.FieldID, deploymentstatus.FieldDeploymentID: + case deploymentstatus.FieldID, deploymentstatus.FieldDeploymentID, deploymentstatus.FieldRepoID: values[i] = new(sql.NullInt64) case deploymentstatus.FieldStatus, deploymentstatus.FieldDescription, deploymentstatus.FieldLogURL: values[i] = new(sql.NullString) @@ -136,6 +155,12 @@ func (ds *DeploymentStatus) assignValues(columns []string, values []interface{}) } else if value.Valid { ds.DeploymentID = int(value.Int64) } + case deploymentstatus.FieldRepoID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field repo_id", values[i]) + } else if value.Valid { + ds.RepoID = value.Int64 + } } } return nil @@ -146,6 +171,11 @@ func (ds *DeploymentStatus) QueryDeployment() *DeploymentQuery { return (&DeploymentStatusClient{config: ds.config}).QueryDeployment(ds) } +// QueryRepo queries the "repo" edge of the DeploymentStatus entity. +func (ds *DeploymentStatus) QueryRepo() *RepoQuery { + return (&DeploymentStatusClient{config: ds.config}).QueryRepo(ds) +} + // QueryEvent queries the "event" edge of the DeploymentStatus entity. func (ds *DeploymentStatus) QueryEvent() *EventQuery { return (&DeploymentStatusClient{config: ds.config}).QueryEvent(ds) @@ -186,6 +216,8 @@ func (ds *DeploymentStatus) String() string { builder.WriteString(ds.UpdatedAt.Format(time.ANSIC)) builder.WriteString(", deployment_id=") builder.WriteString(fmt.Sprintf("%v", ds.DeploymentID)) + builder.WriteString(", repo_id=") + builder.WriteString(fmt.Sprintf("%v", ds.RepoID)) builder.WriteByte(')') return builder.String() } diff --git a/model/ent/deploymentstatus/deploymentstatus.go b/model/ent/deploymentstatus/deploymentstatus.go index 7a98cb88..45cf71fa 100644 --- a/model/ent/deploymentstatus/deploymentstatus.go +++ b/model/ent/deploymentstatus/deploymentstatus.go @@ -23,8 +23,12 @@ const ( FieldUpdatedAt = "updated_at" // FieldDeploymentID holds the string denoting the deployment_id field in the database. FieldDeploymentID = "deployment_id" + // FieldRepoID holds the string denoting the repo_id field in the database. + FieldRepoID = "repo_id" // EdgeDeployment holds the string denoting the deployment edge name in mutations. EdgeDeployment = "deployment" + // EdgeRepo holds the string denoting the repo edge name in mutations. + EdgeRepo = "repo" // EdgeEvent holds the string denoting the event edge name in mutations. EdgeEvent = "event" // Table holds the table name of the deploymentstatus in the database. @@ -36,6 +40,13 @@ const ( DeploymentInverseTable = "deployments" // DeploymentColumn is the table column denoting the deployment relation/edge. DeploymentColumn = "deployment_id" + // RepoTable is the table that holds the repo relation/edge. + RepoTable = "deployment_status" + // RepoInverseTable is the table name for the Repo entity. + // It exists in this package in order to avoid circular dependency with the "repo" package. + RepoInverseTable = "repos" + // RepoColumn is the table column denoting the repo relation/edge. + RepoColumn = "repo_id" // EventTable is the table that holds the event relation/edge. EventTable = "events" // EventInverseTable is the table name for the Event entity. @@ -54,6 +65,7 @@ var Columns = []string{ FieldCreatedAt, FieldUpdatedAt, FieldDeploymentID, + FieldRepoID, } // ValidColumn reports if the column name is valid (part of the table columns). diff --git a/model/ent/deploymentstatus/where.go b/model/ent/deploymentstatus/where.go index 23c608e1..ad431c53 100644 --- a/model/ent/deploymentstatus/where.go +++ b/model/ent/deploymentstatus/where.go @@ -135,6 +135,13 @@ func DeploymentID(v int) predicate.DeploymentStatus { }) } +// RepoID applies equality check predicate on the "repo_id" field. It's identical to RepoIDEQ. +func RepoID(v int64) predicate.DeploymentStatus { + return predicate.DeploymentStatus(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldRepoID), v)) + }) +} + // StatusEQ applies the EQ predicate on the "status" field. func StatusEQ(v string) predicate.DeploymentStatus { return predicate.DeploymentStatus(func(s *sql.Selector) { @@ -696,6 +703,54 @@ func DeploymentIDNotIn(vs ...int) predicate.DeploymentStatus { }) } +// RepoIDEQ applies the EQ predicate on the "repo_id" field. +func RepoIDEQ(v int64) predicate.DeploymentStatus { + return predicate.DeploymentStatus(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldRepoID), v)) + }) +} + +// RepoIDNEQ applies the NEQ predicate on the "repo_id" field. +func RepoIDNEQ(v int64) predicate.DeploymentStatus { + return predicate.DeploymentStatus(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldRepoID), v)) + }) +} + +// RepoIDIn applies the In predicate on the "repo_id" field. +func RepoIDIn(vs ...int64) predicate.DeploymentStatus { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentStatus(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(FieldRepoID), v...)) + }) +} + +// RepoIDNotIn applies the NotIn predicate on the "repo_id" field. +func RepoIDNotIn(vs ...int64) predicate.DeploymentStatus { + v := make([]interface{}, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.DeploymentStatus(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(FieldRepoID), v...)) + }) +} + // HasDeployment applies the HasEdge predicate on the "deployment" edge. func HasDeployment() predicate.DeploymentStatus { return predicate.DeploymentStatus(func(s *sql.Selector) { @@ -724,6 +779,34 @@ func HasDeploymentWith(preds ...predicate.Deployment) predicate.DeploymentStatus }) } +// HasRepo applies the HasEdge predicate on the "repo" edge. +func HasRepo() predicate.DeploymentStatus { + return predicate.DeploymentStatus(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RepoTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RepoTable, RepoColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRepoWith applies the HasEdge predicate on the "repo" edge with a given conditions (other predicates). +func HasRepoWith(preds ...predicate.Repo) predicate.DeploymentStatus { + return predicate.DeploymentStatus(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RepoInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, RepoTable, RepoColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasEvent applies the HasEdge predicate on the "event" edge. func HasEvent() predicate.DeploymentStatus { return predicate.DeploymentStatus(func(s *sql.Selector) { diff --git a/model/ent/deploymentstatus_create.go b/model/ent/deploymentstatus_create.go index d03af385..c8f8c733 100644 --- a/model/ent/deploymentstatus_create.go +++ b/model/ent/deploymentstatus_create.go @@ -13,6 +13,7 @@ import ( "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" + "github.com/gitploy-io/gitploy/model/ent/repo" ) // DeploymentStatusCreate is the builder for creating a DeploymentStatus entity. @@ -90,11 +91,22 @@ func (dsc *DeploymentStatusCreate) SetDeploymentID(i int) *DeploymentStatusCreat return dsc } +// SetRepoID sets the "repo_id" field. +func (dsc *DeploymentStatusCreate) SetRepoID(i int64) *DeploymentStatusCreate { + dsc.mutation.SetRepoID(i) + return dsc +} + // SetDeployment sets the "deployment" edge to the Deployment entity. func (dsc *DeploymentStatusCreate) SetDeployment(d *Deployment) *DeploymentStatusCreate { return dsc.SetDeploymentID(d.ID) } +// SetRepo sets the "repo" edge to the Repo entity. +func (dsc *DeploymentStatusCreate) SetRepo(r *Repo) *DeploymentStatusCreate { + return dsc.SetRepoID(r.ID) +} + // AddEventIDs adds the "event" edge to the Event entity by IDs. func (dsc *DeploymentStatusCreate) AddEventIDs(ids ...int) *DeploymentStatusCreate { dsc.mutation.AddEventIDs(ids...) @@ -205,9 +217,15 @@ func (dsc *DeploymentStatusCreate) check() error { if _, ok := dsc.mutation.DeploymentID(); !ok { return &ValidationError{Name: "deployment_id", err: errors.New(`ent: missing required field "DeploymentStatus.deployment_id"`)} } + if _, ok := dsc.mutation.RepoID(); !ok { + return &ValidationError{Name: "repo_id", err: errors.New(`ent: missing required field "DeploymentStatus.repo_id"`)} + } if _, ok := dsc.mutation.DeploymentID(); !ok { return &ValidationError{Name: "deployment", err: errors.New(`ent: missing required edge "DeploymentStatus.deployment"`)} } + if _, ok := dsc.mutation.RepoID(); !ok { + return &ValidationError{Name: "repo", err: errors.New(`ent: missing required edge "DeploymentStatus.repo"`)} + } return nil } @@ -295,6 +313,26 @@ func (dsc *DeploymentStatusCreate) createSpec() (*DeploymentStatus, *sqlgraph.Cr _node.DeploymentID = nodes[0] _spec.Edges = append(_spec.Edges, edge) } + if nodes := dsc.mutation.RepoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: deploymentstatus.RepoTable, + Columns: []string{deploymentstatus.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: repo.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.RepoID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } if nodes := dsc.mutation.EventIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/model/ent/deploymentstatus_query.go b/model/ent/deploymentstatus_query.go index a3b05b46..715b9077 100644 --- a/model/ent/deploymentstatus_query.go +++ b/model/ent/deploymentstatus_query.go @@ -17,6 +17,7 @@ import ( "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/predicate" + "github.com/gitploy-io/gitploy/model/ent/repo" ) // DeploymentStatusQuery is the builder for querying DeploymentStatus entities. @@ -30,6 +31,7 @@ type DeploymentStatusQuery struct { predicates []predicate.DeploymentStatus // eager-loading edges. withDeployment *DeploymentQuery + withRepo *RepoQuery withEvent *EventQuery modifiers []func(s *sql.Selector) // intermediate query (i.e. traversal path). @@ -90,6 +92,28 @@ func (dsq *DeploymentStatusQuery) QueryDeployment() *DeploymentQuery { return query } +// QueryRepo chains the current query on the "repo" edge. +func (dsq *DeploymentStatusQuery) QueryRepo() *RepoQuery { + query := &RepoQuery{config: dsq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := dsq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := dsq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(deploymentstatus.Table, deploymentstatus.FieldID, selector), + sqlgraph.To(repo.Table, repo.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, deploymentstatus.RepoTable, deploymentstatus.RepoColumn), + ) + fromU = sqlgraph.SetNeighbors(dsq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryEvent chains the current query on the "event" edge. func (dsq *DeploymentStatusQuery) QueryEvent() *EventQuery { query := &EventQuery{config: dsq.config} @@ -294,6 +318,7 @@ func (dsq *DeploymentStatusQuery) Clone() *DeploymentStatusQuery { order: append([]OrderFunc{}, dsq.order...), predicates: append([]predicate.DeploymentStatus{}, dsq.predicates...), withDeployment: dsq.withDeployment.Clone(), + withRepo: dsq.withRepo.Clone(), withEvent: dsq.withEvent.Clone(), // clone intermediate query. sql: dsq.sql.Clone(), @@ -313,6 +338,17 @@ func (dsq *DeploymentStatusQuery) WithDeployment(opts ...func(*DeploymentQuery)) return dsq } +// WithRepo tells the query-builder to eager-load the nodes that are connected to +// the "repo" edge. The optional arguments are used to configure the query builder of the edge. +func (dsq *DeploymentStatusQuery) WithRepo(opts ...func(*RepoQuery)) *DeploymentStatusQuery { + query := &RepoQuery{config: dsq.config} + for _, opt := range opts { + opt(query) + } + dsq.withRepo = query + return dsq +} + // WithEvent tells the query-builder to eager-load the nodes that are connected to // the "event" edge. The optional arguments are used to configure the query builder of the edge. func (dsq *DeploymentStatusQuery) WithEvent(opts ...func(*EventQuery)) *DeploymentStatusQuery { @@ -389,8 +425,9 @@ func (dsq *DeploymentStatusQuery) sqlAll(ctx context.Context) ([]*DeploymentStat var ( nodes = []*DeploymentStatus{} _spec = dsq.querySpec() - loadedTypes = [2]bool{ + loadedTypes = [3]bool{ dsq.withDeployment != nil, + dsq.withRepo != nil, dsq.withEvent != nil, } ) @@ -443,6 +480,32 @@ func (dsq *DeploymentStatusQuery) sqlAll(ctx context.Context) ([]*DeploymentStat } } + if query := dsq.withRepo; query != nil { + ids := make([]int64, 0, len(nodes)) + nodeids := make(map[int64][]*DeploymentStatus) + for i := range nodes { + fk := nodes[i].RepoID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(repo.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 "repo_id" returned %v`, n.ID) + } + for i := range nodes { + nodes[i].Edges.Repo = n + } + } + } + if query := dsq.withEvent; query != nil { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[int]*DeploymentStatus) diff --git a/model/ent/deploymentstatus_update.go b/model/ent/deploymentstatus_update.go index cd696d55..692de5f0 100644 --- a/model/ent/deploymentstatus_update.go +++ b/model/ent/deploymentstatus_update.go @@ -15,6 +15,7 @@ import ( "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/predicate" + "github.com/gitploy-io/gitploy/model/ent/repo" ) // DeploymentStatusUpdate is the builder for updating DeploymentStatus entities. @@ -102,11 +103,22 @@ func (dsu *DeploymentStatusUpdate) SetDeploymentID(i int) *DeploymentStatusUpdat return dsu } +// SetRepoID sets the "repo_id" field. +func (dsu *DeploymentStatusUpdate) SetRepoID(i int64) *DeploymentStatusUpdate { + dsu.mutation.SetRepoID(i) + return dsu +} + // SetDeployment sets the "deployment" edge to the Deployment entity. func (dsu *DeploymentStatusUpdate) SetDeployment(d *Deployment) *DeploymentStatusUpdate { return dsu.SetDeploymentID(d.ID) } +// SetRepo sets the "repo" edge to the Repo entity. +func (dsu *DeploymentStatusUpdate) SetRepo(r *Repo) *DeploymentStatusUpdate { + return dsu.SetRepoID(r.ID) +} + // AddEventIDs adds the "event" edge to the Event entity by IDs. func (dsu *DeploymentStatusUpdate) AddEventIDs(ids ...int) *DeploymentStatusUpdate { dsu.mutation.AddEventIDs(ids...) @@ -133,6 +145,12 @@ func (dsu *DeploymentStatusUpdate) ClearDeployment() *DeploymentStatusUpdate { return dsu } +// ClearRepo clears the "repo" edge to the Repo entity. +func (dsu *DeploymentStatusUpdate) ClearRepo() *DeploymentStatusUpdate { + dsu.mutation.ClearRepo() + return dsu +} + // ClearEvent clears all "event" edges to the Event entity. func (dsu *DeploymentStatusUpdate) ClearEvent() *DeploymentStatusUpdate { dsu.mutation.ClearEvent() @@ -228,6 +246,9 @@ func (dsu *DeploymentStatusUpdate) check() error { if _, ok := dsu.mutation.DeploymentID(); dsu.mutation.DeploymentCleared() && !ok { return errors.New(`ent: clearing a required unique edge "DeploymentStatus.deployment"`) } + if _, ok := dsu.mutation.RepoID(); dsu.mutation.RepoCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "DeploymentStatus.repo"`) + } return nil } @@ -331,6 +352,41 @@ func (dsu *DeploymentStatusUpdate) sqlSave(ctx context.Context) (n int, err erro } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if dsu.mutation.RepoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: deploymentstatus.RepoTable, + Columns: []string{deploymentstatus.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: repo.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := dsu.mutation.RepoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: deploymentstatus.RepoTable, + Columns: []string{deploymentstatus.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: repo.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if dsu.mutation.EventCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -476,11 +532,22 @@ func (dsuo *DeploymentStatusUpdateOne) SetDeploymentID(i int) *DeploymentStatusU return dsuo } +// SetRepoID sets the "repo_id" field. +func (dsuo *DeploymentStatusUpdateOne) SetRepoID(i int64) *DeploymentStatusUpdateOne { + dsuo.mutation.SetRepoID(i) + return dsuo +} + // SetDeployment sets the "deployment" edge to the Deployment entity. func (dsuo *DeploymentStatusUpdateOne) SetDeployment(d *Deployment) *DeploymentStatusUpdateOne { return dsuo.SetDeploymentID(d.ID) } +// SetRepo sets the "repo" edge to the Repo entity. +func (dsuo *DeploymentStatusUpdateOne) SetRepo(r *Repo) *DeploymentStatusUpdateOne { + return dsuo.SetRepoID(r.ID) +} + // AddEventIDs adds the "event" edge to the Event entity by IDs. func (dsuo *DeploymentStatusUpdateOne) AddEventIDs(ids ...int) *DeploymentStatusUpdateOne { dsuo.mutation.AddEventIDs(ids...) @@ -507,6 +574,12 @@ func (dsuo *DeploymentStatusUpdateOne) ClearDeployment() *DeploymentStatusUpdate return dsuo } +// ClearRepo clears the "repo" edge to the Repo entity. +func (dsuo *DeploymentStatusUpdateOne) ClearRepo() *DeploymentStatusUpdateOne { + dsuo.mutation.ClearRepo() + return dsuo +} + // ClearEvent clears all "event" edges to the Event entity. func (dsuo *DeploymentStatusUpdateOne) ClearEvent() *DeploymentStatusUpdateOne { dsuo.mutation.ClearEvent() @@ -609,6 +682,9 @@ func (dsuo *DeploymentStatusUpdateOne) check() error { if _, ok := dsuo.mutation.DeploymentID(); dsuo.mutation.DeploymentCleared() && !ok { return errors.New(`ent: clearing a required unique edge "DeploymentStatus.deployment"`) } + if _, ok := dsuo.mutation.RepoID(); dsuo.mutation.RepoCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "DeploymentStatus.repo"`) + } return nil } @@ -729,6 +805,41 @@ func (dsuo *DeploymentStatusUpdateOne) sqlSave(ctx context.Context) (_node *Depl } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if dsuo.mutation.RepoCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: deploymentstatus.RepoTable, + Columns: []string{deploymentstatus.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: repo.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := dsuo.mutation.RepoIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: deploymentstatus.RepoTable, + Columns: []string{deploymentstatus.RepoColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt64, + Column: repo.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if dsuo.mutation.EventCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/model/ent/migrate/schema.go b/model/ent/migrate/schema.go index be677e69..5893e55e 100644 --- a/model/ent/migrate/schema.go +++ b/model/ent/migrate/schema.go @@ -156,6 +156,7 @@ var ( {Name: "created_at", Type: field.TypeTime}, {Name: "updated_at", Type: field.TypeTime}, {Name: "deployment_id", Type: field.TypeInt}, + {Name: "repo_id", Type: field.TypeInt64}, } // DeploymentStatusTable holds the schema information for the "deployment_status" table. DeploymentStatusTable = &schema.Table{ @@ -169,6 +170,12 @@ var ( RefColumns: []*schema.Column{DeploymentsColumns[0]}, OnDelete: schema.Cascade, }, + { + Symbol: "deployment_status_repos_deployment_statuses", + Columns: []*schema.Column{DeploymentStatusColumns[7]}, + RefColumns: []*schema.Column{ReposColumns[0]}, + OnDelete: schema.Cascade, + }, }, } // EventsColumns holds the columns for the "events" table. @@ -428,6 +435,7 @@ func init() { DeploymentsTable.ForeignKeys[1].RefTable = UsersTable DeploymentStatisticsTable.ForeignKeys[0].RefTable = ReposTable DeploymentStatusTable.ForeignKeys[0].RefTable = DeploymentsTable + DeploymentStatusTable.ForeignKeys[1].RefTable = ReposTable EventsTable.ForeignKeys[0].RefTable = DeploymentsTable EventsTable.ForeignKeys[1].RefTable = DeploymentStatusTable EventsTable.ForeignKeys[2].RefTable = ReviewsTable diff --git a/model/ent/mutation.go b/model/ent/mutation.go index edf8399e..1ccd9838 100644 --- a/model/ent/mutation.go +++ b/model/ent/mutation.go @@ -3645,6 +3645,8 @@ type DeploymentStatusMutation struct { clearedFields map[string]struct{} deployment *int cleareddeployment bool + repo *int64 + clearedrepo bool event map[int]struct{} removedevent map[int]struct{} clearedevent bool @@ -3993,6 +3995,42 @@ func (m *DeploymentStatusMutation) ResetDeploymentID() { m.deployment = nil } +// SetRepoID sets the "repo_id" field. +func (m *DeploymentStatusMutation) SetRepoID(i int64) { + m.repo = &i +} + +// RepoID returns the value of the "repo_id" field in the mutation. +func (m *DeploymentStatusMutation) RepoID() (r int64, exists bool) { + v := m.repo + if v == nil { + return + } + return *v, true +} + +// OldRepoID returns the old "repo_id" field's value of the DeploymentStatus entity. +// If the DeploymentStatus 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 *DeploymentStatusMutation) OldRepoID(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRepoID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRepoID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRepoID: %w", err) + } + return oldValue.RepoID, nil +} + +// ResetRepoID resets all changes to the "repo_id" field. +func (m *DeploymentStatusMutation) ResetRepoID() { + m.repo = nil +} + // ClearDeployment clears the "deployment" edge to the Deployment entity. func (m *DeploymentStatusMutation) ClearDeployment() { m.cleareddeployment = true @@ -4019,6 +4057,32 @@ func (m *DeploymentStatusMutation) ResetDeployment() { m.cleareddeployment = false } +// ClearRepo clears the "repo" edge to the Repo entity. +func (m *DeploymentStatusMutation) ClearRepo() { + m.clearedrepo = true +} + +// RepoCleared reports if the "repo" edge to the Repo entity was cleared. +func (m *DeploymentStatusMutation) RepoCleared() bool { + return m.clearedrepo +} + +// RepoIDs returns the "repo" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// RepoID instead. It exists only for internal usage by the builders. +func (m *DeploymentStatusMutation) RepoIDs() (ids []int64) { + if id := m.repo; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetRepo resets all changes to the "repo" edge. +func (m *DeploymentStatusMutation) ResetRepo() { + m.repo = nil + m.clearedrepo = false +} + // AddEventIDs adds the "event" edge to the Event entity by ids. func (m *DeploymentStatusMutation) AddEventIDs(ids ...int) { if m.event == nil { @@ -4092,7 +4156,7 @@ func (m *DeploymentStatusMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *DeploymentStatusMutation) Fields() []string { - fields := make([]string, 0, 6) + fields := make([]string, 0, 7) if m.status != nil { fields = append(fields, deploymentstatus.FieldStatus) } @@ -4111,6 +4175,9 @@ func (m *DeploymentStatusMutation) Fields() []string { if m.deployment != nil { fields = append(fields, deploymentstatus.FieldDeploymentID) } + if m.repo != nil { + fields = append(fields, deploymentstatus.FieldRepoID) + } return fields } @@ -4131,6 +4198,8 @@ func (m *DeploymentStatusMutation) Field(name string) (ent.Value, bool) { return m.UpdatedAt() case deploymentstatus.FieldDeploymentID: return m.DeploymentID() + case deploymentstatus.FieldRepoID: + return m.RepoID() } return nil, false } @@ -4152,6 +4221,8 @@ func (m *DeploymentStatusMutation) OldField(ctx context.Context, name string) (e return m.OldUpdatedAt(ctx) case deploymentstatus.FieldDeploymentID: return m.OldDeploymentID(ctx) + case deploymentstatus.FieldRepoID: + return m.OldRepoID(ctx) } return nil, fmt.Errorf("unknown DeploymentStatus field %s", name) } @@ -4203,6 +4274,13 @@ func (m *DeploymentStatusMutation) SetField(name string, value ent.Value) error } m.SetDeploymentID(v) return nil + case deploymentstatus.FieldRepoID: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRepoID(v) + return nil } return fmt.Errorf("unknown DeploymentStatus field %s", name) } @@ -4288,16 +4366,22 @@ func (m *DeploymentStatusMutation) ResetField(name string) error { case deploymentstatus.FieldDeploymentID: m.ResetDeploymentID() return nil + case deploymentstatus.FieldRepoID: + m.ResetRepoID() + return nil } return fmt.Errorf("unknown DeploymentStatus field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. func (m *DeploymentStatusMutation) AddedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.deployment != nil { edges = append(edges, deploymentstatus.EdgeDeployment) } + if m.repo != nil { + edges = append(edges, deploymentstatus.EdgeRepo) + } if m.event != nil { edges = append(edges, deploymentstatus.EdgeEvent) } @@ -4312,6 +4396,10 @@ func (m *DeploymentStatusMutation) AddedIDs(name string) []ent.Value { if id := m.deployment; id != nil { return []ent.Value{*id} } + case deploymentstatus.EdgeRepo: + if id := m.repo; id != nil { + return []ent.Value{*id} + } case deploymentstatus.EdgeEvent: ids := make([]ent.Value, 0, len(m.event)) for id := range m.event { @@ -4324,7 +4412,7 @@ func (m *DeploymentStatusMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *DeploymentStatusMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.removedevent != nil { edges = append(edges, deploymentstatus.EdgeEvent) } @@ -4347,10 +4435,13 @@ func (m *DeploymentStatusMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *DeploymentStatusMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) + edges := make([]string, 0, 3) if m.cleareddeployment { edges = append(edges, deploymentstatus.EdgeDeployment) } + if m.clearedrepo { + edges = append(edges, deploymentstatus.EdgeRepo) + } if m.clearedevent { edges = append(edges, deploymentstatus.EdgeEvent) } @@ -4363,6 +4454,8 @@ func (m *DeploymentStatusMutation) EdgeCleared(name string) bool { switch name { case deploymentstatus.EdgeDeployment: return m.cleareddeployment + case deploymentstatus.EdgeRepo: + return m.clearedrepo case deploymentstatus.EdgeEvent: return m.clearedevent } @@ -4376,6 +4469,9 @@ func (m *DeploymentStatusMutation) ClearEdge(name string) error { case deploymentstatus.EdgeDeployment: m.ClearDeployment() return nil + case deploymentstatus.EdgeRepo: + m.ClearRepo() + return nil } return fmt.Errorf("unknown DeploymentStatus unique edge %s", name) } @@ -4387,6 +4483,9 @@ func (m *DeploymentStatusMutation) ResetEdge(name string) error { case deploymentstatus.EdgeDeployment: m.ResetDeployment() return nil + case deploymentstatus.EdgeRepo: + m.ResetRepo() + return nil case deploymentstatus.EdgeEvent: m.ResetEvent() return nil @@ -7099,6 +7198,9 @@ type RepoMutation struct { deployments map[int]struct{} removeddeployments map[int]struct{} cleareddeployments bool + deployment_statuses map[int]struct{} + removeddeployment_statuses map[int]struct{} + cleareddeployment_statuses bool locks map[int]struct{} removedlocks map[int]struct{} clearedlocks bool @@ -7744,6 +7846,60 @@ func (m *RepoMutation) ResetDeployments() { m.removeddeployments = nil } +// AddDeploymentStatusIDs adds the "deployment_statuses" edge to the DeploymentStatus entity by ids. +func (m *RepoMutation) AddDeploymentStatusIDs(ids ...int) { + if m.deployment_statuses == nil { + m.deployment_statuses = make(map[int]struct{}) + } + for i := range ids { + m.deployment_statuses[ids[i]] = struct{}{} + } +} + +// ClearDeploymentStatuses clears the "deployment_statuses" edge to the DeploymentStatus entity. +func (m *RepoMutation) ClearDeploymentStatuses() { + m.cleareddeployment_statuses = true +} + +// DeploymentStatusesCleared reports if the "deployment_statuses" edge to the DeploymentStatus entity was cleared. +func (m *RepoMutation) DeploymentStatusesCleared() bool { + return m.cleareddeployment_statuses +} + +// RemoveDeploymentStatusIDs removes the "deployment_statuses" edge to the DeploymentStatus entity by IDs. +func (m *RepoMutation) RemoveDeploymentStatusIDs(ids ...int) { + if m.removeddeployment_statuses == nil { + m.removeddeployment_statuses = make(map[int]struct{}) + } + for i := range ids { + delete(m.deployment_statuses, ids[i]) + m.removeddeployment_statuses[ids[i]] = struct{}{} + } +} + +// RemovedDeploymentStatuses returns the removed IDs of the "deployment_statuses" edge to the DeploymentStatus entity. +func (m *RepoMutation) RemovedDeploymentStatusesIDs() (ids []int) { + for id := range m.removeddeployment_statuses { + ids = append(ids, id) + } + return +} + +// DeploymentStatusesIDs returns the "deployment_statuses" edge IDs in the mutation. +func (m *RepoMutation) DeploymentStatusesIDs() (ids []int) { + for id := range m.deployment_statuses { + ids = append(ids, id) + } + return +} + +// ResetDeploymentStatuses resets all changes to the "deployment_statuses" edge. +func (m *RepoMutation) ResetDeploymentStatuses() { + m.deployment_statuses = nil + m.cleareddeployment_statuses = false + m.removeddeployment_statuses = nil +} + // AddLockIDs adds the "locks" edge to the Lock entity by ids. func (m *RepoMutation) AddLockIDs(ids ...int) { if m.locks == nil { @@ -8185,13 +8341,16 @@ func (m *RepoMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *RepoMutation) AddedEdges() []string { - edges := make([]string, 0, 5) + edges := make([]string, 0, 6) if m.perms != nil { edges = append(edges, repo.EdgePerms) } if m.deployments != nil { edges = append(edges, repo.EdgeDeployments) } + if m.deployment_statuses != nil { + edges = append(edges, repo.EdgeDeploymentStatuses) + } if m.locks != nil { edges = append(edges, repo.EdgeLocks) } @@ -8220,6 +8379,12 @@ func (m *RepoMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case repo.EdgeDeploymentStatuses: + ids := make([]ent.Value, 0, len(m.deployment_statuses)) + for id := range m.deployment_statuses { + ids = append(ids, id) + } + return ids case repo.EdgeLocks: ids := make([]ent.Value, 0, len(m.locks)) for id := range m.locks { @@ -8242,13 +8407,16 @@ func (m *RepoMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *RepoMutation) RemovedEdges() []string { - edges := make([]string, 0, 5) + edges := make([]string, 0, 6) if m.removedperms != nil { edges = append(edges, repo.EdgePerms) } if m.removeddeployments != nil { edges = append(edges, repo.EdgeDeployments) } + if m.removeddeployment_statuses != nil { + edges = append(edges, repo.EdgeDeploymentStatuses) + } if m.removedlocks != nil { edges = append(edges, repo.EdgeLocks) } @@ -8274,6 +8442,12 @@ func (m *RepoMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case repo.EdgeDeploymentStatuses: + ids := make([]ent.Value, 0, len(m.removeddeployment_statuses)) + for id := range m.removeddeployment_statuses { + ids = append(ids, id) + } + return ids case repo.EdgeLocks: ids := make([]ent.Value, 0, len(m.removedlocks)) for id := range m.removedlocks { @@ -8292,13 +8466,16 @@ func (m *RepoMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *RepoMutation) ClearedEdges() []string { - edges := make([]string, 0, 5) + edges := make([]string, 0, 6) if m.clearedperms { edges = append(edges, repo.EdgePerms) } if m.cleareddeployments { edges = append(edges, repo.EdgeDeployments) } + if m.cleareddeployment_statuses { + edges = append(edges, repo.EdgeDeploymentStatuses) + } if m.clearedlocks { edges = append(edges, repo.EdgeLocks) } @@ -8319,6 +8496,8 @@ func (m *RepoMutation) EdgeCleared(name string) bool { return m.clearedperms case repo.EdgeDeployments: return m.cleareddeployments + case repo.EdgeDeploymentStatuses: + return m.cleareddeployment_statuses case repo.EdgeLocks: return m.clearedlocks case repo.EdgeDeploymentStatistics: @@ -8350,6 +8529,9 @@ func (m *RepoMutation) ResetEdge(name string) error { case repo.EdgeDeployments: m.ResetDeployments() return nil + case repo.EdgeDeploymentStatuses: + m.ResetDeploymentStatuses() + return nil case repo.EdgeLocks: m.ResetLocks() return nil diff --git a/model/ent/repo.go b/model/ent/repo.go index b19bbf0c..46c1eac7 100644 --- a/model/ent/repo.go +++ b/model/ent/repo.go @@ -48,6 +48,8 @@ type RepoEdges struct { Perms []*Perm `json:"perms,omitempty"` // Deployments holds the value of the deployments edge. Deployments []*Deployment `json:"deployments,omitempty"` + // DeploymentStatuses holds the value of the deployment_statuses edge. + DeploymentStatuses []*DeploymentStatus `json:"deployment_statuses,omitempty"` // Locks holds the value of the locks edge. Locks []*Lock `json:"locks,omitempty"` // DeploymentStatistics holds the value of the deployment_statistics edge. @@ -56,7 +58,7 @@ type RepoEdges struct { Owner *User `json:"owner,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 } // PermsOrErr returns the Perms value or an error if the edge @@ -77,10 +79,19 @@ func (e RepoEdges) DeploymentsOrErr() ([]*Deployment, error) { return nil, &NotLoadedError{edge: "deployments"} } +// DeploymentStatusesOrErr returns the DeploymentStatuses value or an error if the edge +// was not loaded in eager-loading. +func (e RepoEdges) DeploymentStatusesOrErr() ([]*DeploymentStatus, error) { + if e.loadedTypes[2] { + return e.DeploymentStatuses, nil + } + return nil, &NotLoadedError{edge: "deployment_statuses"} +} + // LocksOrErr returns the Locks value or an error if the edge // was not loaded in eager-loading. func (e RepoEdges) LocksOrErr() ([]*Lock, error) { - if e.loadedTypes[2] { + if e.loadedTypes[3] { return e.Locks, nil } return nil, &NotLoadedError{edge: "locks"} @@ -89,7 +100,7 @@ func (e RepoEdges) LocksOrErr() ([]*Lock, error) { // DeploymentStatisticsOrErr returns the DeploymentStatistics value or an error if the edge // was not loaded in eager-loading. func (e RepoEdges) DeploymentStatisticsOrErr() ([]*DeploymentStatistics, error) { - if e.loadedTypes[3] { + if e.loadedTypes[4] { return e.DeploymentStatistics, nil } return nil, &NotLoadedError{edge: "deployment_statistics"} @@ -98,7 +109,7 @@ func (e RepoEdges) DeploymentStatisticsOrErr() ([]*DeploymentStatistics, error) // OwnerOrErr returns the Owner value or an error if the edge // was not loaded in eager-loading, or loaded but was not found. func (e RepoEdges) OwnerOrErr() (*User, error) { - if e.loadedTypes[4] { + if e.loadedTypes[5] { if e.Owner == nil { // The edge owner was loaded in eager-loading, // but was not found. @@ -218,6 +229,11 @@ func (r *Repo) QueryDeployments() *DeploymentQuery { return (&RepoClient{config: r.config}).QueryDeployments(r) } +// QueryDeploymentStatuses queries the "deployment_statuses" edge of the Repo entity. +func (r *Repo) QueryDeploymentStatuses() *DeploymentStatusQuery { + return (&RepoClient{config: r.config}).QueryDeploymentStatuses(r) +} + // QueryLocks queries the "locks" edge of the Repo entity. func (r *Repo) QueryLocks() *LockQuery { return (&RepoClient{config: r.config}).QueryLocks(r) diff --git a/model/ent/repo/repo.go b/model/ent/repo/repo.go index 64dbcbd0..9c180828 100644 --- a/model/ent/repo/repo.go +++ b/model/ent/repo/repo.go @@ -35,6 +35,8 @@ const ( EdgePerms = "perms" // EdgeDeployments holds the string denoting the deployments edge name in mutations. EdgeDeployments = "deployments" + // EdgeDeploymentStatuses holds the string denoting the deployment_statuses edge name in mutations. + EdgeDeploymentStatuses = "deployment_statuses" // EdgeLocks holds the string denoting the locks edge name in mutations. EdgeLocks = "locks" // EdgeDeploymentStatistics holds the string denoting the deployment_statistics edge name in mutations. @@ -57,6 +59,13 @@ const ( DeploymentsInverseTable = "deployments" // DeploymentsColumn is the table column denoting the deployments relation/edge. DeploymentsColumn = "repo_id" + // DeploymentStatusesTable is the table that holds the deployment_statuses relation/edge. + DeploymentStatusesTable = "deployment_status" + // DeploymentStatusesInverseTable is the table name for the DeploymentStatus entity. + // It exists in this package in order to avoid circular dependency with the "deploymentstatus" package. + DeploymentStatusesInverseTable = "deployment_status" + // DeploymentStatusesColumn is the table column denoting the deployment_statuses relation/edge. + DeploymentStatusesColumn = "repo_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/model/ent/repo/where.go b/model/ent/repo/where.go index b432cfa4..b3e3e4cb 100644 --- a/model/ent/repo/where.go +++ b/model/ent/repo/where.go @@ -1071,6 +1071,34 @@ func HasDeploymentsWith(preds ...predicate.Deployment) predicate.Repo { }) } +// HasDeploymentStatuses applies the HasEdge predicate on the "deployment_statuses" edge. +func HasDeploymentStatuses() predicate.Repo { + return predicate.Repo(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DeploymentStatusesTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, DeploymentStatusesTable, DeploymentStatusesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasDeploymentStatusesWith applies the HasEdge predicate on the "deployment_statuses" edge with a given conditions (other predicates). +func HasDeploymentStatusesWith(preds ...predicate.DeploymentStatus) predicate.Repo { + return predicate.Repo(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(DeploymentStatusesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, DeploymentStatusesTable, DeploymentStatusesColumn), + ) + 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.Repo { return predicate.Repo(func(s *sql.Selector) { diff --git a/model/ent/repo_create.go b/model/ent/repo_create.go index 14fa6fd4..31a9d29a 100644 --- a/model/ent/repo_create.go +++ b/model/ent/repo_create.go @@ -12,6 +12,7 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatistics" + "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/lock" "github.com/gitploy-io/gitploy/model/ent/perm" "github.com/gitploy-io/gitploy/model/ent/repo" @@ -177,6 +178,21 @@ func (rc *RepoCreate) AddDeployments(d ...*Deployment) *RepoCreate { return rc.AddDeploymentIDs(ids...) } +// AddDeploymentStatusIDs adds the "deployment_statuses" edge to the DeploymentStatus entity by IDs. +func (rc *RepoCreate) AddDeploymentStatusIDs(ids ...int) *RepoCreate { + rc.mutation.AddDeploymentStatusIDs(ids...) + return rc +} + +// AddDeploymentStatuses adds the "deployment_statuses" edges to the DeploymentStatus entity. +func (rc *RepoCreate) AddDeploymentStatuses(d ...*DeploymentStatus) *RepoCreate { + ids := make([]int, len(d)) + for i := range d { + ids[i] = d[i].ID + } + return rc.AddDeploymentStatusIDs(ids...) +} + // AddLockIDs adds the "locks" edge to the Lock entity by IDs. func (rc *RepoCreate) AddLockIDs(ids ...int) *RepoCreate { rc.mutation.AddLockIDs(ids...) @@ -471,6 +487,25 @@ func (rc *RepoCreate) createSpec() (*Repo, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := rc.mutation.DeploymentStatusesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repo.DeploymentStatusesTable, + Columns: []string{repo.DeploymentStatusesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } if nodes := rc.mutation.LocksIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/model/ent/repo_query.go b/model/ent/repo_query.go index d6c8df84..49264d8b 100644 --- a/model/ent/repo_query.go +++ b/model/ent/repo_query.go @@ -15,6 +15,7 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatistics" + "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/lock" "github.com/gitploy-io/gitploy/model/ent/perm" "github.com/gitploy-io/gitploy/model/ent/predicate" @@ -34,6 +35,7 @@ type RepoQuery struct { // eager-loading edges. withPerms *PermQuery withDeployments *DeploymentQuery + withDeploymentStatuses *DeploymentStatusQuery withLocks *LockQuery withDeploymentStatistics *DeploymentStatisticsQuery withOwner *UserQuery @@ -118,6 +120,28 @@ func (rq *RepoQuery) QueryDeployments() *DeploymentQuery { return query } +// QueryDeploymentStatuses chains the current query on the "deployment_statuses" edge. +func (rq *RepoQuery) QueryDeploymentStatuses() *DeploymentStatusQuery { + query := &DeploymentStatusQuery{config: rq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := rq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := rq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(repo.Table, repo.FieldID, selector), + sqlgraph.To(deploymentstatus.Table, deploymentstatus.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, repo.DeploymentStatusesTable, repo.DeploymentStatusesColumn), + ) + fromU = sqlgraph.SetNeighbors(rq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryLocks chains the current query on the "locks" edge. func (rq *RepoQuery) QueryLocks() *LockQuery { query := &LockQuery{config: rq.config} @@ -367,6 +391,7 @@ func (rq *RepoQuery) Clone() *RepoQuery { predicates: append([]predicate.Repo{}, rq.predicates...), withPerms: rq.withPerms.Clone(), withDeployments: rq.withDeployments.Clone(), + withDeploymentStatuses: rq.withDeploymentStatuses.Clone(), withLocks: rq.withLocks.Clone(), withDeploymentStatistics: rq.withDeploymentStatistics.Clone(), withOwner: rq.withOwner.Clone(), @@ -399,6 +424,17 @@ func (rq *RepoQuery) WithDeployments(opts ...func(*DeploymentQuery)) *RepoQuery return rq } +// 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 (rq *RepoQuery) WithDeploymentStatuses(opts ...func(*DeploymentStatusQuery)) *RepoQuery { + query := &DeploymentStatusQuery{config: rq.config} + for _, opt := range opts { + opt(query) + } + rq.withDeploymentStatuses = query + return rq +} + // 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 (rq *RepoQuery) WithLocks(opts ...func(*LockQuery)) *RepoQuery { @@ -497,9 +533,10 @@ func (rq *RepoQuery) sqlAll(ctx context.Context) ([]*Repo, error) { var ( nodes = []*Repo{} _spec = rq.querySpec() - loadedTypes = [5]bool{ + loadedTypes = [6]bool{ rq.withPerms != nil, rq.withDeployments != nil, + rq.withDeploymentStatuses != nil, rq.withLocks != nil, rq.withDeploymentStatistics != nil, rq.withOwner != nil, @@ -578,6 +615,31 @@ func (rq *RepoQuery) sqlAll(ctx context.Context) ([]*Repo, error) { } } + if query := rq.withDeploymentStatuses; query != nil { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int64]*Repo) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + nodes[i].Edges.DeploymentStatuses = []*DeploymentStatus{} + } + query.Where(predicate.DeploymentStatus(func(s *sql.Selector) { + s.Where(sql.InValues(repo.DeploymentStatusesColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, n := range neighbors { + fk := n.RepoID + node, ok := nodeids[fk] + if !ok { + return nil, fmt.Errorf(`unexpected foreign-key "repo_id" returned %v for node %v`, fk, n.ID) + } + node.Edges.DeploymentStatuses = append(node.Edges.DeploymentStatuses, n) + } + } + if query := rq.withLocks; query != nil { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[int64]*Repo) diff --git a/model/ent/repo_update.go b/model/ent/repo_update.go index 0b516239..ca3d1b2a 100644 --- a/model/ent/repo_update.go +++ b/model/ent/repo_update.go @@ -13,6 +13,7 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatistics" + "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/lock" "github.com/gitploy-io/gitploy/model/ent/perm" "github.com/gitploy-io/gitploy/model/ent/predicate" @@ -196,6 +197,21 @@ func (ru *RepoUpdate) AddDeployments(d ...*Deployment) *RepoUpdate { return ru.AddDeploymentIDs(ids...) } +// AddDeploymentStatusIDs adds the "deployment_statuses" edge to the DeploymentStatus entity by IDs. +func (ru *RepoUpdate) AddDeploymentStatusIDs(ids ...int) *RepoUpdate { + ru.mutation.AddDeploymentStatusIDs(ids...) + return ru +} + +// AddDeploymentStatuses adds the "deployment_statuses" edges to the DeploymentStatus entity. +func (ru *RepoUpdate) AddDeploymentStatuses(d ...*DeploymentStatus) *RepoUpdate { + ids := make([]int, len(d)) + for i := range d { + ids[i] = d[i].ID + } + return ru.AddDeploymentStatusIDs(ids...) +} + // AddLockIDs adds the "locks" edge to the Lock entity by IDs. func (ru *RepoUpdate) AddLockIDs(ids ...int) *RepoUpdate { ru.mutation.AddLockIDs(ids...) @@ -278,6 +294,27 @@ func (ru *RepoUpdate) RemoveDeployments(d ...*Deployment) *RepoUpdate { return ru.RemoveDeploymentIDs(ids...) } +// ClearDeploymentStatuses clears all "deployment_statuses" edges to the DeploymentStatus entity. +func (ru *RepoUpdate) ClearDeploymentStatuses() *RepoUpdate { + ru.mutation.ClearDeploymentStatuses() + return ru +} + +// RemoveDeploymentStatusIDs removes the "deployment_statuses" edge to DeploymentStatus entities by IDs. +func (ru *RepoUpdate) RemoveDeploymentStatusIDs(ids ...int) *RepoUpdate { + ru.mutation.RemoveDeploymentStatusIDs(ids...) + return ru +} + +// RemoveDeploymentStatuses removes "deployment_statuses" edges to DeploymentStatus entities. +func (ru *RepoUpdate) RemoveDeploymentStatuses(d ...*DeploymentStatus) *RepoUpdate { + ids := make([]int, len(d)) + for i := range d { + ids[i] = d[i].ID + } + return ru.RemoveDeploymentStatusIDs(ids...) +} + // ClearLocks clears all "locks" edges to the Lock entity. func (ru *RepoUpdate) ClearLocks() *RepoUpdate { ru.mutation.ClearLocks() @@ -597,6 +634,60 @@ func (ru *RepoUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if ru.mutation.DeploymentStatusesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repo.DeploymentStatusesTable, + Columns: []string{repo.DeploymentStatusesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ru.mutation.RemovedDeploymentStatusesIDs(); len(nodes) > 0 && !ru.mutation.DeploymentStatusesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repo.DeploymentStatusesTable, + Columns: []string{repo.DeploymentStatusesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ru.mutation.DeploymentStatusesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repo.DeploymentStatusesTable, + Columns: []string{repo.DeploymentStatusesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if ru.mutation.LocksCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -922,6 +1013,21 @@ func (ruo *RepoUpdateOne) AddDeployments(d ...*Deployment) *RepoUpdateOne { return ruo.AddDeploymentIDs(ids...) } +// AddDeploymentStatusIDs adds the "deployment_statuses" edge to the DeploymentStatus entity by IDs. +func (ruo *RepoUpdateOne) AddDeploymentStatusIDs(ids ...int) *RepoUpdateOne { + ruo.mutation.AddDeploymentStatusIDs(ids...) + return ruo +} + +// AddDeploymentStatuses adds the "deployment_statuses" edges to the DeploymentStatus entity. +func (ruo *RepoUpdateOne) AddDeploymentStatuses(d ...*DeploymentStatus) *RepoUpdateOne { + ids := make([]int, len(d)) + for i := range d { + ids[i] = d[i].ID + } + return ruo.AddDeploymentStatusIDs(ids...) +} + // AddLockIDs adds the "locks" edge to the Lock entity by IDs. func (ruo *RepoUpdateOne) AddLockIDs(ids ...int) *RepoUpdateOne { ruo.mutation.AddLockIDs(ids...) @@ -1004,6 +1110,27 @@ func (ruo *RepoUpdateOne) RemoveDeployments(d ...*Deployment) *RepoUpdateOne { return ruo.RemoveDeploymentIDs(ids...) } +// ClearDeploymentStatuses clears all "deployment_statuses" edges to the DeploymentStatus entity. +func (ruo *RepoUpdateOne) ClearDeploymentStatuses() *RepoUpdateOne { + ruo.mutation.ClearDeploymentStatuses() + return ruo +} + +// RemoveDeploymentStatusIDs removes the "deployment_statuses" edge to DeploymentStatus entities by IDs. +func (ruo *RepoUpdateOne) RemoveDeploymentStatusIDs(ids ...int) *RepoUpdateOne { + ruo.mutation.RemoveDeploymentStatusIDs(ids...) + return ruo +} + +// RemoveDeploymentStatuses removes "deployment_statuses" edges to DeploymentStatus entities. +func (ruo *RepoUpdateOne) RemoveDeploymentStatuses(d ...*DeploymentStatus) *RepoUpdateOne { + ids := make([]int, len(d)) + for i := range d { + ids[i] = d[i].ID + } + return ruo.RemoveDeploymentStatusIDs(ids...) +} + // ClearLocks clears all "locks" edges to the Lock entity. func (ruo *RepoUpdateOne) ClearLocks() *RepoUpdateOne { ruo.mutation.ClearLocks() @@ -1347,6 +1474,60 @@ func (ruo *RepoUpdateOne) sqlSave(ctx context.Context) (_node *Repo, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if ruo.mutation.DeploymentStatusesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repo.DeploymentStatusesTable, + Columns: []string{repo.DeploymentStatusesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ruo.mutation.RemovedDeploymentStatusesIDs(); len(nodes) > 0 && !ruo.mutation.DeploymentStatusesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repo.DeploymentStatusesTable, + Columns: []string{repo.DeploymentStatusesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := ruo.mutation.DeploymentStatusesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: repo.DeploymentStatusesTable, + Columns: []string{repo.DeploymentStatusesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeInt, + Column: deploymentstatus.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if ruo.mutation.LocksCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/model/ent/schema/deploymentstatus.go b/model/ent/schema/deploymentstatus.go index b71b0f9b..7bb4aaa8 100644 --- a/model/ent/schema/deploymentstatus.go +++ b/model/ent/schema/deploymentstatus.go @@ -28,6 +28,9 @@ func (DeploymentStatus) Fields() []ent.Field { // edges field.Int("deployment_id"), + // Denormalize the 'repo_id' field so that + // we can figure out the repository easily. + field.Int64("repo_id"), } } @@ -39,6 +42,11 @@ func (DeploymentStatus) Edges() []ent.Edge { Field("deployment_id"). Unique(). Required(), + edge.From("repo", Repo.Type). + Ref("deployment_statuses"). + Field("repo_id"). + Unique(). + Required(), edge.To("event", Event.Type). Annotations(entsql.Annotation{ OnDelete: entsql.Cascade, diff --git a/model/ent/schema/repo.go b/model/ent/schema/repo.go index 02823580..e69f5cbf 100644 --- a/model/ent/schema/repo.go +++ b/model/ent/schema/repo.go @@ -53,6 +53,10 @@ func (Repo) Edges() []ent.Edge { Annotations(entsql.Annotation{ OnDelete: entsql.Cascade, }), + edge.To("deployment_statuses", DeploymentStatus.Type). + Annotations(entsql.Annotation{ + OnDelete: entsql.Cascade, + }), edge.To("locks", Lock.Type). Annotations(entsql.Annotation{ OnDelete: entsql.Cascade, From 277d5623866ca92af9208a9a4fffae5ccf0eb0bc Mon Sep 17 00:00:00 2001 From: noah Date: Sat, 23 Apr 2022 17:23:42 +0900 Subject: [PATCH 6/9] Fix to add `RepoID` when creating a status --- internal/interactor/deployment.go | 4 +++ internal/pkg/store/deploymentstatus.go | 25 +++++++++++-------- internal/pkg/store/event.go | 3 ++- internal/server/hooks/hook.go | 1 + model/ent/deploymentstatus.go | 2 +- model/ent/deploymentstatus/where.go | 14 +++++++++++ model/ent/deploymentstatus_create.go | 14 ++++++----- model/ent/deploymentstatus_update.go | 34 +++++++++++++++++++++----- model/ent/migrate/schema.go | 2 +- model/ent/mutation.go | 21 +++++++++++++++- model/ent/schema/deploymentstatus.go | 6 ++--- openapi/v1.yaml | 13 ++++++++++ 12 files changed, 110 insertions(+), 29 deletions(-) diff --git a/internal/interactor/deployment.go b/internal/interactor/deployment.go index 7316f319..3e23e004 100644 --- a/internal/interactor/deployment.go +++ b/internal/interactor/deployment.go @@ -125,6 +125,7 @@ func (i *DeploymentInteractor) Deploy(ctx context.Context, u *ent.User, r *ent.R Status: string(deployment.StatusWaiting), Description: "Gitploy waits the reviews.", DeploymentID: d.ID, + RepoID: r.ID, }); err != nil { i.log.Error("Failed to create a deployment status.", zap.Error(err)) } @@ -153,6 +154,7 @@ func (i *DeploymentInteractor) Deploy(ctx context.Context, u *ent.User, r *ent.R Status: string(deployment.StatusCreated), Description: "Gitploy starts to deploy.", DeploymentID: d.ID, + RepoID: r.ID, }); err != nil { i.log.Error("Failed to create a deployment status.", zap.Error(err)) } @@ -235,6 +237,7 @@ func (i *DeploymentInteractor) DeployToRemote(ctx context.Context, u *ent.User, Status: string(deployment.StatusCreated), Description: "Gitploy start to deploy.", DeploymentID: d.ID, + RepoID: r.ID, }) return d, nil @@ -301,6 +304,7 @@ L: Status: "canceled", Description: "Gitploy cancels the inactive deployment.", DeploymentID: d.ID, + RepoID: d.RepoID, } if err := i.scm.CancelDeployment(ctx, d.Edges.User, d.Edges.Repo, d, s); err != nil { i.log.Error("It has failed to cancel the remote deployment.", zap.Error(err)) diff --git a/internal/pkg/store/deploymentstatus.go b/internal/pkg/store/deploymentstatus.go index 47290f3e..bc6b96d9 100644 --- a/internal/pkg/store/deploymentstatus.go +++ b/internal/pkg/store/deploymentstatus.go @@ -21,13 +21,27 @@ func (s *Store) ListDeploymentStatuses(ctx context.Context, d *ent.Deployment) ( return dss, nil } +func (s *Store) FindDeploymentStatusByID(ctx context.Context, id int) (*ent.DeploymentStatus, error) { + ds, err := s.c.DeploymentStatus.Query(). + Where(deploymentstatus.IDEQ(id)). + WithDeployment(). + WithRepo(). + Only(ctx) + if ent.IsNotFound(err) { + return nil, e.NewError(e.ErrorCodeEntityNotFound, err) + } + + return ds, nil +} + func (s *Store) CreateEntDeploymentStatus(ctx context.Context, ds *ent.DeploymentStatus) (*ent.DeploymentStatus, error) { // Build the query creating a deployment status. qry := s.c.DeploymentStatus.Create(). SetStatus(ds.Status). SetDescription(ds.Description). SetLogURL(ds.LogURL). - SetDeploymentID(ds.DeploymentID) + SetDeploymentID(ds.DeploymentID). + SetRepoID(ds.RepoID) if !ds.CreatedAt.IsZero() { qry.SetCreatedAt(ds.CreatedAt.UTC()) @@ -49,12 +63,3 @@ func (s *Store) CreateEntDeploymentStatus(ctx context.Context, ds *ent.Deploymen return ret, nil } - -func (s *Store) FindDeploymentStatusByID(ctx context.Context, id int) (*ent.DeploymentStatus, error) { - ds, err := s.c.DeploymentStatus.Get(ctx, id) - if ent.IsNotFound(err) { - return nil, e.NewError(e.ErrorCodeEntityNotFound, err) - } - - return ds, nil -} diff --git a/internal/pkg/store/event.go b/internal/pkg/store/event.go index c5ab9371..1221ad5d 100644 --- a/internal/pkg/store/event.go +++ b/internal/pkg/store/event.go @@ -30,7 +30,8 @@ func (s *Store) ListEventsGreaterThanTime(ctx context.Context, t time.Time) ([]* }). WithDeploymentStatus(func(dsq *ent.DeploymentStatusQuery) { dsq. - WithDeployment() + WithDeployment(). + WithRepo() }). WithReview(func(rq *ent.ReviewQuery) { rq. diff --git a/internal/server/hooks/hook.go b/internal/server/hooks/hook.go index 4a3cf7ea..b3a59e67 100644 --- a/internal/server/hooks/hook.go +++ b/internal/server/hooks/hook.go @@ -117,6 +117,7 @@ func (h *Hooks) handleGithubDeploymentEvent(c *gin.Context) { } ds.DeploymentID = d.ID + ds.RepoID = d.RepoID if ds, err = h.i.CreateDeploymentStatus(ctx, ds); err != nil { h.log.Check(gb.GetZapLogLevel(err), "Failed to create a new the deployment status.").Write(zap.Error(err)) gb.ResponseWithError(c, err) diff --git a/model/ent/deploymentstatus.go b/model/ent/deploymentstatus.go index 8061d809..22558976 100644 --- a/model/ent/deploymentstatus.go +++ b/model/ent/deploymentstatus.go @@ -31,7 +31,7 @@ type DeploymentStatus struct { // DeploymentID holds the value of the "deployment_id" field. DeploymentID int `json:"deployment_id"` // RepoID holds the value of the "repo_id" field. - RepoID int64 `json:"repo_id"` + RepoID int64 `json:"repo_id,omitemtpy"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the DeploymentStatusQuery when eager-loading is set. Edges DeploymentStatusEdges `json:"edges"` diff --git a/model/ent/deploymentstatus/where.go b/model/ent/deploymentstatus/where.go index ad431c53..ca482b0b 100644 --- a/model/ent/deploymentstatus/where.go +++ b/model/ent/deploymentstatus/where.go @@ -751,6 +751,20 @@ func RepoIDNotIn(vs ...int64) predicate.DeploymentStatus { }) } +// RepoIDIsNil applies the IsNil predicate on the "repo_id" field. +func RepoIDIsNil() predicate.DeploymentStatus { + return predicate.DeploymentStatus(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldRepoID))) + }) +} + +// RepoIDNotNil applies the NotNil predicate on the "repo_id" field. +func RepoIDNotNil() predicate.DeploymentStatus { + return predicate.DeploymentStatus(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldRepoID))) + }) +} + // HasDeployment applies the HasEdge predicate on the "deployment" edge. func HasDeployment() predicate.DeploymentStatus { return predicate.DeploymentStatus(func(s *sql.Selector) { diff --git a/model/ent/deploymentstatus_create.go b/model/ent/deploymentstatus_create.go index c8f8c733..675d78c4 100644 --- a/model/ent/deploymentstatus_create.go +++ b/model/ent/deploymentstatus_create.go @@ -97,6 +97,14 @@ func (dsc *DeploymentStatusCreate) SetRepoID(i int64) *DeploymentStatusCreate { return dsc } +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (dsc *DeploymentStatusCreate) SetNillableRepoID(i *int64) *DeploymentStatusCreate { + if i != nil { + dsc.SetRepoID(*i) + } + return dsc +} + // SetDeployment sets the "deployment" edge to the Deployment entity. func (dsc *DeploymentStatusCreate) SetDeployment(d *Deployment) *DeploymentStatusCreate { return dsc.SetDeploymentID(d.ID) @@ -217,15 +225,9 @@ func (dsc *DeploymentStatusCreate) check() error { if _, ok := dsc.mutation.DeploymentID(); !ok { return &ValidationError{Name: "deployment_id", err: errors.New(`ent: missing required field "DeploymentStatus.deployment_id"`)} } - if _, ok := dsc.mutation.RepoID(); !ok { - return &ValidationError{Name: "repo_id", err: errors.New(`ent: missing required field "DeploymentStatus.repo_id"`)} - } if _, ok := dsc.mutation.DeploymentID(); !ok { return &ValidationError{Name: "deployment", err: errors.New(`ent: missing required edge "DeploymentStatus.deployment"`)} } - if _, ok := dsc.mutation.RepoID(); !ok { - return &ValidationError{Name: "repo", err: errors.New(`ent: missing required edge "DeploymentStatus.repo"`)} - } return nil } diff --git a/model/ent/deploymentstatus_update.go b/model/ent/deploymentstatus_update.go index 692de5f0..844e84a9 100644 --- a/model/ent/deploymentstatus_update.go +++ b/model/ent/deploymentstatus_update.go @@ -109,6 +109,20 @@ func (dsu *DeploymentStatusUpdate) SetRepoID(i int64) *DeploymentStatusUpdate { return dsu } +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (dsu *DeploymentStatusUpdate) SetNillableRepoID(i *int64) *DeploymentStatusUpdate { + if i != nil { + dsu.SetRepoID(*i) + } + return dsu +} + +// ClearRepoID clears the value of the "repo_id" field. +func (dsu *DeploymentStatusUpdate) ClearRepoID() *DeploymentStatusUpdate { + dsu.mutation.ClearRepoID() + return dsu +} + // SetDeployment sets the "deployment" edge to the Deployment entity. func (dsu *DeploymentStatusUpdate) SetDeployment(d *Deployment) *DeploymentStatusUpdate { return dsu.SetDeploymentID(d.ID) @@ -246,9 +260,6 @@ func (dsu *DeploymentStatusUpdate) check() error { if _, ok := dsu.mutation.DeploymentID(); dsu.mutation.DeploymentCleared() && !ok { return errors.New(`ent: clearing a required unique edge "DeploymentStatus.deployment"`) } - if _, ok := dsu.mutation.RepoID(); dsu.mutation.RepoCleared() && !ok { - return errors.New(`ent: clearing a required unique edge "DeploymentStatus.repo"`) - } return nil } @@ -538,6 +549,20 @@ func (dsuo *DeploymentStatusUpdateOne) SetRepoID(i int64) *DeploymentStatusUpdat return dsuo } +// SetNillableRepoID sets the "repo_id" field if the given value is not nil. +func (dsuo *DeploymentStatusUpdateOne) SetNillableRepoID(i *int64) *DeploymentStatusUpdateOne { + if i != nil { + dsuo.SetRepoID(*i) + } + return dsuo +} + +// ClearRepoID clears the value of the "repo_id" field. +func (dsuo *DeploymentStatusUpdateOne) ClearRepoID() *DeploymentStatusUpdateOne { + dsuo.mutation.ClearRepoID() + return dsuo +} + // SetDeployment sets the "deployment" edge to the Deployment entity. func (dsuo *DeploymentStatusUpdateOne) SetDeployment(d *Deployment) *DeploymentStatusUpdateOne { return dsuo.SetDeploymentID(d.ID) @@ -682,9 +707,6 @@ func (dsuo *DeploymentStatusUpdateOne) check() error { if _, ok := dsuo.mutation.DeploymentID(); dsuo.mutation.DeploymentCleared() && !ok { return errors.New(`ent: clearing a required unique edge "DeploymentStatus.deployment"`) } - if _, ok := dsuo.mutation.RepoID(); dsuo.mutation.RepoCleared() && !ok { - return errors.New(`ent: clearing a required unique edge "DeploymentStatus.repo"`) - } return nil } diff --git a/model/ent/migrate/schema.go b/model/ent/migrate/schema.go index 5893e55e..5210f674 100644 --- a/model/ent/migrate/schema.go +++ b/model/ent/migrate/schema.go @@ -156,7 +156,7 @@ var ( {Name: "created_at", Type: field.TypeTime}, {Name: "updated_at", Type: field.TypeTime}, {Name: "deployment_id", Type: field.TypeInt}, - {Name: "repo_id", Type: field.TypeInt64}, + {Name: "repo_id", Type: field.TypeInt64, Nullable: true}, } // DeploymentStatusTable holds the schema information for the "deployment_status" table. DeploymentStatusTable = &schema.Table{ diff --git a/model/ent/mutation.go b/model/ent/mutation.go index 1ccd9838..c0bcbeeb 100644 --- a/model/ent/mutation.go +++ b/model/ent/mutation.go @@ -4026,9 +4026,22 @@ func (m *DeploymentStatusMutation) OldRepoID(ctx context.Context) (v int64, err return oldValue.RepoID, nil } +// ClearRepoID clears the value of the "repo_id" field. +func (m *DeploymentStatusMutation) ClearRepoID() { + m.repo = nil + m.clearedFields[deploymentstatus.FieldRepoID] = struct{}{} +} + +// RepoIDCleared returns if the "repo_id" field was cleared in this mutation. +func (m *DeploymentStatusMutation) RepoIDCleared() bool { + _, ok := m.clearedFields[deploymentstatus.FieldRepoID] + return ok +} + // ResetRepoID resets all changes to the "repo_id" field. func (m *DeploymentStatusMutation) ResetRepoID() { m.repo = nil + delete(m.clearedFields, deploymentstatus.FieldRepoID) } // ClearDeployment clears the "deployment" edge to the Deployment entity. @@ -4064,7 +4077,7 @@ func (m *DeploymentStatusMutation) ClearRepo() { // RepoCleared reports if the "repo" edge to the Repo entity was cleared. func (m *DeploymentStatusMutation) RepoCleared() bool { - return m.clearedrepo + return m.RepoIDCleared() || m.clearedrepo } // RepoIDs returns the "repo" edge IDs in the mutation. @@ -4320,6 +4333,9 @@ func (m *DeploymentStatusMutation) ClearedFields() []string { if m.FieldCleared(deploymentstatus.FieldLogURL) { fields = append(fields, deploymentstatus.FieldLogURL) } + if m.FieldCleared(deploymentstatus.FieldRepoID) { + fields = append(fields, deploymentstatus.FieldRepoID) + } return fields } @@ -4340,6 +4356,9 @@ func (m *DeploymentStatusMutation) ClearField(name string) error { case deploymentstatus.FieldLogURL: m.ClearLogURL() return nil + case deploymentstatus.FieldRepoID: + m.ClearRepoID() + return nil } return fmt.Errorf("unknown DeploymentStatus nullable field %s", name) } diff --git a/model/ent/schema/deploymentstatus.go b/model/ent/schema/deploymentstatus.go index 7bb4aaa8..143572e6 100644 --- a/model/ent/schema/deploymentstatus.go +++ b/model/ent/schema/deploymentstatus.go @@ -30,7 +30,8 @@ func (DeploymentStatus) Fields() []ent.Field { field.Int("deployment_id"), // Denormalize the 'repo_id' field so that // we can figure out the repository easily. - field.Int64("repo_id"), + field.Int64("repo_id"). + Optional(), } } @@ -45,8 +46,7 @@ func (DeploymentStatus) Edges() []ent.Edge { edge.From("repo", Repo.Type). Ref("deployment_statuses"). Field("repo_id"). - Unique(). - Required(), + Unique(), edge.To("event", Event.Type). Annotations(entsql.Annotation{ OnDelete: entsql.Cascade, diff --git a/openapi/v1.yaml b/openapi/v1.yaml index 1bb1f696..397198d3 100644 --- a/openapi/v1.yaml +++ b/openapi/v1.yaml @@ -1751,11 +1751,24 @@ components: type: string updated_at: type: string + deployment_id: + type: number + repo_id: + type: number + edges: + type: object + properties: + deployment: + $ref: '#/components/schemas/DeploymentStatus' + repo: + $ref: '#/components/schemas/Repository' required: - id - status - created_at - updated_at + - deployment_id + - repo_id RemoteDeploymentStatus: type: object properties: From b926519b4dba5b70f54838edc8f411bceefd343a Mon Sep 17 00:00:00 2001 From: noah Date: Sat, 23 Apr 2022 20:06:18 +0900 Subject: [PATCH 7/9] Subscribe the deployment status event in UI --- ui/src/apis/deployment.ts | 9 ++++- ui/src/apis/events.ts | 21 ++++++++++-- ui/src/apis/index.ts | 1 + ui/src/models/Deployment.ts | 6 ++++ ui/src/redux/deployment.tsx | 21 ++++++++++++ ui/src/redux/main.ts | 55 +++++++++++++++++++++++++++++++ ui/src/views/deployment/index.tsx | 7 ++++ ui/src/views/main/index.tsx | 14 +++++++- 8 files changed, 129 insertions(+), 5 deletions(-) diff --git a/ui/src/apis/deployment.ts b/ui/src/apis/deployment.ts index c9e6b488..2863d3f5 100644 --- a/ui/src/apis/deployment.ts +++ b/ui/src/apis/deployment.ts @@ -117,7 +117,8 @@ function mapDeploymentStatusEnum(s: string) { } } -function mapDataToDeploymentStatus(data: any): DeploymentStatus { +// eslint-disable-next-line +export function mapDataToDeploymentStatus(data: any): DeploymentStatus { return { id: data.id, status: data.status, @@ -125,6 +126,12 @@ function mapDataToDeploymentStatus(data: any): DeploymentStatus { logUrl: data.log_url, createdAt: data.created_at, updatedAt: data.updated_at, + deploymentId: data.deployment_id, + repoId: data.repo_id, + edges: { + deployment: (data.edges.deployment)? mapDataToDeployment(data.edges.deployment) : undefined, + repo: (data.edges.repo)? mapDataToRepo(data.edges.repo) : undefined + } } } diff --git a/ui/src/apis/events.ts b/ui/src/apis/events.ts index 600ed2ba..1fb46f2b 100644 --- a/ui/src/apis/events.ts +++ b/ui/src/apis/events.ts @@ -1,8 +1,8 @@ import { instance } from './setting' -import { mapDataToDeployment } from "./deployment" -import { mapDataToReview } from "./review" -import { Deployment, Review } from "../models" +import { mapDataToDeployment, mapDataToDeploymentStatus } from "./deployment" +import { mapDataToReview } from "./review" +import { Deployment, DeploymentStatus, Review } from "../models" export const subscribeDeploymentEvents = (cb: (deployment: Deployment) => void): EventSource => { @@ -20,6 +20,21 @@ export const subscribeDeploymentEvents = (cb: (deployment: Deployment) => void): return sse } +export const subscribeDeploymentStatusEvents = (cb: (status: DeploymentStatus) => void): EventSource => { + const sse = new EventSource(`${instance}/api/v1/stream/events`, { + withCredentials: true, + }) + + sse.addEventListener("deployment_status", (e: any) => { + const data = JSON.parse(e.data) + const status = mapDataToDeploymentStatus(data) + + cb(status) + }) + + return sse +} + export const subscribeReviewEvents = (cb: (review: Review) => void): EventSource => { const sse = new EventSource(`${instance}/api/v1/stream/events`, { withCredentials: true, diff --git a/ui/src/apis/index.ts b/ui/src/apis/index.ts index f5b8fcba..c0b09e3f 100644 --- a/ui/src/apis/index.ts +++ b/ui/src/apis/index.ts @@ -66,5 +66,6 @@ export { } from "./license" export { subscribeDeploymentEvents, + subscribeDeploymentStatusEvents, subscribeReviewEvents, } from "./events" diff --git a/ui/src/models/Deployment.ts b/ui/src/models/Deployment.ts index 969c4cac..6d8c3c06 100644 --- a/ui/src/models/Deployment.ts +++ b/ui/src/models/Deployment.ts @@ -41,4 +41,10 @@ export interface DeploymentStatus { logUrl: string createdAt: string updatedAt: string + deploymentId: number + repoId: number + edges?: { + deployment?: Deployment + repo?: Repo + } } \ No newline at end of file diff --git a/ui/src/redux/deployment.tsx b/ui/src/redux/deployment.tsx index 593dd932..79094017 100644 --- a/ui/src/redux/deployment.tsx +++ b/ui/src/redux/deployment.tsx @@ -3,6 +3,7 @@ import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit' import { Deployment, + DeploymentStatus, Commit, Review, RequestStatus, @@ -165,6 +166,21 @@ export const fetchUserReview = createAsyncThunk( + "deployment/handleDeploymentStatusEvent", + async (deploymentStatus, { rejectWithValue }) => { + if (deploymentStatus.edges === undefined) { + return rejectWithValue(new Error("Edges is not included.")) + } + + const { repo, deployment } = deploymentStatus.edges + if (repo === undefined || deployment === undefined) { + return rejectWithValue(new Error("Repo or Deployment is not included in the edges.")) + } + + return await getDeployment(repo.namespace, repo.name, deployment.number) + } +) export const deploymentSlice = createSlice({ name: "deployment", @@ -228,5 +244,10 @@ export const deploymentSlice = createSlice({ .addCase(fetchUserReview.fulfilled, (state, action) => { state.userReview = action.payload }) + .addCase(handleDeploymentStatusEvent.fulfilled, (state, action) => { + if (action.payload.id === state.deployment?.id) { + state.deployment = action.payload + } + }) } }) \ No newline at end of file diff --git a/ui/src/redux/main.ts b/ui/src/redux/main.ts index 3022cc3f..13dd880b 100644 --- a/ui/src/redux/main.ts +++ b/ui/src/redux/main.ts @@ -11,11 +11,13 @@ import { HttpPaymentRequiredError, License, ReviewStatusEnum, + DeploymentStatus, } from "../models" import { getMe, searchDeployments as _searchDeployments, searchReviews as _searchReviews, + getDeployment, getLicense } from "../apis" import { getShortRef } from "../libs" @@ -157,6 +159,27 @@ export const notifyDeploymentEvent = createAsyncThunk( + "main/notifyDeploymentStatusEvent", + async (deploymentStatus, {rejectWithValue}) => { + if (deploymentStatus.edges === undefined) { + return rejectWithValue(new Error("Edges is not included.")) + } + + const { repo, deployment } = deploymentStatus.edges + if (repo === undefined || deployment === undefined) { + return rejectWithValue(new Error("Repo or Deployment is not included in the edges.")) + } + + notify(`${repo.namespace}/${repo.name} #${deployment.number}`, { + icon: "/logo192.png", + body: `${deploymentStatus.status} - ${deploymentStatus.description}`, + tag: String(deployment.id), + + }) + } +) + /** * The browser notifies the requester when the review is responded to, * but it should notify the reviewer when the review is requested. @@ -183,6 +206,22 @@ export const notifyReviewmentEvent = createAsyncThunk( + "main/handleDeploymentStatusEvent", + async (deploymentStatus, { rejectWithValue }) => { + if (deploymentStatus.edges === undefined) { + return rejectWithValue(new Error("Edges is not included.")) + } + + const { repo, deployment } = deploymentStatus.edges + if (repo === undefined || deployment === undefined) { + return rejectWithValue(new Error("Repo or Deployment is not included in the edges.")) + } + + return await getDeployment(repo.namespace, repo.name, deployment.number) + } +) + export const mainSlice = createSlice({ name: "main", initialState, @@ -240,5 +279,21 @@ export const mainSlice = createSlice({ .addCase(fetchLicense.fulfilled, (state, action) => { state.license = action.payload }) + + .addCase(handleDeploymentStatusEvent.fulfilled, (state, { payload: deployment }) => { + if (deployment.status === DeploymentStatusEnum.Created) { + state.deployments.unshift(deployment) + return + } + + state.deployments = state.deployments.map((item) => { + return (item.id === deployment.id)? deployment : item + }) + + state.deployments = state.deployments.filter((item) => { + return !(item.status === DeploymentStatusEnum.Success + || item.status === DeploymentStatusEnum.Failure) + }) + }) } }) \ No newline at end of file diff --git a/ui/src/views/deployment/index.tsx b/ui/src/views/deployment/index.tsx index 1ae3f935..58218a51 100644 --- a/ui/src/views/deployment/index.tsx +++ b/ui/src/views/deployment/index.tsx @@ -14,6 +14,7 @@ import { fetchUserReview, approve, reject, + handleDeploymentStatusEvent } from "../../redux/deployment" import { Deployment, @@ -24,6 +25,7 @@ import { } from "../../models" import { subscribeDeploymentEvents, + subscribeDeploymentStatusEvents, subscribeReviewEvents } from "../../apis" @@ -68,12 +70,17 @@ export default (): JSX.Element => { dispatch(slice.actions.handleDeploymentEvent(deployment)) }) + const deploymentStatusEvent = subscribeDeploymentStatusEvents((deploymentStatus) => { + dispatch(handleDeploymentStatusEvent(deploymentStatus)) + }) + const reviewEvent = subscribeReviewEvents((review) => { dispatch(slice.actions.handleReviewEvent(review)) }) return () => { deploymentEvent.close() + deploymentStatusEvent.close() reviewEvent.close() } // eslint-disable-next-line diff --git a/ui/src/views/main/index.tsx b/ui/src/views/main/index.tsx index b1716eba..a34f98f4 100644 --- a/ui/src/views/main/index.tsx +++ b/ui/src/views/main/index.tsx @@ -5,14 +5,20 @@ import { Helmet } from "react-helmet" import moment from "moment" import { useAppSelector, useAppDispatch } from "../../redux/hooks" -import { subscribeDeploymentEvents, subscribeReviewEvents } from "../../apis" +import { + subscribeDeploymentEvents, + subscribeDeploymentStatusEvents, + subscribeReviewEvents +} from "../../apis" import { init, searchDeployments, searchReviews, fetchLicense, notifyDeploymentEvent, + notifyDeploymentStatusEvent, notifyReviewmentEvent, + handleDeploymentStatusEvent, mainSlice as slice } from "../../redux/main" @@ -45,6 +51,11 @@ export default (props: React.PropsWithChildren): JSX.Element => { dispatch(notifyDeploymentEvent(deployment)) }) + const deploymentStatusEvents = subscribeDeploymentStatusEvents((deploymentStatus) => { + dispatch(handleDeploymentStatusEvent(deploymentStatus)) + dispatch(notifyDeploymentStatusEvent(deploymentStatus)) + }) + const reviewEvents = subscribeReviewEvents((review) => { dispatch(slice.actions.handleReviewEvent(review)) dispatch(notifyReviewmentEvent(review)) @@ -52,6 +63,7 @@ export default (props: React.PropsWithChildren): JSX.Element => { return () => { deploymentEvents.close() + deploymentStatusEvents.close() reviewEvents.close() } }, [dispatch]) From 61b1763dfbc8ca54ffdc40391e9b48f82db38c36 Mon Sep 17 00:00:00 2001 From: noah Date: Sat, 23 Apr 2022 20:17:37 +0900 Subject: [PATCH 8/9] Fix unit tests --- internal/interactor/deployment_test.go | 20 ++++++++++++++++---- internal/pkg/store/event_test.go | 14 +++++--------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/internal/interactor/deployment_test.go b/internal/interactor/deployment_test.go index 1bd1af32..49dc03eb 100644 --- a/internal/interactor/deployment_test.go +++ b/internal/interactor/deployment_test.go @@ -52,12 +52,13 @@ func TestInteractor_Deploy(t *testing.T) { store. EXPECT(). - CreateEvent(gomock.Any(), gomock.AssignableToTypeOf(&ent.Event{})). - Return(&ent.Event{}, nil) + CreateEntDeploymentStatus(ctx, gomock.AssignableToTypeOf(&ent.DeploymentStatus{})). + Return(&ent.DeploymentStatus{}, nil) store. EXPECT(). - CreateEntDeploymentStatus(ctx, gomock.AssignableToTypeOf(&ent.DeploymentStatus{})) + CreateEvent(gomock.Any(), gomock.AssignableToTypeOf(&ent.Event{})). + Return(&ent.Event{}, nil) it := i.NewInteractor(&i.InteractorConfig{ Store: store, @@ -99,6 +100,11 @@ func TestInteractor_Deploy(t *testing.T) { return d, nil }) + store. + EXPECT(). + CreateEntDeploymentStatus(ctx, gomock.AssignableToTypeOf(&ent.DeploymentStatus{})). + Return(&ent.DeploymentStatus{}, nil) + store. EXPECT(). CreateEvent(gomock.Any(), gomock.AssignableToTypeOf(&ent.Event{})). @@ -160,7 +166,13 @@ func TestInteractor_DeployToRemote(t *testing.T) { store. EXPECT(). - CreateEntDeploymentStatus(ctx, gomock.AssignableToTypeOf(&ent.DeploymentStatus{})) + CreateEntDeploymentStatus(ctx, gomock.AssignableToTypeOf(&ent.DeploymentStatus{})). + Return(&ent.DeploymentStatus{}, nil) + + store. + EXPECT(). + CreateEvent(gomock.Any(), gomock.AssignableToTypeOf(&ent.Event{})). + Return(&ent.Event{}, nil) it := i.NewInteractor(&i.InteractorConfig{ Store: store, diff --git a/internal/pkg/store/event_test.go b/internal/pkg/store/event_test.go index c7793ae2..681e3a2e 100644 --- a/internal/pkg/store/event_test.go +++ b/internal/pkg/store/event_test.go @@ -12,7 +12,7 @@ import ( func TestStore_CreateEvent(t *testing.T) { - t.Run("Create a new deleted event", func(t *testing.T) { + t.Run("Create a new deployment_status event", func(t *testing.T) { ctx := context.Background() client := enttest.Open(t, "sqlite3", "file:ent?mode=memory&cache=shared&_fk=1", @@ -22,17 +22,13 @@ func TestStore_CreateEvent(t *testing.T) { s := NewStore(client) - e, err := s.CreateEvent(ctx, &ent.Event{ - Kind: event.KindReview, - Type: event.TypeDeleted, - DeletedID: 1, + _, err := s.CreateEvent(ctx, &ent.Event{ + Kind: event.KindDeploymentStatus, + Type: event.TypeCreated, + DeploymentStatusID: 1, }) if err != nil { t.Fatalf("CreateEvent returns an error: %s", err) } - - if e.DeletedID != 1 { - t.Fatalf("event.DeletedID = %v, wanted %v", e.DeletedID, 1) - } }) } From a74b28a8e07c20e51a640ea1fe6102c0bae59bae Mon Sep 17 00:00:00 2001 From: noah Date: Sat, 23 Apr 2022 20:43:34 +0900 Subject: [PATCH 9/9] Deprecate the deployment event --- internal/pkg/store/event.go | 6 - internal/server/api/v1/stream/events.go | 17 -- model/ent/client.go | 32 ---- model/ent/deployment.go | 18 +- model/ent/deployment/deployment.go | 9 - model/ent/deployment/where.go | 28 --- model/ent/deployment_create.go | 35 ---- model/ent/deployment_query.go | 64 +------ model/ent/deployment_update.go | 181 -------------------- model/ent/event.go | 42 +---- model/ent/event/event.go | 15 +- model/ent/event/where.go | 97 ----------- model/ent/event_create.go | 40 ----- model/ent/event_query.go | 65 +------ model/ent/event_update.go | 133 --------------- model/ent/migrate/schema.go | 18 +- model/ent/mutation.go | 215 +----------------------- model/ent/schema/deployment.go | 4 - model/ent/schema/event.go | 7 - openapi/v1.yaml | 2 - ui/src/apis/events.ts | 19 +-- ui/src/apis/index.ts | 1 - ui/src/redux/deployment.tsx | 5 - ui/src/redux/main.ts | 42 ----- ui/src/views/deployment/index.tsx | 6 - ui/src/views/main/index.tsx | 8 - 26 files changed, 23 insertions(+), 1086 deletions(-) diff --git a/internal/pkg/store/event.go b/internal/pkg/store/event.go index 1221ad5d..6c56ac1f 100644 --- a/internal/pkg/store/event.go +++ b/internal/pkg/store/event.go @@ -22,12 +22,6 @@ func (s *Store) ListEventsGreaterThanTime(ctx context.Context, t time.Time) ([]* Where( event.CreatedAtGT(t), ). - WithDeployment(func(dq *ent.DeploymentQuery) { - dq. - WithUser(). - WithRepo(). - WithDeploymentStatuses() - }). WithDeploymentStatus(func(dsq *ent.DeploymentStatusQuery) { dsq. WithDeployment(). diff --git a/internal/server/api/v1/stream/events.go b/internal/server/api/v1/stream/events.go index fc9b0705..480a4592 100644 --- a/internal/server/api/v1/stream/events.go +++ b/internal/server/api/v1/stream/events.go @@ -31,23 +31,6 @@ func (s *Stream) GetEvents(c *gin.Context) { // it'll unsubscribe after the connection is closed. sub := func(e *ent.Event) { switch e.Kind { - case event.KindDeployment: - d, err := s.i.FindDeploymentByID(ctx, e.DeploymentID) - if err != nil { - s.log.Error("Failed to find the deployment.", zap.Error(err)) - return - } - - if _, err := s.i.FindPermOfRepo(ctx, d.Edges.Repo, u); err != nil { - s.log.Debug("Skip the event. The permission is denied.", zap.Error(err)) - return - } - - s.log.Debug("Dispatch a deployment event.", zap.Int("id", d.ID)) - events <- &sse.Event{ - Event: "deployment", - Data: d, - } case event.KindDeploymentStatus: ds, err := s.i.FindDeploymentStatusByID(ctx, e.DeploymentStatusID) if err != nil { diff --git a/model/ent/client.go b/model/ent/client.go index 30a20473..652967d5 100644 --- a/model/ent/client.go +++ b/model/ent/client.go @@ -448,22 +448,6 @@ func (c *DeploymentClient) QueryDeploymentStatuses(d *Deployment) *DeploymentSta return query } -// QueryEvent queries the event edge of a Deployment. -func (c *DeploymentClient) QueryEvent(d *Deployment) *EventQuery { - query := &EventQuery{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(event.Table, event.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, deployment.EventTable, deployment.EventColumn), - ) - fromV = sqlgraph.Neighbors(d.driver.Dialect(), step) - return fromV, nil - } - return query -} - // Hooks returns the client hooks. func (c *DeploymentClient) Hooks() []Hook { return c.hooks.Deployment @@ -798,22 +782,6 @@ func (c *EventClient) GetX(ctx context.Context, id int) *Event { return obj } -// QueryDeployment queries the deployment edge of a Event. -func (c *EventClient) QueryDeployment(e *Event) *DeploymentQuery { - query := &DeploymentQuery{config: c.config} - query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) { - id := e.ID - step := sqlgraph.NewStep( - sqlgraph.From(event.Table, event.FieldID, id), - sqlgraph.To(deployment.Table, deployment.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, event.DeploymentTable, event.DeploymentColumn), - ) - fromV = sqlgraph.Neighbors(e.driver.Dialect(), step) - return fromV, nil - } - return query -} - // QueryDeploymentStatus queries the deployment_status edge of a Event. func (c *EventClient) QueryDeploymentStatus(e *Event) *DeploymentStatusQuery { query := &DeploymentStatusQuery{config: c.config} diff --git a/model/ent/deployment.go b/model/ent/deployment.go index 13fed970..103c0650 100644 --- a/model/ent/deployment.go +++ b/model/ent/deployment.go @@ -68,11 +68,9 @@ type DeploymentEdges struct { Reviews []*Review `json:"reviews,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 [4]bool } // UserOrErr returns the User value or an error if the edge @@ -121,15 +119,6 @@ func (e DeploymentEdges) DeploymentStatusesOrErr() ([]*DeploymentStatus, error) return nil, &NotLoadedError{edge: "deployment_statuses"} } -// 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] { - return e.Event, nil - } - return nil, &NotLoadedError{edge: "event"} -} - // scanValues returns the types for scanning values from sql.Rows. func (*Deployment) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) @@ -297,11 +286,6 @@ func (d *Deployment) QueryDeploymentStatuses() *DeploymentStatusQuery { return (&DeploymentClient{config: d.config}).QueryDeploymentStatuses(d) } -// QueryEvent queries the "event" edge of the Deployment entity. -func (d *Deployment) QueryEvent() *EventQuery { - return (&DeploymentClient{config: d.config}).QueryEvent(d) -} - // Update returns a builder for updating this Deployment. // Note that you need to call Deployment.Unwrap() before calling this method if this Deployment // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/model/ent/deployment/deployment.go b/model/ent/deployment/deployment.go index 340f4cff..4ca6f8d7 100644 --- a/model/ent/deployment/deployment.go +++ b/model/ent/deployment/deployment.go @@ -54,8 +54,6 @@ const ( EdgeReviews = "reviews" // 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. - EdgeEvent = "event" // Table holds the table name of the deployment in the database. Table = "deployments" // UserTable is the table that holds the user relation/edge. @@ -86,13 +84,6 @@ const ( DeploymentStatusesInverseTable = "deployment_status" // DeploymentStatusesColumn is the table column denoting the deployment_statuses relation/edge. DeploymentStatusesColumn = "deployment_id" - // EventTable is the table that holds the event relation/edge. - EventTable = "events" - // EventInverseTable is the table name for the Event entity. - // It exists in this package in order to avoid circular dependency with the "event" package. - EventInverseTable = "events" - // EventColumn is the table column denoting the event relation/edge. - EventColumn = "deployment_id" ) // Columns holds all SQL columns for deployment fields. diff --git a/model/ent/deployment/where.go b/model/ent/deployment/where.go index 3e70d11e..aca3c43c 100644 --- a/model/ent/deployment/where.go +++ b/model/ent/deployment/where.go @@ -1445,34 +1445,6 @@ func HasDeploymentStatusesWith(preds ...predicate.DeploymentStatus) predicate.De }) } -// HasEvent applies the HasEdge predicate on the "event" edge. -func HasEvent() predicate.Deployment { - return predicate.Deployment(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(EventTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, EventTable, EventColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasEventWith applies the HasEdge predicate on the "event" edge with a given conditions (other predicates). -func HasEventWith(preds ...predicate.Event) predicate.Deployment { - return predicate.Deployment(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(EventInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, EventTable, EventColumn), - ) - 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.Deployment) predicate.Deployment { return predicate.Deployment(func(s *sql.Selector) { diff --git a/model/ent/deployment_create.go b/model/ent/deployment_create.go index fc56cc68..0089cf77 100644 --- a/model/ent/deployment_create.go +++ b/model/ent/deployment_create.go @@ -12,7 +12,6 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" - "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/repo" "github.com/gitploy-io/gitploy/model/ent/review" "github.com/gitploy-io/gitploy/model/ent/user" @@ -255,21 +254,6 @@ func (dc *DeploymentCreate) AddDeploymentStatuses(d ...*DeploymentStatus) *Deplo return dc.AddDeploymentStatusIDs(ids...) } -// AddEventIDs adds the "event" edge to the Event entity by IDs. -func (dc *DeploymentCreate) AddEventIDs(ids ...int) *DeploymentCreate { - dc.mutation.AddEventIDs(ids...) - return dc -} - -// AddEvent adds the "event" edges to the Event entity. -func (dc *DeploymentCreate) AddEvent(e ...*Event) *DeploymentCreate { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return dc.AddEventIDs(ids...) -} - // Mutation returns the DeploymentMutation object of the builder. func (dc *DeploymentCreate) Mutation() *DeploymentMutation { return dc.mutation @@ -648,25 +632,6 @@ func (dc *DeploymentCreate) createSpec() (*Deployment, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } - if nodes := dc.mutation.EventIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: deployment.EventTable, - Columns: []string{deployment.EventColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: event.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } return _node, _spec } diff --git a/model/ent/deployment_query.go b/model/ent/deployment_query.go index 31b9d33d..67fc9ca6 100644 --- a/model/ent/deployment_query.go +++ b/model/ent/deployment_query.go @@ -15,7 +15,6 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" - "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/predicate" "github.com/gitploy-io/gitploy/model/ent/repo" "github.com/gitploy-io/gitploy/model/ent/review" @@ -36,7 +35,6 @@ type DeploymentQuery struct { withRepo *RepoQuery withReviews *ReviewQuery withDeploymentStatuses *DeploymentStatusQuery - withEvent *EventQuery modifiers []func(s *sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -162,28 +160,6 @@ func (dq *DeploymentQuery) QueryDeploymentStatuses() *DeploymentStatusQuery { return query } -// QueryEvent chains the current query on the "event" edge. -func (dq *DeploymentQuery) QueryEvent() *EventQuery { - query := &EventQuery{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(event.Table, event.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, deployment.EventTable, deployment.EventColumn), - ) - fromU = sqlgraph.SetNeighbors(dq.driver.Dialect(), step) - return fromU, nil - } - return query -} - // First returns the first Deployment entity from the query. // Returns a *NotFoundError when no Deployment was found. func (dq *DeploymentQuery) First(ctx context.Context) (*Deployment, error) { @@ -369,7 +345,6 @@ func (dq *DeploymentQuery) Clone() *DeploymentQuery { withRepo: dq.withRepo.Clone(), withReviews: dq.withReviews.Clone(), withDeploymentStatuses: dq.withDeploymentStatuses.Clone(), - withEvent: dq.withEvent.Clone(), // clone intermediate query. sql: dq.sql.Clone(), path: dq.path, @@ -421,17 +396,6 @@ func (dq *DeploymentQuery) WithDeploymentStatuses(opts ...func(*DeploymentStatus return dq } -// WithEvent tells the query-builder to eager-load the nodes that are connected to -// the "event" edge. The optional arguments are used to configure the query builder of the edge. -func (dq *DeploymentQuery) WithEvent(opts ...func(*EventQuery)) *DeploymentQuery { - query := &EventQuery{config: dq.config} - for _, opt := range opts { - opt(query) - } - dq.withEvent = query - return dq -} - // 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. // @@ -497,12 +461,11 @@ func (dq *DeploymentQuery) sqlAll(ctx context.Context) ([]*Deployment, error) { var ( nodes = []*Deployment{} _spec = dq.querySpec() - loadedTypes = [5]bool{ + loadedTypes = [4]bool{ dq.withUser != nil, dq.withRepo != nil, dq.withReviews != nil, dq.withDeploymentStatuses != nil, - dq.withEvent != nil, } ) _spec.ScanValues = func(columns []string) ([]interface{}, error) { @@ -630,31 +593,6 @@ func (dq *DeploymentQuery) sqlAll(ctx context.Context) ([]*Deployment, error) { } } - if query := dq.withEvent; 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.Event = []*Event{} - } - query.Where(predicate.Event(func(s *sql.Selector) { - s.Where(sql.InValues(deployment.EventColumn, 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.Event = append(node.Edges.Event, n) - } - } - return nodes, nil } diff --git a/model/ent/deployment_update.go b/model/ent/deployment_update.go index 2b11c847..1bb7fcfc 100644 --- a/model/ent/deployment_update.go +++ b/model/ent/deployment_update.go @@ -13,7 +13,6 @@ import ( "entgo.io/ent/schema/field" "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" - "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/predicate" "github.com/gitploy-io/gitploy/model/ent/repo" "github.com/gitploy-io/gitploy/model/ent/review" @@ -312,21 +311,6 @@ func (du *DeploymentUpdate) AddDeploymentStatuses(d ...*DeploymentStatus) *Deplo return du.AddDeploymentStatusIDs(ids...) } -// AddEventIDs adds the "event" edge to the Event entity by IDs. -func (du *DeploymentUpdate) AddEventIDs(ids ...int) *DeploymentUpdate { - du.mutation.AddEventIDs(ids...) - return du -} - -// AddEvent adds the "event" edges to the Event entity. -func (du *DeploymentUpdate) AddEvent(e ...*Event) *DeploymentUpdate { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return du.AddEventIDs(ids...) -} - // Mutation returns the DeploymentMutation object of the builder. func (du *DeploymentUpdate) Mutation() *DeploymentMutation { return du.mutation @@ -386,27 +370,6 @@ func (du *DeploymentUpdate) RemoveDeploymentStatuses(d ...*DeploymentStatus) *De return du.RemoveDeploymentStatusIDs(ids...) } -// ClearEvent clears all "event" edges to the Event entity. -func (du *DeploymentUpdate) ClearEvent() *DeploymentUpdate { - du.mutation.ClearEvent() - return du -} - -// RemoveEventIDs removes the "event" edge to Event entities by IDs. -func (du *DeploymentUpdate) RemoveEventIDs(ids ...int) *DeploymentUpdate { - du.mutation.RemoveEventIDs(ids...) - return du -} - -// RemoveEvent removes "event" edges to Event entities. -func (du *DeploymentUpdate) RemoveEvent(e ...*Event) *DeploymentUpdate { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return du.RemoveEventIDs(ids...) -} - // Save executes the query and returns the number of nodes affected by the update operation. func (du *DeploymentUpdate) Save(ctx context.Context) (int, error) { var ( @@ -860,60 +823,6 @@ func (du *DeploymentUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if du.mutation.EventCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: deployment.EventTable, - Columns: []string{deployment.EventColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: event.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := du.mutation.RemovedEventIDs(); len(nodes) > 0 && !du.mutation.EventCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: deployment.EventTable, - Columns: []string{deployment.EventColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: event.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.EventIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: deployment.EventTable, - Columns: []string{deployment.EventColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: event.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, du.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{deployment.Label} @@ -1212,21 +1121,6 @@ func (duo *DeploymentUpdateOne) AddDeploymentStatuses(d ...*DeploymentStatus) *D return duo.AddDeploymentStatusIDs(ids...) } -// AddEventIDs adds the "event" edge to the Event entity by IDs. -func (duo *DeploymentUpdateOne) AddEventIDs(ids ...int) *DeploymentUpdateOne { - duo.mutation.AddEventIDs(ids...) - return duo -} - -// AddEvent adds the "event" edges to the Event entity. -func (duo *DeploymentUpdateOne) AddEvent(e ...*Event) *DeploymentUpdateOne { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return duo.AddEventIDs(ids...) -} - // Mutation returns the DeploymentMutation object of the builder. func (duo *DeploymentUpdateOne) Mutation() *DeploymentMutation { return duo.mutation @@ -1286,27 +1180,6 @@ func (duo *DeploymentUpdateOne) RemoveDeploymentStatuses(d ...*DeploymentStatus) return duo.RemoveDeploymentStatusIDs(ids...) } -// ClearEvent clears all "event" edges to the Event entity. -func (duo *DeploymentUpdateOne) ClearEvent() *DeploymentUpdateOne { - duo.mutation.ClearEvent() - return duo -} - -// RemoveEventIDs removes the "event" edge to Event entities by IDs. -func (duo *DeploymentUpdateOne) RemoveEventIDs(ids ...int) *DeploymentUpdateOne { - duo.mutation.RemoveEventIDs(ids...) - return duo -} - -// RemoveEvent removes "event" edges to Event entities. -func (duo *DeploymentUpdateOne) RemoveEvent(e ...*Event) *DeploymentUpdateOne { - ids := make([]int, len(e)) - for i := range e { - ids[i] = e[i].ID - } - return duo.RemoveEventIDs(ids...) -} - // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. func (duo *DeploymentUpdateOne) Select(field string, fields ...string) *DeploymentUpdateOne { @@ -1784,60 +1657,6 @@ func (duo *DeploymentUpdateOne) sqlSave(ctx context.Context) (_node *Deployment, } _spec.Edges.Add = append(_spec.Edges.Add, edge) } - if duo.mutation.EventCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: deployment.EventTable, - Columns: []string{deployment.EventColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: event.FieldID, - }, - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := duo.mutation.RemovedEventIDs(); len(nodes) > 0 && !duo.mutation.EventCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: deployment.EventTable, - Columns: []string{deployment.EventColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: event.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.EventIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: deployment.EventTable, - Columns: []string{deployment.EventColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: &sqlgraph.FieldSpec{ - Type: field.TypeInt, - Column: event.FieldID, - }, - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } _node = &Deployment{config: duo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/model/ent/event.go b/model/ent/event.go index 2810aa81..36a1d445 100644 --- a/model/ent/event.go +++ b/model/ent/event.go @@ -8,7 +8,6 @@ import ( "time" "entgo.io/ent/dialect/sql" - "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/notificationrecord" @@ -26,8 +25,6 @@ type Event struct { Type event.Type `json:"type"` // CreatedAt holds the value of the "created_at" field. CreatedAt time.Time `json:"created_at"` - // DeploymentID holds the value of the "deployment_id" field. - DeploymentID int `json:"deployment_id,omitemtpy"` // DeploymentStatusID holds the value of the "deployment_status_id" field. DeploymentStatusID int `json:"deployment_status_id,omitemtpy"` // ReviewID holds the value of the "review_id" field. @@ -41,8 +38,6 @@ type Event struct { // EventEdges holds the relations/edges for other nodes in the graph. type EventEdges struct { - // Deployment holds the value of the deployment edge. - Deployment *Deployment `json:"deployment,omitempty"` // DeploymentStatus holds the value of the deployment_status edge. DeploymentStatus *DeploymentStatus `json:"deployment_status,omitempty"` // Review holds the value of the review edge. @@ -51,27 +46,13 @@ type EventEdges struct { NotificationRecord *NotificationRecord `json:"notification_record,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [4]bool -} - -// 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 EventEdges) DeploymentOrErr() (*Deployment, error) { - if e.loadedTypes[0] { - 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"} + loadedTypes [3]bool } // DeploymentStatusOrErr returns the DeploymentStatus value or an error if the edge // was not loaded in eager-loading, or loaded but was not found. func (e EventEdges) DeploymentStatusOrErr() (*DeploymentStatus, error) { - if e.loadedTypes[1] { + if e.loadedTypes[0] { if e.DeploymentStatus == nil { // The edge deployment_status was loaded in eager-loading, // but was not found. @@ -85,7 +66,7 @@ func (e EventEdges) DeploymentStatusOrErr() (*DeploymentStatus, error) { // ReviewOrErr returns the Review value or an error if the edge // was not loaded in eager-loading, or loaded but was not found. func (e EventEdges) ReviewOrErr() (*Review, error) { - if e.loadedTypes[2] { + if e.loadedTypes[1] { if e.Review == nil { // The edge review was loaded in eager-loading, // but was not found. @@ -99,7 +80,7 @@ func (e EventEdges) ReviewOrErr() (*Review, error) { // NotificationRecordOrErr returns the NotificationRecord value or an error if the edge // was not loaded in eager-loading, or loaded but was not found. func (e EventEdges) NotificationRecordOrErr() (*NotificationRecord, error) { - if e.loadedTypes[3] { + if e.loadedTypes[2] { if e.NotificationRecord == nil { // The edge notification_record was loaded in eager-loading, // but was not found. @@ -115,7 +96,7 @@ func (*Event) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) for i := range columns { switch columns[i] { - case event.FieldID, event.FieldDeploymentID, event.FieldDeploymentStatusID, event.FieldReviewID, event.FieldDeletedID: + case event.FieldID, event.FieldDeploymentStatusID, event.FieldReviewID, event.FieldDeletedID: values[i] = new(sql.NullInt64) case event.FieldKind, event.FieldType: values[i] = new(sql.NullString) @@ -160,12 +141,6 @@ func (e *Event) assignValues(columns []string, values []interface{}) error { } else if value.Valid { e.CreatedAt = value.Time } - case event.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 { - e.DeploymentID = int(value.Int64) - } case event.FieldDeploymentStatusID: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field deployment_status_id", values[i]) @@ -189,11 +164,6 @@ func (e *Event) assignValues(columns []string, values []interface{}) error { return nil } -// QueryDeployment queries the "deployment" edge of the Event entity. -func (e *Event) QueryDeployment() *DeploymentQuery { - return (&EventClient{config: e.config}).QueryDeployment(e) -} - // QueryDeploymentStatus queries the "deployment_status" edge of the Event entity. func (e *Event) QueryDeploymentStatus() *DeploymentStatusQuery { return (&EventClient{config: e.config}).QueryDeploymentStatus(e) @@ -238,8 +208,6 @@ func (e *Event) String() string { builder.WriteString(fmt.Sprintf("%v", e.Type)) builder.WriteString(", created_at=") builder.WriteString(e.CreatedAt.Format(time.ANSIC)) - builder.WriteString(", deployment_id=") - builder.WriteString(fmt.Sprintf("%v", e.DeploymentID)) builder.WriteString(", deployment_status_id=") builder.WriteString(fmt.Sprintf("%v", e.DeploymentStatusID)) builder.WriteString(", review_id=") diff --git a/model/ent/event/event.go b/model/ent/event/event.go index c71c7fb8..81ffd3b2 100644 --- a/model/ent/event/event.go +++ b/model/ent/event/event.go @@ -18,16 +18,12 @@ const ( FieldType = "type" // FieldCreatedAt holds the string denoting the created_at field in the database. FieldCreatedAt = "created_at" - // FieldDeploymentID holds the string denoting the deployment_id field in the database. - FieldDeploymentID = "deployment_id" // FieldDeploymentStatusID holds the string denoting the deployment_status_id field in the database. FieldDeploymentStatusID = "deployment_status_id" // FieldReviewID holds the string denoting the review_id field in the database. FieldReviewID = "review_id" // FieldDeletedID holds the string denoting the deleted_id field in the database. FieldDeletedID = "deleted_id" - // EdgeDeployment holds the string denoting the deployment edge name in mutations. - EdgeDeployment = "deployment" // EdgeDeploymentStatus holds the string denoting the deployment_status edge name in mutations. EdgeDeploymentStatus = "deployment_status" // EdgeReview holds the string denoting the review edge name in mutations. @@ -36,13 +32,6 @@ const ( EdgeNotificationRecord = "notification_record" // Table holds the table name of the event in the database. Table = "events" - // DeploymentTable is the table that holds the deployment relation/edge. - DeploymentTable = "events" - // 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" // DeploymentStatusTable is the table that holds the deployment_status relation/edge. DeploymentStatusTable = "events" // DeploymentStatusInverseTable is the table name for the DeploymentStatus entity. @@ -72,7 +61,6 @@ var Columns = []string{ FieldKind, FieldType, FieldCreatedAt, - FieldDeploymentID, FieldDeploymentStatusID, FieldReviewID, FieldDeletedID, @@ -98,7 +86,6 @@ type Kind string // Kind values. const ( - KindDeployment Kind = "deployment" KindDeploymentStatus Kind = "deployment_status" KindReview Kind = "review" ) @@ -110,7 +97,7 @@ func (k Kind) String() string { // KindValidator is a validator for the "kind" field enum values. It is called by the builders before save. func KindValidator(k Kind) error { switch k { - case KindDeployment, KindDeploymentStatus, KindReview: + case KindDeploymentStatus, KindReview: return nil default: return fmt.Errorf("event: invalid enum value for kind field: %q", k) diff --git a/model/ent/event/where.go b/model/ent/event/where.go index c27012ac..e6329234 100644 --- a/model/ent/event/where.go +++ b/model/ent/event/where.go @@ -100,13 +100,6 @@ func CreatedAt(v time.Time) predicate.Event { }) } -// DeploymentID applies equality check predicate on the "deployment_id" field. It's identical to DeploymentIDEQ. -func DeploymentID(v int) predicate.Event { - return predicate.Event(func(s *sql.Selector) { - s.Where(sql.EQ(s.C(FieldDeploymentID), v)) - }) -} - // DeploymentStatusID applies equality check predicate on the "deployment_status_id" field. It's identical to DeploymentStatusIDEQ. func DeploymentStatusID(v int) predicate.Event { return predicate.Event(func(s *sql.Selector) { @@ -300,68 +293,6 @@ func CreatedAtLTE(v time.Time) predicate.Event { }) } -// DeploymentIDEQ applies the EQ predicate on the "deployment_id" field. -func DeploymentIDEQ(v int) predicate.Event { - return predicate.Event(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.Event { - return predicate.Event(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.Event { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Event(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.Event { - v := make([]interface{}, len(vs)) - for i := range v { - v[i] = vs[i] - } - return predicate.Event(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...)) - }) -} - -// DeploymentIDIsNil applies the IsNil predicate on the "deployment_id" field. -func DeploymentIDIsNil() predicate.Event { - return predicate.Event(func(s *sql.Selector) { - s.Where(sql.IsNull(s.C(FieldDeploymentID))) - }) -} - -// DeploymentIDNotNil applies the NotNil predicate on the "deployment_id" field. -func DeploymentIDNotNil() predicate.Event { - return predicate.Event(func(s *sql.Selector) { - s.Where(sql.NotNull(s.C(FieldDeploymentID))) - }) -} - // DeploymentStatusIDEQ applies the EQ predicate on the "deployment_status_id" field. func DeploymentStatusIDEQ(v int) predicate.Event { return predicate.Event(func(s *sql.Selector) { @@ -576,34 +507,6 @@ func DeletedIDNotNil() predicate.Event { }) } -// HasDeployment applies the HasEdge predicate on the "deployment" edge. -func HasDeployment() predicate.Event { - return predicate.Event(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.Event { - return predicate.Event(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) - } - }) - }) -} - // HasDeploymentStatus applies the HasEdge predicate on the "deployment_status" edge. func HasDeploymentStatus() predicate.Event { return predicate.Event(func(s *sql.Selector) { diff --git a/model/ent/event_create.go b/model/ent/event_create.go index 55ae8cdd..f6eb2ba5 100644 --- a/model/ent/event_create.go +++ b/model/ent/event_create.go @@ -10,7 +10,6 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/notificationrecord" @@ -50,20 +49,6 @@ func (ec *EventCreate) SetNillableCreatedAt(t *time.Time) *EventCreate { return ec } -// SetDeploymentID sets the "deployment_id" field. -func (ec *EventCreate) SetDeploymentID(i int) *EventCreate { - ec.mutation.SetDeploymentID(i) - return ec -} - -// SetNillableDeploymentID sets the "deployment_id" field if the given value is not nil. -func (ec *EventCreate) SetNillableDeploymentID(i *int) *EventCreate { - if i != nil { - ec.SetDeploymentID(*i) - } - return ec -} - // SetDeploymentStatusID sets the "deployment_status_id" field. func (ec *EventCreate) SetDeploymentStatusID(i int) *EventCreate { ec.mutation.SetDeploymentStatusID(i) @@ -106,11 +91,6 @@ func (ec *EventCreate) SetNillableDeletedID(i *int) *EventCreate { return ec } -// SetDeployment sets the "deployment" edge to the Deployment entity. -func (ec *EventCreate) SetDeployment(d *Deployment) *EventCreate { - return ec.SetDeploymentID(d.ID) -} - // SetDeploymentStatus sets the "deployment_status" edge to the DeploymentStatus entity. func (ec *EventCreate) SetDeploymentStatus(d *DeploymentStatus) *EventCreate { return ec.SetDeploymentStatusID(d.ID) @@ -297,26 +277,6 @@ func (ec *EventCreate) createSpec() (*Event, *sqlgraph.CreateSpec) { }) _node.DeletedID = value } - if nodes := ec.mutation.DeploymentIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: event.DeploymentTable, - Columns: []string{event.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) - } if nodes := ec.mutation.DeploymentStatusIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, diff --git a/model/ent/event_query.go b/model/ent/event_query.go index d9e257fc..02730c96 100644 --- a/model/ent/event_query.go +++ b/model/ent/event_query.go @@ -13,7 +13,6 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/notificationrecord" @@ -31,7 +30,6 @@ type EventQuery struct { fields []string predicates []predicate.Event // eager-loading edges. - withDeployment *DeploymentQuery withDeploymentStatus *DeploymentStatusQuery withReview *ReviewQuery withNotificationRecord *NotificationRecordQuery @@ -72,28 +70,6 @@ func (eq *EventQuery) Order(o ...OrderFunc) *EventQuery { return eq } -// QueryDeployment chains the current query on the "deployment" edge. -func (eq *EventQuery) QueryDeployment() *DeploymentQuery { - query := &DeploymentQuery{config: eq.config} - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := eq.prepareQuery(ctx); err != nil { - return nil, err - } - selector := eq.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(event.Table, event.FieldID, selector), - sqlgraph.To(deployment.Table, deployment.FieldID), - sqlgraph.Edge(sqlgraph.M2O, true, event.DeploymentTable, event.DeploymentColumn), - ) - fromU = sqlgraph.SetNeighbors(eq.driver.Dialect(), step) - return fromU, nil - } - return query -} - // QueryDeploymentStatus chains the current query on the "deployment_status" edge. func (eq *EventQuery) QueryDeploymentStatus() *DeploymentStatusQuery { query := &DeploymentStatusQuery{config: eq.config} @@ -341,7 +317,6 @@ func (eq *EventQuery) Clone() *EventQuery { offset: eq.offset, order: append([]OrderFunc{}, eq.order...), predicates: append([]predicate.Event{}, eq.predicates...), - withDeployment: eq.withDeployment.Clone(), withDeploymentStatus: eq.withDeploymentStatus.Clone(), withReview: eq.withReview.Clone(), withNotificationRecord: eq.withNotificationRecord.Clone(), @@ -352,17 +327,6 @@ func (eq *EventQuery) Clone() *EventQuery { } } -// 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 (eq *EventQuery) WithDeployment(opts ...func(*DeploymentQuery)) *EventQuery { - query := &DeploymentQuery{config: eq.config} - for _, opt := range opts { - opt(query) - } - eq.withDeployment = query - return eq -} - // WithDeploymentStatus tells the query-builder to eager-load the nodes that are connected to // the "deployment_status" edge. The optional arguments are used to configure the query builder of the edge. func (eq *EventQuery) WithDeploymentStatus(opts ...func(*DeploymentStatusQuery)) *EventQuery { @@ -461,8 +425,7 @@ func (eq *EventQuery) sqlAll(ctx context.Context) ([]*Event, error) { var ( nodes = []*Event{} _spec = eq.querySpec() - loadedTypes = [4]bool{ - eq.withDeployment != nil, + loadedTypes = [3]bool{ eq.withDeploymentStatus != nil, eq.withReview != nil, eq.withNotificationRecord != nil, @@ -491,32 +454,6 @@ func (eq *EventQuery) sqlAll(ctx context.Context) ([]*Event, error) { return nodes, nil } - if query := eq.withDeployment; query != nil { - ids := make([]int, 0, len(nodes)) - nodeids := make(map[int][]*Event) - 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 - } - } - } - if query := eq.withDeploymentStatus; query != nil { ids := make([]int, 0, len(nodes)) nodeids := make(map[int][]*Event) diff --git a/model/ent/event_update.go b/model/ent/event_update.go index be3759c2..fea6acad 100644 --- a/model/ent/event_update.go +++ b/model/ent/event_update.go @@ -11,7 +11,6 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/gitploy-io/gitploy/model/ent/deployment" "github.com/gitploy-io/gitploy/model/ent/deploymentstatus" "github.com/gitploy-io/gitploy/model/ent/event" "github.com/gitploy-io/gitploy/model/ent/notificationrecord" @@ -58,26 +57,6 @@ func (eu *EventUpdate) SetNillableCreatedAt(t *time.Time) *EventUpdate { return eu } -// SetDeploymentID sets the "deployment_id" field. -func (eu *EventUpdate) SetDeploymentID(i int) *EventUpdate { - eu.mutation.SetDeploymentID(i) - return eu -} - -// SetNillableDeploymentID sets the "deployment_id" field if the given value is not nil. -func (eu *EventUpdate) SetNillableDeploymentID(i *int) *EventUpdate { - if i != nil { - eu.SetDeploymentID(*i) - } - return eu -} - -// ClearDeploymentID clears the value of the "deployment_id" field. -func (eu *EventUpdate) ClearDeploymentID() *EventUpdate { - eu.mutation.ClearDeploymentID() - return eu -} - // SetDeploymentStatusID sets the "deployment_status_id" field. func (eu *EventUpdate) SetDeploymentStatusID(i int) *EventUpdate { eu.mutation.SetDeploymentStatusID(i) @@ -145,11 +124,6 @@ func (eu *EventUpdate) ClearDeletedID() *EventUpdate { return eu } -// SetDeployment sets the "deployment" edge to the Deployment entity. -func (eu *EventUpdate) SetDeployment(d *Deployment) *EventUpdate { - return eu.SetDeploymentID(d.ID) -} - // SetDeploymentStatus sets the "deployment_status" edge to the DeploymentStatus entity. func (eu *EventUpdate) SetDeploymentStatus(d *DeploymentStatus) *EventUpdate { return eu.SetDeploymentStatusID(d.ID) @@ -184,12 +158,6 @@ func (eu *EventUpdate) Mutation() *EventMutation { return eu.mutation } -// ClearDeployment clears the "deployment" edge to the Deployment entity. -func (eu *EventUpdate) ClearDeployment() *EventUpdate { - eu.mutation.ClearDeployment() - return eu -} - // ClearDeploymentStatus clears the "deployment_status" edge to the DeploymentStatus entity. func (eu *EventUpdate) ClearDeploymentStatus() *EventUpdate { eu.mutation.ClearDeploymentStatus() @@ -342,41 +310,6 @@ func (eu *EventUpdate) sqlSave(ctx context.Context) (n int, err error) { Column: event.FieldDeletedID, }) } - if eu.mutation.DeploymentCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: event.DeploymentTable, - Columns: []string{event.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 := eu.mutation.DeploymentIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: event.DeploymentTable, - Columns: []string{event.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 eu.mutation.DeploymentStatusCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -527,26 +460,6 @@ func (euo *EventUpdateOne) SetNillableCreatedAt(t *time.Time) *EventUpdateOne { return euo } -// SetDeploymentID sets the "deployment_id" field. -func (euo *EventUpdateOne) SetDeploymentID(i int) *EventUpdateOne { - euo.mutation.SetDeploymentID(i) - return euo -} - -// SetNillableDeploymentID sets the "deployment_id" field if the given value is not nil. -func (euo *EventUpdateOne) SetNillableDeploymentID(i *int) *EventUpdateOne { - if i != nil { - euo.SetDeploymentID(*i) - } - return euo -} - -// ClearDeploymentID clears the value of the "deployment_id" field. -func (euo *EventUpdateOne) ClearDeploymentID() *EventUpdateOne { - euo.mutation.ClearDeploymentID() - return euo -} - // SetDeploymentStatusID sets the "deployment_status_id" field. func (euo *EventUpdateOne) SetDeploymentStatusID(i int) *EventUpdateOne { euo.mutation.SetDeploymentStatusID(i) @@ -614,11 +527,6 @@ func (euo *EventUpdateOne) ClearDeletedID() *EventUpdateOne { return euo } -// SetDeployment sets the "deployment" edge to the Deployment entity. -func (euo *EventUpdateOne) SetDeployment(d *Deployment) *EventUpdateOne { - return euo.SetDeploymentID(d.ID) -} - // SetDeploymentStatus sets the "deployment_status" edge to the DeploymentStatus entity. func (euo *EventUpdateOne) SetDeploymentStatus(d *DeploymentStatus) *EventUpdateOne { return euo.SetDeploymentStatusID(d.ID) @@ -653,12 +561,6 @@ func (euo *EventUpdateOne) Mutation() *EventMutation { return euo.mutation } -// ClearDeployment clears the "deployment" edge to the Deployment entity. -func (euo *EventUpdateOne) ClearDeployment() *EventUpdateOne { - euo.mutation.ClearDeployment() - return euo -} - // ClearDeploymentStatus clears the "deployment_status" edge to the DeploymentStatus entity. func (euo *EventUpdateOne) ClearDeploymentStatus() *EventUpdateOne { euo.mutation.ClearDeploymentStatus() @@ -835,41 +737,6 @@ func (euo *EventUpdateOne) sqlSave(ctx context.Context) (_node *Event, err error Column: event.FieldDeletedID, }) } - if euo.mutation.DeploymentCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: event.DeploymentTable, - Columns: []string{event.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 := euo.mutation.DeploymentIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: true, - Table: event.DeploymentTable, - Columns: []string{event.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 euo.mutation.DeploymentStatusCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, diff --git a/model/ent/migrate/schema.go b/model/ent/migrate/schema.go index 5210f674..491a25aa 100644 --- a/model/ent/migrate/schema.go +++ b/model/ent/migrate/schema.go @@ -181,11 +181,10 @@ var ( // EventsColumns holds the columns for the "events" table. EventsColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "kind", Type: field.TypeEnum, Enums: []string{"deployment", "deployment_status", "review"}}, + {Name: "kind", Type: field.TypeEnum, Enums: []string{"deployment_status", "review"}}, {Name: "type", Type: field.TypeEnum, Enums: []string{"created", "updated", "deleted"}}, {Name: "created_at", Type: field.TypeTime}, {Name: "deleted_id", Type: field.TypeInt, Nullable: true}, - {Name: "deployment_id", Type: field.TypeInt, Nullable: true}, {Name: "deployment_status_id", Type: field.TypeInt, Nullable: true}, {Name: "review_id", Type: field.TypeInt, Nullable: true}, } @@ -195,21 +194,15 @@ var ( Columns: EventsColumns, PrimaryKey: []*schema.Column{EventsColumns[0]}, ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "events_deployments_event", - Columns: []*schema.Column{EventsColumns[5]}, - RefColumns: []*schema.Column{DeploymentsColumns[0]}, - OnDelete: schema.Cascade, - }, { Symbol: "events_deployment_status_event", - Columns: []*schema.Column{EventsColumns[6]}, + Columns: []*schema.Column{EventsColumns[5]}, RefColumns: []*schema.Column{DeploymentStatusColumns[0]}, OnDelete: schema.Cascade, }, { Symbol: "events_reviews_event", - Columns: []*schema.Column{EventsColumns[7]}, + Columns: []*schema.Column{EventsColumns[6]}, RefColumns: []*schema.Column{ReviewsColumns[0]}, OnDelete: schema.Cascade, }, @@ -436,9 +429,8 @@ func init() { DeploymentStatisticsTable.ForeignKeys[0].RefTable = ReposTable DeploymentStatusTable.ForeignKeys[0].RefTable = DeploymentsTable DeploymentStatusTable.ForeignKeys[1].RefTable = ReposTable - EventsTable.ForeignKeys[0].RefTable = DeploymentsTable - EventsTable.ForeignKeys[1].RefTable = DeploymentStatusTable - EventsTable.ForeignKeys[2].RefTable = ReviewsTable + EventsTable.ForeignKeys[0].RefTable = DeploymentStatusTable + EventsTable.ForeignKeys[1].RefTable = ReviewsTable LocksTable.ForeignKeys[0].RefTable = ReposTable LocksTable.ForeignKeys[1].RefTable = UsersTable NotificationRecordsTable.ForeignKeys[0].RefTable = EventsTable diff --git a/model/ent/mutation.go b/model/ent/mutation.go index c0bcbeeb..0c2b4389 100644 --- a/model/ent/mutation.go +++ b/model/ent/mutation.go @@ -781,9 +781,6 @@ type DeploymentMutation struct { deployment_statuses map[int]struct{} removeddeployment_statuses map[int]struct{} cleareddeployment_statuses bool - event map[int]struct{} - removedevent map[int]struct{} - clearedevent bool done bool oldValue func(context.Context) (*Deployment, error) predicates []predicate.Deployment @@ -1799,60 +1796,6 @@ func (m *DeploymentMutation) ResetDeploymentStatuses() { m.removeddeployment_statuses = nil } -// AddEventIDs adds the "event" edge to the Event entity by ids. -func (m *DeploymentMutation) AddEventIDs(ids ...int) { - if m.event == nil { - m.event = make(map[int]struct{}) - } - for i := range ids { - m.event[ids[i]] = struct{}{} - } -} - -// ClearEvent clears the "event" edge to the Event entity. -func (m *DeploymentMutation) ClearEvent() { - m.clearedevent = true -} - -// EventCleared reports if the "event" edge to the Event entity was cleared. -func (m *DeploymentMutation) EventCleared() bool { - return m.clearedevent -} - -// RemoveEventIDs removes the "event" edge to the Event entity by IDs. -func (m *DeploymentMutation) RemoveEventIDs(ids ...int) { - if m.removedevent == nil { - m.removedevent = make(map[int]struct{}) - } - for i := range ids { - delete(m.event, ids[i]) - m.removedevent[ids[i]] = struct{}{} - } -} - -// RemovedEvent returns the removed IDs of the "event" edge to the Event entity. -func (m *DeploymentMutation) RemovedEventIDs() (ids []int) { - for id := range m.removedevent { - ids = append(ids, id) - } - return -} - -// EventIDs returns the "event" edge IDs in the mutation. -func (m *DeploymentMutation) EventIDs() (ids []int) { - for id := range m.event { - ids = append(ids, id) - } - return -} - -// ResetEvent resets all changes to the "event" edge. -func (m *DeploymentMutation) ResetEvent() { - m.event = nil - m.clearedevent = false - m.removedevent = nil -} - // Where appends a list predicates to the DeploymentMutation builder. func (m *DeploymentMutation) Where(ps ...predicate.Deployment) { m.predicates = append(m.predicates, ps...) @@ -2321,7 +2264,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, 4) if m.user != nil { edges = append(edges, deployment.EdgeUser) } @@ -2334,9 +2277,6 @@ func (m *DeploymentMutation) AddedEdges() []string { if m.deployment_statuses != nil { edges = append(edges, deployment.EdgeDeploymentStatuses) } - if m.event != nil { - edges = append(edges, deployment.EdgeEvent) - } return edges } @@ -2364,28 +2304,19 @@ func (m *DeploymentMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids - case deployment.EdgeEvent: - ids := make([]ent.Value, 0, len(m.event)) - for id := range m.event { - ids = append(ids, id) - } - return ids } return nil } // 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, 4) if m.removedreviews != nil { edges = append(edges, deployment.EdgeReviews) } if m.removeddeployment_statuses != nil { edges = append(edges, deployment.EdgeDeploymentStatuses) } - if m.removedevent != nil { - edges = append(edges, deployment.EdgeEvent) - } return edges } @@ -2405,19 +2336,13 @@ func (m *DeploymentMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids - case deployment.EdgeEvent: - ids := make([]ent.Value, 0, len(m.removedevent)) - for id := range m.removedevent { - ids = append(ids, id) - } - return ids } return nil } // 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, 4) if m.cleareduser { edges = append(edges, deployment.EdgeUser) } @@ -2430,9 +2355,6 @@ func (m *DeploymentMutation) ClearedEdges() []string { if m.cleareddeployment_statuses { edges = append(edges, deployment.EdgeDeploymentStatuses) } - if m.clearedevent { - edges = append(edges, deployment.EdgeEvent) - } return edges } @@ -2448,8 +2370,6 @@ func (m *DeploymentMutation) EdgeCleared(name string) bool { return m.clearedreviews case deployment.EdgeDeploymentStatuses: return m.cleareddeployment_statuses - case deployment.EdgeEvent: - return m.clearedevent } return false } @@ -2484,9 +2404,6 @@ func (m *DeploymentMutation) ResetEdge(name string) error { case deployment.EdgeDeploymentStatuses: m.ResetDeploymentStatuses() return nil - case deployment.EdgeEvent: - m.ResetEvent() - return nil } return fmt.Errorf("unknown Deployment edge %s", name) } @@ -4524,8 +4441,6 @@ type EventMutation struct { deleted_id *int adddeleted_id *int clearedFields map[string]struct{} - deployment *int - cleareddeployment bool deployment_status *int cleareddeployment_status bool review *int @@ -4743,55 +4658,6 @@ func (m *EventMutation) ResetCreatedAt() { m.created_at = nil } -// SetDeploymentID sets the "deployment_id" field. -func (m *EventMutation) SetDeploymentID(i int) { - m.deployment = &i -} - -// DeploymentID returns the value of the "deployment_id" field in the mutation. -func (m *EventMutation) 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 Event entity. -// If the Event 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 *EventMutation) OldDeploymentID(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeploymentID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("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 -} - -// ClearDeploymentID clears the value of the "deployment_id" field. -func (m *EventMutation) ClearDeploymentID() { - m.deployment = nil - m.clearedFields[event.FieldDeploymentID] = struct{}{} -} - -// DeploymentIDCleared returns if the "deployment_id" field was cleared in this mutation. -func (m *EventMutation) DeploymentIDCleared() bool { - _, ok := m.clearedFields[event.FieldDeploymentID] - return ok -} - -// ResetDeploymentID resets all changes to the "deployment_id" field. -func (m *EventMutation) ResetDeploymentID() { - m.deployment = nil - delete(m.clearedFields, event.FieldDeploymentID) -} - // SetDeploymentStatusID sets the "deployment_status_id" field. func (m *EventMutation) SetDeploymentStatusID(i int) { m.deployment_status = &i @@ -4960,32 +4826,6 @@ func (m *EventMutation) ResetDeletedID() { delete(m.clearedFields, event.FieldDeletedID) } -// ClearDeployment clears the "deployment" edge to the Deployment entity. -func (m *EventMutation) ClearDeployment() { - m.cleareddeployment = true -} - -// DeploymentCleared reports if the "deployment" edge to the Deployment entity was cleared. -func (m *EventMutation) DeploymentCleared() bool { - return m.DeploymentIDCleared() || 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 *EventMutation) DeploymentIDs() (ids []int) { - if id := m.deployment; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetDeployment resets all changes to the "deployment" edge. -func (m *EventMutation) ResetDeployment() { - m.deployment = nil - m.cleareddeployment = false -} - // ClearDeploymentStatus clears the "deployment_status" edge to the DeploymentStatus entity. func (m *EventMutation) ClearDeploymentStatus() { m.cleareddeployment_status = true @@ -5096,7 +4936,7 @@ func (m *EventMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *EventMutation) Fields() []string { - fields := make([]string, 0, 7) + fields := make([]string, 0, 6) if m.kind != nil { fields = append(fields, event.FieldKind) } @@ -5106,9 +4946,6 @@ func (m *EventMutation) Fields() []string { if m.created_at != nil { fields = append(fields, event.FieldCreatedAt) } - if m.deployment != nil { - fields = append(fields, event.FieldDeploymentID) - } if m.deployment_status != nil { fields = append(fields, event.FieldDeploymentStatusID) } @@ -5132,8 +4969,6 @@ func (m *EventMutation) Field(name string) (ent.Value, bool) { return m.GetType() case event.FieldCreatedAt: return m.CreatedAt() - case event.FieldDeploymentID: - return m.DeploymentID() case event.FieldDeploymentStatusID: return m.DeploymentStatusID() case event.FieldReviewID: @@ -5155,8 +4990,6 @@ func (m *EventMutation) OldField(ctx context.Context, name string) (ent.Value, e return m.OldType(ctx) case event.FieldCreatedAt: return m.OldCreatedAt(ctx) - case event.FieldDeploymentID: - return m.OldDeploymentID(ctx) case event.FieldDeploymentStatusID: return m.OldDeploymentStatusID(ctx) case event.FieldReviewID: @@ -5193,13 +5026,6 @@ func (m *EventMutation) SetField(name string, value ent.Value) error { } m.SetCreatedAt(v) return nil - case event.FieldDeploymentID: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeploymentID(v) - return nil case event.FieldDeploymentStatusID: v, ok := value.(int) if !ok { @@ -5266,9 +5092,6 @@ func (m *EventMutation) AddField(name string, value ent.Value) error { // mutation. func (m *EventMutation) ClearedFields() []string { var fields []string - if m.FieldCleared(event.FieldDeploymentID) { - fields = append(fields, event.FieldDeploymentID) - } if m.FieldCleared(event.FieldDeploymentStatusID) { fields = append(fields, event.FieldDeploymentStatusID) } @@ -5292,9 +5115,6 @@ func (m *EventMutation) FieldCleared(name string) bool { // error if the field is not defined in the schema. func (m *EventMutation) ClearField(name string) error { switch name { - case event.FieldDeploymentID: - m.ClearDeploymentID() - return nil case event.FieldDeploymentStatusID: m.ClearDeploymentStatusID() return nil @@ -5321,9 +5141,6 @@ func (m *EventMutation) ResetField(name string) error { case event.FieldCreatedAt: m.ResetCreatedAt() return nil - case event.FieldDeploymentID: - m.ResetDeploymentID() - return nil case event.FieldDeploymentStatusID: m.ResetDeploymentStatusID() return nil @@ -5339,10 +5156,7 @@ func (m *EventMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *EventMutation) AddedEdges() []string { - edges := make([]string, 0, 4) - if m.deployment != nil { - edges = append(edges, event.EdgeDeployment) - } + edges := make([]string, 0, 3) if m.deployment_status != nil { edges = append(edges, event.EdgeDeploymentStatus) } @@ -5359,10 +5173,6 @@ func (m *EventMutation) AddedEdges() []string { // name in this mutation. func (m *EventMutation) AddedIDs(name string) []ent.Value { switch name { - case event.EdgeDeployment: - if id := m.deployment; id != nil { - return []ent.Value{*id} - } case event.EdgeDeploymentStatus: if id := m.deployment_status; id != nil { return []ent.Value{*id} @@ -5381,7 +5191,7 @@ func (m *EventMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *EventMutation) RemovedEdges() []string { - edges := make([]string, 0, 4) + edges := make([]string, 0, 3) return edges } @@ -5395,10 +5205,7 @@ func (m *EventMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *EventMutation) ClearedEdges() []string { - edges := make([]string, 0, 4) - if m.cleareddeployment { - edges = append(edges, event.EdgeDeployment) - } + edges := make([]string, 0, 3) if m.cleareddeployment_status { edges = append(edges, event.EdgeDeploymentStatus) } @@ -5415,8 +5222,6 @@ func (m *EventMutation) ClearedEdges() []string { // was cleared in this mutation. func (m *EventMutation) EdgeCleared(name string) bool { switch name { - case event.EdgeDeployment: - return m.cleareddeployment case event.EdgeDeploymentStatus: return m.cleareddeployment_status case event.EdgeReview: @@ -5431,9 +5236,6 @@ func (m *EventMutation) EdgeCleared(name string) bool { // if that edge is not defined in the schema. func (m *EventMutation) ClearEdge(name string) error { switch name { - case event.EdgeDeployment: - m.ClearDeployment() - return nil case event.EdgeDeploymentStatus: m.ClearDeploymentStatus() return nil @@ -5451,9 +5253,6 @@ func (m *EventMutation) ClearEdge(name string) error { // It returns an error if the edge is not defined in the schema. func (m *EventMutation) ResetEdge(name string) error { switch name { - case event.EdgeDeployment: - m.ResetDeployment() - return nil case event.EdgeDeploymentStatus: m.ResetDeploymentStatus() return nil diff --git a/model/ent/schema/deployment.go b/model/ent/schema/deployment.go index d24dd310..8fe444fe 100644 --- a/model/ent/schema/deployment.go +++ b/model/ent/schema/deployment.go @@ -92,10 +92,6 @@ func (Deployment) Edges() []ent.Edge { Annotations(entsql.Annotation{ OnDelete: entsql.Cascade, }), - edge.To("event", Event.Type). - Annotations(entsql.Annotation{ - OnDelete: entsql.Cascade, - }), } } diff --git a/model/ent/schema/event.go b/model/ent/schema/event.go index 65e5fc29..ed428392 100644 --- a/model/ent/schema/event.go +++ b/model/ent/schema/event.go @@ -17,7 +17,6 @@ func (Event) Fields() []ent.Field { return []ent.Field{ field.Enum("kind"). Values( - "deployment", "deployment_status", "review", ), @@ -29,8 +28,6 @@ func (Event) Fields() []ent.Field { ), field.Time("created_at"). Default(nowUTC), - field.Int("deployment_id"). - Optional(), field.Int("deployment_status_id"). Optional(), field.Int("review_id"). @@ -44,10 +41,6 @@ func (Event) Fields() []ent.Field { // Edges of the Event. func (Event) Edges() []ent.Edge { return []ent.Edge{ - edge.From("deployment", Deployment.Type). - Ref("event"). - Field("deployment_id"). - Unique(), edge.From("deployment_status", DeploymentStatus.Type). Ref("event"). Field("deployment_status_id"). diff --git a/openapi/v1.yaml b/openapi/v1.yaml index 397198d3..b4913065 100644 --- a/openapi/v1.yaml +++ b/openapi/v1.yaml @@ -1437,12 +1437,10 @@ paths: event: type: string enum: - - deployment - deployment_status - review data: oneOf: - - $ref: '#/components/schemas/Deployment' - $ref: '#/components/schemas/DeploymentStatus' - $ref: '#/components/schemas/Review' /sync: diff --git a/ui/src/apis/events.ts b/ui/src/apis/events.ts index 1fb46f2b..22d88402 100644 --- a/ui/src/apis/events.ts +++ b/ui/src/apis/events.ts @@ -1,25 +1,10 @@ import { instance } from './setting' -import { mapDataToDeployment, mapDataToDeploymentStatus } from "./deployment" +import { mapDataToDeploymentStatus } from "./deployment" import { mapDataToReview } from "./review" -import { Deployment, DeploymentStatus, Review } from "../models" +import { DeploymentStatus, Review } from "../models" -export const subscribeDeploymentEvents = (cb: (deployment: Deployment) => void): EventSource => { - const sse = new EventSource(`${instance}/api/v1/stream/events`, { - withCredentials: true, - }) - - sse.addEventListener("deployment", (e: any) => { - const data = JSON.parse(e.data) - const deployment = mapDataToDeployment(data) - - cb(deployment) - }) - - return sse -} - export const subscribeDeploymentStatusEvents = (cb: (status: DeploymentStatus) => void): EventSource => { const sse = new EventSource(`${instance}/api/v1/stream/events`, { withCredentials: true, diff --git a/ui/src/apis/index.ts b/ui/src/apis/index.ts index c0b09e3f..beaa1546 100644 --- a/ui/src/apis/index.ts +++ b/ui/src/apis/index.ts @@ -65,7 +65,6 @@ export { getLicense } from "./license" export { - subscribeDeploymentEvents, subscribeDeploymentStatusEvents, subscribeReviewEvents, } from "./events" diff --git a/ui/src/redux/deployment.tsx b/ui/src/redux/deployment.tsx index 79094017..218cd8f4 100644 --- a/ui/src/redux/deployment.tsx +++ b/ui/src/redux/deployment.tsx @@ -194,11 +194,6 @@ export const deploymentSlice = createSlice({ setDisplay: (state, action: PayloadAction) => { state.display = action.payload }, - handleDeploymentEvent: (state, action: PayloadAction) => { - if (action.payload.id === state.deployment?.id) { - state.deployment = action.payload - } - }, handleReviewEvent: (state, action: PayloadAction) => { state.reviews = state.reviews.map((review) => { return (action.payload.id === review.id)? action.payload : review diff --git a/ui/src/redux/main.ts b/ui/src/redux/main.ts index 13dd880b..d13da0f1 100644 --- a/ui/src/redux/main.ts +++ b/ui/src/redux/main.ts @@ -20,7 +20,6 @@ import { getDeployment, getLicense } from "../apis" -import { getShortRef } from "../libs" interface MainState { available: boolean @@ -136,29 +135,6 @@ const notify = (title: string, options?: NotificationOptions) => { new Notification(title, options) } -/** - * The browser notifies only the user who triggers the deployment. - */ -export const notifyDeploymentEvent = createAsyncThunk( - "main/notifyDeploymentEvent", - async (deployment) => { - if (deployment.status === DeploymentStatusEnum.Created) { - notify(`New Deployment #${deployment.number}`, { - icon: "/logo192.png", - body: `Start to deploy ${getShortRef(deployment)} to the ${deployment.env} environment of ${deployment.repo?.namespace}/${deployment.repo?.name}.`, - tag: String(deployment.id), - }) - return - } - - notify(`Deployment Updated #${deployment.number}`, { - icon: "/logo192.png", - body: `The deployment ${deployment.number} of ${deployment.repo?.namespace}/${deployment.repo?.name} is updated ${deployment.status}.`, - tag: String(deployment.id), - }) - } -) - export const notifyDeploymentStatusEvent = createAsyncThunk( "main/notifyDeploymentStatusEvent", async (deploymentStatus, {rejectWithValue}) => { @@ -235,24 +211,6 @@ export const mainSlice = createSlice({ setExpired: (state, action: PayloadAction) => { state.expired = action.payload }, - /** - * Update the status of the deployment with an event. - */ - handleDeploymentEvent: (state, { payload: deployment }: PayloadAction) => { - if (deployment.status === DeploymentStatusEnum.Created) { - state.deployments.unshift(deployment) - return - } - - state.deployments = state.deployments.filter((item) => { - return !(item.status === DeploymentStatusEnum.Success - || item.status === DeploymentStatusEnum.Failure) - }) - - state.deployments = state.deployments.map((item) => { - return (item.id === deployment.id)? deployment : item - }) - }, /** * Reviews are removed from the state. */ diff --git a/ui/src/views/deployment/index.tsx b/ui/src/views/deployment/index.tsx index 58218a51..d4119a6d 100644 --- a/ui/src/views/deployment/index.tsx +++ b/ui/src/views/deployment/index.tsx @@ -24,7 +24,6 @@ import { RequestStatus } from "../../models" import { - subscribeDeploymentEvents, subscribeDeploymentStatusEvents, subscribeReviewEvents } from "../../apis" @@ -66,10 +65,6 @@ export default (): JSX.Element => { } f() - const deploymentEvent = subscribeDeploymentEvents((deployment) => { - dispatch(slice.actions.handleDeploymentEvent(deployment)) - }) - const deploymentStatusEvent = subscribeDeploymentStatusEvents((deploymentStatus) => { dispatch(handleDeploymentStatusEvent(deploymentStatus)) }) @@ -79,7 +74,6 @@ export default (): JSX.Element => { }) return () => { - deploymentEvent.close() deploymentStatusEvent.close() reviewEvent.close() } diff --git a/ui/src/views/main/index.tsx b/ui/src/views/main/index.tsx index a34f98f4..e6af2ae4 100644 --- a/ui/src/views/main/index.tsx +++ b/ui/src/views/main/index.tsx @@ -6,7 +6,6 @@ import moment from "moment" import { useAppSelector, useAppDispatch } from "../../redux/hooks" import { - subscribeDeploymentEvents, subscribeDeploymentStatusEvents, subscribeReviewEvents } from "../../apis" @@ -15,7 +14,6 @@ import { searchDeployments, searchReviews, fetchLicense, - notifyDeploymentEvent, notifyDeploymentStatusEvent, notifyReviewmentEvent, handleDeploymentStatusEvent, @@ -46,11 +44,6 @@ export default (props: React.PropsWithChildren): JSX.Element => { dispatch(searchReviews()) dispatch(fetchLicense()) - const deploymentEvents = subscribeDeploymentEvents((deployment) => { - dispatch(slice.actions.handleDeploymentEvent(deployment)) - dispatch(notifyDeploymentEvent(deployment)) - }) - const deploymentStatusEvents = subscribeDeploymentStatusEvents((deploymentStatus) => { dispatch(handleDeploymentStatusEvent(deploymentStatus)) dispatch(notifyDeploymentStatusEvent(deploymentStatus)) @@ -62,7 +55,6 @@ export default (props: React.PropsWithChildren): JSX.Element => { }) return () => { - deploymentEvents.close() deploymentStatusEvents.close() reviewEvents.close() }