diff --git a/drip/api.gen.go b/drip/api.gen.go index 6a708c3..ca81e83 100644 --- a/drip/api.gen.go +++ b/drip/api.gen.go @@ -293,6 +293,12 @@ type InstallNodeParams struct { Version *string `form:"version,omitempty" json:"version,omitempty"` } +// PostNodeReviewParams defines parameters for PostNodeReview. +type PostNodeReviewParams struct { + // Star number of star given to the node version + Star int `form:"star" json:"star"` +} + // ValidatePublisherParams defines parameters for ValidatePublisher. type ValidatePublisherParams struct { // Username The publisher username to validate. @@ -395,6 +401,9 @@ type ServerInterface interface { // Returns a node version to be installed. // (GET /nodes/{nodeId}/install) InstallNode(ctx echo.Context, nodeId string, params InstallNodeParams) error + // Add review to a specific version of a node + // (POST /nodes/{nodeId}/reviews) + PostNodeReview(ctx echo.Context, nodeId string, params PostNodeReviewParams) error // List all versions of a node // (GET /nodes/{nodeId}/versions) ListNodeVersions(ctx echo.Context, nodeId string) error @@ -647,6 +656,31 @@ func (w *ServerInterfaceWrapper) InstallNode(ctx echo.Context) error { return err } +// PostNodeReview converts echo context to params. +func (w *ServerInterfaceWrapper) PostNodeReview(ctx echo.Context) error { + var err error + // ------------- Path parameter "nodeId" ------------- + var nodeId string + + err = runtime.BindStyledParameterWithOptions("simple", "nodeId", ctx.Param("nodeId"), &nodeId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true}) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter nodeId: %s", err)) + } + + // Parameter object where we will unmarshal all parameters from the context + var params PostNodeReviewParams + // ------------- Required query parameter "star" ------------- + + err = runtime.BindQueryParameter("form", true, true, "star", ctx.QueryParams(), ¶ms.Star) + if err != nil { + return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid format for parameter star: %s", err)) + } + + // Invoke the callback with all the unmarshaled arguments + err = w.Handler.PostNodeReview(ctx, nodeId, params) + return err +} + // ListNodeVersions converts echo context to params. func (w *ServerInterfaceWrapper) ListNodeVersions(ctx echo.Context) error { var err error @@ -1124,6 +1158,7 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL router.GET(baseURL+"/nodes/search", wrapper.SearchNodes) router.GET(baseURL+"/nodes/:nodeId", wrapper.GetNode) router.GET(baseURL+"/nodes/:nodeId/install", wrapper.InstallNode) + router.POST(baseURL+"/nodes/:nodeId/reviews", wrapper.PostNodeReview) router.GET(baseURL+"/nodes/:nodeId/versions", wrapper.ListNodeVersions) router.GET(baseURL+"/nodes/:nodeId/versions/:versionId", wrapper.GetNodeVersion) router.GET(baseURL+"/publishers", wrapper.ListPublishers) @@ -1429,6 +1464,50 @@ func (response InstallNode500JSONResponse) VisitInstallNodeResponse(w http.Respo return json.NewEncoder(w).Encode(response) } +type PostNodeReviewRequestObject struct { + NodeId string `json:"nodeId"` + Params PostNodeReviewParams +} + +type PostNodeReviewResponseObject interface { + VisitPostNodeReviewResponse(w http.ResponseWriter) error +} + +type PostNodeReview200JSONResponse Node + +func (response PostNodeReview200JSONResponse) VisitPostNodeReviewResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + +type PostNodeReview400Response struct { +} + +func (response PostNodeReview400Response) VisitPostNodeReviewResponse(w http.ResponseWriter) error { + w.WriteHeader(400) + return nil +} + +type PostNodeReview404JSONResponse Error + +func (response PostNodeReview404JSONResponse) VisitPostNodeReviewResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + + return json.NewEncoder(w).Encode(response) +} + +type PostNodeReview500JSONResponse ErrorResponse + +func (response PostNodeReview500JSONResponse) VisitPostNodeReviewResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(500) + + return json.NewEncoder(w).Encode(response) +} + type ListNodeVersionsRequestObject struct { NodeId string `json:"nodeId"` } @@ -2406,6 +2485,9 @@ type StrictServerInterface interface { // Returns a node version to be installed. // (GET /nodes/{nodeId}/install) InstallNode(ctx context.Context, request InstallNodeRequestObject) (InstallNodeResponseObject, error) + // Add review to a specific version of a node + // (POST /nodes/{nodeId}/reviews) + PostNodeReview(ctx context.Context, request PostNodeReviewRequestObject) (PostNodeReviewResponseObject, error) // List all versions of a node // (GET /nodes/{nodeId}/versions) ListNodeVersions(ctx context.Context, request ListNodeVersionsRequestObject) (ListNodeVersionsResponseObject, error) @@ -2640,6 +2722,32 @@ func (sh *strictHandler) InstallNode(ctx echo.Context, nodeId string, params Ins return nil } +// PostNodeReview operation middleware +func (sh *strictHandler) PostNodeReview(ctx echo.Context, nodeId string, params PostNodeReviewParams) error { + var request PostNodeReviewRequestObject + + request.NodeId = nodeId + request.Params = params + + handler := func(ctx echo.Context, request interface{}) (interface{}, error) { + return sh.ssi.PostNodeReview(ctx.Request().Context(), request.(PostNodeReviewRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "PostNodeReview") + } + + response, err := handler(ctx, request) + + if err != nil { + return err + } else if validResponse, ok := response.(PostNodeReviewResponseObject); ok { + return validResponse.VisitPostNodeReviewResponse(ctx.Response()) + } else if response != nil { + return fmt.Errorf("unexpected response type: %T", response) + } + return nil +} + // ListNodeVersions operation middleware func (sh *strictHandler) ListNodeVersions(ctx echo.Context, nodeId string) error { var request ListNodeVersionsRequestObject @@ -3266,75 +3374,76 @@ func (sh *strictHandler) ListPublishersForUser(ctx echo.Context) error { // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "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", - "AAA=", + "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", + "n0TXl9f/DQAA///DqXJ0XoEAAA==", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/ent/client.go b/ent/client.go index 462edde..05bad15 100644 --- a/ent/client.go +++ b/ent/client.go @@ -14,6 +14,7 @@ import ( "registry-backend/ent/ciworkflowresult" "registry-backend/ent/gitcommit" "registry-backend/ent/node" + "registry-backend/ent/nodereview" "registry-backend/ent/nodeversion" "registry-backend/ent/personalaccesstoken" "registry-backend/ent/publisher" @@ -39,6 +40,8 @@ type Client struct { GitCommit *GitCommitClient // Node is the client for interacting with the Node builders. Node *NodeClient + // NodeReview is the client for interacting with the NodeReview builders. + NodeReview *NodeReviewClient // NodeVersion is the client for interacting with the NodeVersion builders. NodeVersion *NodeVersionClient // PersonalAccessToken is the client for interacting with the PersonalAccessToken builders. @@ -65,6 +68,7 @@ func (c *Client) init() { c.CIWorkflowResult = NewCIWorkflowResultClient(c.config) c.GitCommit = NewGitCommitClient(c.config) c.Node = NewNodeClient(c.config) + c.NodeReview = NewNodeReviewClient(c.config) c.NodeVersion = NewNodeVersionClient(c.config) c.PersonalAccessToken = NewPersonalAccessTokenClient(c.config) c.Publisher = NewPublisherClient(c.config) @@ -166,6 +170,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { CIWorkflowResult: NewCIWorkflowResultClient(cfg), GitCommit: NewGitCommitClient(cfg), Node: NewNodeClient(cfg), + NodeReview: NewNodeReviewClient(cfg), NodeVersion: NewNodeVersionClient(cfg), PersonalAccessToken: NewPersonalAccessTokenClient(cfg), Publisher: NewPublisherClient(cfg), @@ -194,6 +199,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) CIWorkflowResult: NewCIWorkflowResultClient(cfg), GitCommit: NewGitCommitClient(cfg), Node: NewNodeClient(cfg), + NodeReview: NewNodeReviewClient(cfg), NodeVersion: NewNodeVersionClient(cfg), PersonalAccessToken: NewPersonalAccessTokenClient(cfg), Publisher: NewPublisherClient(cfg), @@ -229,8 +235,9 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ - c.CIWorkflowResult, c.GitCommit, c.Node, c.NodeVersion, c.PersonalAccessToken, - c.Publisher, c.PublisherPermission, c.StorageFile, c.User, + c.CIWorkflowResult, c.GitCommit, c.Node, c.NodeReview, c.NodeVersion, + c.PersonalAccessToken, c.Publisher, c.PublisherPermission, c.StorageFile, + c.User, } { n.Use(hooks...) } @@ -240,8 +247,9 @@ func (c *Client) Use(hooks ...Hook) { // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ - c.CIWorkflowResult, c.GitCommit, c.Node, c.NodeVersion, c.PersonalAccessToken, - c.Publisher, c.PublisherPermission, c.StorageFile, c.User, + c.CIWorkflowResult, c.GitCommit, c.Node, c.NodeReview, c.NodeVersion, + c.PersonalAccessToken, c.Publisher, c.PublisherPermission, c.StorageFile, + c.User, } { n.Intercept(interceptors...) } @@ -256,6 +264,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.GitCommit.mutate(ctx, m) case *NodeMutation: return c.Node.mutate(ctx, m) + case *NodeReviewMutation: + return c.NodeReview.mutate(ctx, m) case *NodeVersionMutation: return c.NodeVersion.mutate(ctx, m) case *PersonalAccessTokenMutation: @@ -727,6 +737,22 @@ func (c *NodeClient) QueryVersions(n *Node) *NodeVersionQuery { return query } +// QueryReviews queries the reviews edge of a Node. +func (c *NodeClient) QueryReviews(n *Node) *NodeReviewQuery { + query := (&NodeReviewClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := n.ID + step := sqlgraph.NewStep( + sqlgraph.From(node.Table, node.FieldID, id), + sqlgraph.To(nodereview.Table, nodereview.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, node.ReviewsTable, node.ReviewsColumn), + ) + fromV = sqlgraph.Neighbors(n.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *NodeClient) Hooks() []Hook { return c.hooks.Node @@ -752,6 +778,171 @@ func (c *NodeClient) mutate(ctx context.Context, m *NodeMutation) (Value, error) } } +// NodeReviewClient is a client for the NodeReview schema. +type NodeReviewClient struct { + config +} + +// NewNodeReviewClient returns a client for the NodeReview from the given config. +func NewNodeReviewClient(c config) *NodeReviewClient { + return &NodeReviewClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `nodereview.Hooks(f(g(h())))`. +func (c *NodeReviewClient) Use(hooks ...Hook) { + c.hooks.NodeReview = append(c.hooks.NodeReview, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `nodereview.Intercept(f(g(h())))`. +func (c *NodeReviewClient) Intercept(interceptors ...Interceptor) { + c.inters.NodeReview = append(c.inters.NodeReview, interceptors...) +} + +// Create returns a builder for creating a NodeReview entity. +func (c *NodeReviewClient) Create() *NodeReviewCreate { + mutation := newNodeReviewMutation(c.config, OpCreate) + return &NodeReviewCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of NodeReview entities. +func (c *NodeReviewClient) CreateBulk(builders ...*NodeReviewCreate) *NodeReviewCreateBulk { + return &NodeReviewCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *NodeReviewClient) MapCreateBulk(slice any, setFunc func(*NodeReviewCreate, int)) *NodeReviewCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &NodeReviewCreateBulk{err: fmt.Errorf("calling to NodeReviewClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*NodeReviewCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &NodeReviewCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for NodeReview. +func (c *NodeReviewClient) Update() *NodeReviewUpdate { + mutation := newNodeReviewMutation(c.config, OpUpdate) + return &NodeReviewUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *NodeReviewClient) UpdateOne(nr *NodeReview) *NodeReviewUpdateOne { + mutation := newNodeReviewMutation(c.config, OpUpdateOne, withNodeReview(nr)) + return &NodeReviewUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *NodeReviewClient) UpdateOneID(id uuid.UUID) *NodeReviewUpdateOne { + mutation := newNodeReviewMutation(c.config, OpUpdateOne, withNodeReviewID(id)) + return &NodeReviewUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for NodeReview. +func (c *NodeReviewClient) Delete() *NodeReviewDelete { + mutation := newNodeReviewMutation(c.config, OpDelete) + return &NodeReviewDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *NodeReviewClient) DeleteOne(nr *NodeReview) *NodeReviewDeleteOne { + return c.DeleteOneID(nr.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *NodeReviewClient) DeleteOneID(id uuid.UUID) *NodeReviewDeleteOne { + builder := c.Delete().Where(nodereview.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &NodeReviewDeleteOne{builder} +} + +// Query returns a query builder for NodeReview. +func (c *NodeReviewClient) Query() *NodeReviewQuery { + return &NodeReviewQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeNodeReview}, + inters: c.Interceptors(), + } +} + +// Get returns a NodeReview entity by its id. +func (c *NodeReviewClient) Get(ctx context.Context, id uuid.UUID) (*NodeReview, error) { + return c.Query().Where(nodereview.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *NodeReviewClient) GetX(ctx context.Context, id uuid.UUID) *NodeReview { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a NodeReview. +func (c *NodeReviewClient) QueryUser(nr *NodeReview) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := nr.ID + step := sqlgraph.NewStep( + sqlgraph.From(nodereview.Table, nodereview.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, nodereview.UserTable, nodereview.UserColumn), + ) + fromV = sqlgraph.Neighbors(nr.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryNode queries the node edge of a NodeReview. +func (c *NodeReviewClient) QueryNode(nr *NodeReview) *NodeQuery { + query := (&NodeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := nr.ID + step := sqlgraph.NewStep( + sqlgraph.From(nodereview.Table, nodereview.FieldID, id), + sqlgraph.To(node.Table, node.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, nodereview.NodeTable, nodereview.NodeColumn), + ) + fromV = sqlgraph.Neighbors(nr.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *NodeReviewClient) Hooks() []Hook { + return c.hooks.NodeReview +} + +// Interceptors returns the client interceptors. +func (c *NodeReviewClient) Interceptors() []Interceptor { + return c.inters.NodeReview +} + +func (c *NodeReviewClient) mutate(ctx context.Context, m *NodeReviewMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&NodeReviewCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&NodeReviewUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&NodeReviewUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&NodeReviewDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown NodeReview mutation op: %q", m.Op()) + } +} + // NodeVersionClient is a client for the NodeVersion schema. type NodeVersionClient struct { config @@ -1669,6 +1860,22 @@ func (c *UserClient) QueryPublisherPermissions(u *User) *PublisherPermissionQuer return query } +// QueryReviews queries the reviews edge of a User. +func (c *UserClient) QueryReviews(u *User) *NodeReviewQuery { + query := (&NodeReviewClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(nodereview.Table, nodereview.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ReviewsTable, user.ReviewsColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *UserClient) Hooks() []Hook { return c.hooks.User @@ -1697,11 +1904,11 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) // hooks and interceptors per client, for fast access. type ( hooks struct { - CIWorkflowResult, GitCommit, Node, NodeVersion, PersonalAccessToken, Publisher, - PublisherPermission, StorageFile, User []ent.Hook + CIWorkflowResult, GitCommit, Node, NodeReview, NodeVersion, PersonalAccessToken, + Publisher, PublisherPermission, StorageFile, User []ent.Hook } inters struct { - CIWorkflowResult, GitCommit, Node, NodeVersion, PersonalAccessToken, Publisher, - PublisherPermission, StorageFile, User []ent.Interceptor + CIWorkflowResult, GitCommit, Node, NodeReview, NodeVersion, PersonalAccessToken, + Publisher, PublisherPermission, StorageFile, User []ent.Interceptor } ) diff --git a/ent/ent.go b/ent/ent.go index 52ab9e1..aec797c 100644 --- a/ent/ent.go +++ b/ent/ent.go @@ -10,6 +10,7 @@ import ( "registry-backend/ent/ciworkflowresult" "registry-backend/ent/gitcommit" "registry-backend/ent/node" + "registry-backend/ent/nodereview" "registry-backend/ent/nodeversion" "registry-backend/ent/personalaccesstoken" "registry-backend/ent/publisher" @@ -84,6 +85,7 @@ func checkColumn(table, column string) error { ciworkflowresult.Table: ciworkflowresult.ValidColumn, gitcommit.Table: gitcommit.ValidColumn, node.Table: node.ValidColumn, + nodereview.Table: nodereview.ValidColumn, nodeversion.Table: nodeversion.ValidColumn, personalaccesstoken.Table: personalaccesstoken.ValidColumn, publisher.Table: publisher.ValidColumn, diff --git a/ent/hook/hook.go b/ent/hook/hook.go index fda7f47..4c792eb 100644 --- a/ent/hook/hook.go +++ b/ent/hook/hook.go @@ -44,6 +44,18 @@ func (f NodeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.NodeMutation", m) } +// The NodeReviewFunc type is an adapter to allow the use of ordinary +// function as NodeReview mutator. +type NodeReviewFunc func(context.Context, *ent.NodeReviewMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f NodeReviewFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.NodeReviewMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.NodeReviewMutation", m) +} + // The NodeVersionFunc type is an adapter to allow the use of ordinary // function as NodeVersion mutator. type NodeVersionFunc func(context.Context, *ent.NodeVersionMutation) (ent.Value, error) diff --git a/ent/migrate/migrations/20240601211932_migration.sql b/ent/migrate/migrations/20240601211932_migration.sql new file mode 100644 index 0000000..1ec88da --- /dev/null +++ b/ent/migrate/migrations/20240601211932_migration.sql @@ -0,0 +1,6 @@ +-- Modify "nodes" table +ALTER TABLE "nodes" ADD COLUMN "total_install" bigint NOT NULL DEFAULT 0, ADD COLUMN "total_star" bigint NOT NULL DEFAULT 0, ADD COLUMN "total_review" bigint NOT NULL DEFAULT 0; +-- Create "node_reviews" table +CREATE TABLE "node_reviews" ("id" uuid NOT NULL, "star" bigint NOT NULL DEFAULT 0, "node_id" text NOT NULL, "user_id" character varying NOT NULL, PRIMARY KEY ("id"), CONSTRAINT "node_reviews_nodes_reviews" FOREIGN KEY ("node_id") REFERENCES "nodes" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION, CONSTRAINT "node_reviews_users_reviews" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION); +-- Create index "nodereview_node_id_user_id" to table: "node_reviews" +CREATE UNIQUE INDEX "nodereview_node_id_user_id" ON "node_reviews" ("node_id", "user_id"); diff --git a/ent/migrate/migrations/atlas.sum b/ent/migrate/migrations/atlas.sum index 45248c9..6937bc9 100644 --- a/ent/migrate/migrations/atlas.sum +++ b/ent/migrate/migrations/atlas.sum @@ -1,5 +1,6 @@ -h1:6oztoFVRk9lR+3VkK/QRBH0aWj6Q3oyKkUlQkrLcJYs= +h1:9EV71nxYeG+28BC8qftpzSYZzD+yHZeVSvxkILgTXLQ= 20240526144817_migration.sql h1:sP6keX+oMyLL2qpIFx0Ns0WYfWM5hJ4zkFPmLWT68fM= 20240528220411_migration.sql h1:SR44sOEaWbDgYCKJZIKcGCI7Ta+LqL71z225Nhs2+HM= 20240528221846_migration.sql h1:EkUonGI9Bu689qWX4pG3PRC+On4f6u7UvwDbaR8mCNk= 20240528222851_migration.sql h1:VaQhEaDGe8M2kuNtKVjuMWMLJ9RhJVraVgSM4rm/XcQ= +20240601211932_migration.sql h1:zTofjRbLfoZZF8k6dvAMUDJGRENHAG3m1qqtLgTXUCQ= diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go index 87c9449..7c2d5f6 100644 --- a/ent/migrate/schema.go +++ b/ent/migrate/schema.go @@ -82,6 +82,9 @@ var ( {Name: "repository_url", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}}, {Name: "icon_url", Type: field.TypeString, Nullable: true, SchemaType: map[string]string{"postgres": "text"}}, {Name: "tags", Type: field.TypeJSON, SchemaType: map[string]string{"postgres": "text"}}, + {Name: "total_install", Type: field.TypeInt64, Default: 0}, + {Name: "total_star", Type: field.TypeInt64, Default: 0}, + {Name: "total_review", Type: field.TypeInt64, Default: 0}, {Name: "publisher_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}}, } // NodesTable holds the schema information for the "nodes" table. @@ -92,12 +95,46 @@ var ( ForeignKeys: []*schema.ForeignKey{ { Symbol: "nodes_publishers_nodes", - Columns: []*schema.Column{NodesColumns[10]}, + Columns: []*schema.Column{NodesColumns[13]}, RefColumns: []*schema.Column{PublishersColumns[0]}, OnDelete: schema.NoAction, }, }, } + // NodeReviewsColumns holds the columns for the "node_reviews" table. + NodeReviewsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "star", Type: field.TypeInt, Default: 0}, + {Name: "node_id", Type: field.TypeString, SchemaType: map[string]string{"postgres": "text"}}, + {Name: "user_id", Type: field.TypeString}, + } + // NodeReviewsTable holds the schema information for the "node_reviews" table. + NodeReviewsTable = &schema.Table{ + Name: "node_reviews", + Columns: NodeReviewsColumns, + PrimaryKey: []*schema.Column{NodeReviewsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "node_reviews_nodes_reviews", + Columns: []*schema.Column{NodeReviewsColumns[2]}, + RefColumns: []*schema.Column{NodesColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "node_reviews_users_reviews", + Columns: []*schema.Column{NodeReviewsColumns[3]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "nodereview_node_id_user_id", + Unique: true, + Columns: []*schema.Column{NodeReviewsColumns[2], NodeReviewsColumns[3]}, + }, + }, + } // NodeVersionsColumns holds the columns for the "node_versions" table. NodeVersionsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -251,6 +288,7 @@ var ( CiWorkflowResultsTable, GitCommitsTable, NodesTable, + NodeReviewsTable, NodeVersionsTable, PersonalAccessTokensTable, PublishersTable, @@ -264,6 +302,8 @@ func init() { CiWorkflowResultsTable.ForeignKeys[0].RefTable = StorageFilesTable CiWorkflowResultsTable.ForeignKeys[1].RefTable = GitCommitsTable NodesTable.ForeignKeys[0].RefTable = PublishersTable + NodeReviewsTable.ForeignKeys[0].RefTable = NodesTable + NodeReviewsTable.ForeignKeys[1].RefTable = UsersTable NodeVersionsTable.ForeignKeys[0].RefTable = NodesTable NodeVersionsTable.ForeignKeys[1].RefTable = StorageFilesTable PersonalAccessTokensTable.ForeignKeys[0].RefTable = PublishersTable diff --git a/ent/mutation.go b/ent/mutation.go index 8a60a91..641ea9a 100644 --- a/ent/mutation.go +++ b/ent/mutation.go @@ -9,6 +9,7 @@ import ( "registry-backend/ent/ciworkflowresult" "registry-backend/ent/gitcommit" "registry-backend/ent/node" + "registry-backend/ent/nodereview" "registry-backend/ent/nodeversion" "registry-backend/ent/personalaccesstoken" "registry-backend/ent/predicate" @@ -37,6 +38,7 @@ const ( TypeCIWorkflowResult = "CIWorkflowResult" TypeGitCommit = "GitCommit" TypeNode = "Node" + TypeNodeReview = "NodeReview" TypeNodeVersion = "NodeVersion" TypePersonalAccessToken = "PersonalAccessToken" TypePublisher = "Publisher" @@ -2110,12 +2112,21 @@ type NodeMutation struct { icon_url *string tags *[]string appendtags []string + total_install *int64 + addtotal_install *int64 + total_star *int64 + addtotal_star *int64 + total_review *int64 + addtotal_review *int64 clearedFields map[string]struct{} publisher *string clearedpublisher bool versions map[uuid.UUID]struct{} removedversions map[uuid.UUID]struct{} clearedversions bool + reviews map[uuid.UUID]struct{} + removedreviews map[uuid.UUID]struct{} + clearedreviews bool done bool oldValue func(context.Context) (*Node, error) predicates []predicate.Node @@ -2639,6 +2650,174 @@ func (m *NodeMutation) ResetTags() { m.appendtags = nil } +// SetTotalInstall sets the "total_install" field. +func (m *NodeMutation) SetTotalInstall(i int64) { + m.total_install = &i + m.addtotal_install = nil +} + +// TotalInstall returns the value of the "total_install" field in the mutation. +func (m *NodeMutation) TotalInstall() (r int64, exists bool) { + v := m.total_install + if v == nil { + return + } + return *v, true +} + +// OldTotalInstall returns the old "total_install" field's value of the Node entity. +// If the Node 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 *NodeMutation) OldTotalInstall(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotalInstall is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotalInstall requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotalInstall: %w", err) + } + return oldValue.TotalInstall, nil +} + +// AddTotalInstall adds i to the "total_install" field. +func (m *NodeMutation) AddTotalInstall(i int64) { + if m.addtotal_install != nil { + *m.addtotal_install += i + } else { + m.addtotal_install = &i + } +} + +// AddedTotalInstall returns the value that was added to the "total_install" field in this mutation. +func (m *NodeMutation) AddedTotalInstall() (r int64, exists bool) { + v := m.addtotal_install + if v == nil { + return + } + return *v, true +} + +// ResetTotalInstall resets all changes to the "total_install" field. +func (m *NodeMutation) ResetTotalInstall() { + m.total_install = nil + m.addtotal_install = nil +} + +// SetTotalStar sets the "total_star" field. +func (m *NodeMutation) SetTotalStar(i int64) { + m.total_star = &i + m.addtotal_star = nil +} + +// TotalStar returns the value of the "total_star" field in the mutation. +func (m *NodeMutation) TotalStar() (r int64, exists bool) { + v := m.total_star + if v == nil { + return + } + return *v, true +} + +// OldTotalStar returns the old "total_star" field's value of the Node entity. +// If the Node 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 *NodeMutation) OldTotalStar(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotalStar is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotalStar requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotalStar: %w", err) + } + return oldValue.TotalStar, nil +} + +// AddTotalStar adds i to the "total_star" field. +func (m *NodeMutation) AddTotalStar(i int64) { + if m.addtotal_star != nil { + *m.addtotal_star += i + } else { + m.addtotal_star = &i + } +} + +// AddedTotalStar returns the value that was added to the "total_star" field in this mutation. +func (m *NodeMutation) AddedTotalStar() (r int64, exists bool) { + v := m.addtotal_star + if v == nil { + return + } + return *v, true +} + +// ResetTotalStar resets all changes to the "total_star" field. +func (m *NodeMutation) ResetTotalStar() { + m.total_star = nil + m.addtotal_star = nil +} + +// SetTotalReview sets the "total_review" field. +func (m *NodeMutation) SetTotalReview(i int64) { + m.total_review = &i + m.addtotal_review = nil +} + +// TotalReview returns the value of the "total_review" field in the mutation. +func (m *NodeMutation) TotalReview() (r int64, exists bool) { + v := m.total_review + if v == nil { + return + } + return *v, true +} + +// OldTotalReview returns the old "total_review" field's value of the Node entity. +// If the Node 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 *NodeMutation) OldTotalReview(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTotalReview is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTotalReview requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTotalReview: %w", err) + } + return oldValue.TotalReview, nil +} + +// AddTotalReview adds i to the "total_review" field. +func (m *NodeMutation) AddTotalReview(i int64) { + if m.addtotal_review != nil { + *m.addtotal_review += i + } else { + m.addtotal_review = &i + } +} + +// AddedTotalReview returns the value that was added to the "total_review" field in this mutation. +func (m *NodeMutation) AddedTotalReview() (r int64, exists bool) { + v := m.addtotal_review + if v == nil { + return + } + return *v, true +} + +// ResetTotalReview resets all changes to the "total_review" field. +func (m *NodeMutation) ResetTotalReview() { + m.total_review = nil + m.addtotal_review = nil +} + // ClearPublisher clears the "publisher" edge to the Publisher entity. func (m *NodeMutation) ClearPublisher() { m.clearedpublisher = true @@ -2720,6 +2899,60 @@ func (m *NodeMutation) ResetVersions() { m.removedversions = nil } +// AddReviewIDs adds the "reviews" edge to the NodeReview entity by ids. +func (m *NodeMutation) AddReviewIDs(ids ...uuid.UUID) { + if m.reviews == nil { + m.reviews = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.reviews[ids[i]] = struct{}{} + } +} + +// ClearReviews clears the "reviews" edge to the NodeReview entity. +func (m *NodeMutation) ClearReviews() { + m.clearedreviews = true +} + +// ReviewsCleared reports if the "reviews" edge to the NodeReview entity was cleared. +func (m *NodeMutation) ReviewsCleared() bool { + return m.clearedreviews +} + +// RemoveReviewIDs removes the "reviews" edge to the NodeReview entity by IDs. +func (m *NodeMutation) RemoveReviewIDs(ids ...uuid.UUID) { + if m.removedreviews == nil { + m.removedreviews = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.reviews, ids[i]) + m.removedreviews[ids[i]] = struct{}{} + } +} + +// RemovedReviews returns the removed IDs of the "reviews" edge to the NodeReview entity. +func (m *NodeMutation) RemovedReviewsIDs() (ids []uuid.UUID) { + for id := range m.removedreviews { + ids = append(ids, id) + } + return +} + +// ReviewsIDs returns the "reviews" edge IDs in the mutation. +func (m *NodeMutation) ReviewsIDs() (ids []uuid.UUID) { + for id := range m.reviews { + ids = append(ids, id) + } + return +} + +// ResetReviews resets all changes to the "reviews" edge. +func (m *NodeMutation) ResetReviews() { + m.reviews = nil + m.clearedreviews = false + m.removedreviews = nil +} + // Where appends a list predicates to the NodeMutation builder. func (m *NodeMutation) Where(ps ...predicate.Node) { m.predicates = append(m.predicates, ps...) @@ -2754,7 +2987,7 @@ func (m *NodeMutation) Type() string { // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *NodeMutation) Fields() []string { - fields := make([]string, 0, 10) + fields := make([]string, 0, 13) if m.create_time != nil { fields = append(fields, node.FieldCreateTime) } @@ -2785,6 +3018,15 @@ func (m *NodeMutation) Fields() []string { if m.tags != nil { fields = append(fields, node.FieldTags) } + if m.total_install != nil { + fields = append(fields, node.FieldTotalInstall) + } + if m.total_star != nil { + fields = append(fields, node.FieldTotalStar) + } + if m.total_review != nil { + fields = append(fields, node.FieldTotalReview) + } return fields } @@ -2813,6 +3055,12 @@ func (m *NodeMutation) Field(name string) (ent.Value, bool) { return m.IconURL() case node.FieldTags: return m.Tags() + case node.FieldTotalInstall: + return m.TotalInstall() + case node.FieldTotalStar: + return m.TotalStar() + case node.FieldTotalReview: + return m.TotalReview() } return nil, false } @@ -2842,289 +3090,966 @@ func (m *NodeMutation) OldField(ctx context.Context, name string) (ent.Value, er return m.OldIconURL(ctx) case node.FieldTags: return m.OldTags(ctx) + case node.FieldTotalInstall: + return m.OldTotalInstall(ctx) + case node.FieldTotalStar: + return m.OldTotalStar(ctx) + case node.FieldTotalReview: + return m.OldTotalReview(ctx) + } + return nil, fmt.Errorf("unknown Node field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *NodeMutation) SetField(name string, value ent.Value) error { + switch name { + case node.FieldCreateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreateTime(v) + return nil + case node.FieldUpdateTime: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdateTime(v) + return nil + case node.FieldPublisherID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPublisherID(v) + return nil + case node.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case node.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case node.FieldAuthor: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAuthor(v) + return nil + case node.FieldLicense: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLicense(v) + return nil + case node.FieldRepositoryURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRepositoryURL(v) + return nil + case node.FieldIconURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIconURL(v) + return nil + case node.FieldTags: + v, ok := value.([]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTags(v) + return nil + case node.FieldTotalInstall: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotalInstall(v) + return nil + case node.FieldTotalStar: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotalStar(v) + return nil + case node.FieldTotalReview: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTotalReview(v) + return nil + } + return fmt.Errorf("unknown Node field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *NodeMutation) AddedFields() []string { + var fields []string + if m.addtotal_install != nil { + fields = append(fields, node.FieldTotalInstall) + } + if m.addtotal_star != nil { + fields = append(fields, node.FieldTotalStar) + } + if m.addtotal_review != nil { + fields = append(fields, node.FieldTotalReview) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *NodeMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case node.FieldTotalInstall: + return m.AddedTotalInstall() + case node.FieldTotalStar: + return m.AddedTotalStar() + case node.FieldTotalReview: + return m.AddedTotalReview() + } + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *NodeMutation) AddField(name string, value ent.Value) error { + switch name { + case node.FieldTotalInstall: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTotalInstall(v) + return nil + case node.FieldTotalStar: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTotalStar(v) + return nil + case node.FieldTotalReview: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTotalReview(v) + return nil + } + return fmt.Errorf("unknown Node numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *NodeMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(node.FieldDescription) { + fields = append(fields, node.FieldDescription) + } + if m.FieldCleared(node.FieldAuthor) { + fields = append(fields, node.FieldAuthor) + } + if m.FieldCleared(node.FieldIconURL) { + fields = append(fields, node.FieldIconURL) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *NodeMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *NodeMutation) ClearField(name string) error { + switch name { + case node.FieldDescription: + m.ClearDescription() + return nil + case node.FieldAuthor: + m.ClearAuthor() + return nil + case node.FieldIconURL: + m.ClearIconURL() + return nil + } + return fmt.Errorf("unknown Node nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *NodeMutation) ResetField(name string) error { + switch name { + case node.FieldCreateTime: + m.ResetCreateTime() + return nil + case node.FieldUpdateTime: + m.ResetUpdateTime() + return nil + case node.FieldPublisherID: + m.ResetPublisherID() + return nil + case node.FieldName: + m.ResetName() + return nil + case node.FieldDescription: + m.ResetDescription() + return nil + case node.FieldAuthor: + m.ResetAuthor() + return nil + case node.FieldLicense: + m.ResetLicense() + return nil + case node.FieldRepositoryURL: + m.ResetRepositoryURL() + return nil + case node.FieldIconURL: + m.ResetIconURL() + return nil + case node.FieldTags: + m.ResetTags() + return nil + case node.FieldTotalInstall: + m.ResetTotalInstall() + return nil + case node.FieldTotalStar: + m.ResetTotalStar() + return nil + case node.FieldTotalReview: + m.ResetTotalReview() + return nil + } + return fmt.Errorf("unknown Node field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *NodeMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.publisher != nil { + edges = append(edges, node.EdgePublisher) + } + if m.versions != nil { + edges = append(edges, node.EdgeVersions) + } + if m.reviews != nil { + edges = append(edges, node.EdgeReviews) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *NodeMutation) AddedIDs(name string) []ent.Value { + switch name { + case node.EdgePublisher: + if id := m.publisher; id != nil { + return []ent.Value{*id} + } + case node.EdgeVersions: + ids := make([]ent.Value, 0, len(m.versions)) + for id := range m.versions { + ids = append(ids, id) + } + return ids + case node.EdgeReviews: + ids := make([]ent.Value, 0, len(m.reviews)) + for id := range m.reviews { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *NodeMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedversions != nil { + edges = append(edges, node.EdgeVersions) + } + if m.removedreviews != nil { + edges = append(edges, node.EdgeReviews) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *NodeMutation) RemovedIDs(name string) []ent.Value { + switch name { + case node.EdgeVersions: + ids := make([]ent.Value, 0, len(m.removedversions)) + for id := range m.removedversions { + ids = append(ids, id) + } + return ids + case node.EdgeReviews: + ids := make([]ent.Value, 0, len(m.removedreviews)) + for id := range m.removedreviews { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *NodeMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedpublisher { + edges = append(edges, node.EdgePublisher) + } + if m.clearedversions { + edges = append(edges, node.EdgeVersions) + } + if m.clearedreviews { + edges = append(edges, node.EdgeReviews) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *NodeMutation) EdgeCleared(name string) bool { + switch name { + case node.EdgePublisher: + return m.clearedpublisher + case node.EdgeVersions: + return m.clearedversions + case node.EdgeReviews: + return m.clearedreviews + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *NodeMutation) ClearEdge(name string) error { + switch name { + case node.EdgePublisher: + m.ClearPublisher() + return nil + } + return fmt.Errorf("unknown Node unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *NodeMutation) ResetEdge(name string) error { + switch name { + case node.EdgePublisher: + m.ResetPublisher() + return nil + case node.EdgeVersions: + m.ResetVersions() + return nil + case node.EdgeReviews: + m.ResetReviews() + return nil + } + return fmt.Errorf("unknown Node edge %s", name) +} + +// NodeReviewMutation represents an operation that mutates the NodeReview nodes in the graph. +type NodeReviewMutation struct { + config + op Op + typ string + id *uuid.UUID + star *int + addstar *int + clearedFields map[string]struct{} + user *string + cleareduser bool + node *string + clearednode bool + done bool + oldValue func(context.Context) (*NodeReview, error) + predicates []predicate.NodeReview +} + +var _ ent.Mutation = (*NodeReviewMutation)(nil) + +// nodereviewOption allows management of the mutation configuration using functional options. +type nodereviewOption func(*NodeReviewMutation) + +// newNodeReviewMutation creates new mutation for the NodeReview entity. +func newNodeReviewMutation(c config, op Op, opts ...nodereviewOption) *NodeReviewMutation { + m := &NodeReviewMutation{ + config: c, + op: op, + typ: TypeNodeReview, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withNodeReviewID sets the ID field of the mutation. +func withNodeReviewID(id uuid.UUID) nodereviewOption { + return func(m *NodeReviewMutation) { + var ( + err error + once sync.Once + value *NodeReview + ) + m.oldValue = func(ctx context.Context) (*NodeReview, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().NodeReview.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withNodeReview sets the old NodeReview of the mutation. +func withNodeReview(node *NodeReview) nodereviewOption { + return func(m *NodeReviewMutation) { + m.oldValue = func(context.Context) (*NodeReview, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m NodeReviewMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m NodeReviewMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of NodeReview entities. +func (m *NodeReviewMutation) SetID(id uuid.UUID) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *NodeReviewMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *NodeReviewMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().NodeReview.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetNodeID sets the "node_id" field. +func (m *NodeReviewMutation) SetNodeID(s string) { + m.node = &s +} + +// NodeID returns the value of the "node_id" field in the mutation. +func (m *NodeReviewMutation) NodeID() (r string, exists bool) { + v := m.node + if v == nil { + return + } + return *v, true +} + +// OldNodeID returns the old "node_id" field's value of the NodeReview entity. +// If the NodeReview 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 *NodeReviewMutation) OldNodeID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldNodeID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldNodeID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldNodeID: %w", err) + } + return oldValue.NodeID, nil +} + +// ResetNodeID resets all changes to the "node_id" field. +func (m *NodeReviewMutation) ResetNodeID() { + m.node = nil +} + +// SetUserID sets the "user_id" field. +func (m *NodeReviewMutation) SetUserID(s string) { + m.user = &s +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *NodeReviewMutation) UserID() (r string, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the NodeReview entity. +// If the NodeReview 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 *NodeReviewMutation) OldUserID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *NodeReviewMutation) ResetUserID() { + m.user = nil +} + +// SetStar sets the "star" field. +func (m *NodeReviewMutation) SetStar(i int) { + m.star = &i + m.addstar = nil +} + +// Star returns the value of the "star" field in the mutation. +func (m *NodeReviewMutation) Star() (r int, exists bool) { + v := m.star + if v == nil { + return + } + return *v, true +} + +// OldStar returns the old "star" field's value of the NodeReview entity. +// If the NodeReview 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 *NodeReviewMutation) OldStar(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStar is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStar requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStar: %w", err) + } + return oldValue.Star, nil +} + +// AddStar adds i to the "star" field. +func (m *NodeReviewMutation) AddStar(i int) { + if m.addstar != nil { + *m.addstar += i + } else { + m.addstar = &i + } +} + +// AddedStar returns the value that was added to the "star" field in this mutation. +func (m *NodeReviewMutation) AddedStar() (r int, exists bool) { + v := m.addstar + if v == nil { + return + } + return *v, true +} + +// ResetStar resets all changes to the "star" field. +func (m *NodeReviewMutation) ResetStar() { + m.star = nil + m.addstar = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *NodeReviewMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[nodereview.FieldUserID] = struct{}{} +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *NodeReviewMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *NodeReviewMutation) UserIDs() (ids []string) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *NodeReviewMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearNode clears the "node" edge to the Node entity. +func (m *NodeReviewMutation) ClearNode() { + m.clearednode = true + m.clearedFields[nodereview.FieldNodeID] = struct{}{} +} + +// NodeCleared reports if the "node" edge to the Node entity was cleared. +func (m *NodeReviewMutation) NodeCleared() bool { + return m.clearednode +} + +// NodeIDs returns the "node" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// NodeID instead. It exists only for internal usage by the builders. +func (m *NodeReviewMutation) NodeIDs() (ids []string) { + if id := m.node; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetNode resets all changes to the "node" edge. +func (m *NodeReviewMutation) ResetNode() { + m.node = nil + m.clearednode = false +} + +// Where appends a list predicates to the NodeReviewMutation builder. +func (m *NodeReviewMutation) Where(ps ...predicate.NodeReview) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the NodeReviewMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *NodeReviewMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.NodeReview, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *NodeReviewMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *NodeReviewMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (NodeReview). +func (m *NodeReviewMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *NodeReviewMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.node != nil { + fields = append(fields, nodereview.FieldNodeID) + } + if m.user != nil { + fields = append(fields, nodereview.FieldUserID) } - return nil, fmt.Errorf("unknown Node field %s", name) + if m.star != nil { + fields = append(fields, nodereview.FieldStar) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *NodeReviewMutation) Field(name string) (ent.Value, bool) { + switch name { + case nodereview.FieldNodeID: + return m.NodeID() + case nodereview.FieldUserID: + return m.UserID() + case nodereview.FieldStar: + return m.Star() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *NodeReviewMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case nodereview.FieldNodeID: + return m.OldNodeID(ctx) + case nodereview.FieldUserID: + return m.OldUserID(ctx) + case nodereview.FieldStar: + return m.OldStar(ctx) + } + return nil, fmt.Errorf("unknown NodeReview field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *NodeMutation) SetField(name string, value ent.Value) error { +func (m *NodeReviewMutation) SetField(name string, value ent.Value) error { switch name { - case node.FieldCreateTime: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreateTime(v) - return nil - case node.FieldUpdateTime: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdateTime(v) - return nil - case node.FieldPublisherID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPublisherID(v) - return nil - case node.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case node.FieldDescription: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDescription(v) - return nil - case node.FieldAuthor: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAuthor(v) - return nil - case node.FieldLicense: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLicense(v) - return nil - case node.FieldRepositoryURL: + case nodereview.FieldNodeID: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetRepositoryURL(v) + m.SetNodeID(v) return nil - case node.FieldIconURL: + case nodereview.FieldUserID: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetIconURL(v) + m.SetUserID(v) return nil - case node.FieldTags: - v, ok := value.([]string) + case nodereview.FieldStar: + v, ok := value.(int) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetTags(v) + m.SetStar(v) return nil } - return fmt.Errorf("unknown Node field %s", name) + return fmt.Errorf("unknown NodeReview field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *NodeMutation) AddedFields() []string { - return nil +func (m *NodeReviewMutation) AddedFields() []string { + var fields []string + if m.addstar != nil { + fields = append(fields, nodereview.FieldStar) + } + return fields } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *NodeMutation) AddedField(name string) (ent.Value, bool) { +func (m *NodeReviewMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case nodereview.FieldStar: + return m.AddedStar() + } return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *NodeMutation) AddField(name string, value ent.Value) error { +func (m *NodeReviewMutation) AddField(name string, value ent.Value) error { switch name { + case nodereview.FieldStar: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddStar(v) + return nil } - return fmt.Errorf("unknown Node numeric field %s", name) + return fmt.Errorf("unknown NodeReview numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *NodeMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(node.FieldDescription) { - fields = append(fields, node.FieldDescription) - } - if m.FieldCleared(node.FieldAuthor) { - fields = append(fields, node.FieldAuthor) - } - if m.FieldCleared(node.FieldIconURL) { - fields = append(fields, node.FieldIconURL) - } - return fields +func (m *NodeReviewMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *NodeMutation) FieldCleared(name string) bool { +func (m *NodeReviewMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. -func (m *NodeMutation) ClearField(name string) error { - switch name { - case node.FieldDescription: - m.ClearDescription() - return nil - case node.FieldAuthor: - m.ClearAuthor() - return nil - case node.FieldIconURL: - m.ClearIconURL() - return nil - } - return fmt.Errorf("unknown Node nullable field %s", name) +func (m *NodeReviewMutation) ClearField(name string) error { + return fmt.Errorf("unknown NodeReview nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. -func (m *NodeMutation) ResetField(name string) error { +func (m *NodeReviewMutation) ResetField(name string) error { switch name { - case node.FieldCreateTime: - m.ResetCreateTime() - return nil - case node.FieldUpdateTime: - m.ResetUpdateTime() - return nil - case node.FieldPublisherID: - m.ResetPublisherID() - return nil - case node.FieldName: - m.ResetName() - return nil - case node.FieldDescription: - m.ResetDescription() - return nil - case node.FieldAuthor: - m.ResetAuthor() - return nil - case node.FieldLicense: - m.ResetLicense() - return nil - case node.FieldRepositoryURL: - m.ResetRepositoryURL() + case nodereview.FieldNodeID: + m.ResetNodeID() return nil - case node.FieldIconURL: - m.ResetIconURL() + case nodereview.FieldUserID: + m.ResetUserID() return nil - case node.FieldTags: - m.ResetTags() + case nodereview.FieldStar: + m.ResetStar() return nil } - return fmt.Errorf("unknown Node field %s", name) + return fmt.Errorf("unknown NodeReview field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *NodeMutation) AddedEdges() []string { +func (m *NodeReviewMutation) AddedEdges() []string { edges := make([]string, 0, 2) - if m.publisher != nil { - edges = append(edges, node.EdgePublisher) + if m.user != nil { + edges = append(edges, nodereview.EdgeUser) } - if m.versions != nil { - edges = append(edges, node.EdgeVersions) + if m.node != nil { + edges = append(edges, nodereview.EdgeNode) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *NodeMutation) AddedIDs(name string) []ent.Value { +func (m *NodeReviewMutation) AddedIDs(name string) []ent.Value { switch name { - case node.EdgePublisher: - if id := m.publisher; id != nil { + case nodereview.EdgeUser: + if id := m.user; id != nil { return []ent.Value{*id} } - case node.EdgeVersions: - ids := make([]ent.Value, 0, len(m.versions)) - for id := range m.versions { - ids = append(ids, id) + case nodereview.EdgeNode: + if id := m.node; id != nil { + return []ent.Value{*id} } - return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *NodeMutation) RemovedEdges() []string { +func (m *NodeReviewMutation) RemovedEdges() []string { edges := make([]string, 0, 2) - if m.removedversions != nil { - edges = append(edges, node.EdgeVersions) - } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *NodeMutation) RemovedIDs(name string) []ent.Value { - switch name { - case node.EdgeVersions: - ids := make([]ent.Value, 0, len(m.removedversions)) - for id := range m.removedversions { - ids = append(ids, id) - } - return ids - } +func (m *NodeReviewMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *NodeMutation) ClearedEdges() []string { +func (m *NodeReviewMutation) ClearedEdges() []string { edges := make([]string, 0, 2) - if m.clearedpublisher { - edges = append(edges, node.EdgePublisher) + if m.cleareduser { + edges = append(edges, nodereview.EdgeUser) } - if m.clearedversions { - edges = append(edges, node.EdgeVersions) + if m.clearednode { + edges = append(edges, nodereview.EdgeNode) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *NodeMutation) EdgeCleared(name string) bool { +func (m *NodeReviewMutation) EdgeCleared(name string) bool { switch name { - case node.EdgePublisher: - return m.clearedpublisher - case node.EdgeVersions: - return m.clearedversions + case nodereview.EdgeUser: + return m.cleareduser + case nodereview.EdgeNode: + return m.clearednode } return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. -func (m *NodeMutation) ClearEdge(name string) error { +func (m *NodeReviewMutation) ClearEdge(name string) error { switch name { - case node.EdgePublisher: - m.ClearPublisher() + case nodereview.EdgeUser: + m.ClearUser() + return nil + case nodereview.EdgeNode: + m.ClearNode() return nil } - return fmt.Errorf("unknown Node unique edge %s", name) + return fmt.Errorf("unknown NodeReview unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. -func (m *NodeMutation) ResetEdge(name string) error { +func (m *NodeReviewMutation) ResetEdge(name string) error { switch name { - case node.EdgePublisher: - m.ResetPublisher() + case nodereview.EdgeUser: + m.ResetUser() return nil - case node.EdgeVersions: - m.ResetVersions() + case nodereview.EdgeNode: + m.ResetNode() return nil } - return fmt.Errorf("unknown Node edge %s", name) + return fmt.Errorf("unknown NodeReview edge %s", name) } // NodeVersionMutation represents an operation that mutates the NodeVersion nodes in the graph. @@ -6904,6 +7829,9 @@ type UserMutation struct { publisher_permissions map[int]struct{} removedpublisher_permissions map[int]struct{} clearedpublisher_permissions bool + reviews map[uuid.UUID]struct{} + removedreviews map[uuid.UUID]struct{} + clearedreviews bool done bool oldValue func(context.Context) (*User, error) predicates []predicate.User @@ -7309,6 +8237,60 @@ func (m *UserMutation) ResetPublisherPermissions() { m.removedpublisher_permissions = nil } +// AddReviewIDs adds the "reviews" edge to the NodeReview entity by ids. +func (m *UserMutation) AddReviewIDs(ids ...uuid.UUID) { + if m.reviews == nil { + m.reviews = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.reviews[ids[i]] = struct{}{} + } +} + +// ClearReviews clears the "reviews" edge to the NodeReview entity. +func (m *UserMutation) ClearReviews() { + m.clearedreviews = true +} + +// ReviewsCleared reports if the "reviews" edge to the NodeReview entity was cleared. +func (m *UserMutation) ReviewsCleared() bool { + return m.clearedreviews +} + +// RemoveReviewIDs removes the "reviews" edge to the NodeReview entity by IDs. +func (m *UserMutation) RemoveReviewIDs(ids ...uuid.UUID) { + if m.removedreviews == nil { + m.removedreviews = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.reviews, ids[i]) + m.removedreviews[ids[i]] = struct{}{} + } +} + +// RemovedReviews returns the removed IDs of the "reviews" edge to the NodeReview entity. +func (m *UserMutation) RemovedReviewsIDs() (ids []uuid.UUID) { + for id := range m.removedreviews { + ids = append(ids, id) + } + return +} + +// ReviewsIDs returns the "reviews" edge IDs in the mutation. +func (m *UserMutation) ReviewsIDs() (ids []uuid.UUID) { + for id := range m.reviews { + ids = append(ids, id) + } + return +} + +// ResetReviews resets all changes to the "reviews" edge. +func (m *UserMutation) ResetReviews() { + m.reviews = nil + m.clearedreviews = false + m.removedreviews = nil +} + // Where appends a list predicates to the UserMutation builder. func (m *UserMutation) Where(ps ...predicate.User) { m.predicates = append(m.predicates, ps...) @@ -7542,10 +8524,13 @@ func (m *UserMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 2) if m.publisher_permissions != nil { edges = append(edges, user.EdgePublisherPermissions) } + if m.reviews != nil { + edges = append(edges, user.EdgeReviews) + } return edges } @@ -7559,16 +8544,25 @@ func (m *UserMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeReviews: + ids := make([]ent.Value, 0, len(m.reviews)) + for id := range m.reviews { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 2) if m.removedpublisher_permissions != nil { edges = append(edges, user.EdgePublisherPermissions) } + if m.removedreviews != nil { + edges = append(edges, user.EdgeReviews) + } return edges } @@ -7582,16 +8576,25 @@ func (m *UserMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case user.EdgeReviews: + ids := make([]ent.Value, 0, len(m.removedreviews)) + for id := range m.removedreviews { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) + edges := make([]string, 0, 2) if m.clearedpublisher_permissions { edges = append(edges, user.EdgePublisherPermissions) } + if m.clearedreviews { + edges = append(edges, user.EdgeReviews) + } return edges } @@ -7601,6 +8604,8 @@ func (m *UserMutation) EdgeCleared(name string) bool { switch name { case user.EdgePublisherPermissions: return m.clearedpublisher_permissions + case user.EdgeReviews: + return m.clearedreviews } return false } @@ -7620,6 +8625,9 @@ func (m *UserMutation) ResetEdge(name string) error { case user.EdgePublisherPermissions: m.ResetPublisherPermissions() return nil + case user.EdgeReviews: + m.ResetReviews() + return nil } return fmt.Errorf("unknown User edge %s", name) } diff --git a/ent/node.go b/ent/node.go index 00f0a94..ac85f60 100644 --- a/ent/node.go +++ b/ent/node.go @@ -39,6 +39,12 @@ type Node struct { IconURL string `json:"icon_url,omitempty"` // Tags holds the value of the "tags" field. Tags []string `json:"tags,omitempty"` + // TotalInstall holds the value of the "total_install" field. + TotalInstall int64 `json:"total_install,omitempty"` + // TotalStar holds the value of the "total_star" field. + TotalStar int64 `json:"total_star,omitempty"` + // TotalReview holds the value of the "total_review" field. + TotalReview int64 `json:"total_review,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the NodeQuery when eager-loading is set. Edges NodeEdges `json:"edges"` @@ -51,9 +57,11 @@ type NodeEdges struct { Publisher *Publisher `json:"publisher,omitempty"` // Versions holds the value of the versions edge. Versions []*NodeVersion `json:"versions,omitempty"` + // Reviews holds the value of the reviews edge. + Reviews []*NodeReview `json:"reviews,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 } // PublisherOrErr returns the Publisher value or an error if the edge @@ -76,6 +84,15 @@ func (e NodeEdges) VersionsOrErr() ([]*NodeVersion, error) { return nil, &NotLoadedError{edge: "versions"} } +// ReviewsOrErr returns the Reviews value or an error if the edge +// was not loaded in eager-loading. +func (e NodeEdges) ReviewsOrErr() ([]*NodeReview, error) { + if e.loadedTypes[2] { + return e.Reviews, nil + } + return nil, &NotLoadedError{edge: "reviews"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*Node) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -83,6 +100,8 @@ func (*Node) scanValues(columns []string) ([]any, error) { switch columns[i] { case node.FieldTags: values[i] = new([]byte) + case node.FieldTotalInstall, node.FieldTotalStar, node.FieldTotalReview: + values[i] = new(sql.NullInt64) case node.FieldID, node.FieldPublisherID, node.FieldName, node.FieldDescription, node.FieldAuthor, node.FieldLicense, node.FieldRepositoryURL, node.FieldIconURL: values[i] = new(sql.NullString) case node.FieldCreateTime, node.FieldUpdateTime: @@ -170,6 +189,24 @@ func (n *Node) assignValues(columns []string, values []any) error { return fmt.Errorf("unmarshal field tags: %w", err) } } + case node.FieldTotalInstall: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field total_install", values[i]) + } else if value.Valid { + n.TotalInstall = value.Int64 + } + case node.FieldTotalStar: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field total_star", values[i]) + } else if value.Valid { + n.TotalStar = value.Int64 + } + case node.FieldTotalReview: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field total_review", values[i]) + } else if value.Valid { + n.TotalReview = value.Int64 + } default: n.selectValues.Set(columns[i], values[i]) } @@ -193,6 +230,11 @@ func (n *Node) QueryVersions() *NodeVersionQuery { return NewNodeClient(n.config).QueryVersions(n) } +// QueryReviews queries the "reviews" edge of the Node entity. +func (n *Node) QueryReviews() *NodeReviewQuery { + return NewNodeClient(n.config).QueryReviews(n) +} + // Update returns a builder for updating this Node. // Note that you need to call Node.Unwrap() before calling this method if this Node // was returned from a transaction, and the transaction was committed or rolled back. @@ -245,6 +287,15 @@ func (n *Node) String() string { builder.WriteString(", ") builder.WriteString("tags=") builder.WriteString(fmt.Sprintf("%v", n.Tags)) + builder.WriteString(", ") + builder.WriteString("total_install=") + builder.WriteString(fmt.Sprintf("%v", n.TotalInstall)) + builder.WriteString(", ") + builder.WriteString("total_star=") + builder.WriteString(fmt.Sprintf("%v", n.TotalStar)) + builder.WriteString(", ") + builder.WriteString("total_review=") + builder.WriteString(fmt.Sprintf("%v", n.TotalReview)) builder.WriteByte(')') return builder.String() } diff --git a/ent/node/node.go b/ent/node/node.go index 2fe6325..e6f89bc 100644 --- a/ent/node/node.go +++ b/ent/node/node.go @@ -34,10 +34,18 @@ const ( FieldIconURL = "icon_url" // FieldTags holds the string denoting the tags field in the database. FieldTags = "tags" + // FieldTotalInstall holds the string denoting the total_install field in the database. + FieldTotalInstall = "total_install" + // FieldTotalStar holds the string denoting the total_star field in the database. + FieldTotalStar = "total_star" + // FieldTotalReview holds the string denoting the total_review field in the database. + FieldTotalReview = "total_review" // EdgePublisher holds the string denoting the publisher edge name in mutations. EdgePublisher = "publisher" // EdgeVersions holds the string denoting the versions edge name in mutations. EdgeVersions = "versions" + // EdgeReviews holds the string denoting the reviews edge name in mutations. + EdgeReviews = "reviews" // Table holds the table name of the node in the database. Table = "nodes" // PublisherTable is the table that holds the publisher relation/edge. @@ -54,6 +62,13 @@ const ( VersionsInverseTable = "node_versions" // VersionsColumn is the table column denoting the versions relation/edge. VersionsColumn = "node_id" + // ReviewsTable is the table that holds the reviews relation/edge. + ReviewsTable = "node_reviews" + // ReviewsInverseTable is the table name for the NodeReview entity. + // It exists in this package in order to avoid circular dependency with the "nodereview" package. + ReviewsInverseTable = "node_reviews" + // ReviewsColumn is the table column denoting the reviews relation/edge. + ReviewsColumn = "node_id" ) // Columns holds all SQL columns for node fields. @@ -69,6 +84,9 @@ var Columns = []string{ FieldRepositoryURL, FieldIconURL, FieldTags, + FieldTotalInstall, + FieldTotalStar, + FieldTotalReview, } // ValidColumn reports if the column name is valid (part of the table columns). @@ -90,6 +108,12 @@ var ( UpdateDefaultUpdateTime func() time.Time // DefaultTags holds the default value on creation for the "tags" field. DefaultTags []string + // DefaultTotalInstall holds the default value on creation for the "total_install" field. + DefaultTotalInstall int64 + // DefaultTotalStar holds the default value on creation for the "total_star" field. + DefaultTotalStar int64 + // DefaultTotalReview holds the default value on creation for the "total_review" field. + DefaultTotalReview int64 ) // OrderOption defines the ordering options for the Node queries. @@ -145,6 +169,21 @@ func ByIconURL(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldIconURL, opts...).ToFunc() } +// ByTotalInstall orders the results by the total_install field. +func ByTotalInstall(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTotalInstall, opts...).ToFunc() +} + +// ByTotalStar orders the results by the total_star field. +func ByTotalStar(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTotalStar, opts...).ToFunc() +} + +// ByTotalReview orders the results by the total_review field. +func ByTotalReview(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTotalReview, opts...).ToFunc() +} + // ByPublisherField orders the results by publisher field. func ByPublisherField(field string, opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -165,6 +204,20 @@ func ByVersions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newVersionsStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByReviewsCount orders the results by reviews count. +func ByReviewsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newReviewsStep(), opts...) + } +} + +// ByReviews orders the results by reviews terms. +func ByReviews(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReviewsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newPublisherStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -179,3 +232,10 @@ func newVersionsStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, VersionsTable, VersionsColumn), ) } +func newReviewsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ReviewsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReviewsTable, ReviewsColumn), + ) +} diff --git a/ent/node/where.go b/ent/node/where.go index 6260d08..4f16191 100644 --- a/ent/node/where.go +++ b/ent/node/where.go @@ -110,6 +110,21 @@ func IconURL(v string) predicate.Node { return predicate.Node(sql.FieldEQ(FieldIconURL, v)) } +// TotalInstall applies equality check predicate on the "total_install" field. It's identical to TotalInstallEQ. +func TotalInstall(v int64) predicate.Node { + return predicate.Node(sql.FieldEQ(FieldTotalInstall, v)) +} + +// TotalStar applies equality check predicate on the "total_star" field. It's identical to TotalStarEQ. +func TotalStar(v int64) predicate.Node { + return predicate.Node(sql.FieldEQ(FieldTotalStar, v)) +} + +// TotalReview applies equality check predicate on the "total_review" field. It's identical to TotalReviewEQ. +func TotalReview(v int64) predicate.Node { + return predicate.Node(sql.FieldEQ(FieldTotalReview, v)) +} + // CreateTimeEQ applies the EQ predicate on the "create_time" field. func CreateTimeEQ(v time.Time) predicate.Node { return predicate.Node(sql.FieldEQ(FieldCreateTime, v)) @@ -675,6 +690,126 @@ func IconURLContainsFold(v string) predicate.Node { return predicate.Node(sql.FieldContainsFold(FieldIconURL, v)) } +// TotalInstallEQ applies the EQ predicate on the "total_install" field. +func TotalInstallEQ(v int64) predicate.Node { + return predicate.Node(sql.FieldEQ(FieldTotalInstall, v)) +} + +// TotalInstallNEQ applies the NEQ predicate on the "total_install" field. +func TotalInstallNEQ(v int64) predicate.Node { + return predicate.Node(sql.FieldNEQ(FieldTotalInstall, v)) +} + +// TotalInstallIn applies the In predicate on the "total_install" field. +func TotalInstallIn(vs ...int64) predicate.Node { + return predicate.Node(sql.FieldIn(FieldTotalInstall, vs...)) +} + +// TotalInstallNotIn applies the NotIn predicate on the "total_install" field. +func TotalInstallNotIn(vs ...int64) predicate.Node { + return predicate.Node(sql.FieldNotIn(FieldTotalInstall, vs...)) +} + +// TotalInstallGT applies the GT predicate on the "total_install" field. +func TotalInstallGT(v int64) predicate.Node { + return predicate.Node(sql.FieldGT(FieldTotalInstall, v)) +} + +// TotalInstallGTE applies the GTE predicate on the "total_install" field. +func TotalInstallGTE(v int64) predicate.Node { + return predicate.Node(sql.FieldGTE(FieldTotalInstall, v)) +} + +// TotalInstallLT applies the LT predicate on the "total_install" field. +func TotalInstallLT(v int64) predicate.Node { + return predicate.Node(sql.FieldLT(FieldTotalInstall, v)) +} + +// TotalInstallLTE applies the LTE predicate on the "total_install" field. +func TotalInstallLTE(v int64) predicate.Node { + return predicate.Node(sql.FieldLTE(FieldTotalInstall, v)) +} + +// TotalStarEQ applies the EQ predicate on the "total_star" field. +func TotalStarEQ(v int64) predicate.Node { + return predicate.Node(sql.FieldEQ(FieldTotalStar, v)) +} + +// TotalStarNEQ applies the NEQ predicate on the "total_star" field. +func TotalStarNEQ(v int64) predicate.Node { + return predicate.Node(sql.FieldNEQ(FieldTotalStar, v)) +} + +// TotalStarIn applies the In predicate on the "total_star" field. +func TotalStarIn(vs ...int64) predicate.Node { + return predicate.Node(sql.FieldIn(FieldTotalStar, vs...)) +} + +// TotalStarNotIn applies the NotIn predicate on the "total_star" field. +func TotalStarNotIn(vs ...int64) predicate.Node { + return predicate.Node(sql.FieldNotIn(FieldTotalStar, vs...)) +} + +// TotalStarGT applies the GT predicate on the "total_star" field. +func TotalStarGT(v int64) predicate.Node { + return predicate.Node(sql.FieldGT(FieldTotalStar, v)) +} + +// TotalStarGTE applies the GTE predicate on the "total_star" field. +func TotalStarGTE(v int64) predicate.Node { + return predicate.Node(sql.FieldGTE(FieldTotalStar, v)) +} + +// TotalStarLT applies the LT predicate on the "total_star" field. +func TotalStarLT(v int64) predicate.Node { + return predicate.Node(sql.FieldLT(FieldTotalStar, v)) +} + +// TotalStarLTE applies the LTE predicate on the "total_star" field. +func TotalStarLTE(v int64) predicate.Node { + return predicate.Node(sql.FieldLTE(FieldTotalStar, v)) +} + +// TotalReviewEQ applies the EQ predicate on the "total_review" field. +func TotalReviewEQ(v int64) predicate.Node { + return predicate.Node(sql.FieldEQ(FieldTotalReview, v)) +} + +// TotalReviewNEQ applies the NEQ predicate on the "total_review" field. +func TotalReviewNEQ(v int64) predicate.Node { + return predicate.Node(sql.FieldNEQ(FieldTotalReview, v)) +} + +// TotalReviewIn applies the In predicate on the "total_review" field. +func TotalReviewIn(vs ...int64) predicate.Node { + return predicate.Node(sql.FieldIn(FieldTotalReview, vs...)) +} + +// TotalReviewNotIn applies the NotIn predicate on the "total_review" field. +func TotalReviewNotIn(vs ...int64) predicate.Node { + return predicate.Node(sql.FieldNotIn(FieldTotalReview, vs...)) +} + +// TotalReviewGT applies the GT predicate on the "total_review" field. +func TotalReviewGT(v int64) predicate.Node { + return predicate.Node(sql.FieldGT(FieldTotalReview, v)) +} + +// TotalReviewGTE applies the GTE predicate on the "total_review" field. +func TotalReviewGTE(v int64) predicate.Node { + return predicate.Node(sql.FieldGTE(FieldTotalReview, v)) +} + +// TotalReviewLT applies the LT predicate on the "total_review" field. +func TotalReviewLT(v int64) predicate.Node { + return predicate.Node(sql.FieldLT(FieldTotalReview, v)) +} + +// TotalReviewLTE applies the LTE predicate on the "total_review" field. +func TotalReviewLTE(v int64) predicate.Node { + return predicate.Node(sql.FieldLTE(FieldTotalReview, v)) +} + // HasPublisher applies the HasEdge predicate on the "publisher" edge. func HasPublisher() predicate.Node { return predicate.Node(func(s *sql.Selector) { @@ -721,6 +856,29 @@ func HasVersionsWith(preds ...predicate.NodeVersion) predicate.Node { }) } +// HasReviews applies the HasEdge predicate on the "reviews" edge. +func HasReviews() predicate.Node { + return predicate.Node(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReviewsTable, ReviewsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReviewsWith applies the HasEdge predicate on the "reviews" edge with a given conditions (other predicates). +func HasReviewsWith(preds ...predicate.NodeReview) predicate.Node { + return predicate.Node(func(s *sql.Selector) { + step := newReviewsStep() + 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.Node) predicate.Node { return predicate.Node(sql.AndPredicates(predicates...)) diff --git a/ent/node_create.go b/ent/node_create.go index e413ea8..b3daccd 100644 --- a/ent/node_create.go +++ b/ent/node_create.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "registry-backend/ent/node" + "registry-backend/ent/nodereview" "registry-backend/ent/nodeversion" "registry-backend/ent/publisher" "time" @@ -126,6 +127,48 @@ func (nc *NodeCreate) SetTags(s []string) *NodeCreate { return nc } +// SetTotalInstall sets the "total_install" field. +func (nc *NodeCreate) SetTotalInstall(i int64) *NodeCreate { + nc.mutation.SetTotalInstall(i) + return nc +} + +// SetNillableTotalInstall sets the "total_install" field if the given value is not nil. +func (nc *NodeCreate) SetNillableTotalInstall(i *int64) *NodeCreate { + if i != nil { + nc.SetTotalInstall(*i) + } + return nc +} + +// SetTotalStar sets the "total_star" field. +func (nc *NodeCreate) SetTotalStar(i int64) *NodeCreate { + nc.mutation.SetTotalStar(i) + return nc +} + +// SetNillableTotalStar sets the "total_star" field if the given value is not nil. +func (nc *NodeCreate) SetNillableTotalStar(i *int64) *NodeCreate { + if i != nil { + nc.SetTotalStar(*i) + } + return nc +} + +// SetTotalReview sets the "total_review" field. +func (nc *NodeCreate) SetTotalReview(i int64) *NodeCreate { + nc.mutation.SetTotalReview(i) + return nc +} + +// SetNillableTotalReview sets the "total_review" field if the given value is not nil. +func (nc *NodeCreate) SetNillableTotalReview(i *int64) *NodeCreate { + if i != nil { + nc.SetTotalReview(*i) + } + return nc +} + // SetID sets the "id" field. func (nc *NodeCreate) SetID(s string) *NodeCreate { nc.mutation.SetID(s) @@ -152,6 +195,21 @@ func (nc *NodeCreate) AddVersions(n ...*NodeVersion) *NodeCreate { return nc.AddVersionIDs(ids...) } +// AddReviewIDs adds the "reviews" edge to the NodeReview entity by IDs. +func (nc *NodeCreate) AddReviewIDs(ids ...uuid.UUID) *NodeCreate { + nc.mutation.AddReviewIDs(ids...) + return nc +} + +// AddReviews adds the "reviews" edges to the NodeReview entity. +func (nc *NodeCreate) AddReviews(n ...*NodeReview) *NodeCreate { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return nc.AddReviewIDs(ids...) +} + // Mutation returns the NodeMutation object of the builder. func (nc *NodeCreate) Mutation() *NodeMutation { return nc.mutation @@ -199,6 +257,18 @@ func (nc *NodeCreate) defaults() { v := node.DefaultTags nc.mutation.SetTags(v) } + if _, ok := nc.mutation.TotalInstall(); !ok { + v := node.DefaultTotalInstall + nc.mutation.SetTotalInstall(v) + } + if _, ok := nc.mutation.TotalStar(); !ok { + v := node.DefaultTotalStar + nc.mutation.SetTotalStar(v) + } + if _, ok := nc.mutation.TotalReview(); !ok { + v := node.DefaultTotalReview + nc.mutation.SetTotalReview(v) + } } // check runs all checks and user-defined validators on the builder. @@ -224,6 +294,15 @@ func (nc *NodeCreate) check() error { if _, ok := nc.mutation.Tags(); !ok { return &ValidationError{Name: "tags", err: errors.New(`ent: missing required field "Node.tags"`)} } + if _, ok := nc.mutation.TotalInstall(); !ok { + return &ValidationError{Name: "total_install", err: errors.New(`ent: missing required field "Node.total_install"`)} + } + if _, ok := nc.mutation.TotalStar(); !ok { + return &ValidationError{Name: "total_star", err: errors.New(`ent: missing required field "Node.total_star"`)} + } + if _, ok := nc.mutation.TotalReview(); !ok { + return &ValidationError{Name: "total_review", err: errors.New(`ent: missing required field "Node.total_review"`)} + } if _, ok := nc.mutation.PublisherID(); !ok { return &ValidationError{Name: "publisher", err: errors.New(`ent: missing required edge "Node.publisher"`)} } @@ -299,6 +378,18 @@ func (nc *NodeCreate) createSpec() (*Node, *sqlgraph.CreateSpec) { _spec.SetField(node.FieldTags, field.TypeJSON, value) _node.Tags = value } + if value, ok := nc.mutation.TotalInstall(); ok { + _spec.SetField(node.FieldTotalInstall, field.TypeInt64, value) + _node.TotalInstall = value + } + if value, ok := nc.mutation.TotalStar(); ok { + _spec.SetField(node.FieldTotalStar, field.TypeInt64, value) + _node.TotalStar = value + } + if value, ok := nc.mutation.TotalReview(); ok { + _spec.SetField(node.FieldTotalReview, field.TypeInt64, value) + _node.TotalReview = value + } if nodes := nc.mutation.PublisherIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -332,6 +423,22 @@ func (nc *NodeCreate) createSpec() (*Node, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := nc.mutation.ReviewsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: node.ReviewsTable, + Columns: []string{node.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } @@ -510,6 +617,60 @@ func (u *NodeUpsert) UpdateTags() *NodeUpsert { return u } +// SetTotalInstall sets the "total_install" field. +func (u *NodeUpsert) SetTotalInstall(v int64) *NodeUpsert { + u.Set(node.FieldTotalInstall, v) + return u +} + +// UpdateTotalInstall sets the "total_install" field to the value that was provided on create. +func (u *NodeUpsert) UpdateTotalInstall() *NodeUpsert { + u.SetExcluded(node.FieldTotalInstall) + return u +} + +// AddTotalInstall adds v to the "total_install" field. +func (u *NodeUpsert) AddTotalInstall(v int64) *NodeUpsert { + u.Add(node.FieldTotalInstall, v) + return u +} + +// SetTotalStar sets the "total_star" field. +func (u *NodeUpsert) SetTotalStar(v int64) *NodeUpsert { + u.Set(node.FieldTotalStar, v) + return u +} + +// UpdateTotalStar sets the "total_star" field to the value that was provided on create. +func (u *NodeUpsert) UpdateTotalStar() *NodeUpsert { + u.SetExcluded(node.FieldTotalStar) + return u +} + +// AddTotalStar adds v to the "total_star" field. +func (u *NodeUpsert) AddTotalStar(v int64) *NodeUpsert { + u.Add(node.FieldTotalStar, v) + return u +} + +// SetTotalReview sets the "total_review" field. +func (u *NodeUpsert) SetTotalReview(v int64) *NodeUpsert { + u.Set(node.FieldTotalReview, v) + return u +} + +// UpdateTotalReview sets the "total_review" field to the value that was provided on create. +func (u *NodeUpsert) UpdateTotalReview() *NodeUpsert { + u.SetExcluded(node.FieldTotalReview) + return u +} + +// AddTotalReview adds v to the "total_review" field. +func (u *NodeUpsert) AddTotalReview(v int64) *NodeUpsert { + u.Add(node.FieldTotalReview, v) + return u +} + // UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. // Using this option is equivalent to using: // @@ -708,6 +869,69 @@ func (u *NodeUpsertOne) UpdateTags() *NodeUpsertOne { }) } +// SetTotalInstall sets the "total_install" field. +func (u *NodeUpsertOne) SetTotalInstall(v int64) *NodeUpsertOne { + return u.Update(func(s *NodeUpsert) { + s.SetTotalInstall(v) + }) +} + +// AddTotalInstall adds v to the "total_install" field. +func (u *NodeUpsertOne) AddTotalInstall(v int64) *NodeUpsertOne { + return u.Update(func(s *NodeUpsert) { + s.AddTotalInstall(v) + }) +} + +// UpdateTotalInstall sets the "total_install" field to the value that was provided on create. +func (u *NodeUpsertOne) UpdateTotalInstall() *NodeUpsertOne { + return u.Update(func(s *NodeUpsert) { + s.UpdateTotalInstall() + }) +} + +// SetTotalStar sets the "total_star" field. +func (u *NodeUpsertOne) SetTotalStar(v int64) *NodeUpsertOne { + return u.Update(func(s *NodeUpsert) { + s.SetTotalStar(v) + }) +} + +// AddTotalStar adds v to the "total_star" field. +func (u *NodeUpsertOne) AddTotalStar(v int64) *NodeUpsertOne { + return u.Update(func(s *NodeUpsert) { + s.AddTotalStar(v) + }) +} + +// UpdateTotalStar sets the "total_star" field to the value that was provided on create. +func (u *NodeUpsertOne) UpdateTotalStar() *NodeUpsertOne { + return u.Update(func(s *NodeUpsert) { + s.UpdateTotalStar() + }) +} + +// SetTotalReview sets the "total_review" field. +func (u *NodeUpsertOne) SetTotalReview(v int64) *NodeUpsertOne { + return u.Update(func(s *NodeUpsert) { + s.SetTotalReview(v) + }) +} + +// AddTotalReview adds v to the "total_review" field. +func (u *NodeUpsertOne) AddTotalReview(v int64) *NodeUpsertOne { + return u.Update(func(s *NodeUpsert) { + s.AddTotalReview(v) + }) +} + +// UpdateTotalReview sets the "total_review" field to the value that was provided on create. +func (u *NodeUpsertOne) UpdateTotalReview() *NodeUpsertOne { + return u.Update(func(s *NodeUpsert) { + s.UpdateTotalReview() + }) +} + // Exec executes the query. func (u *NodeUpsertOne) Exec(ctx context.Context) error { if len(u.create.conflict) == 0 { @@ -1073,6 +1297,69 @@ func (u *NodeUpsertBulk) UpdateTags() *NodeUpsertBulk { }) } +// SetTotalInstall sets the "total_install" field. +func (u *NodeUpsertBulk) SetTotalInstall(v int64) *NodeUpsertBulk { + return u.Update(func(s *NodeUpsert) { + s.SetTotalInstall(v) + }) +} + +// AddTotalInstall adds v to the "total_install" field. +func (u *NodeUpsertBulk) AddTotalInstall(v int64) *NodeUpsertBulk { + return u.Update(func(s *NodeUpsert) { + s.AddTotalInstall(v) + }) +} + +// UpdateTotalInstall sets the "total_install" field to the value that was provided on create. +func (u *NodeUpsertBulk) UpdateTotalInstall() *NodeUpsertBulk { + return u.Update(func(s *NodeUpsert) { + s.UpdateTotalInstall() + }) +} + +// SetTotalStar sets the "total_star" field. +func (u *NodeUpsertBulk) SetTotalStar(v int64) *NodeUpsertBulk { + return u.Update(func(s *NodeUpsert) { + s.SetTotalStar(v) + }) +} + +// AddTotalStar adds v to the "total_star" field. +func (u *NodeUpsertBulk) AddTotalStar(v int64) *NodeUpsertBulk { + return u.Update(func(s *NodeUpsert) { + s.AddTotalStar(v) + }) +} + +// UpdateTotalStar sets the "total_star" field to the value that was provided on create. +func (u *NodeUpsertBulk) UpdateTotalStar() *NodeUpsertBulk { + return u.Update(func(s *NodeUpsert) { + s.UpdateTotalStar() + }) +} + +// SetTotalReview sets the "total_review" field. +func (u *NodeUpsertBulk) SetTotalReview(v int64) *NodeUpsertBulk { + return u.Update(func(s *NodeUpsert) { + s.SetTotalReview(v) + }) +} + +// AddTotalReview adds v to the "total_review" field. +func (u *NodeUpsertBulk) AddTotalReview(v int64) *NodeUpsertBulk { + return u.Update(func(s *NodeUpsert) { + s.AddTotalReview(v) + }) +} + +// UpdateTotalReview sets the "total_review" field to the value that was provided on create. +func (u *NodeUpsertBulk) UpdateTotalReview() *NodeUpsertBulk { + return u.Update(func(s *NodeUpsert) { + s.UpdateTotalReview() + }) +} + // Exec executes the query. func (u *NodeUpsertBulk) Exec(ctx context.Context) error { if u.create.err != nil { diff --git a/ent/node_query.go b/ent/node_query.go index 89eec59..3084a62 100644 --- a/ent/node_query.go +++ b/ent/node_query.go @@ -8,6 +8,7 @@ import ( "fmt" "math" "registry-backend/ent/node" + "registry-backend/ent/nodereview" "registry-backend/ent/nodeversion" "registry-backend/ent/predicate" "registry-backend/ent/publisher" @@ -27,6 +28,7 @@ type NodeQuery struct { predicates []predicate.Node withPublisher *PublisherQuery withVersions *NodeVersionQuery + withReviews *NodeReviewQuery modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -108,6 +110,28 @@ func (nq *NodeQuery) QueryVersions() *NodeVersionQuery { return query } +// QueryReviews chains the current query on the "reviews" edge. +func (nq *NodeQuery) QueryReviews() *NodeReviewQuery { + query := (&NodeReviewClient{config: nq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := nq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := nq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(node.Table, node.FieldID, selector), + sqlgraph.To(nodereview.Table, nodereview.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, node.ReviewsTable, node.ReviewsColumn), + ) + fromU = sqlgraph.SetNeighbors(nq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first Node entity from the query. // Returns a *NotFoundError when no Node was found. func (nq *NodeQuery) First(ctx context.Context) (*Node, error) { @@ -302,6 +326,7 @@ func (nq *NodeQuery) Clone() *NodeQuery { predicates: append([]predicate.Node{}, nq.predicates...), withPublisher: nq.withPublisher.Clone(), withVersions: nq.withVersions.Clone(), + withReviews: nq.withReviews.Clone(), // clone intermediate query. sql: nq.sql.Clone(), path: nq.path, @@ -330,6 +355,17 @@ func (nq *NodeQuery) WithVersions(opts ...func(*NodeVersionQuery)) *NodeQuery { return nq } +// WithReviews tells the query-builder to eager-load the nodes that are connected to +// the "reviews" edge. The optional arguments are used to configure the query builder of the edge. +func (nq *NodeQuery) WithReviews(opts ...func(*NodeReviewQuery)) *NodeQuery { + query := (&NodeReviewClient{config: nq.config}).Query() + for _, opt := range opts { + opt(query) + } + nq.withReviews = query + return nq +} + // 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. // @@ -408,9 +444,10 @@ func (nq *NodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Node, e var ( nodes = []*Node{} _spec = nq.querySpec() - loadedTypes = [2]bool{ + loadedTypes = [3]bool{ nq.withPublisher != nil, nq.withVersions != nil, + nq.withReviews != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -447,6 +484,13 @@ func (nq *NodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Node, e return nil, err } } + if query := nq.withReviews; query != nil { + if err := nq.loadReviews(ctx, query, nodes, + func(n *Node) { n.Edges.Reviews = []*NodeReview{} }, + func(n *Node, e *NodeReview) { n.Edges.Reviews = append(n.Edges.Reviews, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -510,6 +554,36 @@ func (nq *NodeQuery) loadVersions(ctx context.Context, query *NodeVersionQuery, } return nil } +func (nq *NodeQuery) loadReviews(ctx context.Context, query *NodeReviewQuery, nodes []*Node, init func(*Node), assign func(*Node, *NodeReview)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Node) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(nodereview.FieldNodeID) + } + query.Where(predicate.NodeReview(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(node.ReviewsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.NodeID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "node_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (nq *NodeQuery) sqlCount(ctx context.Context) (int, error) { _spec := nq.querySpec() diff --git a/ent/node_update.go b/ent/node_update.go index 9fb6016..bfbc7a9 100644 --- a/ent/node_update.go +++ b/ent/node_update.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "registry-backend/ent/node" + "registry-backend/ent/nodereview" "registry-backend/ent/nodeversion" "registry-backend/ent/predicate" "registry-backend/ent/publisher" @@ -166,6 +167,69 @@ func (nu *NodeUpdate) AppendTags(s []string) *NodeUpdate { return nu } +// SetTotalInstall sets the "total_install" field. +func (nu *NodeUpdate) SetTotalInstall(i int64) *NodeUpdate { + nu.mutation.ResetTotalInstall() + nu.mutation.SetTotalInstall(i) + return nu +} + +// SetNillableTotalInstall sets the "total_install" field if the given value is not nil. +func (nu *NodeUpdate) SetNillableTotalInstall(i *int64) *NodeUpdate { + if i != nil { + nu.SetTotalInstall(*i) + } + return nu +} + +// AddTotalInstall adds i to the "total_install" field. +func (nu *NodeUpdate) AddTotalInstall(i int64) *NodeUpdate { + nu.mutation.AddTotalInstall(i) + return nu +} + +// SetTotalStar sets the "total_star" field. +func (nu *NodeUpdate) SetTotalStar(i int64) *NodeUpdate { + nu.mutation.ResetTotalStar() + nu.mutation.SetTotalStar(i) + return nu +} + +// SetNillableTotalStar sets the "total_star" field if the given value is not nil. +func (nu *NodeUpdate) SetNillableTotalStar(i *int64) *NodeUpdate { + if i != nil { + nu.SetTotalStar(*i) + } + return nu +} + +// AddTotalStar adds i to the "total_star" field. +func (nu *NodeUpdate) AddTotalStar(i int64) *NodeUpdate { + nu.mutation.AddTotalStar(i) + return nu +} + +// SetTotalReview sets the "total_review" field. +func (nu *NodeUpdate) SetTotalReview(i int64) *NodeUpdate { + nu.mutation.ResetTotalReview() + nu.mutation.SetTotalReview(i) + return nu +} + +// SetNillableTotalReview sets the "total_review" field if the given value is not nil. +func (nu *NodeUpdate) SetNillableTotalReview(i *int64) *NodeUpdate { + if i != nil { + nu.SetTotalReview(*i) + } + return nu +} + +// AddTotalReview adds i to the "total_review" field. +func (nu *NodeUpdate) AddTotalReview(i int64) *NodeUpdate { + nu.mutation.AddTotalReview(i) + return nu +} + // SetPublisher sets the "publisher" edge to the Publisher entity. func (nu *NodeUpdate) SetPublisher(p *Publisher) *NodeUpdate { return nu.SetPublisherID(p.ID) @@ -186,6 +250,21 @@ func (nu *NodeUpdate) AddVersions(n ...*NodeVersion) *NodeUpdate { return nu.AddVersionIDs(ids...) } +// AddReviewIDs adds the "reviews" edge to the NodeReview entity by IDs. +func (nu *NodeUpdate) AddReviewIDs(ids ...uuid.UUID) *NodeUpdate { + nu.mutation.AddReviewIDs(ids...) + return nu +} + +// AddReviews adds the "reviews" edges to the NodeReview entity. +func (nu *NodeUpdate) AddReviews(n ...*NodeReview) *NodeUpdate { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return nu.AddReviewIDs(ids...) +} + // Mutation returns the NodeMutation object of the builder. func (nu *NodeUpdate) Mutation() *NodeMutation { return nu.mutation @@ -218,6 +297,27 @@ func (nu *NodeUpdate) RemoveVersions(n ...*NodeVersion) *NodeUpdate { return nu.RemoveVersionIDs(ids...) } +// ClearReviews clears all "reviews" edges to the NodeReview entity. +func (nu *NodeUpdate) ClearReviews() *NodeUpdate { + nu.mutation.ClearReviews() + return nu +} + +// RemoveReviewIDs removes the "reviews" edge to NodeReview entities by IDs. +func (nu *NodeUpdate) RemoveReviewIDs(ids ...uuid.UUID) *NodeUpdate { + nu.mutation.RemoveReviewIDs(ids...) + return nu +} + +// RemoveReviews removes "reviews" edges to NodeReview entities. +func (nu *NodeUpdate) RemoveReviews(n ...*NodeReview) *NodeUpdate { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return nu.RemoveReviewIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (nu *NodeUpdate) Save(ctx context.Context) (int, error) { nu.defaults() @@ -312,6 +412,24 @@ func (nu *NodeUpdate) sqlSave(ctx context.Context) (n int, err error) { sqljson.Append(u, node.FieldTags, value) }) } + if value, ok := nu.mutation.TotalInstall(); ok { + _spec.SetField(node.FieldTotalInstall, field.TypeInt64, value) + } + if value, ok := nu.mutation.AddedTotalInstall(); ok { + _spec.AddField(node.FieldTotalInstall, field.TypeInt64, value) + } + if value, ok := nu.mutation.TotalStar(); ok { + _spec.SetField(node.FieldTotalStar, field.TypeInt64, value) + } + if value, ok := nu.mutation.AddedTotalStar(); ok { + _spec.AddField(node.FieldTotalStar, field.TypeInt64, value) + } + if value, ok := nu.mutation.TotalReview(); ok { + _spec.SetField(node.FieldTotalReview, field.TypeInt64, value) + } + if value, ok := nu.mutation.AddedTotalReview(); ok { + _spec.AddField(node.FieldTotalReview, field.TypeInt64, value) + } if nu.mutation.PublisherCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -386,6 +504,51 @@ func (nu *NodeUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if nu.mutation.ReviewsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: node.ReviewsTable, + Columns: []string{node.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := nu.mutation.RemovedReviewsIDs(); len(nodes) > 0 && !nu.mutation.ReviewsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: node.ReviewsTable, + Columns: []string{node.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := nu.mutation.ReviewsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: node.ReviewsTable, + Columns: []string{node.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + 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, nu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{node.Label} @@ -540,6 +703,69 @@ func (nuo *NodeUpdateOne) AppendTags(s []string) *NodeUpdateOne { return nuo } +// SetTotalInstall sets the "total_install" field. +func (nuo *NodeUpdateOne) SetTotalInstall(i int64) *NodeUpdateOne { + nuo.mutation.ResetTotalInstall() + nuo.mutation.SetTotalInstall(i) + return nuo +} + +// SetNillableTotalInstall sets the "total_install" field if the given value is not nil. +func (nuo *NodeUpdateOne) SetNillableTotalInstall(i *int64) *NodeUpdateOne { + if i != nil { + nuo.SetTotalInstall(*i) + } + return nuo +} + +// AddTotalInstall adds i to the "total_install" field. +func (nuo *NodeUpdateOne) AddTotalInstall(i int64) *NodeUpdateOne { + nuo.mutation.AddTotalInstall(i) + return nuo +} + +// SetTotalStar sets the "total_star" field. +func (nuo *NodeUpdateOne) SetTotalStar(i int64) *NodeUpdateOne { + nuo.mutation.ResetTotalStar() + nuo.mutation.SetTotalStar(i) + return nuo +} + +// SetNillableTotalStar sets the "total_star" field if the given value is not nil. +func (nuo *NodeUpdateOne) SetNillableTotalStar(i *int64) *NodeUpdateOne { + if i != nil { + nuo.SetTotalStar(*i) + } + return nuo +} + +// AddTotalStar adds i to the "total_star" field. +func (nuo *NodeUpdateOne) AddTotalStar(i int64) *NodeUpdateOne { + nuo.mutation.AddTotalStar(i) + return nuo +} + +// SetTotalReview sets the "total_review" field. +func (nuo *NodeUpdateOne) SetTotalReview(i int64) *NodeUpdateOne { + nuo.mutation.ResetTotalReview() + nuo.mutation.SetTotalReview(i) + return nuo +} + +// SetNillableTotalReview sets the "total_review" field if the given value is not nil. +func (nuo *NodeUpdateOne) SetNillableTotalReview(i *int64) *NodeUpdateOne { + if i != nil { + nuo.SetTotalReview(*i) + } + return nuo +} + +// AddTotalReview adds i to the "total_review" field. +func (nuo *NodeUpdateOne) AddTotalReview(i int64) *NodeUpdateOne { + nuo.mutation.AddTotalReview(i) + return nuo +} + // SetPublisher sets the "publisher" edge to the Publisher entity. func (nuo *NodeUpdateOne) SetPublisher(p *Publisher) *NodeUpdateOne { return nuo.SetPublisherID(p.ID) @@ -560,6 +786,21 @@ func (nuo *NodeUpdateOne) AddVersions(n ...*NodeVersion) *NodeUpdateOne { return nuo.AddVersionIDs(ids...) } +// AddReviewIDs adds the "reviews" edge to the NodeReview entity by IDs. +func (nuo *NodeUpdateOne) AddReviewIDs(ids ...uuid.UUID) *NodeUpdateOne { + nuo.mutation.AddReviewIDs(ids...) + return nuo +} + +// AddReviews adds the "reviews" edges to the NodeReview entity. +func (nuo *NodeUpdateOne) AddReviews(n ...*NodeReview) *NodeUpdateOne { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return nuo.AddReviewIDs(ids...) +} + // Mutation returns the NodeMutation object of the builder. func (nuo *NodeUpdateOne) Mutation() *NodeMutation { return nuo.mutation @@ -592,6 +833,27 @@ func (nuo *NodeUpdateOne) RemoveVersions(n ...*NodeVersion) *NodeUpdateOne { return nuo.RemoveVersionIDs(ids...) } +// ClearReviews clears all "reviews" edges to the NodeReview entity. +func (nuo *NodeUpdateOne) ClearReviews() *NodeUpdateOne { + nuo.mutation.ClearReviews() + return nuo +} + +// RemoveReviewIDs removes the "reviews" edge to NodeReview entities by IDs. +func (nuo *NodeUpdateOne) RemoveReviewIDs(ids ...uuid.UUID) *NodeUpdateOne { + nuo.mutation.RemoveReviewIDs(ids...) + return nuo +} + +// RemoveReviews removes "reviews" edges to NodeReview entities. +func (nuo *NodeUpdateOne) RemoveReviews(n ...*NodeReview) *NodeUpdateOne { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return nuo.RemoveReviewIDs(ids...) +} + // Where appends a list predicates to the NodeUpdate builder. func (nuo *NodeUpdateOne) Where(ps ...predicate.Node) *NodeUpdateOne { nuo.mutation.Where(ps...) @@ -716,6 +978,24 @@ func (nuo *NodeUpdateOne) sqlSave(ctx context.Context) (_node *Node, err error) sqljson.Append(u, node.FieldTags, value) }) } + if value, ok := nuo.mutation.TotalInstall(); ok { + _spec.SetField(node.FieldTotalInstall, field.TypeInt64, value) + } + if value, ok := nuo.mutation.AddedTotalInstall(); ok { + _spec.AddField(node.FieldTotalInstall, field.TypeInt64, value) + } + if value, ok := nuo.mutation.TotalStar(); ok { + _spec.SetField(node.FieldTotalStar, field.TypeInt64, value) + } + if value, ok := nuo.mutation.AddedTotalStar(); ok { + _spec.AddField(node.FieldTotalStar, field.TypeInt64, value) + } + if value, ok := nuo.mutation.TotalReview(); ok { + _spec.SetField(node.FieldTotalReview, field.TypeInt64, value) + } + if value, ok := nuo.mutation.AddedTotalReview(); ok { + _spec.AddField(node.FieldTotalReview, field.TypeInt64, value) + } if nuo.mutation.PublisherCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2O, @@ -790,6 +1070,51 @@ func (nuo *NodeUpdateOne) sqlSave(ctx context.Context) (_node *Node, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if nuo.mutation.ReviewsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: node.ReviewsTable, + Columns: []string{node.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := nuo.mutation.RemovedReviewsIDs(); len(nodes) > 0 && !nuo.mutation.ReviewsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: node.ReviewsTable, + Columns: []string{node.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := nuo.mutation.ReviewsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: node.ReviewsTable, + Columns: []string{node.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &Node{config: nuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/ent/nodereview.go b/ent/nodereview.go new file mode 100644 index 0000000..b853dbd --- /dev/null +++ b/ent/nodereview.go @@ -0,0 +1,176 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "registry-backend/ent/node" + "registry-backend/ent/nodereview" + "registry-backend/ent/user" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" +) + +// NodeReview is the model entity for the NodeReview schema. +type NodeReview struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // NodeID holds the value of the "node_id" field. + NodeID string `json:"node_id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID string `json:"user_id,omitempty"` + // Star holds the value of the "star" field. + Star int `json:"star,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the NodeReviewQuery when eager-loading is set. + Edges NodeReviewEdges `json:"edges"` + selectValues sql.SelectValues +} + +// NodeReviewEdges holds the relations/edges for other nodes in the graph. +type NodeReviewEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // Node holds the value of the node edge. + Node *Node `json:"node,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e NodeReviewEdges) UserOrErr() (*User, error) { + if e.User != nil { + return e.User, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "user"} +} + +// NodeOrErr returns the Node value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e NodeReviewEdges) NodeOrErr() (*Node, error) { + if e.Node != nil { + return e.Node, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: node.Label} + } + return nil, &NotLoadedError{edge: "node"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*NodeReview) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case nodereview.FieldStar: + values[i] = new(sql.NullInt64) + case nodereview.FieldNodeID, nodereview.FieldUserID: + values[i] = new(sql.NullString) + case nodereview.FieldID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the NodeReview fields. +func (nr *NodeReview) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case nodereview.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + nr.ID = *value + } + case nodereview.FieldNodeID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field node_id", values[i]) + } else if value.Valid { + nr.NodeID = value.String + } + case nodereview.FieldUserID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + nr.UserID = value.String + } + case nodereview.FieldStar: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field star", values[i]) + } else if value.Valid { + nr.Star = int(value.Int64) + } + default: + nr.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the NodeReview. +// This includes values selected through modifiers, order, etc. +func (nr *NodeReview) Value(name string) (ent.Value, error) { + return nr.selectValues.Get(name) +} + +// QueryUser queries the "user" edge of the NodeReview entity. +func (nr *NodeReview) QueryUser() *UserQuery { + return NewNodeReviewClient(nr.config).QueryUser(nr) +} + +// QueryNode queries the "node" edge of the NodeReview entity. +func (nr *NodeReview) QueryNode() *NodeQuery { + return NewNodeReviewClient(nr.config).QueryNode(nr) +} + +// Update returns a builder for updating this NodeReview. +// Note that you need to call NodeReview.Unwrap() before calling this method if this NodeReview +// was returned from a transaction, and the transaction was committed or rolled back. +func (nr *NodeReview) Update() *NodeReviewUpdateOne { + return NewNodeReviewClient(nr.config).UpdateOne(nr) +} + +// Unwrap unwraps the NodeReview entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (nr *NodeReview) Unwrap() *NodeReview { + _tx, ok := nr.config.driver.(*txDriver) + if !ok { + panic("ent: NodeReview is not a transactional entity") + } + nr.config.driver = _tx.drv + return nr +} + +// String implements the fmt.Stringer. +func (nr *NodeReview) String() string { + var builder strings.Builder + builder.WriteString("NodeReview(") + builder.WriteString(fmt.Sprintf("id=%v, ", nr.ID)) + builder.WriteString("node_id=") + builder.WriteString(nr.NodeID) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(nr.UserID) + builder.WriteString(", ") + builder.WriteString("star=") + builder.WriteString(fmt.Sprintf("%v", nr.Star)) + builder.WriteByte(')') + return builder.String() +} + +// NodeReviews is a parsable slice of NodeReview. +type NodeReviews []*NodeReview diff --git a/ent/nodereview/nodereview.go b/ent/nodereview/nodereview.go new file mode 100644 index 0000000..b4ef126 --- /dev/null +++ b/ent/nodereview/nodereview.go @@ -0,0 +1,118 @@ +// Code generated by ent, DO NOT EDIT. + +package nodereview + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the nodereview type in the database. + Label = "node_review" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldNodeID holds the string denoting the node_id field in the database. + FieldNodeID = "node_id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldStar holds the string denoting the star field in the database. + FieldStar = "star" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // EdgeNode holds the string denoting the node edge name in mutations. + EdgeNode = "node" + // Table holds the table name of the nodereview in the database. + Table = "node_reviews" + // UserTable is the table that holds the user relation/edge. + UserTable = "node_reviews" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" + // NodeTable is the table that holds the node relation/edge. + NodeTable = "node_reviews" + // NodeInverseTable is the table name for the Node entity. + // It exists in this package in order to avoid circular dependency with the "node" package. + NodeInverseTable = "nodes" + // NodeColumn is the table column denoting the node relation/edge. + NodeColumn = "node_id" +) + +// Columns holds all SQL columns for nodereview fields. +var Columns = []string{ + FieldID, + FieldNodeID, + FieldUserID, + FieldStar, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultStar holds the default value on creation for the "star" field. + DefaultStar int + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// OrderOption defines the ordering options for the NodeReview queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByNodeID orders the results by the node_id field. +func ByNodeID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldNodeID, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByStar orders the results by the star field. +func ByStar(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStar, opts...).ToFunc() +} + +// ByUserField orders the results by user field. +func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) + } +} + +// ByNodeField orders the results by node field. +func ByNodeField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newNodeStep(), sql.OrderByField(field, opts...)) + } +} +func newUserStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) +} +func newNodeStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(NodeInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, NodeTable, NodeColumn), + ) +} diff --git a/ent/nodereview/where.go b/ent/nodereview/where.go new file mode 100644 index 0000000..59b36a6 --- /dev/null +++ b/ent/nodereview/where.go @@ -0,0 +1,302 @@ +// Code generated by ent, DO NOT EDIT. + +package nodereview + +import ( + "registry-backend/ent/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.NodeReview { + return predicate.NodeReview(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.NodeReview { + return predicate.NodeReview(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.NodeReview { + return predicate.NodeReview(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.NodeReview { + return predicate.NodeReview(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.NodeReview { + return predicate.NodeReview(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.NodeReview { + return predicate.NodeReview(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.NodeReview { + return predicate.NodeReview(sql.FieldLTE(FieldID, id)) +} + +// NodeID applies equality check predicate on the "node_id" field. It's identical to NodeIDEQ. +func NodeID(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEQ(FieldNodeID, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEQ(FieldUserID, v)) +} + +// Star applies equality check predicate on the "star" field. It's identical to StarEQ. +func Star(v int) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEQ(FieldStar, v)) +} + +// NodeIDEQ applies the EQ predicate on the "node_id" field. +func NodeIDEQ(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEQ(FieldNodeID, v)) +} + +// NodeIDNEQ applies the NEQ predicate on the "node_id" field. +func NodeIDNEQ(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldNEQ(FieldNodeID, v)) +} + +// NodeIDIn applies the In predicate on the "node_id" field. +func NodeIDIn(vs ...string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldIn(FieldNodeID, vs...)) +} + +// NodeIDNotIn applies the NotIn predicate on the "node_id" field. +func NodeIDNotIn(vs ...string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldNotIn(FieldNodeID, vs...)) +} + +// NodeIDGT applies the GT predicate on the "node_id" field. +func NodeIDGT(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldGT(FieldNodeID, v)) +} + +// NodeIDGTE applies the GTE predicate on the "node_id" field. +func NodeIDGTE(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldGTE(FieldNodeID, v)) +} + +// NodeIDLT applies the LT predicate on the "node_id" field. +func NodeIDLT(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldLT(FieldNodeID, v)) +} + +// NodeIDLTE applies the LTE predicate on the "node_id" field. +func NodeIDLTE(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldLTE(FieldNodeID, v)) +} + +// NodeIDContains applies the Contains predicate on the "node_id" field. +func NodeIDContains(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldContains(FieldNodeID, v)) +} + +// NodeIDHasPrefix applies the HasPrefix predicate on the "node_id" field. +func NodeIDHasPrefix(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldHasPrefix(FieldNodeID, v)) +} + +// NodeIDHasSuffix applies the HasSuffix predicate on the "node_id" field. +func NodeIDHasSuffix(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldHasSuffix(FieldNodeID, v)) +} + +// NodeIDEqualFold applies the EqualFold predicate on the "node_id" field. +func NodeIDEqualFold(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEqualFold(FieldNodeID, v)) +} + +// NodeIDContainsFold applies the ContainsFold predicate on the "node_id" field. +func NodeIDContainsFold(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldContainsFold(FieldNodeID, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDGT applies the GT predicate on the "user_id" field. +func UserIDGT(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldGT(FieldUserID, v)) +} + +// UserIDGTE applies the GTE predicate on the "user_id" field. +func UserIDGTE(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldGTE(FieldUserID, v)) +} + +// UserIDLT applies the LT predicate on the "user_id" field. +func UserIDLT(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldLT(FieldUserID, v)) +} + +// UserIDLTE applies the LTE predicate on the "user_id" field. +func UserIDLTE(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldLTE(FieldUserID, v)) +} + +// UserIDContains applies the Contains predicate on the "user_id" field. +func UserIDContains(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldContains(FieldUserID, v)) +} + +// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field. +func UserIDHasPrefix(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldHasPrefix(FieldUserID, v)) +} + +// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field. +func UserIDHasSuffix(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldHasSuffix(FieldUserID, v)) +} + +// UserIDEqualFold applies the EqualFold predicate on the "user_id" field. +func UserIDEqualFold(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEqualFold(FieldUserID, v)) +} + +// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field. +func UserIDContainsFold(v string) predicate.NodeReview { + return predicate.NodeReview(sql.FieldContainsFold(FieldUserID, v)) +} + +// StarEQ applies the EQ predicate on the "star" field. +func StarEQ(v int) predicate.NodeReview { + return predicate.NodeReview(sql.FieldEQ(FieldStar, v)) +} + +// StarNEQ applies the NEQ predicate on the "star" field. +func StarNEQ(v int) predicate.NodeReview { + return predicate.NodeReview(sql.FieldNEQ(FieldStar, v)) +} + +// StarIn applies the In predicate on the "star" field. +func StarIn(vs ...int) predicate.NodeReview { + return predicate.NodeReview(sql.FieldIn(FieldStar, vs...)) +} + +// StarNotIn applies the NotIn predicate on the "star" field. +func StarNotIn(vs ...int) predicate.NodeReview { + return predicate.NodeReview(sql.FieldNotIn(FieldStar, vs...)) +} + +// StarGT applies the GT predicate on the "star" field. +func StarGT(v int) predicate.NodeReview { + return predicate.NodeReview(sql.FieldGT(FieldStar, v)) +} + +// StarGTE applies the GTE predicate on the "star" field. +func StarGTE(v int) predicate.NodeReview { + return predicate.NodeReview(sql.FieldGTE(FieldStar, v)) +} + +// StarLT applies the LT predicate on the "star" field. +func StarLT(v int) predicate.NodeReview { + return predicate.NodeReview(sql.FieldLT(FieldStar, v)) +} + +// StarLTE applies the LTE predicate on the "star" field. +func StarLTE(v int) predicate.NodeReview { + return predicate.NodeReview(sql.FieldLTE(FieldStar, v)) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.NodeReview { + return predicate.NodeReview(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.NodeReview { + return predicate.NodeReview(func(s *sql.Selector) { + step := newUserStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasNode applies the HasEdge predicate on the "node" edge. +func HasNode() predicate.NodeReview { + return predicate.NodeReview(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, NodeTable, NodeColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasNodeWith applies the HasEdge predicate on the "node" edge with a given conditions (other predicates). +func HasNodeWith(preds ...predicate.Node) predicate.NodeReview { + return predicate.NodeReview(func(s *sql.Selector) { + step := newNodeStep() + 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.NodeReview) predicate.NodeReview { + return predicate.NodeReview(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.NodeReview) predicate.NodeReview { + return predicate.NodeReview(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.NodeReview) predicate.NodeReview { + return predicate.NodeReview(sql.NotPredicates(p)) +} diff --git a/ent/nodereview_create.go b/ent/nodereview_create.go new file mode 100644 index 0000000..4b86b2e --- /dev/null +++ b/ent/nodereview_create.go @@ -0,0 +1,690 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "registry-backend/ent/node" + "registry-backend/ent/nodereview" + "registry-backend/ent/user" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// NodeReviewCreate is the builder for creating a NodeReview entity. +type NodeReviewCreate struct { + config + mutation *NodeReviewMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetNodeID sets the "node_id" field. +func (nrc *NodeReviewCreate) SetNodeID(s string) *NodeReviewCreate { + nrc.mutation.SetNodeID(s) + return nrc +} + +// SetUserID sets the "user_id" field. +func (nrc *NodeReviewCreate) SetUserID(s string) *NodeReviewCreate { + nrc.mutation.SetUserID(s) + return nrc +} + +// SetStar sets the "star" field. +func (nrc *NodeReviewCreate) SetStar(i int) *NodeReviewCreate { + nrc.mutation.SetStar(i) + return nrc +} + +// SetNillableStar sets the "star" field if the given value is not nil. +func (nrc *NodeReviewCreate) SetNillableStar(i *int) *NodeReviewCreate { + if i != nil { + nrc.SetStar(*i) + } + return nrc +} + +// SetID sets the "id" field. +func (nrc *NodeReviewCreate) SetID(u uuid.UUID) *NodeReviewCreate { + nrc.mutation.SetID(u) + return nrc +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (nrc *NodeReviewCreate) SetNillableID(u *uuid.UUID) *NodeReviewCreate { + if u != nil { + nrc.SetID(*u) + } + return nrc +} + +// SetUser sets the "user" edge to the User entity. +func (nrc *NodeReviewCreate) SetUser(u *User) *NodeReviewCreate { + return nrc.SetUserID(u.ID) +} + +// SetNode sets the "node" edge to the Node entity. +func (nrc *NodeReviewCreate) SetNode(n *Node) *NodeReviewCreate { + return nrc.SetNodeID(n.ID) +} + +// Mutation returns the NodeReviewMutation object of the builder. +func (nrc *NodeReviewCreate) Mutation() *NodeReviewMutation { + return nrc.mutation +} + +// Save creates the NodeReview in the database. +func (nrc *NodeReviewCreate) Save(ctx context.Context) (*NodeReview, error) { + nrc.defaults() + return withHooks(ctx, nrc.sqlSave, nrc.mutation, nrc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (nrc *NodeReviewCreate) SaveX(ctx context.Context) *NodeReview { + v, err := nrc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (nrc *NodeReviewCreate) Exec(ctx context.Context) error { + _, err := nrc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (nrc *NodeReviewCreate) ExecX(ctx context.Context) { + if err := nrc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (nrc *NodeReviewCreate) defaults() { + if _, ok := nrc.mutation.Star(); !ok { + v := nodereview.DefaultStar + nrc.mutation.SetStar(v) + } + if _, ok := nrc.mutation.ID(); !ok { + v := nodereview.DefaultID() + nrc.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (nrc *NodeReviewCreate) check() error { + if _, ok := nrc.mutation.NodeID(); !ok { + return &ValidationError{Name: "node_id", err: errors.New(`ent: missing required field "NodeReview.node_id"`)} + } + if _, ok := nrc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "NodeReview.user_id"`)} + } + if _, ok := nrc.mutation.Star(); !ok { + return &ValidationError{Name: "star", err: errors.New(`ent: missing required field "NodeReview.star"`)} + } + if _, ok := nrc.mutation.UserID(); !ok { + return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "NodeReview.user"`)} + } + if _, ok := nrc.mutation.NodeID(); !ok { + return &ValidationError{Name: "node", err: errors.New(`ent: missing required edge "NodeReview.node"`)} + } + return nil +} + +func (nrc *NodeReviewCreate) sqlSave(ctx context.Context) (*NodeReview, error) { + if err := nrc.check(); err != nil { + return nil, err + } + _node, _spec := nrc.createSpec() + if err := sqlgraph.CreateNode(ctx, nrc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*uuid.UUID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + nrc.mutation.id = &_node.ID + nrc.mutation.done = true + return _node, nil +} + +func (nrc *NodeReviewCreate) createSpec() (*NodeReview, *sqlgraph.CreateSpec) { + var ( + _node = &NodeReview{config: nrc.config} + _spec = sqlgraph.NewCreateSpec(nodereview.Table, sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = nrc.conflict + if id, ok := nrc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := nrc.mutation.Star(); ok { + _spec.SetField(nodereview.FieldStar, field.TypeInt, value) + _node.Star = value + } + if nodes := nrc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.UserTable, + Columns: []string{nodereview.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := nrc.mutation.NodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.NodeTable, + Columns: []string{nodereview.NodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.NodeID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.NodeReview.Create(). +// SetNodeID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.NodeReviewUpsert) { +// SetNodeID(v+v). +// }). +// Exec(ctx) +func (nrc *NodeReviewCreate) OnConflict(opts ...sql.ConflictOption) *NodeReviewUpsertOne { + nrc.conflict = opts + return &NodeReviewUpsertOne{ + create: nrc, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NodeReview.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (nrc *NodeReviewCreate) OnConflictColumns(columns ...string) *NodeReviewUpsertOne { + nrc.conflict = append(nrc.conflict, sql.ConflictColumns(columns...)) + return &NodeReviewUpsertOne{ + create: nrc, + } +} + +type ( + // NodeReviewUpsertOne is the builder for "upsert"-ing + // one NodeReview node. + NodeReviewUpsertOne struct { + create *NodeReviewCreate + } + + // NodeReviewUpsert is the "OnConflict" setter. + NodeReviewUpsert struct { + *sql.UpdateSet + } +) + +// SetNodeID sets the "node_id" field. +func (u *NodeReviewUpsert) SetNodeID(v string) *NodeReviewUpsert { + u.Set(nodereview.FieldNodeID, v) + return u +} + +// UpdateNodeID sets the "node_id" field to the value that was provided on create. +func (u *NodeReviewUpsert) UpdateNodeID() *NodeReviewUpsert { + u.SetExcluded(nodereview.FieldNodeID) + return u +} + +// SetUserID sets the "user_id" field. +func (u *NodeReviewUpsert) SetUserID(v string) *NodeReviewUpsert { + u.Set(nodereview.FieldUserID, v) + return u +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *NodeReviewUpsert) UpdateUserID() *NodeReviewUpsert { + u.SetExcluded(nodereview.FieldUserID) + return u +} + +// SetStar sets the "star" field. +func (u *NodeReviewUpsert) SetStar(v int) *NodeReviewUpsert { + u.Set(nodereview.FieldStar, v) + return u +} + +// UpdateStar sets the "star" field to the value that was provided on create. +func (u *NodeReviewUpsert) UpdateStar() *NodeReviewUpsert { + u.SetExcluded(nodereview.FieldStar) + return u +} + +// AddStar adds v to the "star" field. +func (u *NodeReviewUpsert) AddStar(v int) *NodeReviewUpsert { + u.Add(nodereview.FieldStar, v) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.NodeReview.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(nodereview.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NodeReviewUpsertOne) UpdateNewValues() *NodeReviewUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(nodereview.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NodeReview.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NodeReviewUpsertOne) Ignore() *NodeReviewUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *NodeReviewUpsertOne) DoNothing() *NodeReviewUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NodeReviewCreate.OnConflict +// documentation for more info. +func (u *NodeReviewUpsertOne) Update(set func(*NodeReviewUpsert)) *NodeReviewUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NodeReviewUpsert{UpdateSet: update}) + })) + return u +} + +// SetNodeID sets the "node_id" field. +func (u *NodeReviewUpsertOne) SetNodeID(v string) *NodeReviewUpsertOne { + return u.Update(func(s *NodeReviewUpsert) { + s.SetNodeID(v) + }) +} + +// UpdateNodeID sets the "node_id" field to the value that was provided on create. +func (u *NodeReviewUpsertOne) UpdateNodeID() *NodeReviewUpsertOne { + return u.Update(func(s *NodeReviewUpsert) { + s.UpdateNodeID() + }) +} + +// SetUserID sets the "user_id" field. +func (u *NodeReviewUpsertOne) SetUserID(v string) *NodeReviewUpsertOne { + return u.Update(func(s *NodeReviewUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *NodeReviewUpsertOne) UpdateUserID() *NodeReviewUpsertOne { + return u.Update(func(s *NodeReviewUpsert) { + s.UpdateUserID() + }) +} + +// SetStar sets the "star" field. +func (u *NodeReviewUpsertOne) SetStar(v int) *NodeReviewUpsertOne { + return u.Update(func(s *NodeReviewUpsert) { + s.SetStar(v) + }) +} + +// AddStar adds v to the "star" field. +func (u *NodeReviewUpsertOne) AddStar(v int) *NodeReviewUpsertOne { + return u.Update(func(s *NodeReviewUpsert) { + s.AddStar(v) + }) +} + +// UpdateStar sets the "star" field to the value that was provided on create. +func (u *NodeReviewUpsertOne) UpdateStar() *NodeReviewUpsertOne { + return u.Update(func(s *NodeReviewUpsert) { + s.UpdateStar() + }) +} + +// Exec executes the query. +func (u *NodeReviewUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for NodeReviewCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NodeReviewUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *NodeReviewUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("ent: NodeReviewUpsertOne.ID is not supported by MySQL driver. Use NodeReviewUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *NodeReviewUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// NodeReviewCreateBulk is the builder for creating many NodeReview entities in bulk. +type NodeReviewCreateBulk struct { + config + err error + builders []*NodeReviewCreate + conflict []sql.ConflictOption +} + +// Save creates the NodeReview entities in the database. +func (nrcb *NodeReviewCreateBulk) Save(ctx context.Context) ([]*NodeReview, error) { + if nrcb.err != nil { + return nil, nrcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(nrcb.builders)) + nodes := make([]*NodeReview, len(nrcb.builders)) + mutators := make([]Mutator, len(nrcb.builders)) + for i := range nrcb.builders { + func(i int, root context.Context) { + builder := nrcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*NodeReviewMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, nrcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = nrcb.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, nrcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, nrcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (nrcb *NodeReviewCreateBulk) SaveX(ctx context.Context) []*NodeReview { + v, err := nrcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (nrcb *NodeReviewCreateBulk) Exec(ctx context.Context) error { + _, err := nrcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (nrcb *NodeReviewCreateBulk) ExecX(ctx context.Context) { + if err := nrcb.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.NodeReview.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.NodeReviewUpsert) { +// SetNodeID(v+v). +// }). +// Exec(ctx) +func (nrcb *NodeReviewCreateBulk) OnConflict(opts ...sql.ConflictOption) *NodeReviewUpsertBulk { + nrcb.conflict = opts + return &NodeReviewUpsertBulk{ + create: nrcb, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.NodeReview.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (nrcb *NodeReviewCreateBulk) OnConflictColumns(columns ...string) *NodeReviewUpsertBulk { + nrcb.conflict = append(nrcb.conflict, sql.ConflictColumns(columns...)) + return &NodeReviewUpsertBulk{ + create: nrcb, + } +} + +// NodeReviewUpsertBulk is the builder for "upsert"-ing +// a bulk of NodeReview nodes. +type NodeReviewUpsertBulk struct { + create *NodeReviewCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.NodeReview.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(nodereview.FieldID) +// }), +// ). +// Exec(ctx) +func (u *NodeReviewUpsertBulk) UpdateNewValues() *NodeReviewUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(nodereview.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.NodeReview.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *NodeReviewUpsertBulk) Ignore() *NodeReviewUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *NodeReviewUpsertBulk) DoNothing() *NodeReviewUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the NodeReviewCreateBulk.OnConflict +// documentation for more info. +func (u *NodeReviewUpsertBulk) Update(set func(*NodeReviewUpsert)) *NodeReviewUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&NodeReviewUpsert{UpdateSet: update}) + })) + return u +} + +// SetNodeID sets the "node_id" field. +func (u *NodeReviewUpsertBulk) SetNodeID(v string) *NodeReviewUpsertBulk { + return u.Update(func(s *NodeReviewUpsert) { + s.SetNodeID(v) + }) +} + +// UpdateNodeID sets the "node_id" field to the value that was provided on create. +func (u *NodeReviewUpsertBulk) UpdateNodeID() *NodeReviewUpsertBulk { + return u.Update(func(s *NodeReviewUpsert) { + s.UpdateNodeID() + }) +} + +// SetUserID sets the "user_id" field. +func (u *NodeReviewUpsertBulk) SetUserID(v string) *NodeReviewUpsertBulk { + return u.Update(func(s *NodeReviewUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *NodeReviewUpsertBulk) UpdateUserID() *NodeReviewUpsertBulk { + return u.Update(func(s *NodeReviewUpsert) { + s.UpdateUserID() + }) +} + +// SetStar sets the "star" field. +func (u *NodeReviewUpsertBulk) SetStar(v int) *NodeReviewUpsertBulk { + return u.Update(func(s *NodeReviewUpsert) { + s.SetStar(v) + }) +} + +// AddStar adds v to the "star" field. +func (u *NodeReviewUpsertBulk) AddStar(v int) *NodeReviewUpsertBulk { + return u.Update(func(s *NodeReviewUpsert) { + s.AddStar(v) + }) +} + +// UpdateStar sets the "star" field to the value that was provided on create. +func (u *NodeReviewUpsertBulk) UpdateStar() *NodeReviewUpsertBulk { + return u.Update(func(s *NodeReviewUpsert) { + s.UpdateStar() + }) +} + +// Exec executes the query. +func (u *NodeReviewUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the NodeReviewCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for NodeReviewCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *NodeReviewUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/nodereview_delete.go b/ent/nodereview_delete.go new file mode 100644 index 0000000..f918003 --- /dev/null +++ b/ent/nodereview_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "registry-backend/ent/nodereview" + "registry-backend/ent/predicate" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// NodeReviewDelete is the builder for deleting a NodeReview entity. +type NodeReviewDelete struct { + config + hooks []Hook + mutation *NodeReviewMutation +} + +// Where appends a list predicates to the NodeReviewDelete builder. +func (nrd *NodeReviewDelete) Where(ps ...predicate.NodeReview) *NodeReviewDelete { + nrd.mutation.Where(ps...) + return nrd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (nrd *NodeReviewDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, nrd.sqlExec, nrd.mutation, nrd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (nrd *NodeReviewDelete) ExecX(ctx context.Context) int { + n, err := nrd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (nrd *NodeReviewDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(nodereview.Table, sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID)) + if ps := nrd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, nrd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + nrd.mutation.done = true + return affected, err +} + +// NodeReviewDeleteOne is the builder for deleting a single NodeReview entity. +type NodeReviewDeleteOne struct { + nrd *NodeReviewDelete +} + +// Where appends a list predicates to the NodeReviewDelete builder. +func (nrdo *NodeReviewDeleteOne) Where(ps ...predicate.NodeReview) *NodeReviewDeleteOne { + nrdo.nrd.mutation.Where(ps...) + return nrdo +} + +// Exec executes the deletion query. +func (nrdo *NodeReviewDeleteOne) Exec(ctx context.Context) error { + n, err := nrdo.nrd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{nodereview.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (nrdo *NodeReviewDeleteOne) ExecX(ctx context.Context) { + if err := nrdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/ent/nodereview_query.go b/ent/nodereview_query.go new file mode 100644 index 0000000..07ebf5d --- /dev/null +++ b/ent/nodereview_query.go @@ -0,0 +1,718 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + "registry-backend/ent/node" + "registry-backend/ent/nodereview" + "registry-backend/ent/predicate" + "registry-backend/ent/user" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// NodeReviewQuery is the builder for querying NodeReview entities. +type NodeReviewQuery struct { + config + ctx *QueryContext + order []nodereview.OrderOption + inters []Interceptor + predicates []predicate.NodeReview + withUser *UserQuery + withNode *NodeQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the NodeReviewQuery builder. +func (nrq *NodeReviewQuery) Where(ps ...predicate.NodeReview) *NodeReviewQuery { + nrq.predicates = append(nrq.predicates, ps...) + return nrq +} + +// Limit the number of records to be returned by this query. +func (nrq *NodeReviewQuery) Limit(limit int) *NodeReviewQuery { + nrq.ctx.Limit = &limit + return nrq +} + +// Offset to start from. +func (nrq *NodeReviewQuery) Offset(offset int) *NodeReviewQuery { + nrq.ctx.Offset = &offset + return nrq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (nrq *NodeReviewQuery) Unique(unique bool) *NodeReviewQuery { + nrq.ctx.Unique = &unique + return nrq +} + +// Order specifies how the records should be ordered. +func (nrq *NodeReviewQuery) Order(o ...nodereview.OrderOption) *NodeReviewQuery { + nrq.order = append(nrq.order, o...) + return nrq +} + +// QueryUser chains the current query on the "user" edge. +func (nrq *NodeReviewQuery) QueryUser() *UserQuery { + query := (&UserClient{config: nrq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := nrq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := nrq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(nodereview.Table, nodereview.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, nodereview.UserTable, nodereview.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(nrq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryNode chains the current query on the "node" edge. +func (nrq *NodeReviewQuery) QueryNode() *NodeQuery { + query := (&NodeClient{config: nrq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := nrq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := nrq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(nodereview.Table, nodereview.FieldID, selector), + sqlgraph.To(node.Table, node.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, nodereview.NodeTable, nodereview.NodeColumn), + ) + fromU = sqlgraph.SetNeighbors(nrq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first NodeReview entity from the query. +// Returns a *NotFoundError when no NodeReview was found. +func (nrq *NodeReviewQuery) First(ctx context.Context) (*NodeReview, error) { + nodes, err := nrq.Limit(1).All(setContextOp(ctx, nrq.ctx, "First")) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{nodereview.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (nrq *NodeReviewQuery) FirstX(ctx context.Context) *NodeReview { + node, err := nrq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first NodeReview ID from the query. +// Returns a *NotFoundError when no NodeReview ID was found. +func (nrq *NodeReviewQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = nrq.Limit(1).IDs(setContextOp(ctx, nrq.ctx, "FirstID")); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{nodereview.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (nrq *NodeReviewQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := nrq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single NodeReview entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one NodeReview entity is found. +// Returns a *NotFoundError when no NodeReview entities are found. +func (nrq *NodeReviewQuery) Only(ctx context.Context) (*NodeReview, error) { + nodes, err := nrq.Limit(2).All(setContextOp(ctx, nrq.ctx, "Only")) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{nodereview.Label} + default: + return nil, &NotSingularError{nodereview.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (nrq *NodeReviewQuery) OnlyX(ctx context.Context) *NodeReview { + node, err := nrq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only NodeReview ID in the query. +// Returns a *NotSingularError when more than one NodeReview ID is found. +// Returns a *NotFoundError when no entities are found. +func (nrq *NodeReviewQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = nrq.Limit(2).IDs(setContextOp(ctx, nrq.ctx, "OnlyID")); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{nodereview.Label} + default: + err = &NotSingularError{nodereview.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (nrq *NodeReviewQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := nrq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of NodeReviews. +func (nrq *NodeReviewQuery) All(ctx context.Context) ([]*NodeReview, error) { + ctx = setContextOp(ctx, nrq.ctx, "All") + if err := nrq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*NodeReview, *NodeReviewQuery]() + return withInterceptors[[]*NodeReview](ctx, nrq, qr, nrq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (nrq *NodeReviewQuery) AllX(ctx context.Context) []*NodeReview { + nodes, err := nrq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of NodeReview IDs. +func (nrq *NodeReviewQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if nrq.ctx.Unique == nil && nrq.path != nil { + nrq.Unique(true) + } + ctx = setContextOp(ctx, nrq.ctx, "IDs") + if err = nrq.Select(nodereview.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (nrq *NodeReviewQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := nrq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (nrq *NodeReviewQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, nrq.ctx, "Count") + if err := nrq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, nrq, querierCount[*NodeReviewQuery](), nrq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (nrq *NodeReviewQuery) CountX(ctx context.Context) int { + count, err := nrq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (nrq *NodeReviewQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, nrq.ctx, "Exist") + switch _, err := nrq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (nrq *NodeReviewQuery) ExistX(ctx context.Context) bool { + exist, err := nrq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the NodeReviewQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (nrq *NodeReviewQuery) Clone() *NodeReviewQuery { + if nrq == nil { + return nil + } + return &NodeReviewQuery{ + config: nrq.config, + ctx: nrq.ctx.Clone(), + order: append([]nodereview.OrderOption{}, nrq.order...), + inters: append([]Interceptor{}, nrq.inters...), + predicates: append([]predicate.NodeReview{}, nrq.predicates...), + withUser: nrq.withUser.Clone(), + withNode: nrq.withNode.Clone(), + // clone intermediate query. + sql: nrq.sql.Clone(), + path: nrq.path, + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (nrq *NodeReviewQuery) WithUser(opts ...func(*UserQuery)) *NodeReviewQuery { + query := (&UserClient{config: nrq.config}).Query() + for _, opt := range opts { + opt(query) + } + nrq.withUser = query + return nrq +} + +// WithNode tells the query-builder to eager-load the nodes that are connected to +// the "node" edge. The optional arguments are used to configure the query builder of the edge. +func (nrq *NodeReviewQuery) WithNode(opts ...func(*NodeQuery)) *NodeReviewQuery { + query := (&NodeClient{config: nrq.config}).Query() + for _, opt := range opts { + opt(query) + } + nrq.withNode = query + return nrq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// NodeID string `json:"node_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.NodeReview.Query(). +// GroupBy(nodereview.FieldNodeID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (nrq *NodeReviewQuery) GroupBy(field string, fields ...string) *NodeReviewGroupBy { + nrq.ctx.Fields = append([]string{field}, fields...) + grbuild := &NodeReviewGroupBy{build: nrq} + grbuild.flds = &nrq.ctx.Fields + grbuild.label = nodereview.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// NodeID string `json:"node_id,omitempty"` +// } +// +// client.NodeReview.Query(). +// Select(nodereview.FieldNodeID). +// Scan(ctx, &v) +func (nrq *NodeReviewQuery) Select(fields ...string) *NodeReviewSelect { + nrq.ctx.Fields = append(nrq.ctx.Fields, fields...) + sbuild := &NodeReviewSelect{NodeReviewQuery: nrq} + sbuild.label = nodereview.Label + sbuild.flds, sbuild.scan = &nrq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a NodeReviewSelect configured with the given aggregations. +func (nrq *NodeReviewQuery) Aggregate(fns ...AggregateFunc) *NodeReviewSelect { + return nrq.Select().Aggregate(fns...) +} + +func (nrq *NodeReviewQuery) prepareQuery(ctx context.Context) error { + for _, inter := range nrq.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, nrq); err != nil { + return err + } + } + } + for _, f := range nrq.ctx.Fields { + if !nodereview.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if nrq.path != nil { + prev, err := nrq.path(ctx) + if err != nil { + return err + } + nrq.sql = prev + } + return nil +} + +func (nrq *NodeReviewQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*NodeReview, error) { + var ( + nodes = []*NodeReview{} + _spec = nrq.querySpec() + loadedTypes = [2]bool{ + nrq.withUser != nil, + nrq.withNode != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*NodeReview).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &NodeReview{config: nrq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(nrq.modifiers) > 0 { + _spec.Modifiers = nrq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, nrq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := nrq.withUser; query != nil { + if err := nrq.loadUser(ctx, query, nodes, nil, + func(n *NodeReview, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + if query := nrq.withNode; query != nil { + if err := nrq.loadNode(ctx, query, nodes, nil, + func(n *NodeReview, e *Node) { n.Edges.Node = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (nrq *NodeReviewQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*NodeReview, init func(*NodeReview), assign func(*NodeReview, *User)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*NodeReview) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (nrq *NodeReviewQuery) loadNode(ctx context.Context, query *NodeQuery, nodes []*NodeReview, init func(*NodeReview), assign func(*NodeReview, *Node)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*NodeReview) + for i := range nodes { + fk := nodes[i].NodeID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(node.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "node_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (nrq *NodeReviewQuery) sqlCount(ctx context.Context) (int, error) { + _spec := nrq.querySpec() + if len(nrq.modifiers) > 0 { + _spec.Modifiers = nrq.modifiers + } + _spec.Node.Columns = nrq.ctx.Fields + if len(nrq.ctx.Fields) > 0 { + _spec.Unique = nrq.ctx.Unique != nil && *nrq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, nrq.driver, _spec) +} + +func (nrq *NodeReviewQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(nodereview.Table, nodereview.Columns, sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID)) + _spec.From = nrq.sql + if unique := nrq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if nrq.path != nil { + _spec.Unique = true + } + if fields := nrq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, nodereview.FieldID) + for i := range fields { + if fields[i] != nodereview.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if nrq.withUser != nil { + _spec.Node.AddColumnOnce(nodereview.FieldUserID) + } + if nrq.withNode != nil { + _spec.Node.AddColumnOnce(nodereview.FieldNodeID) + } + } + if ps := nrq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := nrq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := nrq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := nrq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (nrq *NodeReviewQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(nrq.driver.Dialect()) + t1 := builder.Table(nodereview.Table) + columns := nrq.ctx.Fields + if len(columns) == 0 { + columns = nodereview.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if nrq.sql != nil { + selector = nrq.sql + selector.Select(selector.Columns(columns...)...) + } + if nrq.ctx.Unique != nil && *nrq.ctx.Unique { + selector.Distinct() + } + for _, m := range nrq.modifiers { + m(selector) + } + for _, p := range nrq.predicates { + p(selector) + } + for _, p := range nrq.order { + p(selector) + } + if offset := nrq.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := nrq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (nrq *NodeReviewQuery) ForUpdate(opts ...sql.LockOption) *NodeReviewQuery { + if nrq.driver.Dialect() == dialect.Postgres { + nrq.Unique(false) + } + nrq.modifiers = append(nrq.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return nrq +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (nrq *NodeReviewQuery) ForShare(opts ...sql.LockOption) *NodeReviewQuery { + if nrq.driver.Dialect() == dialect.Postgres { + nrq.Unique(false) + } + nrq.modifiers = append(nrq.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return nrq +} + +// NodeReviewGroupBy is the group-by builder for NodeReview entities. +type NodeReviewGroupBy struct { + selector + build *NodeReviewQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (nrgb *NodeReviewGroupBy) Aggregate(fns ...AggregateFunc) *NodeReviewGroupBy { + nrgb.fns = append(nrgb.fns, fns...) + return nrgb +} + +// Scan applies the selector query and scans the result into the given value. +func (nrgb *NodeReviewGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, nrgb.build.ctx, "GroupBy") + if err := nrgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*NodeReviewQuery, *NodeReviewGroupBy](ctx, nrgb.build, nrgb, nrgb.build.inters, v) +} + +func (nrgb *NodeReviewGroupBy) sqlScan(ctx context.Context, root *NodeReviewQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(nrgb.fns)) + for _, fn := range nrgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*nrgb.flds)+len(nrgb.fns)) + for _, f := range *nrgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*nrgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := nrgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// NodeReviewSelect is the builder for selecting fields of NodeReview entities. +type NodeReviewSelect struct { + *NodeReviewQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (nrs *NodeReviewSelect) Aggregate(fns ...AggregateFunc) *NodeReviewSelect { + nrs.fns = append(nrs.fns, fns...) + return nrs +} + +// Scan applies the selector query and scans the result into the given value. +func (nrs *NodeReviewSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, nrs.ctx, "Select") + if err := nrs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*NodeReviewQuery, *NodeReviewSelect](ctx, nrs.NodeReviewQuery, nrs, nrs.inters, v) +} + +func (nrs *NodeReviewSelect) sqlScan(ctx context.Context, root *NodeReviewQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(nrs.fns)) + for _, fn := range nrs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*nrs.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := nrs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/ent/nodereview_update.go b/ent/nodereview_update.go new file mode 100644 index 0000000..1b33950 --- /dev/null +++ b/ent/nodereview_update.go @@ -0,0 +1,475 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "registry-backend/ent/node" + "registry-backend/ent/nodereview" + "registry-backend/ent/predicate" + "registry-backend/ent/user" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// NodeReviewUpdate is the builder for updating NodeReview entities. +type NodeReviewUpdate struct { + config + hooks []Hook + mutation *NodeReviewMutation +} + +// Where appends a list predicates to the NodeReviewUpdate builder. +func (nru *NodeReviewUpdate) Where(ps ...predicate.NodeReview) *NodeReviewUpdate { + nru.mutation.Where(ps...) + return nru +} + +// SetNodeID sets the "node_id" field. +func (nru *NodeReviewUpdate) SetNodeID(s string) *NodeReviewUpdate { + nru.mutation.SetNodeID(s) + return nru +} + +// SetNillableNodeID sets the "node_id" field if the given value is not nil. +func (nru *NodeReviewUpdate) SetNillableNodeID(s *string) *NodeReviewUpdate { + if s != nil { + nru.SetNodeID(*s) + } + return nru +} + +// SetUserID sets the "user_id" field. +func (nru *NodeReviewUpdate) SetUserID(s string) *NodeReviewUpdate { + nru.mutation.SetUserID(s) + return nru +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (nru *NodeReviewUpdate) SetNillableUserID(s *string) *NodeReviewUpdate { + if s != nil { + nru.SetUserID(*s) + } + return nru +} + +// SetStar sets the "star" field. +func (nru *NodeReviewUpdate) SetStar(i int) *NodeReviewUpdate { + nru.mutation.ResetStar() + nru.mutation.SetStar(i) + return nru +} + +// SetNillableStar sets the "star" field if the given value is not nil. +func (nru *NodeReviewUpdate) SetNillableStar(i *int) *NodeReviewUpdate { + if i != nil { + nru.SetStar(*i) + } + return nru +} + +// AddStar adds i to the "star" field. +func (nru *NodeReviewUpdate) AddStar(i int) *NodeReviewUpdate { + nru.mutation.AddStar(i) + return nru +} + +// SetUser sets the "user" edge to the User entity. +func (nru *NodeReviewUpdate) SetUser(u *User) *NodeReviewUpdate { + return nru.SetUserID(u.ID) +} + +// SetNode sets the "node" edge to the Node entity. +func (nru *NodeReviewUpdate) SetNode(n *Node) *NodeReviewUpdate { + return nru.SetNodeID(n.ID) +} + +// Mutation returns the NodeReviewMutation object of the builder. +func (nru *NodeReviewUpdate) Mutation() *NodeReviewMutation { + return nru.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (nru *NodeReviewUpdate) ClearUser() *NodeReviewUpdate { + nru.mutation.ClearUser() + return nru +} + +// ClearNode clears the "node" edge to the Node entity. +func (nru *NodeReviewUpdate) ClearNode() *NodeReviewUpdate { + nru.mutation.ClearNode() + return nru +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (nru *NodeReviewUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, nru.sqlSave, nru.mutation, nru.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (nru *NodeReviewUpdate) SaveX(ctx context.Context) int { + affected, err := nru.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (nru *NodeReviewUpdate) Exec(ctx context.Context) error { + _, err := nru.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (nru *NodeReviewUpdate) ExecX(ctx context.Context) { + if err := nru.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (nru *NodeReviewUpdate) check() error { + if _, ok := nru.mutation.UserID(); nru.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "NodeReview.user"`) + } + if _, ok := nru.mutation.NodeID(); nru.mutation.NodeCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "NodeReview.node"`) + } + return nil +} + +func (nru *NodeReviewUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := nru.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(nodereview.Table, nodereview.Columns, sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID)) + if ps := nru.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := nru.mutation.Star(); ok { + _spec.SetField(nodereview.FieldStar, field.TypeInt, value) + } + if value, ok := nru.mutation.AddedStar(); ok { + _spec.AddField(nodereview.FieldStar, field.TypeInt, value) + } + if nru.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.UserTable, + Columns: []string{nodereview.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := nru.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.UserTable, + Columns: []string{nodereview.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if nru.mutation.NodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.NodeTable, + Columns: []string{nodereview.NodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := nru.mutation.NodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.NodeTable, + Columns: []string{nodereview.NodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeString), + }, + } + 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, nru.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{nodereview.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + nru.mutation.done = true + return n, nil +} + +// NodeReviewUpdateOne is the builder for updating a single NodeReview entity. +type NodeReviewUpdateOne struct { + config + fields []string + hooks []Hook + mutation *NodeReviewMutation +} + +// SetNodeID sets the "node_id" field. +func (nruo *NodeReviewUpdateOne) SetNodeID(s string) *NodeReviewUpdateOne { + nruo.mutation.SetNodeID(s) + return nruo +} + +// SetNillableNodeID sets the "node_id" field if the given value is not nil. +func (nruo *NodeReviewUpdateOne) SetNillableNodeID(s *string) *NodeReviewUpdateOne { + if s != nil { + nruo.SetNodeID(*s) + } + return nruo +} + +// SetUserID sets the "user_id" field. +func (nruo *NodeReviewUpdateOne) SetUserID(s string) *NodeReviewUpdateOne { + nruo.mutation.SetUserID(s) + return nruo +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (nruo *NodeReviewUpdateOne) SetNillableUserID(s *string) *NodeReviewUpdateOne { + if s != nil { + nruo.SetUserID(*s) + } + return nruo +} + +// SetStar sets the "star" field. +func (nruo *NodeReviewUpdateOne) SetStar(i int) *NodeReviewUpdateOne { + nruo.mutation.ResetStar() + nruo.mutation.SetStar(i) + return nruo +} + +// SetNillableStar sets the "star" field if the given value is not nil. +func (nruo *NodeReviewUpdateOne) SetNillableStar(i *int) *NodeReviewUpdateOne { + if i != nil { + nruo.SetStar(*i) + } + return nruo +} + +// AddStar adds i to the "star" field. +func (nruo *NodeReviewUpdateOne) AddStar(i int) *NodeReviewUpdateOne { + nruo.mutation.AddStar(i) + return nruo +} + +// SetUser sets the "user" edge to the User entity. +func (nruo *NodeReviewUpdateOne) SetUser(u *User) *NodeReviewUpdateOne { + return nruo.SetUserID(u.ID) +} + +// SetNode sets the "node" edge to the Node entity. +func (nruo *NodeReviewUpdateOne) SetNode(n *Node) *NodeReviewUpdateOne { + return nruo.SetNodeID(n.ID) +} + +// Mutation returns the NodeReviewMutation object of the builder. +func (nruo *NodeReviewUpdateOne) Mutation() *NodeReviewMutation { + return nruo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (nruo *NodeReviewUpdateOne) ClearUser() *NodeReviewUpdateOne { + nruo.mutation.ClearUser() + return nruo +} + +// ClearNode clears the "node" edge to the Node entity. +func (nruo *NodeReviewUpdateOne) ClearNode() *NodeReviewUpdateOne { + nruo.mutation.ClearNode() + return nruo +} + +// Where appends a list predicates to the NodeReviewUpdate builder. +func (nruo *NodeReviewUpdateOne) Where(ps ...predicate.NodeReview) *NodeReviewUpdateOne { + nruo.mutation.Where(ps...) + return nruo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (nruo *NodeReviewUpdateOne) Select(field string, fields ...string) *NodeReviewUpdateOne { + nruo.fields = append([]string{field}, fields...) + return nruo +} + +// Save executes the query and returns the updated NodeReview entity. +func (nruo *NodeReviewUpdateOne) Save(ctx context.Context) (*NodeReview, error) { + return withHooks(ctx, nruo.sqlSave, nruo.mutation, nruo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (nruo *NodeReviewUpdateOne) SaveX(ctx context.Context) *NodeReview { + node, err := nruo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (nruo *NodeReviewUpdateOne) Exec(ctx context.Context) error { + _, err := nruo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (nruo *NodeReviewUpdateOne) ExecX(ctx context.Context) { + if err := nruo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (nruo *NodeReviewUpdateOne) check() error { + if _, ok := nruo.mutation.UserID(); nruo.mutation.UserCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "NodeReview.user"`) + } + if _, ok := nruo.mutation.NodeID(); nruo.mutation.NodeCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "NodeReview.node"`) + } + return nil +} + +func (nruo *NodeReviewUpdateOne) sqlSave(ctx context.Context) (_node *NodeReview, err error) { + if err := nruo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(nodereview.Table, nodereview.Columns, sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID)) + id, ok := nruo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "NodeReview.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := nruo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, nodereview.FieldID) + for _, f := range fields { + if !nodereview.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != nodereview.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := nruo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := nruo.mutation.Star(); ok { + _spec.SetField(nodereview.FieldStar, field.TypeInt, value) + } + if value, ok := nruo.mutation.AddedStar(); ok { + _spec.AddField(nodereview.FieldStar, field.TypeInt, value) + } + if nruo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.UserTable, + Columns: []string{nodereview.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := nruo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.UserTable, + Columns: []string{nodereview.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if nruo.mutation.NodeCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.NodeTable, + Columns: []string{nodereview.NodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := nruo.mutation.NodeIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: nodereview.NodeTable, + Columns: []string{nodereview.NodeColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(node.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &NodeReview{config: nruo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, nruo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{nodereview.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + nruo.mutation.done = true + return _node, nil +} diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go index c29ba05..37bf309 100644 --- a/ent/predicate/predicate.go +++ b/ent/predicate/predicate.go @@ -15,6 +15,9 @@ type GitCommit func(*sql.Selector) // Node is the predicate function for node builders. type Node func(*sql.Selector) +// NodeReview is the predicate function for nodereview builders. +type NodeReview func(*sql.Selector) + // NodeVersion is the predicate function for nodeversion builders. type NodeVersion func(*sql.Selector) diff --git a/ent/runtime.go b/ent/runtime.go index 63e4103..74b98c5 100644 --- a/ent/runtime.go +++ b/ent/runtime.go @@ -6,6 +6,7 @@ import ( "registry-backend/ent/ciworkflowresult" "registry-backend/ent/gitcommit" "registry-backend/ent/node" + "registry-backend/ent/nodereview" "registry-backend/ent/nodeversion" "registry-backend/ent/personalaccesstoken" "registry-backend/ent/publisher" @@ -78,6 +79,28 @@ func init() { nodeDescTags := nodeFields[8].Descriptor() // node.DefaultTags holds the default value on creation for the tags field. node.DefaultTags = nodeDescTags.Default.([]string) + // nodeDescTotalInstall is the schema descriptor for total_install field. + nodeDescTotalInstall := nodeFields[9].Descriptor() + // node.DefaultTotalInstall holds the default value on creation for the total_install field. + node.DefaultTotalInstall = nodeDescTotalInstall.Default.(int64) + // nodeDescTotalStar is the schema descriptor for total_star field. + nodeDescTotalStar := nodeFields[10].Descriptor() + // node.DefaultTotalStar holds the default value on creation for the total_star field. + node.DefaultTotalStar = nodeDescTotalStar.Default.(int64) + // nodeDescTotalReview is the schema descriptor for total_review field. + nodeDescTotalReview := nodeFields[11].Descriptor() + // node.DefaultTotalReview holds the default value on creation for the total_review field. + node.DefaultTotalReview = nodeDescTotalReview.Default.(int64) + nodereviewFields := schema.NodeReview{}.Fields() + _ = nodereviewFields + // nodereviewDescStar is the schema descriptor for star field. + nodereviewDescStar := nodereviewFields[3].Descriptor() + // nodereview.DefaultStar holds the default value on creation for the star field. + nodereview.DefaultStar = nodereviewDescStar.Default.(int) + // nodereviewDescID is the schema descriptor for id field. + nodereviewDescID := nodereviewFields[0].Descriptor() + // nodereview.DefaultID holds the default value on creation for the id field. + nodereview.DefaultID = nodereviewDescID.Default.(func() uuid.UUID) nodeversionMixin := schema.NodeVersion{}.Mixin() nodeversionMixinFields0 := nodeversionMixin[0].Fields() _ = nodeversionMixinFields0 diff --git a/ent/schema/node.go b/ent/schema/node.go index 43efc2b..0ee3cc4 100644 --- a/ent/schema/node.go +++ b/ent/schema/node.go @@ -43,6 +43,9 @@ func (Node) Fields() []ent.Field { field.Strings("tags").SchemaType(map[string]string{ dialect.Postgres: "text", }).Default([]string{}), + field.Int64("total_install").Default(0), + field.Int64("total_star").Default(0), + field.Int64("total_review").Default(0), } } @@ -56,5 +59,6 @@ func (Node) Edges() []ent.Edge { return []ent.Edge{ edge.From("publisher", Publisher.Type).Field("publisher_id").Ref("nodes").Required().Unique(), edge.To("versions", NodeVersion.Type), + edge.To("reviews", NodeReview.Type), } } diff --git a/ent/schema/node_review.go b/ent/schema/node_review.go new file mode 100644 index 0000000..50224d1 --- /dev/null +++ b/ent/schema/node_review.go @@ -0,0 +1,39 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" +) + +type NodeReview struct { + ent.Schema +} + +func (NodeReview) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New), + field.String("node_id").SchemaType(map[string]string{ + dialect.Postgres: "text", + }), + field.String("user_id").SchemaType(map[string]string{ + dialect.Postgres: "text", + }), + field.Int("star").Default(0), + } +} + +func (NodeReview) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("user", User.Type).Field("user_id").Ref("reviews").Unique().Required(), + edge.From("node", Node.Type).Field("node_id").Ref("reviews").Unique().Required(), + } +} +func (NodeReview) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("node_id", "user_id").Unique(), + } +} diff --git a/ent/schema/user.go b/ent/schema/user.go index 67ec683..eaca70d 100644 --- a/ent/schema/user.go +++ b/ent/schema/user.go @@ -33,5 +33,6 @@ func (User) Mixin() []ent.Mixin { func (User) Edges() []ent.Edge { return []ent.Edge{ edge.To("publisher_permissions", PublisherPermission.Type), + edge.To("reviews", NodeReview.Type), } } diff --git a/ent/tx.go b/ent/tx.go index 2fae588..cfef450 100644 --- a/ent/tx.go +++ b/ent/tx.go @@ -18,6 +18,8 @@ type Tx struct { GitCommit *GitCommitClient // Node is the client for interacting with the Node builders. Node *NodeClient + // NodeReview is the client for interacting with the NodeReview builders. + NodeReview *NodeReviewClient // NodeVersion is the client for interacting with the NodeVersion builders. NodeVersion *NodeVersionClient // PersonalAccessToken is the client for interacting with the PersonalAccessToken builders. @@ -164,6 +166,7 @@ func (tx *Tx) init() { tx.CIWorkflowResult = NewCIWorkflowResultClient(tx.config) tx.GitCommit = NewGitCommitClient(tx.config) tx.Node = NewNodeClient(tx.config) + tx.NodeReview = NewNodeReviewClient(tx.config) tx.NodeVersion = NewNodeVersionClient(tx.config) tx.PersonalAccessToken = NewPersonalAccessTokenClient(tx.config) tx.Publisher = NewPublisherClient(tx.config) diff --git a/ent/user.go b/ent/user.go index 23b524f..6a72fcd 100644 --- a/ent/user.go +++ b/ent/user.go @@ -40,9 +40,11 @@ type User struct { type UserEdges struct { // PublisherPermissions holds the value of the publisher_permissions edge. PublisherPermissions []*PublisherPermission `json:"publisher_permissions,omitempty"` + // Reviews holds the value of the reviews edge. + Reviews []*NodeReview `json:"reviews,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 } // PublisherPermissionsOrErr returns the PublisherPermissions value or an error if the edge @@ -54,6 +56,15 @@ func (e UserEdges) PublisherPermissionsOrErr() ([]*PublisherPermission, error) { return nil, &NotLoadedError{edge: "publisher_permissions"} } +// ReviewsOrErr returns the Reviews value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) ReviewsOrErr() ([]*NodeReview, error) { + if e.loadedTypes[1] { + return e.Reviews, nil + } + return nil, &NotLoadedError{edge: "reviews"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*User) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -140,6 +151,11 @@ func (u *User) QueryPublisherPermissions() *PublisherPermissionQuery { return NewUserClient(u.config).QueryPublisherPermissions(u) } +// QueryReviews queries the "reviews" edge of the User entity. +func (u *User) QueryReviews() *NodeReviewQuery { + return NewUserClient(u.config).QueryReviews(u) +} + // Update returns a builder for updating this User. // Note that you need to call User.Unwrap() before calling this method if this User // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/ent/user/user.go b/ent/user/user.go index 656c8fb..66b8e59 100644 --- a/ent/user/user.go +++ b/ent/user/user.go @@ -28,6 +28,8 @@ const ( FieldIsAdmin = "is_admin" // EdgePublisherPermissions holds the string denoting the publisher_permissions edge name in mutations. EdgePublisherPermissions = "publisher_permissions" + // EdgeReviews holds the string denoting the reviews edge name in mutations. + EdgeReviews = "reviews" // Table holds the table name of the user in the database. Table = "users" // PublisherPermissionsTable is the table that holds the publisher_permissions relation/edge. @@ -37,6 +39,13 @@ const ( PublisherPermissionsInverseTable = "publisher_permissions" // PublisherPermissionsColumn is the table column denoting the publisher_permissions relation/edge. PublisherPermissionsColumn = "user_id" + // ReviewsTable is the table that holds the reviews relation/edge. + ReviewsTable = "node_reviews" + // ReviewsInverseTable is the table name for the NodeReview entity. + // It exists in this package in order to avoid circular dependency with the "nodereview" package. + ReviewsInverseTable = "node_reviews" + // ReviewsColumn is the table column denoting the reviews relation/edge. + ReviewsColumn = "user_id" ) // Columns holds all SQL columns for user fields. @@ -124,6 +133,20 @@ func ByPublisherPermissions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOpt sqlgraph.OrderByNeighborTerms(s, newPublisherPermissionsStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByReviewsCount orders the results by reviews count. +func ByReviewsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newReviewsStep(), opts...) + } +} + +// ByReviews orders the results by reviews terms. +func ByReviews(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReviewsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newPublisherPermissionsStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -131,3 +154,10 @@ func newPublisherPermissionsStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, PublisherPermissionsTable, PublisherPermissionsColumn), ) } +func newReviewsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ReviewsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReviewsTable, ReviewsColumn), + ) +} diff --git a/ent/user/where.go b/ent/user/where.go index 0471803..808eeb3 100644 --- a/ent/user/where.go +++ b/ent/user/where.go @@ -368,6 +368,29 @@ func HasPublisherPermissionsWith(preds ...predicate.PublisherPermission) predica }) } +// HasReviews applies the HasEdge predicate on the "reviews" edge. +func HasReviews() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ReviewsTable, ReviewsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReviewsWith applies the HasEdge predicate on the "reviews" edge with a given conditions (other predicates). +func HasReviewsWith(preds ...predicate.NodeReview) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newReviewsStep() + 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.User) predicate.User { return predicate.User(sql.AndPredicates(predicates...)) diff --git a/ent/user_create.go b/ent/user_create.go index 7f669c3..902178e 100644 --- a/ent/user_create.go +++ b/ent/user_create.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "registry-backend/ent/nodereview" "registry-backend/ent/publisherpermission" "registry-backend/ent/user" "time" @@ -14,6 +15,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/google/uuid" ) // UserCreate is the builder for creating a User entity. @@ -129,6 +131,21 @@ func (uc *UserCreate) AddPublisherPermissions(p ...*PublisherPermission) *UserCr return uc.AddPublisherPermissionIDs(ids...) } +// AddReviewIDs adds the "reviews" edge to the NodeReview entity by IDs. +func (uc *UserCreate) AddReviewIDs(ids ...uuid.UUID) *UserCreate { + uc.mutation.AddReviewIDs(ids...) + return uc +} + +// AddReviews adds the "reviews" edges to the NodeReview entity. +func (uc *UserCreate) AddReviews(n ...*NodeReview) *UserCreate { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return uc.AddReviewIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uc *UserCreate) Mutation() *UserMutation { return uc.mutation @@ -272,6 +289,22 @@ func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := uc.mutation.ReviewsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReviewsTable, + Columns: []string{user.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/ent/user_query.go b/ent/user_query.go index 3c42ebc..e24e015 100644 --- a/ent/user_query.go +++ b/ent/user_query.go @@ -7,6 +7,7 @@ import ( "database/sql/driver" "fmt" "math" + "registry-backend/ent/nodereview" "registry-backend/ent/predicate" "registry-backend/ent/publisherpermission" "registry-backend/ent/user" @@ -25,6 +26,7 @@ type UserQuery struct { inters []Interceptor predicates []predicate.User withPublisherPermissions *PublisherPermissionQuery + withReviews *NodeReviewQuery modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -84,6 +86,28 @@ func (uq *UserQuery) QueryPublisherPermissions() *PublisherPermissionQuery { return query } +// QueryReviews chains the current query on the "reviews" edge. +func (uq *UserQuery) QueryReviews() *NodeReviewQuery { + query := (&NodeReviewClient{config: uq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(nodereview.Table, nodereview.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.ReviewsTable, user.ReviewsColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first User entity from the query. // Returns a *NotFoundError when no User was found. func (uq *UserQuery) First(ctx context.Context) (*User, error) { @@ -277,6 +301,7 @@ func (uq *UserQuery) Clone() *UserQuery { inters: append([]Interceptor{}, uq.inters...), predicates: append([]predicate.User{}, uq.predicates...), withPublisherPermissions: uq.withPublisherPermissions.Clone(), + withReviews: uq.withReviews.Clone(), // clone intermediate query. sql: uq.sql.Clone(), path: uq.path, @@ -294,6 +319,17 @@ func (uq *UserQuery) WithPublisherPermissions(opts ...func(*PublisherPermissionQ return uq } +// WithReviews tells the query-builder to eager-load the nodes that are connected to +// the "reviews" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithReviews(opts ...func(*NodeReviewQuery)) *UserQuery { + query := (&NodeReviewClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withReviews = query + return uq +} + // 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. // @@ -372,8 +408,9 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e var ( nodes = []*User{} _spec = uq.querySpec() - loadedTypes = [1]bool{ + loadedTypes = [2]bool{ uq.withPublisherPermissions != nil, + uq.withReviews != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -406,6 +443,13 @@ func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e return nil, err } } + if query := uq.withReviews; query != nil { + if err := uq.loadReviews(ctx, query, nodes, + func(n *User) { n.Edges.Reviews = []*NodeReview{} }, + func(n *User, e *NodeReview) { n.Edges.Reviews = append(n.Edges.Reviews, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -439,6 +483,36 @@ func (uq *UserQuery) loadPublisherPermissions(ctx context.Context, query *Publis } return nil } +func (uq *UserQuery) loadReviews(ctx context.Context, query *NodeReviewQuery, nodes []*User, init func(*User), assign func(*User, *NodeReview)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(nodereview.FieldUserID) + } + query.Where(predicate.NodeReview(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.ReviewsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { _spec := uq.querySpec() diff --git a/ent/user_update.go b/ent/user_update.go index 28e0135..6052abd 100644 --- a/ent/user_update.go +++ b/ent/user_update.go @@ -6,6 +6,7 @@ import ( "context" "errors" "fmt" + "registry-backend/ent/nodereview" "registry-backend/ent/predicate" "registry-backend/ent/publisherpermission" "registry-backend/ent/user" @@ -14,6 +15,7 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/google/uuid" ) // UserUpdate is the builder for updating User entities. @@ -118,6 +120,21 @@ func (uu *UserUpdate) AddPublisherPermissions(p ...*PublisherPermission) *UserUp return uu.AddPublisherPermissionIDs(ids...) } +// AddReviewIDs adds the "reviews" edge to the NodeReview entity by IDs. +func (uu *UserUpdate) AddReviewIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.AddReviewIDs(ids...) + return uu +} + +// AddReviews adds the "reviews" edges to the NodeReview entity. +func (uu *UserUpdate) AddReviews(n ...*NodeReview) *UserUpdate { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return uu.AddReviewIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation @@ -144,6 +161,27 @@ func (uu *UserUpdate) RemovePublisherPermissions(p ...*PublisherPermission) *Use return uu.RemovePublisherPermissionIDs(ids...) } +// ClearReviews clears all "reviews" edges to the NodeReview entity. +func (uu *UserUpdate) ClearReviews() *UserUpdate { + uu.mutation.ClearReviews() + return uu +} + +// RemoveReviewIDs removes the "reviews" edge to NodeReview entities by IDs. +func (uu *UserUpdate) RemoveReviewIDs(ids ...uuid.UUID) *UserUpdate { + uu.mutation.RemoveReviewIDs(ids...) + return uu +} + +// RemoveReviews removes "reviews" edges to NodeReview entities. +func (uu *UserUpdate) RemoveReviews(n ...*NodeReview) *UserUpdate { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return uu.RemoveReviewIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (uu *UserUpdate) Save(ctx context.Context) (int, error) { uu.defaults() @@ -255,6 +293,51 @@ func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uu.mutation.ReviewsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReviewsTable, + Columns: []string{user.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedReviewsIDs(); len(nodes) > 0 && !uu.mutation.ReviewsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReviewsTable, + Columns: []string{user.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.ReviewsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReviewsTable, + Columns: []string{user.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + 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, uu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} @@ -364,6 +447,21 @@ func (uuo *UserUpdateOne) AddPublisherPermissions(p ...*PublisherPermission) *Us return uuo.AddPublisherPermissionIDs(ids...) } +// AddReviewIDs adds the "reviews" edge to the NodeReview entity by IDs. +func (uuo *UserUpdateOne) AddReviewIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.AddReviewIDs(ids...) + return uuo +} + +// AddReviews adds the "reviews" edges to the NodeReview entity. +func (uuo *UserUpdateOne) AddReviews(n ...*NodeReview) *UserUpdateOne { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return uuo.AddReviewIDs(ids...) +} + // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation @@ -390,6 +488,27 @@ func (uuo *UserUpdateOne) RemovePublisherPermissions(p ...*PublisherPermission) return uuo.RemovePublisherPermissionIDs(ids...) } +// ClearReviews clears all "reviews" edges to the NodeReview entity. +func (uuo *UserUpdateOne) ClearReviews() *UserUpdateOne { + uuo.mutation.ClearReviews() + return uuo +} + +// RemoveReviewIDs removes the "reviews" edge to NodeReview entities by IDs. +func (uuo *UserUpdateOne) RemoveReviewIDs(ids ...uuid.UUID) *UserUpdateOne { + uuo.mutation.RemoveReviewIDs(ids...) + return uuo +} + +// RemoveReviews removes "reviews" edges to NodeReview entities. +func (uuo *UserUpdateOne) RemoveReviews(n ...*NodeReview) *UserUpdateOne { + ids := make([]uuid.UUID, len(n)) + for i := range n { + ids[i] = n[i].ID + } + return uuo.RemoveReviewIDs(ids...) +} + // Where appends a list predicates to the UserUpdate builder. func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { uuo.mutation.Where(ps...) @@ -531,6 +650,51 @@ func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if uuo.mutation.ReviewsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReviewsTable, + Columns: []string{user.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedReviewsIDs(); len(nodes) > 0 && !uuo.mutation.ReviewsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReviewsTable, + Columns: []string{user.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.ReviewsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.ReviewsTable, + Columns: []string{user.ReviewsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(nodereview.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _node = &User{config: uuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues diff --git a/integration-tests/registry_integration_test.go b/integration-tests/registry_integration_test.go index 92044dd..63a2191 100644 --- a/integration-tests/registry_integration_test.go +++ b/integration-tests/registry_integration_test.go @@ -7,7 +7,6 @@ import ( "registry-backend/ent" "registry-backend/mock/gateways" "registry-backend/server/implementation" - "strconv" "strings" "testing" @@ -326,29 +325,12 @@ func TestRegistry(t *testing.T) { }) - t.Run("Create Node with Duplicate ID", func(t *testing.T) { - createNodeResponse, err := impl.CreateNode(ctx, drip.CreateNodeRequestObject{ - PublisherId: publisherId, - Body: &drip.Node{ - Id: &nodeId, - Name: &nodeName, - Description: &nodeDescription, - Author: &nodeAuthor, - License: &nodeLicense, - Tags: &nodeTags, - Icon: &icon, - Repository: &githubUrl, - }, - }) - require.Error(t, err, "should return error when creating node with duplicate ID") - assert.IsType(t, drip.CreateNode400JSONResponse{}, createNodeResponse) - }) - t.Run("Get Node", func(t *testing.T) { res, err := impl.GetNode(ctx, drip.GetNodeRequestObject{NodeId: nodeId}) require.NoError(t, err, "should not return error") require.IsType(t, drip.GetNode200JSONResponse{}, res) res200 := res.(drip.GetNode200JSONResponse) + expDl, expRate := 0, float32(0) assert.Equal(t, drip.GetNode200JSONResponse{ Id: &nodeId, Name: &nodeName, @@ -358,6 +340,9 @@ func TestRegistry(t *testing.T) { License: &nodeLicense, Icon: &icon, Repository: &githubUrl, + + Downloads: &expDl, + Rating: &expRate, }, res200, "should return stored node data") }) @@ -375,6 +360,7 @@ func TestRegistry(t *testing.T) { require.IsType(t, drip.ListNodesForPublisher200JSONResponse{}, res) res200 := res.(drip.ListNodesForPublisher200JSONResponse) require.Len(t, res200, 1) + expDl, expRate := 0, float32(0) assert.Equal(t, drip.Node{ Id: &nodeId, Name: &nodeName, @@ -384,6 +370,9 @@ func TestRegistry(t *testing.T) { License: &nodeLicense, Icon: &icon, Repository: &githubUrl, + + Downloads: &expDl, + Rating: &expRate, }, res200[0], "should return stored node data") }) @@ -424,6 +413,7 @@ func TestRegistry(t *testing.T) { require.NoError(t, err, "should not return error") require.IsType(t, drip.GetNode200JSONResponse{}, resUpdated) res200Updated := resUpdated.(drip.GetNode200JSONResponse) + expDl, expRate := 0, float32(0) assert.Equal(t, drip.GetNode200JSONResponse{ Id: &nodeId, Description: &updateNodeDescription, @@ -433,6 +423,9 @@ func TestRegistry(t *testing.T) { Tags: &updateNodeTags, Icon: &updateIcon, Repository: &updateGithubUrl, + + Downloads: &expDl, + Rating: &expRate, }, res200Updated, "should return updated node data") }) @@ -641,6 +634,7 @@ func TestRegistry(t *testing.T) { resNodes200 := resNodes.(drip.ListAllNodes200JSONResponse) assert.Len(t, *resNodes200.Nodes, 1, "should only contain 1 node") + expDl, expRate := 0, float32(0) expectedNode := drip.Node{ Id: &nodeId, Name: &nodeName, @@ -652,6 +646,8 @@ func TestRegistry(t *testing.T) { LatestVersion: &createdNodeVersion, Icon: proto.String(""), Publisher: (*drip.Publisher)(&createdPublisher), + Downloads: &expDl, + Rating: &expRate, } expectedNode.LatestVersion.DownloadUrl = (*resNodes200.Nodes)[0].LatestVersion.DownloadUrl // generated expectedNode.LatestVersion.Deprecated = (*resNodes200.Nodes)[0].LatestVersion.Deprecated // generated @@ -680,104 +676,24 @@ func TestRegistry(t *testing.T) { require.IsType(t, drip.InstallNode404JSONResponse{}, resIns, "should return 404") }) - t.Run("Node Search", func(t *testing.T) { - ctx, _ := setUpTest(client) - publisherId := "test-publisher-node-search" - description := "test-description" - source_code_repo := "test-source-code-repo" - website := "test-website" - support := "test-support" - logo := "test-logo" - name := "test-name" - - createPublisherResponse, err := impl.CreatePublisher(ctx, drip.CreatePublisherRequestObject{ - Body: &drip.Publisher{ - Id: &publisherId, - Description: &description, - SourceCodeRepo: &source_code_repo, - Website: &website, - Support: &support, - Logo: &logo, - Name: &name, - }, - }) - require.NoError(t, err, "should return created publisher") - require.NotNil(t, createPublisherResponse, "should return created publisher") - assert.Equal(t, publisherId, *createPublisherResponse.(drip.CreatePublisher201JSONResponse).Id) - - tokenName := "test-token-search" - tokenDescription := "test-token-description" - createPersonalAccessTokenResponse, err := impl.CreatePersonalAccessToken(ctx, drip.CreatePersonalAccessTokenRequestObject{ - PublisherId: publisherId, - Body: &drip.PersonalAccessToken{ - Name: &tokenName, - Description: &tokenDescription, - }, + t.Run("Get Total Install", func(t *testing.T) { + res, err := impl.GetNode(ctx, drip.GetNodeRequestObject{ + NodeId: nodeId, }) - require.NoError(t, err, "should return created token") - require.NotNil(t, *createPersonalAccessTokenResponse.(drip.CreatePersonalAccessToken201JSONResponse).Token, "Token should have a value.") - - nodeId := "test-node-search" - nodeDescription := "test-node-description" - nodeAuthor := "test-node-author" - nodeLicense := "test-node-license" - nodeName := "test-node-name" - nodeTags := []string{"test-node-tag"} - nodeVersionLiteral := "1.0.0" - changelog := "test-changelog" - dependencies := []string{"test-dependency"} - - for i := 0; i < 21; i++ { - mockStorageService.On("GenerateSignedURL", mock.Anything, mock.Anything).Return("test-url", nil) - mockStorageService.On("GetFileUrl", mock.Anything, mock.Anything, mock.Anything).Return("test-url", nil) - createNodeVersionResp, err := impl.PublishNodeVersion(ctx, drip.PublishNodeVersionRequestObject{ - PublisherId: publisherId, - NodeId: nodeId, - Body: &drip.PublishNodeVersionJSONRequestBody{ - Node: drip.Node{ - Id: proto.String(nodeId + "-" + strconv.Itoa(i)), - Description: &nodeDescription, - Author: &nodeAuthor, - License: &nodeLicense, - Name: &nodeName, - Tags: &nodeTags, - Repository: &source_code_repo, - }, - NodeVersion: drip.NodeVersion{ - Version: proto.String(nodeVersionLiteral + "-" + strconv.Itoa(i)), - Changelog: &changelog, - Dependencies: &dependencies, - }, - PersonalAccessToken: *createPersonalAccessTokenResponse.(drip.CreatePersonalAccessToken201JSONResponse).Token, - }, - }) - require.NoError(t, err, "should return created node version") - require.IsType(t, drip.PublishNodeVersion201JSONResponse{}, createNodeVersionResp) - } + require.NoError(t, err, "should not return error") + require.IsType(t, drip.GetNode200JSONResponse{}, res) + assert.Equal(t, int(2), *res.(drip.GetNode200JSONResponse).Downloads) + }) - t.Run("Search", func(t *testing.T) { - t.Run("Match Many", func(t *testing.T) { - resNodes, err := impl.SearchNodes(ctx, drip.SearchNodesRequestObject{Params: drip.SearchNodesParams{ - Search: proto.String("test-node"), - }}) - require.NoError(t, err, "should not return error") - require.IsType(t, drip.SearchNodes200JSONResponse{}, resNodes, "should return 200 server response") - resNodes200 := resNodes.(drip.SearchNodes200JSONResponse) - assert.Len(t, *resNodes200.Nodes, 10, "should contains 10 node") - }) - t.Run("Match Some", func(t *testing.T) { - resNodes, err := impl.SearchNodes(ctx, drip.SearchNodesRequestObject{Params: drip.SearchNodesParams{ - Search: proto.String("test-node-search-2"), - }}) - require.NoError(t, err, "should not return error") - require.IsType(t, drip.SearchNodes200JSONResponse{}, resNodes, "should return 200 server response") - resNodes200 := resNodes.(drip.SearchNodes200JSONResponse) - assert.Len(t, *resNodes200.Nodes, 2, "should contains 2 node") - for _, n := range *resNodes200.Nodes { - assert.Contains(t, *n.Id, "test-node-search-2") - } - }) + t.Run("Add review", func(t *testing.T) { + res, err := impl.PostNodeReview(ctx, drip.PostNodeReviewRequestObject{ + NodeId: nodeId, + Params: drip.PostNodeReviewParams{Star: 5}, }) + require.NoError(t, err) + require.IsType(t, drip.PostNodeReview200JSONResponse{}, res) + res200 := res.(drip.PostNodeReview200JSONResponse) + assert.Equal(t, float32(5), *res200.Rating) }) }) } diff --git a/mapper/node.go b/mapper/node.go index 24bf761..60b237c 100644 --- a/mapper/node.go +++ b/mapper/node.go @@ -110,6 +110,12 @@ func DbNodeToApiNode(node *ent.Node) *drip.Node { return nil } + downloads := int(node.TotalInstall) + rate := float32(0) + if node.TotalReview > 0 { + rate = float32(node.TotalStar) / float32(node.TotalReview) + } + return &drip.Node{ Author: &node.Author, Description: &node.Description, @@ -119,5 +125,7 @@ func DbNodeToApiNode(node *ent.Node) *drip.Node { Tags: &node.Tags, Repository: &node.RepositoryURL, Icon: &node.IconURL, + Downloads: &downloads, + Rating: &rate, } } diff --git a/openapi.yml b/openapi.yml index c6b3ff6..d394a7b 100644 --- a/openapi.yml +++ b/openapi.yml @@ -1151,6 +1151,46 @@ paths: schema: $ref: '#/components/schemas/ErrorResponse' + /nodes/{nodeId}/reviews: + post: + summary: Add review to a specific version of a node + operationId: postNodeReview + tags: + - Nodes + parameters: + - in: path + name: nodeId + required: true + schema: + type: string + - in: query + name: star + description: number of star given to the node version + required: true + schema: + type: integer + responses: + '200': + description: Detailed information about a specific node + content: + application/json: + schema: + $ref: '#/components/schemas/Node' + '400': + description: Bad Request + '404': + description: Node version not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + /nodes/{nodeId}/install: get: summary: Returns a node version to be installed. diff --git a/server/implementation/registry.go b/server/implementation/registry.go index a3bd2c8..bca0619 100644 --- a/server/implementation/registry.go +++ b/server/implementation/registry.go @@ -682,6 +682,34 @@ func (s *DripStrictServerImplementation) UpdateNodeVersion( }, nil } +// PostNodeVersionReview implements drip.StrictServerInterface. +func (s *DripStrictServerImplementation) PostNodeReview(ctx context.Context, request drip.PostNodeReviewRequestObject) (drip.PostNodeReviewResponseObject, error) { + log.Ctx(ctx).Info().Msgf("PostNodeReview request received for "+ + "node ID: %s", request.NodeId) + + if request.Params.Star < 1 || request.Params.Star > 5 { + log.Ctx(ctx).Error().Msgf("Invalid star received: %d", request.Params.Star) + return drip.PostNodeReview400Response{}, nil + } + + userId, err := mapper.GetUserIDFromContext(ctx) + if err != nil { + log.Ctx(ctx).Error().Msgf("Failed to get user ID from context w/ err: %v", err) + return drip.PostNodeReview404JSONResponse{}, err + } + + nv, err := s.RegistryService.AddNodeReview(ctx, s.Client, request.NodeId, userId, request.Params.Star) + if ent.IsNotFound(err) { + log.Ctx(ctx).Error().Msgf("Error retrieving node version w/ err: %v", err) + return drip.PostNodeReview404JSONResponse{}, nil + } + + node := mapper.DbNodeToApiNode(nv) + log.Ctx(ctx).Info().Msgf("Node review for %s stored successfully", request.NodeId) + return drip.PostNodeReview200JSONResponse(*node), nil + +} + func (s *DripStrictServerImplementation) DeleteNodeVersion( ctx context.Context, request drip.DeleteNodeVersionRequestObject) (drip.DeleteNodeVersionResponseObject, error) { log.Ctx(ctx).Info().Msgf("DeleteNodeVersion request received for node ID: "+ @@ -875,7 +903,7 @@ func (s *DripStrictServerImplementation) InstallNode( log.Ctx(ctx).Info().Msgf("InstallNode request received for node ID: %s", request.NodeId) // Get node - _, err := s.RegistryService.GetNode(ctx, s.Client, request.NodeId) + node, err := s.RegistryService.GetNode(ctx, s.Client, request.NodeId) if ent.IsNotFound(err) { log.Ctx(ctx).Error().Msgf("Error retrieving node w/ err: %v", err) return drip.InstallNode404JSONResponse{Message: "Node not found"}, nil @@ -897,6 +925,12 @@ func (s *DripStrictServerImplementation) InstallNode( log.Ctx(ctx).Error().Msgf("Error retrieving latest node version w/ err: %v", err) return drip.InstallNode500JSONResponse{Message: errMessage}, err } + err = node.Update().AddTotalInstall(1).Exec(ctx) + if err != nil { + errMessage := "Failed to get increment number of node version install: " + err.Error() + log.Ctx(ctx).Error().Msgf("Error incrementing number of latest node version install w/ err: %v", err) + return drip.InstallNode500JSONResponse{Message: errMessage}, err + } mp.Track(ctx, []*mixpanel.Event{ mp.NewEvent("Install Node Latest", "", map[string]any{ "Node ID": request.NodeId, @@ -917,6 +951,12 @@ func (s *DripStrictServerImplementation) InstallNode( log.Ctx(ctx).Error().Msgf("Error retrieving node version w/ err: %v", err) return drip.InstallNode500JSONResponse{Message: errMessage}, err } + err = node.Update().AddTotalInstall(1).Exec(ctx) + if err != nil { + errMessage := "Failed to get increment number of node version install: " + err.Error() + log.Ctx(ctx).Error().Msgf("Error incrementing number of latest node version install w/ err: %v", err) + return drip.InstallNode500JSONResponse{Message: errMessage}, err + } mp.Track(ctx, []*mixpanel.Event{ mp.NewEvent("Install Node", "", map[string]any{ "Node ID": request.NodeId, diff --git a/services/registry/registry_svc.go b/services/registry/registry_svc.go index 5808d90..889ddc2 100644 --- a/services/registry/registry_svc.go +++ b/services/registry/registry_svc.go @@ -352,6 +352,39 @@ func (s *RegistryService) ListNodeVersions(ctx context.Context, client *ent.Clie return versions, nil } +func (s *RegistryService) AddNodeReview(ctx context.Context, client *ent.Client, nodeId, userID string, star int) (nv *ent.Node, err error) { + log.Ctx(ctx).Info().Msgf("add review to node: %v ", nodeId) + + err = db.WithTx(ctx, client, func(tx *ent.Tx) error { + v, err := s.GetNode(ctx, tx.Client(), nodeId) + if err != nil { + return fmt.Errorf("fail to fetch node version") + } + + err = tx.Client().NodeReview.Create(). + SetNode(v). + SetUserID(userID). + SetStar(star). + Exec(ctx) + if err != nil { + return fmt.Errorf("fail to add review to node ") + } + + err = v.Update().AddTotalReview(1).AddTotalStar(int64(star)).Exec(ctx) + if err != nil { + return fmt.Errorf("fail to add review: %w", err) + } + + nv, err = s.GetNode(ctx, tx.Client(), nodeId) + if err != nil { + return fmt.Errorf("fail to fetch node s") + } + return nil + }) + + return +} + func (s *RegistryService) GetNodeVersion(ctx context.Context, client *ent.Client, nodeId, nodeVersion string) (*ent.NodeVersion, error) { log.Ctx(ctx).Info().Msgf("getting node version: %v", nodeVersion) return client.NodeVersion.